stock-bot/libs/data/questdb/src/ilp-v2-writer.ts

550 lines
16 KiB
TypeScript

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,
};
});
},
};
}