diff --git a/libs/data/questdb/src/ilp-v2-writer.ts b/libs/data/questdb/src/ilp-v2-writer.ts new file mode 100644 index 00000000..2d64a7c8 --- /dev/null +++ b/libs/data/questdb/src/ilp-v2-writer.ts @@ -0,0 +1,521 @@ +import type { Bar1mRow } from './types'; + +/** QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). */ +export const ILP_V2_DOUBLE_TYPE = 0x10; + +/** Default maximum buffered bytes before flushing a batch (1 MiB). */ +export const DEFAULT_ILP_MAX_BATCH_BYTES = 1_048_576; + +/** Default maximum buffered rows before flushing a batch. */ +export const DEFAULT_ILP_MAX_BATCH_ROWS = 10_000; + +const TABLE_BARS_1M = 'bars_1m'; +const TABLE_FX_1M = 'fx_1m'; + +const INT32_MIN = -2_147_483_648; +const INT32_MAX = 2_147_483_647; +const INT64_MIN = -(2n ** 63n); +const INT64_MAX = 2n ** 63n - 1n; + +const BYTE_SPACE = 0x20; +const BYTE_COMMA = 0x2c; +const BYTE_EQUALS = 0x3d; +const BYTE_LF = 0x0a; +const BYTE_CR = 0x0d; +const BYTE_BACKSLASH = 0x5c; + +const textEncoder = new TextEncoder(); + +const BARS_1M_OPEN_PREFIX = textEncoder.encode(' open=='); +const HIGH_PREFIX = textEncoder.encode(',high=='); +const LOW_PREFIX = textEncoder.encode(',low=='); +const CLOSE_PREFIX = textEncoder.encode(',close=='); +const VOLUME_PREFIX = textEncoder.encode(',volume=='); +const FX_1M_PREFIX = textEncoder.encode(`${TABLE_FX_1M},pair=`); +const FX_1M_SOURCE_PREFIX = textEncoder.encode(',source='); + +/** Valid intraday trading session tags for `bars_1m`. */ +export type Bar1mSession = 'PRE' | 'RTH' | 'POST'; + +/** + * Curated `bars_1m` row input for QuestDB ILP v2 encoding. + * + * Derived from read-side `Bar1mRow` with `vwap` omitted (left NULL in QuestDB) and + * `session` / `source` narrowed to required non-null write values matching `M2_INTRADAY_SCHEMAS.bars_1m`. + */ +export type Bar1mIlpV2Row = Omit & { + session: Bar1mSession; + source: string; +}; + +/** + * Curated `fx_1m` row input for QuestDB ILP v2 encoding. + * + * Matches `M2_INTRADAY_SCHEMAS.fx_1m`: symbols `pair`, `source`; binary doubles + * `open`, `high`, `low`, `close`; designated timestamp `ts` (UTC epoch microseconds). + */ +export interface Fx1mIlpV2Row { + pair: string; + source: string; + open: number; + high: number; + low: number; + close: number; + ts: bigint; +} + +/** Discriminated error kinds for `IlpV2EncodeError`. */ +export type IlpV2EncodeErrorKind = + | 'empty-symbol' + | 'invalid-session' + | 'invalid-listing-id' + | 'non-finite-double' + | 'negative-timestamp' + | 'timestamp-out-of-range'; + +/** + * Typed validation error thrown by `encodeBar1mIlpV2` and `encodeFx1mIlpV2`. + * + * Validation runs atomically before any bytes are encoded or buffered. + */ +export class IlpV2EncodeError extends Error { + public readonly kind: IlpV2EncodeErrorKind; + public readonly field: string; + public readonly value?: number | bigint | string; + + constructor( + kind: IlpV2EncodeErrorKind, + field: string, + message: string, + value?: number | bigint | string + ) { + super(message); + this.name = 'IlpV2EncodeError'; + this.kind = kind; + this.field = field; + if (value !== undefined) { + this.value = value; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Injected output port for `createIlpV2BatchWriter`. */ +export interface IlpV2BatchSink { + write(batch: Uint8Array): Promise; +} + +/** Configuration options for `createIlpV2BatchWriter`. */ +export interface IlpV2BatchWriterOptions { + sink: IlpV2BatchSink; + maxBatchBytes?: number; + maxBatchRows?: number; +} + +/** Write summary returned by `IlpV2BatchWriter.finish()`. */ +export interface IlpV2BatchWriterStats { + rows: number; + batches: number; + bytes: number; +} + +/** Pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. */ +export interface IlpV2BatchWriter { + writeBar1m(row: Bar1mIlpV2Row): Promise; + writeFx1m(row: Fx1mIlpV2Row): Promise; + flush(): Promise; + finish(): Promise; +} + +function validateNonEmptySymbol(field: string, value: string): void { + if (typeof value !== 'string' || value.length === 0) { + throw new IlpV2EncodeError('empty-symbol', field, `empty ILP symbol field '${field}'`); + } +} + +function validateSession(value: Bar1mSession): void { + if (typeof value !== 'string' || value.length === 0) { + throw new IlpV2EncodeError('empty-symbol', 'session', "empty ILP symbol field 'session'"); + } + if (value !== 'PRE' && value !== 'RTH' && value !== 'POST') { + throw new IlpV2EncodeError( + 'invalid-session', + 'session', + `invalid ILP session '${String(value)}' (expected PRE, RTH, or POST)`, + String(value) + ); + } +} + +function validateListingId(value: number): void { + if ( + typeof value !== 'number' || + !Number.isInteger(value) || + value < INT32_MIN || + value > INT32_MAX + ) { + throw new IlpV2EncodeError( + 'invalid-listing-id', + 'listing_id', + `invalid ILP listing_id '${String(value)}' (expected signed 32-bit integer)`, + value + ); + } +} + +function validateFiniteDouble(field: string, value: number): void { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new IlpV2EncodeError( + 'non-finite-double', + field, + `non-finite ILP double field '${field}': ${String(value)}`, + value + ); + } +} + +function validateInt64Timestamp(field: string, value: bigint): void { + if (typeof value !== 'bigint' || value < INT64_MIN || value > INT64_MAX) { + throw new IlpV2EncodeError( + 'timestamp-out-of-range', + field, + `ILP timestamp '${field}' out of signed 64-bit range: ${String(value)}`, + typeof value === 'bigint' ? value : undefined + ); + } +} + +function validateDesignatedTimestamp(field: string, value: bigint): void { + validateInt64Timestamp(field, value); + if (value < 0n) { + throw new IlpV2EncodeError( + 'negative-timestamp', + field, + `negative ILP designated timestamp '${field}': ${value.toString(10)} (must be >= 0)`, + value + ); + } +} + +function needsSymbolEscape(byte: number): boolean { + return ( + byte === BYTE_SPACE || + byte === BYTE_COMMA || + byte === BYTE_EQUALS || + byte === BYTE_LF || + byte === BYTE_CR || + byte === BYTE_BACKSLASH + ); +} + +/** + * Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. + */ +function encodeEscapedSymbol(value: string): Uint8Array { + const raw = textEncoder.encode(value); + let extra = 0; + for (const b of raw) { + if (needsSymbolEscape(b)) { + extra += 1; + } + } + if (extra === 0) { + return raw; + } + + const escaped = new Uint8Array(raw.length + extra); + let out = 0; + for (const b of raw) { + if (needsSymbolEscape(b)) { + escaped[out++] = BYTE_BACKSLASH; + } + escaped[out++] = b; + } + return escaped; +} + +function writeBinaryDoubleField( + out: Uint8Array, + view: DataView, + offset: number, + prefix: Uint8Array, + value: number +): number { + out.set(prefix, offset); + const typeOffset = offset + prefix.byteLength; + out[typeOffset] = ILP_V2_DOUBLE_TYPE; + view.setFloat64(typeOffset + 1, value, true); + return typeOffset + 9; +} + +/** + * Encodes one curated `bars_1m` row in QuestDB ILP v2 format. + * + * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_bar_1m`): + * - Table `bars_1m` + * - Symbols `listing_id` (decimal), `session` (`PRE`/`RTH`/`POST`), `source` (escaped) + * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close`, `volume` (`vwap` omitted) + * - Timestamp column `known_at=t` (signed 64-bit integer preserved as supplied) + * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) + */ +export function encodeBar1mIlpV2(row: Bar1mIlpV2Row): Uint8Array { + validateListingId(row.listing_id); + validateSession(row.session); + validateNonEmptySymbol('source', row.source); + validateFiniteDouble('open', row.open); + validateFiniteDouble('high', row.high); + validateFiniteDouble('low', row.low); + validateFiniteDouble('close', row.close); + validateFiniteDouble('volume', row.volume); + validateInt64Timestamp('known_at', row.known_at); + validateDesignatedTimestamp('ts', row.ts); + + const listingIdDecimal = row.listing_id === 0 ? '0' : String(row.listing_id); + const prefixBytes = textEncoder.encode( + `${TABLE_BARS_1M},listing_id=${listingIdDecimal},session=${row.session},source=` + ); + const escapedSourceBytes = encodeEscapedSymbol(row.source); + const suffixBytes = textEncoder.encode( + `,known_at=${row.known_at.toString(10)}t ${row.ts.toString(10)}t\n` + ); + + // Binary doubles section: ' open==\x10<8>,high==\x10<8>,low==\x10<8>,close==\x10<8>,volume==\x10<8>' + const binaryFieldsLen = + BARS_1M_OPEN_PREFIX.byteLength + + 9 + + HIGH_PREFIX.byteLength + + 9 + + LOW_PREFIX.byteLength + + 9 + + CLOSE_PREFIX.byteLength + + 9 + + VOLUME_PREFIX.byteLength + + 9; + + const out = new Uint8Array( + prefixBytes.byteLength + escapedSourceBytes.byteLength + binaryFieldsLen + suffixBytes.byteLength + ); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + + let offset = 0; + out.set(prefixBytes, offset); + offset += prefixBytes.byteLength; + out.set(escapedSourceBytes, offset); + offset += escapedSourceBytes.byteLength; + + offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); + offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); + offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); + offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); + offset = writeBinaryDoubleField(out, view, offset, VOLUME_PREFIX, row.volume); + + out.set(suffixBytes, offset); + return out; +} + +/** + * Encodes one `fx_1m` row in QuestDB ILP v2 format. + * + * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_fx_1m`): + * - Table `fx_1m` + * - Symbols `pair` (escaped), `source` (escaped) + * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close` + * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) + */ +export function encodeFx1mIlpV2(row: Fx1mIlpV2Row): Uint8Array { + validateNonEmptySymbol('pair', row.pair); + validateNonEmptySymbol('source', row.source); + validateFiniteDouble('open', row.open); + validateFiniteDouble('high', row.high); + validateFiniteDouble('low', row.low); + validateFiniteDouble('close', row.close); + validateDesignatedTimestamp('ts', row.ts); + + const escapedPairBytes = encodeEscapedSymbol(row.pair); + const escapedSourceBytes = encodeEscapedSymbol(row.source); + const suffixBytes = textEncoder.encode(` ${row.ts.toString(10)}t\n`); + + const binaryFieldsLen = + BARS_1M_OPEN_PREFIX.byteLength + + 9 + + HIGH_PREFIX.byteLength + + 9 + + LOW_PREFIX.byteLength + + 9 + + CLOSE_PREFIX.byteLength + + 9; + + const out = new Uint8Array( + FX_1M_PREFIX.byteLength + + escapedPairBytes.byteLength + + FX_1M_SOURCE_PREFIX.byteLength + + escapedSourceBytes.byteLength + + binaryFieldsLen + + suffixBytes.byteLength + ); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + + let offset = 0; + out.set(FX_1M_PREFIX, offset); + offset += FX_1M_PREFIX.byteLength; + out.set(escapedPairBytes, offset); + offset += escapedPairBytes.byteLength; + out.set(FX_1M_SOURCE_PREFIX, offset); + offset += FX_1M_SOURCE_PREFIX.byteLength; + out.set(escapedSourceBytes, offset); + offset += escapedSourceBytes.byteLength; + + offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); + offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); + offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); + offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); + + out.set(suffixBytes, offset); + return out; +} + +function assertPositiveIntegerOption(name: string, value: number): void { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) { + throw new RangeError(`ILP v2 batch writer option '${name}' must be a positive integer`); + } +} + +/** + * Creates a pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. + * + * Operations are serialized in call order so overlapping calls never reorder rows or overlap + * sink writes. Batches always end on whole-row boundaries, fail closed on sink errors, and + * reject writes after `finish()`. + */ +export function createIlpV2BatchWriter(options: IlpV2BatchWriterOptions): IlpV2BatchWriter { + if (!options || !options.sink || typeof options.sink.write !== 'function') { + throw new TypeError('ILP v2 batch writer requires a sink with a write(batch) method'); + } + + const maxBatchBytes = options.maxBatchBytes ?? DEFAULT_ILP_MAX_BATCH_BYTES; + const maxBatchRows = options.maxBatchRows ?? DEFAULT_ILP_MAX_BATCH_ROWS; + assertPositiveIntegerOption('maxBatchBytes', maxBatchBytes); + assertPositiveIntegerOption('maxBatchRows', maxBatchRows); + + const { sink } = options; + + const pendingChunks: Uint8Array[] = []; + let pendingBytes = 0; + let pendingRows = 0; + + let writtenRows = 0; + let writtenBatches = 0; + let writtenBytes = 0; + + let finished = false; + let hasSinkFailure = false; + let sinkFailure: unknown = null; + + let queueTail: Promise = Promise.resolve(); + + function enqueue(operation: () => Promise): Promise { + const result = queueTail.then(operation, operation); + queueTail = result.then( + () => undefined, + () => undefined + ); + return result; + } + + function assertHealthyForMutation(action: string): void { + if (hasSinkFailure) { + throw new Error(`ILP v2 batch writer is closed after a sink write failure (${action})`, { + cause: sinkFailure, + }); + } + if (finished) { + throw new Error(`ILP v2 batch writer is already finished (${action})`); + } + } + + async function flushPending(): Promise { + if (pendingChunks.length === 0) { + return; + } + + const batch = new Uint8Array(pendingBytes); + let offset = 0; + for (const chunk of pendingChunks) { + batch.set(chunk, offset); + offset += chunk.byteLength; + } + + const rowCount = pendingRows; + const byteCount = pendingBytes; + + try { + await sink.write(batch); + } catch (error) { + hasSinkFailure = true; + sinkFailure = error; + pendingChunks.length = 0; + pendingBytes = 0; + pendingRows = 0; + throw error; + } + + pendingChunks.length = 0; + pendingBytes = 0; + pendingRows = 0; + writtenRows += rowCount; + writtenBatches += 1; + writtenBytes += byteCount; + } + + async function enqueueEncodedRow(encoded: Uint8Array): Promise { + if (pendingChunks.length > 0 && pendingBytes + encoded.byteLength > maxBatchBytes) { + await flushPending(); + } + + pendingChunks.push(encoded); + pendingBytes += encoded.byteLength; + pendingRows += 1; + + if (pendingRows >= maxBatchRows || pendingBytes >= maxBatchBytes) { + await flushPending(); + } + } + + return { + writeBar1m(row: Bar1mIlpV2Row): Promise { + return enqueue(async () => { + assertHealthyForMutation('writeBar1m'); + const encoded = encodeBar1mIlpV2(row); + await enqueueEncodedRow(encoded); + }); + }, + + writeFx1m(row: Fx1mIlpV2Row): Promise { + return enqueue(async () => { + assertHealthyForMutation('writeFx1m'); + const encoded = encodeFx1mIlpV2(row); + await enqueueEncodedRow(encoded); + }); + }, + + flush(): Promise { + return enqueue(async () => { + assertHealthyForMutation('flush'); + await flushPending(); + }); + }, + + finish(): Promise { + return enqueue(async () => { + assertHealthyForMutation('finish'); + await flushPending(); + finished = true; + return { + rows: writtenRows, + batches: writtenBatches, + bytes: writtenBytes, + }; + }); + }, + }; +} diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 94841d60..6036ae94 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -9,6 +9,23 @@ export { QuestDBClient, readBars1m } from './client'; export { QuestDBHealthMonitor } from './health'; export { QuestDBQueryBuilder } from './query-builder'; export { QuestDBInfluxWriter } from './influx-writer'; +export { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + ILP_V2_DOUBLE_TYPE, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Bar1mSession, + type Fx1mIlpV2Row, + type IlpV2BatchSink, + type IlpV2BatchWriter, + type IlpV2BatchWriterOptions, + type IlpV2BatchWriterStats, + type IlpV2EncodeErrorKind, +} from './ilp-v2-writer'; export { formatCreateTableSQL, getM2IntradayDDL, diff --git a/libs/data/questdb/src/influx-writer.ts b/libs/data/questdb/src/influx-writer.ts index 90e6145b..6f48aae7 100644 --- a/libs/data/questdb/src/influx-writer.ts +++ b/libs/data/questdb/src/influx-writer.ts @@ -11,6 +11,9 @@ interface QuestDBClientInterface { * * Provides high-performance data ingestion using InfluxDB Line Protocol * which QuestDB supports natively for optimal time-series data insertion. + * + * @deprecated Legacy text-ILP writer. Use `createIlpV2BatchWriter` (from `./ilp-v2-writer`) + * for QuestDB ILP v2 binary-double ingestion into `bars_1m` and `fx_1m`. */ export class QuestDBInfluxWriter { private readonly logger: ReturnType; diff --git a/libs/data/questdb/test/ilp-v2-writer.test.ts b/libs/data/questdb/test/ilp-v2-writer.test.ts new file mode 100644 index 00000000..b271a920 --- /dev/null +++ b/libs/data/questdb/test/ilp-v2-writer.test.ts @@ -0,0 +1,741 @@ +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 { + 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 { + 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 { + 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 after every 2 rows. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 2 * rowLen, + maxBatchRows: 100, + }); + for (let i = 0; i < 5; i++) { + await writer.writeBar1m(row); + } + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen }); + expect(batches).toHaveLength(3); + expect(batches[0]).toEqual(concatBytes([oneLine, oneLine])); + expect(batches[1]).toEqual(concatBytes([oneLine, oneLine])); + 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 { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + batches.push(batch.slice()); + return new Promise(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('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 { + sinkCalls += 1; + if (sinkCalls === 1) { + acceptedBatches.push(batch.slice()); + return Promise.resolve(); + } + return new Promise((_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); + }); +});