266 lines
8.3 KiB
TypeScript
266 lines
8.3 KiB
TypeScript
/**
|
|
* Concrete server-side DuckDB executor and `MarketDataStore` wiring over
|
|
* curated Hive-partitioned Parquet datasets (`design/DATA-CONTRACTS.md` §3.A & §4).
|
|
*
|
|
* Uses `@duckdb/node-api` (native N-API bindings, works in both Bun and Node)
|
|
* while keeping `@stock-bot/research` browser-safe and dependency-free.
|
|
*/
|
|
|
|
import { copyFile, link, mkdir, mkdtemp, open, rm, type FileHandle } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { DuckDBInstance, type DuckDBConnection, type DuckDBValue } from '@duckdb/node-api';
|
|
import type { MarketDataStore, TableCell, TableRow } from '@stock-bot/research/market-data-store';
|
|
import {
|
|
createDuckDbMarketDataStore,
|
|
type AdjFactorsArtifactPinner,
|
|
type DuckDbExecutor,
|
|
type DuckDbMarketDataStoreOptions,
|
|
type DuckDbParam,
|
|
type PinnedAdjFactorsArtifact,
|
|
} from '@stock-bot/research/market-data-store-duckdb';
|
|
|
|
const UTF8_DECODER = new TextDecoder('utf-8', { fatal: false });
|
|
const MS_PER_DAY = 86_400_000;
|
|
|
|
export interface CreateNodeDuckDbExecutorOptions {
|
|
/** Optional DuckDB file path; defaults to `':memory:'` for read-only Parquet scans. */
|
|
readonly databasePath?: string;
|
|
}
|
|
|
|
export interface ClosableDuckDbExecutor extends DuckDbExecutor {
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
export interface OpenDuckDbMarketDataStoreOptions
|
|
extends Omit<DuckDbMarketDataStoreOptions, 'executor'> {
|
|
/** Optional DuckDB database path; defaults to `':memory:'`. */
|
|
readonly databasePath?: string;
|
|
}
|
|
|
|
export interface OpenedDuckDbMarketDataStore {
|
|
readonly store: MarketDataStore;
|
|
readonly executor: ClosableDuckDbExecutor;
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
function formatEpochDaysIso(days: number): string {
|
|
const date = new Date(days * MS_PER_DAY);
|
|
const y = String(date.getUTCFullYear()).padStart(4, '0');
|
|
const m = String(date.getUTCMonth() + 1).padStart(2, '0');
|
|
const d = String(date.getUTCDate()).padStart(2, '0');
|
|
return `${y}-${m}-${d}`;
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return value !== null && typeof value === 'object';
|
|
}
|
|
|
|
/**
|
|
* Normalizes a `@duckdb/node-api` cell value into `@stock-bot/research`'s
|
|
* strict `TableCell` (`string | number | boolean | null`) contract.
|
|
*/
|
|
export function normalizeDuckDbCell(value: unknown): TableCell {
|
|
if (value === null || value === undefined) {
|
|
return null;
|
|
}
|
|
if (typeof value === 'string' || typeof value === 'boolean') {
|
|
return value;
|
|
}
|
|
if (typeof value === 'number') {
|
|
return Object.is(value, -0) ? 0 : value;
|
|
}
|
|
if (typeof value === 'bigint') {
|
|
const asNumber = Number(value);
|
|
if (!Number.isSafeInteger(asNumber)) {
|
|
throw new RangeError(
|
|
`DuckDB BIGINT value ${value.toString()} exceeds JavaScript safe integer range.`
|
|
);
|
|
}
|
|
return asNumber;
|
|
}
|
|
if (value instanceof Uint8Array) {
|
|
return UTF8_DECODER.decode(value);
|
|
}
|
|
if (value instanceof Date) {
|
|
return value.getTime();
|
|
}
|
|
if (isRecord(value)) {
|
|
// DuckDBBlobValue / DuckDBBitValue expose `{ bytes: Uint8Array }` (e.g. parquet_kv_metadata)
|
|
if (value.bytes instanceof Uint8Array) {
|
|
return UTF8_DECODER.decode(value.bytes);
|
|
}
|
|
// DuckDBDateValue exposes `{ days: number }`
|
|
if (typeof value.days === 'number' && Number.isFinite(value.days)) {
|
|
return formatEpochDaysIso(value.days);
|
|
}
|
|
// DuckDBTimestampValue / DuckDBTimestampTZValue expose `{ micros: bigint }`
|
|
if (typeof value.micros === 'bigint') {
|
|
const ms = Number(value.micros / 1000n);
|
|
if (!Number.isSafeInteger(ms)) {
|
|
throw new RangeError(
|
|
`DuckDB timestamp micros ${value.micros.toString()} exceeds safe millisecond range.`
|
|
);
|
|
}
|
|
return ms;
|
|
}
|
|
// DuckDBDecimalValue exposes `{ value: bigint, scale: number }`
|
|
if (typeof value.value === 'bigint' && typeof value.scale === 'number') {
|
|
return Number(value.value) / 10 ** value.scale;
|
|
}
|
|
}
|
|
return String(value);
|
|
}
|
|
|
|
/**
|
|
* Opens an in-process `@duckdb/node-api` connection and adapts it to
|
|
* {@link DuckDbExecutor}.
|
|
*/
|
|
export async function createNodeDuckDbExecutor(
|
|
options: CreateNodeDuckDbExecutorOptions = {}
|
|
): Promise<ClosableDuckDbExecutor> {
|
|
const databasePath = options.databasePath ?? ':memory:';
|
|
const instance = await DuckDBInstance.create(databasePath);
|
|
const connection: DuckDBConnection = await instance.connect();
|
|
let closed = false;
|
|
|
|
const assertOpen = (): void => {
|
|
if (closed) {
|
|
throw new Error('DuckDbExecutor connection has already been closed.');
|
|
}
|
|
};
|
|
|
|
return {
|
|
async run(sql: string): Promise<void> {
|
|
assertOpen();
|
|
await connection.run(sql);
|
|
},
|
|
|
|
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
|
assertOpen();
|
|
const values: DuckDBValue[] = params.map(param => param as DuckDBValue);
|
|
const reader =
|
|
values.length > 0
|
|
? await connection.runAndReadAll(sql, values)
|
|
: await connection.runAndReadAll(sql);
|
|
const rawRows = reader.getRowObjects();
|
|
const rows: TableRow[] = new Array(rawRows.length);
|
|
for (let i = 0; i < rawRows.length; i += 1) {
|
|
const raw = rawRows[i];
|
|
const clean: Record<string, TableCell> = {};
|
|
if (raw !== undefined) {
|
|
for (const [col, cell] of Object.entries(raw)) {
|
|
clean[col] = normalizeDuckDbCell(cell);
|
|
}
|
|
}
|
|
rows[i] = clean;
|
|
}
|
|
return rows;
|
|
},
|
|
|
|
async close(): Promise<void> {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
closed = true;
|
|
connection.closeSync();
|
|
instance.closeSync();
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Pins a mutable `<curatedRoot>/adj_factors/part.parquet` path to a single
|
|
* inode/snapshot across footer verification and factor scan so concurrent
|
|
* atomic replacements by `curate-etl` cannot introduce TOCTOU drift.
|
|
*
|
|
* On Linux, opens a read-only file descriptor and exposes `/proc/self/fd/<fd>`.
|
|
* On platforms without `/proc/self/fd`, falls back to a private hardlink (or
|
|
* copy across filesystems) inside a temporary directory cleaned up in `release()`.
|
|
*/
|
|
export function createFsAdjFactorsPinner(): AdjFactorsArtifactPinner {
|
|
return async (sourcePath: string): Promise<PinnedAdjFactorsArtifact> => {
|
|
if (process.platform === 'linux') {
|
|
const handle: FileHandle = await open(sourcePath, 'r');
|
|
let released = false;
|
|
return {
|
|
pinnedPath: `/proc/self/fd/${handle.fd}`,
|
|
async release(): Promise<void> {
|
|
if (released) {
|
|
return;
|
|
}
|
|
released = true;
|
|
await handle.close();
|
|
},
|
|
};
|
|
}
|
|
|
|
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-adj-pin-'));
|
|
const pinnedPath = join(tempDir, 'adj_factors.parquet');
|
|
try {
|
|
await link(sourcePath, pinnedPath);
|
|
} catch {
|
|
await copyFile(sourcePath, pinnedPath);
|
|
}
|
|
let released = false;
|
|
return {
|
|
pinnedPath,
|
|
async release(): Promise<void> {
|
|
if (released) {
|
|
return;
|
|
}
|
|
released = true;
|
|
await rm(tempDir, { recursive: true, force: true });
|
|
},
|
|
};
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Opens a ready-to-use DuckDB-backed {@link MarketDataStore} wired with
|
|
* `@duckdb/node-api` and a filesystem `adj_factors` artifact pinner.
|
|
*/
|
|
export async function openDuckDbMarketDataStore(
|
|
options: OpenDuckDbMarketDataStoreOptions
|
|
): Promise<OpenedDuckDbMarketDataStore> {
|
|
const tempDir = options.env?.STOCK_BOT_DUCKDB_TEMP_DIR;
|
|
if (typeof tempDir === 'string' && tempDir.trim().length > 0) {
|
|
await mkdir(tempDir, { recursive: true });
|
|
}
|
|
|
|
const executor = await createNodeDuckDbExecutor({
|
|
databasePath: options.databasePath,
|
|
});
|
|
|
|
const pinAdjFactorsArtifact =
|
|
options.pinAdjFactorsArtifact ??
|
|
(options.immutableAdjFactorsPath === undefined ? createFsAdjFactorsPinner() : undefined);
|
|
|
|
try {
|
|
const store = createDuckDbMarketDataStore({
|
|
...options,
|
|
executor,
|
|
...(pinAdjFactorsArtifact !== undefined ? { pinAdjFactorsArtifact } : {}),
|
|
});
|
|
|
|
return {
|
|
store,
|
|
executor,
|
|
async close(): Promise<void> {
|
|
await executor.close();
|
|
},
|
|
};
|
|
} catch (err) {
|
|
await executor.close();
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
export {
|
|
createDuckDbMarketDataStore,
|
|
type AdjFactorsArtifactPinner,
|
|
type DuckDbExecutor,
|
|
type DuckDbMarketDataStoreOptions,
|
|
type DuckDbParam,
|
|
type PinnedAdjFactorsArtifact,
|
|
};
|