T-154: M2.3l — libs/data/questdb: pure TypeScript ILP v2 batch writer for bars_1m / fx_1m (ilp-v2-writer.ts, binary doubles + microsecond timestamps over an injected sink, byte-parity with tools/curate-etl/src/ilp.rs; no new deps, no live QuestDB)
This commit is contained in:
commit
a44815fa87
5 changed files with 1816 additions and 0 deletions
550
libs/data/questdb/src/ilp-v2-writer.ts
Normal file
550
libs/data/questdb/src/ilp-v2-writer.ts
Normal file
|
|
@ -0,0 +1,550 @@
|
|||
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<Bar1mRow, 'vwap' | 'session' | 'source'> & {
|
||||
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<void>;
|
||||
}
|
||||
|
||||
/** 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<void>;
|
||||
writeFx1m(row: Fx1mIlpV2Row): Promise<void>;
|
||||
flush(): Promise<void>;
|
||||
finish(): Promise<IlpV2BatchWriterStats>;
|
||||
}
|
||||
|
||||
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=<epoch_micros>t` (signed 64-bit integer preserved as supplied)
|
||||
* - Designated timestamp ` <epoch_micros>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 ` <epoch_micros>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<void> = Promise.resolve();
|
||||
|
||||
function enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotBar1mRow(row: Bar1mIlpV2Row): Bar1mIlpV2Row {
|
||||
return {
|
||||
listing_id: row.listing_id,
|
||||
ts: row.ts,
|
||||
known_at: row.known_at,
|
||||
open: row.open,
|
||||
high: row.high,
|
||||
low: row.low,
|
||||
close: row.close,
|
||||
volume: row.volume,
|
||||
session: row.session,
|
||||
source: row.source,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshotFx1mRow(row: Fx1mIlpV2Row): Fx1mIlpV2Row {
|
||||
return {
|
||||
pair: row.pair,
|
||||
source: row.source,
|
||||
open: row.open,
|
||||
high: row.high,
|
||||
low: row.low,
|
||||
close: row.close,
|
||||
ts: row.ts,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
writeBar1m(row: Bar1mIlpV2Row): Promise<void> {
|
||||
const snapshot = snapshotBar1mRow(row);
|
||||
return enqueue(async () => {
|
||||
assertHealthyForMutation('writeBar1m');
|
||||
const encoded = encodeBar1mIlpV2(snapshot);
|
||||
await enqueueEncodedRow(encoded);
|
||||
});
|
||||
},
|
||||
|
||||
writeFx1m(row: Fx1mIlpV2Row): Promise<void> {
|
||||
const snapshot = snapshotFx1mRow(row);
|
||||
return enqueue(async () => {
|
||||
assertHealthyForMutation('writeFx1m');
|
||||
const encoded = encodeFx1mIlpV2(snapshot);
|
||||
await enqueueEncodedRow(encoded);
|
||||
});
|
||||
},
|
||||
|
||||
flush(): Promise<void> {
|
||||
return enqueue(async () => {
|
||||
assertHealthyForMutation('flush');
|
||||
await flushPending();
|
||||
});
|
||||
},
|
||||
|
||||
finish(): Promise<IlpV2BatchWriterStats> {
|
||||
return enqueue(async () => {
|
||||
assertHealthyForMutation('finish');
|
||||
await flushPending();
|
||||
finished = true;
|
||||
return {
|
||||
rows: writtenRows,
|
||||
batches: writtenBatches,
|
||||
bytes: writtenBytes,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<typeof getLogger>;
|
||||
|
|
|
|||
426
libs/data/questdb/test/ilp-v2-writer-edges.test.ts
Normal file
426
libs/data/questdb/test/ilp-v2-writer-edges.test.ts
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
createIlpV2BatchWriter,
|
||||
DEFAULT_ILP_MAX_BATCH_BYTES,
|
||||
DEFAULT_ILP_MAX_BATCH_ROWS,
|
||||
encodeBar1mIlpV2,
|
||||
encodeFx1mIlpV2,
|
||||
IlpV2EncodeError,
|
||||
type Bar1mIlpV2Row,
|
||||
type Bar1mSession,
|
||||
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 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 expectEncodeError(fn: () => unknown, kind: IlpV2EncodeError['kind'], field: string) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(IlpV2EncodeError);
|
||||
expect((caught as IlpV2EncodeError).kind).toBe(kind);
|
||||
expect((caught as IlpV2EncodeError).field).toBe(field);
|
||||
}
|
||||
|
||||
describe('ILP v2 encoder edge cases', () => {
|
||||
it('matches golden_bytes_literal_ieee754_little_endian_without_to_le_bytes with hand-written bytes', () => {
|
||||
// Mirrors `golden_bytes_literal_ieee754_little_endian_without_to_le_bytes`
|
||||
// in `tools/curate-etl/src/ilp_tests.rs` (key 7, source eod_unadj).
|
||||
const actual = encodeBar1mIlpV2({
|
||||
listing_id: 7,
|
||||
ts: 1_700_000_000_000_000n,
|
||||
known_at: 1_700_000_060_000_000n,
|
||||
open: 1.0,
|
||||
high: 2.0,
|
||||
low: 0.5,
|
||||
close: 1.5,
|
||||
volume: 0.0,
|
||||
session: 'RTH',
|
||||
source: 'eod_unadj',
|
||||
});
|
||||
|
||||
const expected = new Uint8Array([
|
||||
...asciiBytes('bars_1m,listing_id=7,session=RTH,source=eod_unadj '),
|
||||
...asciiBytes('open=='),
|
||||
0x10,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0xf0,
|
||||
0x3f,
|
||||
...asciiBytes(',high=='),
|
||||
0x10,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x40,
|
||||
...asciiBytes(',low=='),
|
||||
0x10,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0xe0,
|
||||
0x3f,
|
||||
...asciiBytes(',close=='),
|
||||
0x10,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0xf8,
|
||||
0x3f,
|
||||
...asciiBytes(',volume=='),
|
||||
0x10,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
...asciiBytes(',known_at=1700000060000000t 1700000000000000t\n'),
|
||||
]);
|
||||
|
||||
expect(actual).toEqual(expected);
|
||||
});
|
||||
|
||||
it('preserves the negative-zero sign bit like Rust f64::to_le_bytes and emits -0 listing_id as 0', () => {
|
||||
const bytes = encodeBar1mIlpV2(sampleBar({ listing_id: -0, volume: -0 }));
|
||||
|
||||
expect(Array.from(bytes.slice(0, 22))).toEqual(asciiBytes('bars_1m,listing_id=0,s'));
|
||||
const volumePrefix = encoder.encode(',volume==');
|
||||
const suffix = encoder.encode(',known_at=1736951460000000t 1736951400000000t\n');
|
||||
const volStart = bytes.byteLength - suffix.byteLength - 9 - volumePrefix.byteLength;
|
||||
expect(bytes.slice(volStart, volStart + volumePrefix.byteLength)).toEqual(volumePrefix);
|
||||
expect(
|
||||
Array.from(
|
||||
bytes.slice(volStart + volumePrefix.byteLength, volStart + volumePrefix.byteLength + 9)
|
||||
)
|
||||
).toEqual([0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]);
|
||||
});
|
||||
|
||||
it('encodes extreme finite doubles (MAX_VALUE, MIN_VALUE subnormal, negative) without rejection', () => {
|
||||
const bytes = encodeFx1mIlpV2(
|
||||
sampleFx({ open: Number.MAX_VALUE, high: Number.MIN_VALUE, low: -1.5, close: 0 })
|
||||
);
|
||||
const head = encoder.encode('fx_1m,pair=USD.CAD,source=eod open==');
|
||||
expect(bytes.slice(0, head.byteLength)).toEqual(head);
|
||||
let o = head.byteLength;
|
||||
// MAX_VALUE = 0x7fefffffffffffff
|
||||
expect(Array.from(bytes.slice(o, o + 9))).toEqual([
|
||||
0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f,
|
||||
]);
|
||||
o += 9 + ',high=='.length;
|
||||
// MIN_VALUE = 0x0000000000000001
|
||||
expect(Array.from(bytes.slice(o, o + 9))).toEqual([
|
||||
0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
]);
|
||||
o += 9 + ',low=='.length;
|
||||
// -1.5 = 0xbff8000000000000
|
||||
expect(Array.from(bytes.slice(o, o + 9))).toEqual([
|
||||
0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf,
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns a fresh buffer per call so mutating one encoding cannot corrupt another', () => {
|
||||
const row = sampleFx();
|
||||
const a = encodeFx1mIlpV2(row);
|
||||
const b = encodeFx1mIlpV2(row);
|
||||
a.fill(0);
|
||||
expect(b).toEqual(encodeFx1mIlpV2(row));
|
||||
expect(b[0]).toBe(0x66); // 'f'
|
||||
});
|
||||
|
||||
it('escapes a symbol consisting only of special characters', () => {
|
||||
const bytes = encodeFx1mIlpV2(sampleFx({ pair: ' ,=\\\n\r' }));
|
||||
const expected = encoder.encode('fx_1m,pair=\\ \\,\\=\\\\\\\n\\\r,source=eod open==');
|
||||
expect(bytes.slice(0, expected.byteLength)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('rejects invalid or empty session tags with a typed error', () => {
|
||||
expectEncodeError(
|
||||
() => encodeBar1mIlpV2(sampleBar({ session: 'rth' as Bar1mSession })),
|
||||
'invalid-session',
|
||||
'session'
|
||||
);
|
||||
expectEncodeError(
|
||||
() => encodeBar1mIlpV2(sampleBar({ session: 'RTH ' as Bar1mSession })),
|
||||
'invalid-session',
|
||||
'session'
|
||||
);
|
||||
expectEncodeError(
|
||||
() => encodeBar1mIlpV2(sampleBar({ session: '' as Bar1mSession })),
|
||||
'empty-symbol',
|
||||
'session'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects non-bigint timestamps (JS number) instead of silently encoding them', () => {
|
||||
expectEncodeError(
|
||||
() => encodeBar1mIlpV2(sampleBar({ ts: 1_700_000_000_000_000 as unknown as bigint })),
|
||||
'timestamp-out-of-range',
|
||||
'ts'
|
||||
);
|
||||
expectEncodeError(
|
||||
() => encodeBar1mIlpV2(sampleBar({ known_at: 5 as unknown as bigint })),
|
||||
'timestamp-out-of-range',
|
||||
'known_at'
|
||||
);
|
||||
expectEncodeError(
|
||||
() => encodeFx1mIlpV2(sampleFx({ ts: 0 as unknown as bigint })),
|
||||
'timestamp-out-of-range',
|
||||
'ts'
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts the fx_1m designated timestamp at INT64_MAX', () => {
|
||||
const max = 2n ** 63n - 1n;
|
||||
const bytes = encodeFx1mIlpV2(sampleFx({ ts: max }));
|
||||
const suffix = encoder.encode(` ${max.toString(10)}t\n`);
|
||||
expect(bytes.slice(bytes.byteLength - suffix.byteLength)).toEqual(suffix);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createIlpV2BatchWriter edge cases', () => {
|
||||
it('rejects construction without a usable sink and rejects unsafe-integer limits', () => {
|
||||
expect(() => createIlpV2BatchWriter(undefined as never)).toThrow(TypeError);
|
||||
expect(() => createIlpV2BatchWriter({} as never)).toThrow(TypeError);
|
||||
expect(() => createIlpV2BatchWriter({ sink: {} as IlpV2BatchSink })).toThrow(TypeError);
|
||||
const sink: IlpV2BatchSink = { write: async () => {} };
|
||||
expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 2 ** 53 })).toThrow(RangeError);
|
||||
expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: '5' as unknown as number })).toThrow(
|
||||
RangeError
|
||||
);
|
||||
expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 1, maxBatchRows: 1 })).not.toThrow();
|
||||
});
|
||||
|
||||
it('flushes at DEFAULT_ILP_MAX_BATCH_ROWS when no limits are supplied', async () => {
|
||||
const batches: Uint8Array[] = [];
|
||||
const writer = createIlpV2BatchWriter({ sink: { write: async b => void batches.push(b) } });
|
||||
const row = sampleFx({ ts: 0n });
|
||||
const rowLen = encodeFx1mIlpV2(row).byteLength;
|
||||
// Row size keeps 10_000 rows well below the 1 MiB default, so only the row limit triggers.
|
||||
expect(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS).toBeLessThan(DEFAULT_ILP_MAX_BATCH_BYTES);
|
||||
|
||||
for (let i = 0; i < DEFAULT_ILP_MAX_BATCH_ROWS - 1; i++) {
|
||||
await writer.writeFx1m(row);
|
||||
}
|
||||
expect(batches).toHaveLength(0);
|
||||
await writer.writeFx1m(row);
|
||||
expect(batches).toHaveLength(1);
|
||||
expect(batches[0]!.byteLength).toBe(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS);
|
||||
|
||||
await writer.writeFx1m(row);
|
||||
const stats = await writer.finish();
|
||||
expect(stats).toEqual({
|
||||
rows: DEFAULT_ILP_MAX_BATCH_ROWS + 1,
|
||||
batches: 2,
|
||||
bytes: rowLen * (DEFAULT_ILP_MAX_BATCH_ROWS + 1),
|
||||
});
|
||||
});
|
||||
|
||||
it('hands the sink a fresh batch buffer per flush so retained batches are never overwritten', async () => {
|
||||
const retained: Uint8Array[] = [];
|
||||
const writer = createIlpV2BatchWriter({
|
||||
sink: { write: async b => void retained.push(b) },
|
||||
maxBatchRows: 1,
|
||||
});
|
||||
const r1 = sampleBar({ listing_id: 1 });
|
||||
const r2 = sampleBar({ listing_id: 2 });
|
||||
await writer.writeBar1m(r1);
|
||||
await writer.writeBar1m(r2);
|
||||
await writer.finish();
|
||||
expect(retained[0]).not.toBe(retained[1]);
|
||||
expect(retained[0]!.buffer).not.toBe(retained[1]!.buffer);
|
||||
expect(retained).toEqual([encodeBar1mIlpV2(r1), encodeBar1mIlpV2(r2)]);
|
||||
});
|
||||
|
||||
it('a rejected row in the middle of overlapping writes does not block or reorder later queued rows', async () => {
|
||||
const batches: Uint8Array[] = [];
|
||||
const writer = createIlpV2BatchWriter({
|
||||
sink: { write: async b => void batches.push(b.slice()) },
|
||||
maxBatchRows: 2,
|
||||
maxBatchBytes: 100_000,
|
||||
});
|
||||
const a = sampleBar({ listing_id: 1 });
|
||||
const c = sampleFx({ pair: 'EUR.USD' });
|
||||
const d = sampleBar({ listing_id: 4 });
|
||||
|
||||
const pa = writer.writeBar1m(a);
|
||||
const pb = writer.writeBar1m(sampleBar({ high: Number.NaN }));
|
||||
const pc = writer.writeFx1m(c);
|
||||
const pd = writer.writeBar1m(d);
|
||||
const pFinish = writer.finish();
|
||||
|
||||
await pa;
|
||||
await expect(pb).rejects.toBeInstanceOf(IlpV2EncodeError);
|
||||
await pc;
|
||||
await pd;
|
||||
const stats = await pFinish;
|
||||
|
||||
const expected = [encodeBar1mIlpV2(a), encodeFx1mIlpV2(c), encodeBar1mIlpV2(d)];
|
||||
expect(batches).toEqual([concatBytes(expected.slice(0, 2)), expected[2]!]);
|
||||
expect(stats).toEqual({
|
||||
rows: 3,
|
||||
batches: 2,
|
||||
bytes: expected.reduce((s, e) => s + e.byteLength, 0),
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a synchronously throwing sink like a rejected write and fails closed', async () => {
|
||||
const boom = new Error('sync sink failure');
|
||||
let calls = 0;
|
||||
const sink: IlpV2BatchSink = {
|
||||
write(): Promise<void> {
|
||||
calls += 1;
|
||||
throw boom;
|
||||
},
|
||||
};
|
||||
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1 });
|
||||
|
||||
await expect(writer.writeBar1m(sampleBar())).rejects.toBe(boom);
|
||||
await expect(writer.writeBar1m(sampleBar())).rejects.toThrow(/sink write failure/i);
|
||||
await expect(writer.flush()).rejects.toThrow(/sink write failure/i);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it('propagates a sink failure on the finish() tail flush, excludes it from stats, and stays closed', async () => {
|
||||
const boom = new Error('tail failure');
|
||||
let calls = 0;
|
||||
const sink: IlpV2BatchSink = {
|
||||
async write(): Promise<void> {
|
||||
calls += 1;
|
||||
if (calls === 2) {
|
||||
throw boom;
|
||||
}
|
||||
},
|
||||
};
|
||||
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 });
|
||||
await writer.writeBar1m(sampleBar({ listing_id: 1 }));
|
||||
await writer.writeBar1m(sampleBar({ listing_id: 2 })); // batch 1 OK
|
||||
await writer.writeBar1m(sampleBar({ listing_id: 3 })); // pending tail
|
||||
|
||||
await expect(writer.finish()).rejects.toBe(boom);
|
||||
expect(calls).toBe(2);
|
||||
|
||||
const err = await writer.finish().then(
|
||||
() => null,
|
||||
(e: unknown) => e as Error
|
||||
);
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err!.message).toMatch(/sink write failure/i);
|
||||
// The original sink error is preserved as the cause for diagnostics.
|
||||
expect(err!.cause).toBe(boom);
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it('flush() on an explicit call propagates sink failure and blocks the tail on finish()', async () => {
|
||||
const boom = new Error('flush failure');
|
||||
let calls = 0;
|
||||
const writer = createIlpV2BatchWriter({
|
||||
sink: {
|
||||
async write(): Promise<void> {
|
||||
calls += 1;
|
||||
throw boom;
|
||||
},
|
||||
},
|
||||
});
|
||||
await writer.writeFx1m(sampleFx());
|
||||
await expect(writer.flush()).rejects.toBe(boom);
|
||||
await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i);
|
||||
await expect(writer.finish()).rejects.toThrow(/sink write failure/i);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it('serializes an overlapping explicit flush() behind in-flight writes', async () => {
|
||||
const order: string[] = [];
|
||||
let release: (() => void) | null = null;
|
||||
const writer = createIlpV2BatchWriter({
|
||||
sink: {
|
||||
write(b: Uint8Array): Promise<void> {
|
||||
order.push(`write:${b.byteLength}`);
|
||||
if (release === null) {
|
||||
return new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
}
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
maxBatchRows: 1,
|
||||
});
|
||||
const row = sampleFx();
|
||||
const len = encodeFx1mIlpV2(row).byteLength;
|
||||
|
||||
const p1 = writer.writeFx1m(row);
|
||||
const pFlush = writer.flush().then(() => order.push('flushed'));
|
||||
const p2 = writer.writeFx1m(row);
|
||||
|
||||
await Promise.resolve();
|
||||
expect(order).toEqual([`write:${len}`]);
|
||||
release!();
|
||||
await Promise.all([p1, pFlush, p2]);
|
||||
expect(order).toEqual([`write:${len}`, 'flushed', `write:${len}`]);
|
||||
});
|
||||
});
|
||||
820
libs/data/questdb/test/ilp-v2-writer.test.ts
Normal file
820
libs/data/questdb/test/ilp-v2-writer.test.ts
Normal file
|
|
@ -0,0 +1,820 @@
|
|||
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue