820 lines
26 KiB
TypeScript
820 lines
26 KiB
TypeScript
import { describe, expect, it } from 'bun:test';
|
|
import {
|
|
createIlpV2BatchWriter,
|
|
DEFAULT_ILP_MAX_BATCH_BYTES,
|
|
DEFAULT_ILP_MAX_BATCH_ROWS,
|
|
encodeBar1mIlpV2,
|
|
encodeFx1mIlpV2,
|
|
ILP_V2_DOUBLE_TYPE,
|
|
IlpV2EncodeError,
|
|
type Bar1mIlpV2Row,
|
|
type Fx1mIlpV2Row,
|
|
type IlpV2BatchSink,
|
|
} from '../src/index';
|
|
|
|
const encoder = new TextEncoder();
|
|
|
|
function asciiBytes(text: string): number[] {
|
|
return Array.from(encoder.encode(text));
|
|
}
|
|
|
|
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
|
|
const total = chunks.reduce((sum, c) => sum + c.byteLength, 0);
|
|
const out = new Uint8Array(total);
|
|
let offset = 0;
|
|
for (const chunk of chunks) {
|
|
out.set(chunk, offset);
|
|
offset += chunk.byteLength;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function indexOfSubarray(haystack: Uint8Array, needle: Uint8Array): number {
|
|
outer: for (let i = 0; i <= haystack.length - needle.length; i++) {
|
|
for (let j = 0; j < needle.length; j++) {
|
|
if (haystack[i + j] !== needle[j]) {
|
|
continue outer;
|
|
}
|
|
}
|
|
return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
function sampleBar(overrides: Partial<Bar1mIlpV2Row> = {}): Bar1mIlpV2Row {
|
|
return {
|
|
listing_id: 42,
|
|
ts: 1_736_951_400_000_000n,
|
|
known_at: 1_736_951_460_000_000n,
|
|
open: 123.45,
|
|
high: 125.75,
|
|
low: 122.125,
|
|
close: 124.5,
|
|
volume: 98_765.0,
|
|
session: 'RTH',
|
|
source: 'eod_unadj',
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function sampleFx(overrides: Partial<Fx1mIlpV2Row> = {}): Fx1mIlpV2Row {
|
|
return {
|
|
pair: 'USD.CAD',
|
|
source: 'eod',
|
|
open: 1.3625,
|
|
high: 1.365,
|
|
low: 1.36125,
|
|
close: 1.364375,
|
|
ts: 1_736_951_400_000_000n,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function createMemorySink(): { sink: IlpV2BatchSink; batches: Uint8Array[] } {
|
|
const batches: Uint8Array[] = [];
|
|
const sink: IlpV2BatchSink = {
|
|
async write(batch: Uint8Array): Promise<void> {
|
|
batches.push(batch.slice());
|
|
},
|
|
};
|
|
return { sink, batches };
|
|
}
|
|
|
|
describe('ILP v2 writer constants', () => {
|
|
it('matches Rust tools/curate-etl/src/ilp.rs constants', () => {
|
|
expect(ILP_V2_DOUBLE_TYPE).toBe(0x10);
|
|
expect(DEFAULT_ILP_MAX_BATCH_BYTES).toBe(1_048_576);
|
|
expect(DEFAULT_ILP_MAX_BATCH_ROWS).toBe(10_000);
|
|
});
|
|
});
|
|
|
|
describe('ILP v2 byte-parity with tools/curate-etl/src/ilp_tests.rs', () => {
|
|
it('matches golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract byte-for-byte', () => {
|
|
// Mirrors `golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract`
|
|
// in `tools/curate-etl/src/ilp_tests.rs`.
|
|
const row: Bar1mIlpV2Row = {
|
|
listing_id: 42,
|
|
ts: 1_736_951_400_000_000n,
|
|
known_at: 1_736_951_460_123_456n,
|
|
open: 150.25,
|
|
high: 151.75,
|
|
low: 149.5,
|
|
close: 151.125,
|
|
volume: 12_345.0,
|
|
session: 'RTH',
|
|
source: 'eod_unadj',
|
|
};
|
|
|
|
const actual = encodeBar1mIlpV2(row);
|
|
|
|
// Expected wire bytes written out literally (little-endian IEEE-754 doubles):
|
|
// 150.25 -> 0x4062c80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x62, 0x40]
|
|
// 151.75 -> 0x4062f80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x62, 0x40]
|
|
// 149.5 -> 0x4062b00000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x62, 0x40]
|
|
// 151.125 -> 0x4062e40000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x62, 0x40]
|
|
// 12345.0 -> 0x40c81c8000000000 -> [0x00, 0x00, 0x00, 0x00, 0x80, 0x1c, 0xc8, 0x40]
|
|
const expected = new Uint8Array([
|
|
...asciiBytes('bars_1m,listing_id=42,session=RTH,source=eod_unadj open=='),
|
|
0x10,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0xc8,
|
|
0x62,
|
|
0x40,
|
|
...asciiBytes(',high=='),
|
|
0x10,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0xf8,
|
|
0x62,
|
|
0x40,
|
|
...asciiBytes(',low=='),
|
|
0x10,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0xb0,
|
|
0x62,
|
|
0x40,
|
|
...asciiBytes(',close=='),
|
|
0x10,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0xe4,
|
|
0x62,
|
|
0x40,
|
|
...asciiBytes(',volume=='),
|
|
0x10,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x00,
|
|
0x80,
|
|
0x1c,
|
|
0xc8,
|
|
0x40,
|
|
...asciiBytes(',known_at=1736951460123456t 1736951400000000t\n'),
|
|
]);
|
|
|
|
expect(actual).toEqual(expected);
|
|
expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1);
|
|
|
|
// Verify PRE and POST session tags as in the Rust golden test.
|
|
const preBytes = encodeBar1mIlpV2({ ...row, session: 'PRE' });
|
|
expect(
|
|
indexOfSubarray(preBytes, encoder.encode('bars_1m,listing_id=42,session=PRE,source=eod_unadj '))
|
|
).toBe(0);
|
|
|
|
const postBytes = encodeBar1mIlpV2({ ...row, session: 'POST' });
|
|
expect(
|
|
indexOfSubarray(
|
|
postBytes,
|
|
encoder.encode('bars_1m,listing_id=42,session=POST,source=eod_unadj ')
|
|
)
|
|
).toBe(0);
|
|
});
|
|
|
|
it('matches golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract byte-for-byte', () => {
|
|
// Mirrors `golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract`
|
|
// in `tools/curate-etl/src/ilp_tests.rs`.
|
|
const row: Fx1mIlpV2Row = {
|
|
pair: 'USD.CAD',
|
|
ts: 1_736_951_400_000_000n,
|
|
open: 1.3625,
|
|
high: 1.365,
|
|
low: 1.36125,
|
|
close: 1.364375,
|
|
source: 'eod',
|
|
};
|
|
|
|
const actual = encodeFx1mIlpV2(row);
|
|
|
|
// Expected wire bytes written out literally (little-endian IEEE-754 doubles):
|
|
// 1.3625 -> 0x3ff5cccccccccccc -> [0xcd, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xf5, 0x3f]
|
|
// 1.365 -> 0x3ff5d70a3d70a3d7 -> [0xd7, 0xa3, 0x70, 0x3d, 0x0a, 0xd7, 0xf5, 0x3f]
|
|
// 1.36125 -> 0x3ff5c7ae147ae148 -> [0x48, 0xe1, 0x7a, 0x14, 0xae, 0xc7, 0xf5, 0x3f]
|
|
// 1.364375 -> 0x3ff5d47ae147ae14 -> [0x14, 0xae, 0x47, 0xe1, 0x7a, 0xd4, 0xf5, 0x3f]
|
|
const expected = new Uint8Array([
|
|
...asciiBytes('fx_1m,pair=USD.CAD,source=eod open=='),
|
|
0x10,
|
|
0xcd,
|
|
0xcc,
|
|
0xcc,
|
|
0xcc,
|
|
0xcc,
|
|
0xcc,
|
|
0xf5,
|
|
0x3f,
|
|
...asciiBytes(',high=='),
|
|
0x10,
|
|
0xd7,
|
|
0xa3,
|
|
0x70,
|
|
0x3d,
|
|
0x0a,
|
|
0xd7,
|
|
0xf5,
|
|
0x3f,
|
|
...asciiBytes(',low=='),
|
|
0x10,
|
|
0x48,
|
|
0xe1,
|
|
0x7a,
|
|
0x14,
|
|
0xae,
|
|
0xc7,
|
|
0xf5,
|
|
0x3f,
|
|
...asciiBytes(',close=='),
|
|
0x10,
|
|
0x14,
|
|
0xae,
|
|
0x47,
|
|
0xe1,
|
|
0x7a,
|
|
0xd4,
|
|
0xf5,
|
|
0x3f,
|
|
...asciiBytes(' 1736951400000000t\n'),
|
|
]);
|
|
|
|
expect(actual).toEqual(expected);
|
|
expect(indexOfSubarray(actual, encoder.encode('known_at'))).toBe(-1);
|
|
expect(indexOfSubarray(actual, encoder.encode('volume'))).toBe(-1);
|
|
expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1);
|
|
});
|
|
});
|
|
|
|
describe('ILP v2 escaping, timestamps, and atomic rejection', () => {
|
|
it('escapes all six ILP symbol characters and preserves UTF-8 and signed known_at', () => {
|
|
// Mirrors `symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection`
|
|
// in `tools/curate-etl/src/ilp_tests.rs`.
|
|
const rawSym = 'a b,c=d\\e\nf\rg caf\u00e9';
|
|
const expectedEscaped = new Uint8Array([
|
|
...asciiBytes('a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf'),
|
|
0xc3,
|
|
0xa9,
|
|
]);
|
|
|
|
// Rust `encode_bar_1m` writes signed `known_at` via `write_i64_decimal` without rejecting < 0.
|
|
const barBytes = encodeBar1mIlpV2(
|
|
sampleBar({
|
|
listing_id: 7,
|
|
ts: 0n,
|
|
known_at: -1n,
|
|
source: rawSym,
|
|
})
|
|
);
|
|
const expectedBarPrefix = concatBytes([
|
|
encoder.encode('bars_1m,listing_id=7,session=RTH,source='),
|
|
expectedEscaped,
|
|
encoder.encode(' '),
|
|
]);
|
|
expect(barBytes.slice(0, expectedBarPrefix.byteLength)).toEqual(expectedBarPrefix);
|
|
const expectedBarSuffix = encoder.encode(',known_at=-1t 0t\n');
|
|
expect(barBytes.slice(barBytes.byteLength - expectedBarSuffix.byteLength)).toEqual(
|
|
expectedBarSuffix
|
|
);
|
|
|
|
// Also check signed 64-bit timestamp endpoints and INT32 listing_id endpoints.
|
|
const int64Min = -(2n ** 63n);
|
|
const int64Max = 2n ** 63n - 1n;
|
|
const endpointBar = encodeBar1mIlpV2(
|
|
sampleBar({
|
|
listing_id: -2_147_483_648,
|
|
known_at: int64Min,
|
|
ts: int64Max,
|
|
})
|
|
);
|
|
expect(
|
|
indexOfSubarray(endpointBar, encoder.encode('bars_1m,listing_id=-2147483648,session=RTH,'))
|
|
).toBe(0);
|
|
const endpointSuffix = encoder.encode(
|
|
`,known_at=${int64Min.toString(10)}t ${int64Max.toString(10)}t\n`
|
|
);
|
|
expect(endpointBar.slice(endpointBar.byteLength - endpointSuffix.byteLength)).toEqual(
|
|
endpointSuffix
|
|
);
|
|
|
|
const maxListingBar = encodeBar1mIlpV2(
|
|
sampleBar({
|
|
listing_id: 2_147_483_647,
|
|
known_at: int64Max,
|
|
ts: 0n,
|
|
})
|
|
);
|
|
expect(
|
|
indexOfSubarray(maxListingBar, encoder.encode('bars_1m,listing_id=2147483647,session=RTH,'))
|
|
).toBe(0);
|
|
|
|
// FX pair and source escaping.
|
|
const fxBytes = encodeFx1mIlpV2(
|
|
sampleFx({
|
|
pair: rawSym,
|
|
source: 'src=1,2 3\\4\n\r',
|
|
ts: 123n,
|
|
})
|
|
);
|
|
const expectedFxPrefix = concatBytes([
|
|
encoder.encode('fx_1m,pair='),
|
|
expectedEscaped,
|
|
encoder.encode(',source=src\\=1\\,2\\ 3\\\\4\\\n\\\r '),
|
|
]);
|
|
expect(fxBytes.slice(0, expectedFxPrefix.byteLength)).toEqual(expectedFxPrefix);
|
|
const expectedFxSuffix = encoder.encode(' 123t\n');
|
|
expect(fxBytes.slice(fxBytes.byteLength - expectedFxSuffix.byteLength)).toEqual(
|
|
expectedFxSuffix
|
|
);
|
|
});
|
|
|
|
it('throws typed IlpV2EncodeError for negative ts, int64 overflow, non-finite doubles, empty symbols, and non-int32 listing_id', () => {
|
|
const expectEncodeError = (
|
|
fn: () => unknown,
|
|
kind: IlpV2EncodeError['kind'],
|
|
field: string
|
|
) => {
|
|
try {
|
|
fn();
|
|
throw new Error('Expected IlpV2EncodeError to be thrown');
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(IlpV2EncodeError);
|
|
const encodeErr = err as IlpV2EncodeError;
|
|
expect(encodeErr.kind).toBe(kind);
|
|
expect(encodeErr.field).toBe(field);
|
|
}
|
|
};
|
|
|
|
// Negative designated timestamps.
|
|
expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ ts: -1n })), 'negative-timestamp', 'ts');
|
|
expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ ts: -42n })), 'negative-timestamp', 'ts');
|
|
|
|
// Signed 64-bit timestamp overflow / underflow.
|
|
const overInt64 = 2n ** 63n;
|
|
const underInt64 = -(2n ** 63n) - 1n;
|
|
expectEncodeError(
|
|
() => encodeBar1mIlpV2(sampleBar({ ts: overInt64 })),
|
|
'timestamp-out-of-range',
|
|
'ts'
|
|
);
|
|
expectEncodeError(
|
|
() => encodeBar1mIlpV2(sampleBar({ ts: underInt64 })),
|
|
'timestamp-out-of-range',
|
|
'ts'
|
|
);
|
|
expectEncodeError(
|
|
() => encodeBar1mIlpV2(sampleBar({ known_at: overInt64 })),
|
|
'timestamp-out-of-range',
|
|
'known_at'
|
|
);
|
|
expectEncodeError(
|
|
() => encodeBar1mIlpV2(sampleBar({ known_at: underInt64 })),
|
|
'timestamp-out-of-range',
|
|
'known_at'
|
|
);
|
|
expectEncodeError(
|
|
() => encodeFx1mIlpV2(sampleFx({ ts: overInt64 })),
|
|
'timestamp-out-of-range',
|
|
'ts'
|
|
);
|
|
|
|
// Non-finite doubles across every double column.
|
|
for (const badVal of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
|
|
for (const field of ['open', 'high', 'low', 'close', 'volume'] as const) {
|
|
expectEncodeError(
|
|
() => encodeBar1mIlpV2(sampleBar({ [field]: badVal })),
|
|
'non-finite-double',
|
|
field
|
|
);
|
|
}
|
|
for (const field of ['open', 'high', 'low', 'close'] as const) {
|
|
expectEncodeError(
|
|
() => encodeFx1mIlpV2(sampleFx({ [field]: badVal })),
|
|
'non-finite-double',
|
|
field
|
|
);
|
|
}
|
|
}
|
|
|
|
// Empty symbols.
|
|
expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ source: '' })), 'empty-symbol', 'source');
|
|
expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ pair: '' })), 'empty-symbol', 'pair');
|
|
expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ source: '' })), 'empty-symbol', 'source');
|
|
|
|
// Non-INT32 listing_id.
|
|
for (const badId of [
|
|
1.5,
|
|
-0.25,
|
|
2_147_483_648,
|
|
-2_147_483_649,
|
|
Number.NaN,
|
|
Number.POSITIVE_INFINITY,
|
|
]) {
|
|
expectEncodeError(
|
|
() => encodeBar1mIlpV2(sampleBar({ listing_id: badId })),
|
|
'invalid-listing-id',
|
|
'listing_id'
|
|
);
|
|
}
|
|
});
|
|
|
|
it('rejects invalid rows at a batch boundary without calling sink and preserves pending rows', async () => {
|
|
const validRow = sampleBar({ listing_id: 101 });
|
|
const validBytes = encodeBar1mIlpV2(validRow);
|
|
const { sink, batches } = createMemorySink();
|
|
|
|
// Limit allows 1 row to sit pending right at the byte boundary so a second valid row would flush.
|
|
const writer = createIlpV2BatchWriter({
|
|
sink,
|
|
maxBatchBytes: validBytes.byteLength + 1,
|
|
maxBatchRows: 2,
|
|
});
|
|
|
|
await writer.writeBar1m(validRow);
|
|
expect(batches).toHaveLength(0);
|
|
|
|
// Rejected bar and FX rows must not flush the pending row or write anything to sink.
|
|
await expect(writer.writeBar1m(sampleBar({ ts: -1n }))).rejects.toBeInstanceOf(
|
|
IlpV2EncodeError
|
|
);
|
|
await expect(writer.writeBar1m(sampleBar({ volume: Number.NaN }))).rejects.toBeInstanceOf(
|
|
IlpV2EncodeError
|
|
);
|
|
await expect(writer.writeBar1m(sampleBar({ source: '' }))).rejects.toBeInstanceOf(
|
|
IlpV2EncodeError
|
|
);
|
|
await expect(writer.writeBar1m(sampleBar({ listing_id: 3.14 }))).rejects.toBeInstanceOf(
|
|
IlpV2EncodeError
|
|
);
|
|
await expect(writer.writeFx1m(sampleFx({ pair: '' }))).rejects.toBeInstanceOf(IlpV2EncodeError);
|
|
await expect(writer.writeFx1m(sampleFx({ ts: -5n }))).rejects.toBeInstanceOf(IlpV2EncodeError);
|
|
expect(batches).toHaveLength(0);
|
|
|
|
// Pending valid row is still intact and flushes cleanly on finish().
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 1, batches: 1, bytes: validBytes.byteLength });
|
|
expect(batches).toEqual([validBytes]);
|
|
});
|
|
});
|
|
|
|
describe('createIlpV2BatchWriter batching, boundaries, and option validation', () => {
|
|
it('validates maxBatchBytes and maxBatchRows at construction', () => {
|
|
const { sink } = createMemorySink();
|
|
for (const invalid of [0, -1, -100, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: invalid })).toThrow(RangeError);
|
|
expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: invalid })).toThrow(RangeError);
|
|
}
|
|
});
|
|
|
|
it('flushes on exact maxBatchRows, exact maxBatchBytes, pre-overflow, oversized singleton, and explicit/empty flush', async () => {
|
|
// Include a finite double whose IEEE-754 LE payload contains 0x0a (LF) and a symbol with LF.
|
|
const lfDoubleBuf = new Uint8Array([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]);
|
|
const doubleWithLf = new DataView(lfDoubleBuf.buffer).getFloat64(0, true);
|
|
expect(Number.isFinite(doubleWithLf)).toBe(true);
|
|
|
|
const row = sampleBar({ open: doubleWithLf, source: 'eod\nwith_lf' });
|
|
const oneLine = encodeBar1mIlpV2(row);
|
|
const rowLen = oneLine.byteLength;
|
|
|
|
// 1. Exact row limit (maxBatchRows = 3) + 1 remainder row.
|
|
{
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({
|
|
sink,
|
|
maxBatchBytes: 100_000,
|
|
maxBatchRows: 3,
|
|
});
|
|
for (let i = 0; i < 7; i++) {
|
|
await writer.writeBar1m(row);
|
|
}
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 7, batches: 3, bytes: 7 * rowLen });
|
|
expect(batches).toHaveLength(3);
|
|
expect(batches[0]).toEqual(concatBytes([oneLine, oneLine, oneLine]));
|
|
expect(batches[1]).toEqual(concatBytes([oneLine, oneLine, oneLine]));
|
|
expect(batches[2]).toEqual(oneLine);
|
|
expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true);
|
|
}
|
|
|
|
// 2. Exact byte limit (2 * rowLen): flushes immediately when the 2nd and 4th rows hit the limit.
|
|
{
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({
|
|
sink,
|
|
maxBatchBytes: 2 * rowLen,
|
|
maxBatchRows: 100,
|
|
});
|
|
await writer.writeBar1m(row);
|
|
expect(batches).toHaveLength(0);
|
|
await writer.writeBar1m(row);
|
|
expect(batches).toHaveLength(1);
|
|
expect(batches[0]).toEqual(concatBytes([oneLine, oneLine]));
|
|
await writer.writeBar1m(row);
|
|
expect(batches).toHaveLength(1);
|
|
await writer.writeBar1m(row);
|
|
expect(batches).toHaveLength(2);
|
|
expect(batches[1]).toEqual(concatBytes([oneLine, oneLine]));
|
|
await writer.writeBar1m(row);
|
|
expect(batches).toHaveLength(2);
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen });
|
|
expect(batches).toHaveLength(3);
|
|
expect(batches[2]).toEqual(oneLine);
|
|
}
|
|
|
|
// 3. Row would exceed remaining capacity (2 * rowLen - 1): pre-flushes before appending.
|
|
{
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({
|
|
sink,
|
|
maxBatchBytes: 2 * rowLen - 1,
|
|
maxBatchRows: 100,
|
|
});
|
|
for (let i = 0; i < 3; i++) {
|
|
await writer.writeBar1m(row);
|
|
}
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 3, batches: 3, bytes: 3 * rowLen });
|
|
expect(batches).toEqual([oneLine, oneLine, oneLine]);
|
|
}
|
|
|
|
// 4. Individually oversized row (maxBatchBytes = 16 < rowLen): sent alone, never split.
|
|
{
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({
|
|
sink,
|
|
maxBatchBytes: 16,
|
|
maxBatchRows: 100,
|
|
});
|
|
await writer.writeBar1m(row);
|
|
await writer.writeBar1m(row);
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 2, batches: 2, bytes: 2 * rowLen });
|
|
expect(batches).toEqual([oneLine, oneLine]);
|
|
}
|
|
|
|
// 5. Empty flush, explicit flush, and zero-row finish.
|
|
{
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({ sink, maxBatchBytes: 100_000, maxBatchRows: 10 });
|
|
await writer.flush();
|
|
expect(batches).toHaveLength(0);
|
|
await writer.writeBar1m(row);
|
|
await writer.flush();
|
|
expect(batches).toEqual([oneLine]);
|
|
await writer.flush();
|
|
expect(batches).toHaveLength(1);
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 1, batches: 1, bytes: rowLen });
|
|
}
|
|
|
|
{
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({ sink });
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 0, batches: 0, bytes: 0 });
|
|
expect(batches).toHaveLength(0);
|
|
}
|
|
});
|
|
|
|
it('preserves mixed bars_1m and fx_1m input order and rejects writes after finish()', async () => {
|
|
const bar1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n });
|
|
const fx1 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n });
|
|
const bar2 = sampleBar({ listing_id: 2, ts: 1_700_000_120_000_000n });
|
|
const fx2 = sampleFx({ pair: 'EUR.USD', ts: 1_700_000_180_000_000n });
|
|
|
|
const expectedAll = concatBytes([
|
|
encodeBar1mIlpV2(bar1),
|
|
encodeFx1mIlpV2(fx1),
|
|
encodeBar1mIlpV2(bar2),
|
|
encodeFx1mIlpV2(fx2),
|
|
]);
|
|
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 });
|
|
|
|
await writer.writeBar1m(bar1);
|
|
await writer.writeFx1m(fx1);
|
|
await writer.writeBar1m(bar2);
|
|
await writer.writeFx1m(fx2);
|
|
|
|
const stats = await writer.finish();
|
|
expect(stats).toEqual({ rows: 4, batches: 2, bytes: expectedAll.byteLength });
|
|
expect(concatBytes(batches)).toEqual(expectedAll);
|
|
expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true);
|
|
|
|
// Writes, flush, and finish after finish() throw without calling sink.
|
|
await expect(writer.writeBar1m(bar1)).rejects.toThrow(/already finished/i);
|
|
await expect(writer.writeFx1m(fx1)).rejects.toThrow(/already finished/i);
|
|
await expect(writer.flush()).rejects.toThrow(/already finished/i);
|
|
await expect(writer.finish()).rejects.toThrow(/already finished/i);
|
|
expect(batches).toHaveLength(2);
|
|
});
|
|
});
|
|
|
|
describe('createIlpV2BatchWriter serialization and fail-closed sink errors', () => {
|
|
it('serializes overlapping writes and finish() without overlapping sink calls', async () => {
|
|
let inFlight = 0;
|
|
let maxInFlight = 0;
|
|
const batches: Uint8Array[] = [];
|
|
const resolvers: Array<() => void> = [];
|
|
|
|
const sink: IlpV2BatchSink = {
|
|
write(batch: Uint8Array): Promise<void> {
|
|
inFlight += 1;
|
|
maxInFlight = Math.max(maxInFlight, inFlight);
|
|
batches.push(batch.slice());
|
|
return new Promise<void>(resolve => {
|
|
resolvers.push(() => {
|
|
inFlight -= 1;
|
|
resolve();
|
|
});
|
|
});
|
|
},
|
|
};
|
|
|
|
const row1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n });
|
|
const row2 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n });
|
|
const row3 = sampleBar({ listing_id: 3, ts: 1_700_000_120_000_000n });
|
|
|
|
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 });
|
|
|
|
// Launch overlapping operations without awaiting between calls.
|
|
const p1 = writer.writeBar1m(row1);
|
|
const p2 = writer.writeFx1m(row2);
|
|
const p3 = writer.writeBar1m(row3);
|
|
const pFinish = writer.finish();
|
|
|
|
// Drain queued manual resolutions one by one as each sink.write starts.
|
|
await Promise.resolve();
|
|
expect(resolvers).toHaveLength(1);
|
|
expect(inFlight).toBe(1);
|
|
resolvers[0]!();
|
|
await p1;
|
|
|
|
await Promise.resolve();
|
|
expect(resolvers).toHaveLength(2);
|
|
expect(inFlight).toBe(1);
|
|
resolvers[1]!();
|
|
await p2;
|
|
|
|
await Promise.resolve();
|
|
expect(resolvers).toHaveLength(3);
|
|
expect(inFlight).toBe(1);
|
|
resolvers[2]!();
|
|
await p3;
|
|
|
|
const stats = await pFinish;
|
|
expect(maxInFlight).toBe(1);
|
|
expect(stats).toEqual({
|
|
rows: 3,
|
|
batches: 3,
|
|
bytes:
|
|
encodeBar1mIlpV2(row1).byteLength +
|
|
encodeFx1mIlpV2(row2).byteLength +
|
|
encodeBar1mIlpV2(row3).byteLength,
|
|
});
|
|
expect(batches).toEqual([
|
|
encodeBar1mIlpV2(row1),
|
|
encodeFx1mIlpV2(row2),
|
|
encodeBar1mIlpV2(row3),
|
|
]);
|
|
});
|
|
|
|
it('snapshots row field values at submission when a caller reuses mutable row objects across overlapping writes', async () => {
|
|
const { sink, batches } = createMemorySink();
|
|
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 });
|
|
|
|
const mutableBar = sampleBar({
|
|
listing_id: 10,
|
|
ts: 1_700_000_000_000_000n,
|
|
known_at: 1_700_000_060_000_000n,
|
|
open: 100.0,
|
|
high: 101.0,
|
|
low: 99.5,
|
|
close: 100.5,
|
|
volume: 1_000,
|
|
session: 'PRE',
|
|
source: 'bar_one',
|
|
});
|
|
const expectedBar1 = encodeBar1mIlpV2(mutableBar);
|
|
|
|
const mutableFx = sampleFx({
|
|
pair: 'USD.CAD',
|
|
source: 'fx_one',
|
|
open: 1.35,
|
|
high: 1.36,
|
|
low: 1.34,
|
|
close: 1.355,
|
|
ts: 1_700_000_000_000_000n,
|
|
});
|
|
const expectedFx1 = encodeFx1mIlpV2(mutableFx);
|
|
|
|
// Submit first bar and FX row without awaiting, then mutate both objects in place.
|
|
const pBar1 = writer.writeBar1m(mutableBar);
|
|
const pFx1 = writer.writeFx1m(mutableFx);
|
|
|
|
mutableBar.listing_id = 11;
|
|
mutableBar.ts = 1_700_000_060_000_000n;
|
|
mutableBar.known_at = 1_700_000_120_000_000n;
|
|
mutableBar.open = 200.0;
|
|
mutableBar.high = 202.0;
|
|
mutableBar.low = 199.0;
|
|
mutableBar.close = 201.5;
|
|
mutableBar.volume = 2_000;
|
|
mutableBar.session = 'RTH';
|
|
mutableBar.source = 'bar_two';
|
|
const expectedBar2 = encodeBar1mIlpV2(mutableBar);
|
|
|
|
mutableFx.pair = 'EUR.USD';
|
|
mutableFx.source = 'fx_two';
|
|
mutableFx.open = 1.08;
|
|
mutableFx.high = 1.09;
|
|
mutableFx.low = 1.07;
|
|
mutableFx.close = 1.085;
|
|
mutableFx.ts = 1_700_000_060_000_000n;
|
|
const expectedFx2 = encodeFx1mIlpV2(mutableFx);
|
|
|
|
const pBar2 = writer.writeBar1m(mutableBar);
|
|
const pFx2 = writer.writeFx1m(mutableFx);
|
|
|
|
await Promise.all([pBar1, pFx1, pBar2, pFx2]);
|
|
const stats = await writer.finish();
|
|
|
|
expect(stats).toEqual({
|
|
rows: 4,
|
|
batches: 4,
|
|
bytes:
|
|
expectedBar1.byteLength +
|
|
expectedFx1.byteLength +
|
|
expectedBar2.byteLength +
|
|
expectedFx2.byteLength,
|
|
});
|
|
expect(batches).toEqual([expectedBar1, expectedFx1, expectedBar2, expectedFx2]);
|
|
});
|
|
|
|
it('propagates sink rejection and fails closed for queued and subsequent calls with zero extra sink writes', async () => {
|
|
const boom = new Error('simulated sink EPIPE');
|
|
let sinkCalls = 0;
|
|
const acceptedBatches: Uint8Array[] = [];
|
|
let rejectSecondWrite: ((err: Error) => void) | null = null;
|
|
|
|
const sink: IlpV2BatchSink = {
|
|
write(batch: Uint8Array): Promise<void> {
|
|
sinkCalls += 1;
|
|
if (sinkCalls === 1) {
|
|
acceptedBatches.push(batch.slice());
|
|
return Promise.resolve();
|
|
}
|
|
return new Promise<void>((_resolve, reject) => {
|
|
rejectSecondWrite = reject;
|
|
});
|
|
},
|
|
};
|
|
|
|
const row1 = sampleBar({ listing_id: 1 });
|
|
const row2 = sampleBar({ listing_id: 2 });
|
|
const row3 = sampleBar({ listing_id: 3 });
|
|
|
|
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 });
|
|
|
|
// First batch succeeds.
|
|
await writer.writeBar1m(row1);
|
|
expect(sinkCalls).toBe(1);
|
|
expect(acceptedBatches).toEqual([encodeBar1mIlpV2(row1)]);
|
|
|
|
// Trigger second batch (in-flight) and queue a third write + finish behind it.
|
|
const failingWrite = writer.writeBar1m(row2);
|
|
const queuedWrite = writer.writeBar1m(row3);
|
|
const queuedFinish = writer.finish();
|
|
|
|
await Promise.resolve();
|
|
expect(sinkCalls).toBe(2);
|
|
expect(rejectSecondWrite).not.toBeNull();
|
|
rejectSecondWrite!(boom);
|
|
|
|
// Triggering call receives the exact original error.
|
|
await expect(failingWrite).rejects.toBe(boom);
|
|
// Queued operations fail closed without invoking sink.write again.
|
|
await expect(queuedWrite).rejects.toThrow(/sink write failure/i);
|
|
await expect(queuedFinish).rejects.toThrow(/sink write failure/i);
|
|
|
|
// Later calls also fail closed without invoking sink.write.
|
|
await expect(writer.writeBar1m(row3)).rejects.toThrow(/sink write failure/i);
|
|
await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i);
|
|
await expect(writer.flush()).rejects.toThrow(/sink write failure/i);
|
|
await expect(writer.finish()).rejects.toThrow(/sink write failure/i);
|
|
|
|
expect(sinkCalls).toBe(2);
|
|
});
|
|
});
|