T-117: M1.2ag — data-pipeline: read-only MongoDB → concatenated raw-BSON file exporter for the collections curate-etl consumes (raw: true cursor, byte pass-through, atomic publish) with tests and local benchmark
This commit is contained in:
parent
c0afe5e3f0
commit
0962f66cc3
9 changed files with 2436 additions and 1 deletions
604
apps/stock/data-pipeline/test/export-raw-bson.test.ts
Normal file
604
apps/stock/data-pipeline/test/export-raw-bson.test.ts
Normal file
|
|
@ -0,0 +1,604 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
createReadOnlyMongoRawBsonSource,
|
||||
exportRawBsonCollection,
|
||||
RAW_BSON_EXPORT_COLLECTIONS,
|
||||
RawBsonExportError,
|
||||
validateRawBsonFrame,
|
||||
walkRawBsonFrames,
|
||||
type ExportRawBsonFileHandle,
|
||||
type ExportRawBsonFsHooks,
|
||||
type RawBsonFindOptions,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
type ReadOnlyRawBsonSource,
|
||||
} from '../src/security-master/export-raw-bson';
|
||||
|
||||
const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
||||
|
||||
function sha256Hex(bytes: Uint8Array): string {
|
||||
return createHash('sha256').update(bytes).digest('hex');
|
||||
}
|
||||
|
||||
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
|
||||
const total = chunks.reduce((acc, c) => acc + 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 createFakeSource(
|
||||
docs: readonly unknown[],
|
||||
options: {
|
||||
readOnly?: boolean;
|
||||
errorAfter?: number;
|
||||
error?: Error;
|
||||
onFind?: (collection: string, filter: Record<string, unknown>, findOpts: RawBsonFindOptions) => void;
|
||||
onCursorClose?: () => void;
|
||||
} = {}
|
||||
): ReadOnlyRawBsonSource {
|
||||
const readOnly = options.readOnly ?? true;
|
||||
return {
|
||||
isReadOnly: () => readOnly,
|
||||
find(collection, filter, findOpts) {
|
||||
options.onFind?.(collection, filter, findOpts);
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
let index = 0;
|
||||
try {
|
||||
for (const doc of docs) {
|
||||
if (options.errorAfter !== undefined && index === options.errorAfter) {
|
||||
throw options.error ?? new Error('Simulated mid-stream cursor failure');
|
||||
}
|
||||
yield doc;
|
||||
index += 1;
|
||||
}
|
||||
} finally {
|
||||
options.onCursorClose?.();
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-test-'));
|
||||
try {
|
||||
return await fn(dir);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('exportRawBsonCollection', () => {
|
||||
test('streams raw BSON frames verbatim, matches concatenation, round-trips via 4-byte LE framing, and is deterministic', async () => {
|
||||
const originalDocs = [
|
||||
{
|
||||
eodSearchCode: 'AAPL.US',
|
||||
date: '2025-01-02',
|
||||
open: 248.93,
|
||||
high: 249.1,
|
||||
low: 241.82,
|
||||
close: 243.85,
|
||||
volume: 55740731,
|
||||
ts: new Date('2025-01-02T21:00:00.000Z'),
|
||||
meta: { exchange: 'US', adjusted: false },
|
||||
},
|
||||
{
|
||||
eodSearchCode: 'RY.TO',
|
||||
date: '2025-01-02',
|
||||
open: 173.4,
|
||||
high: 175.0,
|
||||
low: 172.8,
|
||||
close: 174.65,
|
||||
volume: 2150000,
|
||||
tags: ['CA', 'TSX'],
|
||||
},
|
||||
{
|
||||
eodSearchCode: 'NVDA.US',
|
||||
date: '2024-06-10',
|
||||
open: 120.37,
|
||||
high: 123.1,
|
||||
low: 117.01,
|
||||
close: 121.79,
|
||||
volume: 314162700,
|
||||
},
|
||||
];
|
||||
const serialized = originalDocs.map(doc => Uint8Array.from(BSON.serialize(doc)));
|
||||
const expectedBytes = concatBytes(serialized);
|
||||
const expectedSha = sha256Hex(expectedBytes);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const findCalls: Array<{
|
||||
collection: string;
|
||||
filter: Record<string, unknown>;
|
||||
options: RawBsonFindOptions;
|
||||
}> = [];
|
||||
const source = createFakeSource(serialized, {
|
||||
onFind: (collection, filter, options) => {
|
||||
findCalls.push({ collection, filter, options });
|
||||
},
|
||||
});
|
||||
|
||||
const run1 = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
});
|
||||
|
||||
expect(run1.collection).toBe('eodPrices');
|
||||
expect(run1.outPath).toBe(join(outDir, 'eodPrices.bson'));
|
||||
expect(run1.docsWritten).toBe(originalDocs.length);
|
||||
expect(run1.bytesWritten).toBe(expectedBytes.byteLength);
|
||||
expect(run1.elapsedMs).toBeGreaterThanOrEqual(0);
|
||||
expect(run1.sha256).toBe(expectedSha);
|
||||
expect(run1.filter).toEqual({});
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
collection: 'eodPrices',
|
||||
filter: {},
|
||||
options: { raw: true, batchSize: 4096 },
|
||||
},
|
||||
]);
|
||||
|
||||
const fileBytes = Uint8Array.from(await readFile(run1.outPath));
|
||||
expect(fileBytes).toEqual(expectedBytes);
|
||||
|
||||
// Cross-language framing parity: walk output by 4-byte LE length prefix
|
||||
const walked = walkRawBsonFrames(fileBytes);
|
||||
expect(walked).toHaveLength(originalDocs.length);
|
||||
for (let i = 0; i < originalDocs.length; i++) {
|
||||
const frame = walked[i];
|
||||
expect(frame).toEqual(serialized[i]);
|
||||
expect(BSON.deserialize(frame!)).toEqual(originalDocs[i]);
|
||||
}
|
||||
|
||||
// Determinism / replay invariant: running twice yields byte-identical output and sha256
|
||||
const run2 = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
});
|
||||
const fileBytes2 = Uint8Array.from(await readFile(run2.outPath));
|
||||
expect(run2.sha256).toBe(run1.sha256);
|
||||
expect(run2.bytesWritten).toBe(run1.bytesWritten);
|
||||
expect(fileBytes2).toEqual(fileBytes);
|
||||
expect(await readdir(outDir)).toEqual(['eodPrices.bson']);
|
||||
});
|
||||
});
|
||||
|
||||
test('publishes a 0-byte file with docsWritten === 0 and empty SHA-256 for an empty collection', async () => {
|
||||
await withTempDir(async outDir => {
|
||||
const source = createFakeSource([]);
|
||||
const result = await exportRawBsonCollection(source, {
|
||||
collection: 'ceoShorts',
|
||||
outDir,
|
||||
});
|
||||
|
||||
expect(result.collection).toBe('ceoShorts');
|
||||
expect(result.docsWritten).toBe(0);
|
||||
expect(result.bytesWritten).toBe(0);
|
||||
expect(result.sha256).toBe(EMPTY_SHA256);
|
||||
|
||||
const fileBytes = await readFile(result.outPath);
|
||||
expect(fileBytes.byteLength).toBe(0);
|
||||
expect(await readdir(outDir)).toEqual(['ceoShorts.bson']);
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects invalid BSON frames with typed error naming collection and ordinal, cleans temp file, and preserves existing output', async () => {
|
||||
const validDoc = Uint8Array.from(BSON.serialize({ a: 1 }));
|
||||
const shortFrame = new Uint8Array([4, 0, 0, 0]);
|
||||
const tooSmallPrefix = Uint8Array.from(validDoc);
|
||||
tooSmallPrefix[0] = (tooSmallPrefix[0] ?? 0) - 1;
|
||||
const tooLargePrefix = Uint8Array.from(validDoc);
|
||||
tooLargePrefix[0] = (tooLargePrefix[0] ?? 0) + 1;
|
||||
const missingTerminator = Uint8Array.from(validDoc);
|
||||
missingTerminator[missingTerminator.byteLength - 1] = 0x01;
|
||||
const oversizedDoc = Uint8Array.from(BSON.serialize({ payload: 'x'.repeat(200) }));
|
||||
|
||||
const cases: Array<{
|
||||
name: string;
|
||||
docs: unknown[];
|
||||
expectedOrdinal: number;
|
||||
maxDocBytes?: number;
|
||||
}> = [
|
||||
{ name: 'shorter than 5 bytes', docs: [validDoc, shortFrame], expectedOrdinal: 1 },
|
||||
{ name: 'LE prefix smaller than byteLength', docs: [validDoc, tooSmallPrefix], expectedOrdinal: 1 },
|
||||
{ name: 'LE prefix larger than byteLength', docs: [tooLargePrefix], expectedOrdinal: 0 },
|
||||
{ name: 'missing trailing 0x00', docs: [validDoc, validDoc, missingTerminator], expectedOrdinal: 2 },
|
||||
{ name: 'non-Uint8Array chunk', docs: [validDoc, { plain: 'object' }], expectedOrdinal: 1 },
|
||||
{
|
||||
name: 'exceeds maxDocBytes',
|
||||
docs: [validDoc, oversizedDoc],
|
||||
expectedOrdinal: 1,
|
||||
maxDocBytes: 64,
|
||||
},
|
||||
];
|
||||
|
||||
for (const c of cases) {
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmSplits.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: c.name }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
const source = createFakeSource(c.docs);
|
||||
let caught: unknown;
|
||||
try {
|
||||
await exportRawBsonCollection(source, {
|
||||
collection: 'qmSplits',
|
||||
outDir,
|
||||
maxDocBytes: c.maxDocBytes,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(RawBsonExportError);
|
||||
const typed = caught as RawBsonExportError;
|
||||
expect(typed.code).toBe('INVALID_BSON_FRAME');
|
||||
expect(typed.collection).toBe('qmSplits');
|
||||
expect(typed.docOrdinal).toBe(c.expectedOrdinal);
|
||||
expect(typed.message).toContain('qmSplits');
|
||||
expect(typed.message).toContain(`doc#${c.expectedOrdinal}`);
|
||||
|
||||
// No temp file left behind and pre-existing output is byte-identical
|
||||
expect(await readdir(outDir)).toEqual(['qmSplits.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('cleans up temp file, closes cursor/handle, and preserves existing output on mid-stream cursor, write, short-write, fsync, and rename errors', async () => {
|
||||
const docs = [
|
||||
Uint8Array.from(BSON.serialize({ seq: 0 })),
|
||||
Uint8Array.from(BSON.serialize({ seq: 1 })),
|
||||
Uint8Array.from(BSON.serialize({ seq: 2 })),
|
||||
];
|
||||
|
||||
// 1. Mid-stream cursor error
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmDividends.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'cursor-err' }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
let cursorClosed = false;
|
||||
const source = createFakeSource(docs, {
|
||||
errorAfter: 2,
|
||||
error: new Error('Cursor network reset'),
|
||||
onCursorClose: () => {
|
||||
cursorClosed = true;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(source, { collection: 'qmDividends', outDir })
|
||||
).rejects.toThrow('Cursor network reset');
|
||||
|
||||
expect(cursorClosed).toBe(true);
|
||||
expect(await readdir(outDir)).toEqual(['qmDividends.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
|
||||
// 2. Write, short-write, fsync, and rename errors
|
||||
const failureModes = ['write', 'shortWrite', 'sync', 'rename'] as const;
|
||||
for (const mode of failureModes) {
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmPrices.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: mode }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
let handleClosed = false;
|
||||
let tempFileCreated: string | null = null;
|
||||
let unlinkedPath: string | null = null;
|
||||
|
||||
const fsHooks: ExportRawBsonFsHooks = {
|
||||
open: async (filePath: string) => {
|
||||
tempFileCreated = filePath;
|
||||
await writeFile(filePath, new Uint8Array());
|
||||
const handle: ExportRawBsonFileHandle = {
|
||||
write: async (_buf, _off, len) => {
|
||||
if (mode === 'write') {
|
||||
throw new Error('ENOSPC simulated write failure');
|
||||
}
|
||||
if (mode === 'shortWrite') {
|
||||
return { bytesWritten: 0 };
|
||||
}
|
||||
return { bytesWritten: len ?? 0 };
|
||||
},
|
||||
sync: async () => {
|
||||
if (mode === 'sync') {
|
||||
throw new Error('EIO simulated fsync failure');
|
||||
}
|
||||
},
|
||||
close: async () => {
|
||||
handleClosed = true;
|
||||
},
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
rename: async () => {
|
||||
if (mode === 'rename') {
|
||||
throw new Error('EXDEV simulated rename failure');
|
||||
}
|
||||
},
|
||||
unlink: async filePath => {
|
||||
unlinkedPath = String(filePath);
|
||||
await rm(filePath, { force: true });
|
||||
},
|
||||
};
|
||||
|
||||
const source = createFakeSource(docs);
|
||||
await expect(
|
||||
exportRawBsonCollection(source, {
|
||||
collection: 'qmPrices',
|
||||
outDir,
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(handleClosed).toBe(true);
|
||||
expect(tempFileCreated).not.toBeNull();
|
||||
expect(unlinkedPath).toBe(tempFileCreated);
|
||||
expect(await readdir(outDir)).toEqual(['qmPrices.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('enforces bounded write buffer size, handles oversized single docs, and strictly awaits write backpressure', async () => {
|
||||
const smallDocs = Array.from({ length: 120 }, (_, i) =>
|
||||
Uint8Array.from(
|
||||
BSON.serialize({
|
||||
eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`,
|
||||
date: '2025-01-02',
|
||||
open: 10 + i,
|
||||
close: 11 + i,
|
||||
volume: 1000 + i,
|
||||
})
|
||||
)
|
||||
);
|
||||
const largeDoc = Uint8Array.from(
|
||||
BSON.serialize({
|
||||
eodSearchCode: 'LARGE.US',
|
||||
payload: 'A'.repeat(350),
|
||||
})
|
||||
);
|
||||
const allDocs = [...smallDocs.slice(0, 60), largeDoc, ...smallDocs.slice(60)];
|
||||
const expectedConcat = concatBytes(allDocs);
|
||||
const writeBufferBytes = 256;
|
||||
|
||||
expect(largeDoc.byteLength).toBeGreaterThan(writeBufferBytes);
|
||||
|
||||
const writeLengths: number[] = [];
|
||||
const writtenChunks: Uint8Array[] = [];
|
||||
let inFlight = 0;
|
||||
let maxInFlight = 0;
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const fsHooks: ExportRawBsonFsHooks = {
|
||||
open: async () => ({
|
||||
write: async (buf, offset, length) => {
|
||||
inFlight += 1;
|
||||
if (inFlight > maxInFlight) {
|
||||
maxInFlight = inFlight;
|
||||
}
|
||||
const start = offset ?? 0;
|
||||
const len = length ?? buf.byteLength - start;
|
||||
writeLengths.push(len);
|
||||
// Copy slice immediately to simulate kernel read of buffer before async completion
|
||||
const copy = Uint8Array.from(buf.subarray(start, start + len));
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
writtenChunks.push(copy);
|
||||
inFlight -= 1;
|
||||
return { bytesWritten: len };
|
||||
},
|
||||
sync: async () => {},
|
||||
close: async () => {},
|
||||
}),
|
||||
rename: async () => {},
|
||||
unlink: async () => {},
|
||||
};
|
||||
|
||||
const source = createFakeSource(allDocs);
|
||||
const result = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
writeBufferBytes,
|
||||
fs: fsHooks,
|
||||
});
|
||||
|
||||
expect(maxInFlight).toBe(1);
|
||||
expect(writeLengths.length).toBeGreaterThan(10);
|
||||
|
||||
// Every write must be <= writeBufferBytes except the single oversized document write
|
||||
const oversizedWrites = writeLengths.filter(len => len > writeBufferBytes);
|
||||
expect(oversizedWrites).toEqual([largeDoc.byteLength]);
|
||||
for (const len of writeLengths) {
|
||||
expect(len).toBeLessThanOrEqual(Math.max(writeBufferBytes, largeDoc.byteLength));
|
||||
}
|
||||
|
||||
const assembled = concatBytes(writtenChunks);
|
||||
expect(assembled).toEqual(expectedConcat);
|
||||
expect(result.docsWritten).toBe(allDocs.length);
|
||||
expect(result.bytesWritten).toBe(expectedConcat.byteLength);
|
||||
expect(result.sha256).toBe(sha256Hex(expectedConcat));
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects disallowed collections, invalid filters, and non-read-only sources before any source or fs call', async () => {
|
||||
const findMock = mock(() => {
|
||||
throw new Error('source.find should never be called');
|
||||
});
|
||||
const openMock = mock(async () => {
|
||||
throw new Error('fs.open should never be called');
|
||||
});
|
||||
const source: ReadOnlyRawBsonSource = {
|
||||
isReadOnly: () => true,
|
||||
find: findMock,
|
||||
};
|
||||
const fsHooks: ExportRawBsonFsHooks = { open: openMock };
|
||||
|
||||
for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) {
|
||||
await expect(
|
||||
exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks })
|
||||
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed });
|
||||
}
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(source, {
|
||||
collection: 'teMarketData',
|
||||
outDir: '/tmp/unused',
|
||||
eodSymbol: 'CAD.FOREX',
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir: '/tmp/unused',
|
||||
teSymbol: 'USDCAD',
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
|
||||
|
||||
const writableSource: ReadOnlyRawBsonSource = {
|
||||
isReadOnly: () => false,
|
||||
find: findMock,
|
||||
};
|
||||
await expect(
|
||||
exportRawBsonCollection(writableSource, {
|
||||
collection: 'eodPrices',
|
||||
outDir: '/tmp/unused',
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'INVALID_SOURCE' });
|
||||
|
||||
expect(findMock).not.toHaveBeenCalled();
|
||||
expect(openMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('applies eodSymbol, teSymbol, and limit filters and defensively caps output at limit', async () => {
|
||||
const docs = Array.from({ length: 5 }, (_, i) =>
|
||||
Uint8Array.from(BSON.serialize({ seq: i }))
|
||||
);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const calls: Array<{ collection: string; filter: Record<string, unknown>; options: RawBsonFindOptions }> = [];
|
||||
const source = createFakeSource(docs, {
|
||||
onFind: (collection, filter, options) => {
|
||||
calls.push({ collection, filter, options });
|
||||
},
|
||||
});
|
||||
|
||||
const eodRes = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
eodSymbol: 'CAD.FOREX',
|
||||
limit: 2,
|
||||
batchSize: 64,
|
||||
});
|
||||
|
||||
expect(eodRes.docsWritten).toBe(2);
|
||||
expect(eodRes.filter).toEqual({ eodSearchCode: 'CAD.FOREX' });
|
||||
expect(calls[0]).toEqual({
|
||||
collection: 'eodPrices',
|
||||
filter: { eodSearchCode: 'CAD.FOREX' },
|
||||
options: { raw: true, batchSize: 64, limit: 2 },
|
||||
});
|
||||
|
||||
const teRes = await exportRawBsonCollection(source, {
|
||||
collection: 'teMarketData',
|
||||
outDir,
|
||||
teSymbol: 'USDCAD',
|
||||
limit: 3,
|
||||
});
|
||||
|
||||
expect(teRes.docsWritten).toBe(3);
|
||||
expect(teRes.filter).toEqual({ teSymbol: 'USDCAD' });
|
||||
expect(calls[1]).toEqual({
|
||||
collection: 'teMarketData',
|
||||
filter: { teSymbol: 'USDCAD' },
|
||||
options: { raw: true, batchSize: 4096, limit: 3 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('createReadOnlyMongoRawBsonSource enforces read-only, rejects buffered arrays, and always closes cursors', async () => {
|
||||
const writableClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => false,
|
||||
getCollection: () => {
|
||||
throw new Error('should not be called');
|
||||
},
|
||||
};
|
||||
expect(() => createReadOnlyMongoRawBsonSource(writableClient)).toThrow(RawBsonExportError);
|
||||
|
||||
const bufferedArrayClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => [] as unknown as ReturnType<ReadOnlyMongoRawBsonClient['getCollection']> extends {
|
||||
find: (...args: never[]) => infer R;
|
||||
}
|
||||
? R
|
||||
: never,
|
||||
}),
|
||||
};
|
||||
const badSource = createReadOnlyMongoRawBsonSource(bufferedArrayClient);
|
||||
expect(() => badSource.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError);
|
||||
|
||||
// Cursor close is called on normal exhaustion and early break
|
||||
const closeMock = mock(async () => {});
|
||||
const docs = [
|
||||
Uint8Array.from(BSON.serialize({ a: 1 })),
|
||||
Uint8Array.from(BSON.serialize({ a: 2 })),
|
||||
Uint8Array.from(BSON.serialize({ a: 3 })),
|
||||
];
|
||||
const goodClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => ({
|
||||
close: closeMock,
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const d of docs) {
|
||||
yield d;
|
||||
}
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const source = createReadOnlyMongoRawBsonSource(goodClient);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const res = await exportRawBsonCollection(source, {
|
||||
collection: 'qmFilings',
|
||||
outDir,
|
||||
limit: 1,
|
||||
});
|
||||
expect(res.docsWritten).toBe(1);
|
||||
expect(closeMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => {
|
||||
expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([
|
||||
'eodPrices',
|
||||
'qmSplits',
|
||||
'qmDividends',
|
||||
'qmPrices',
|
||||
'teMarketData',
|
||||
'ceoShorts',
|
||||
'qmFilings',
|
||||
'qmEarnings',
|
||||
]);
|
||||
const emptyBson = new Uint8Array([5, 0, 0, 0, 0]);
|
||||
expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson);
|
||||
});
|
||||
});
|
||||
348
apps/stock/data-pipeline/test/run-export-raw-bson.test.ts
Normal file
348
apps/stock/data-pipeline/test/run-export-raw-bson.test.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
RAW_BSON_EXPORT_COLLECTIONS,
|
||||
RawBsonExportError,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
} from '../src/security-master/export-raw-bson';
|
||||
import {
|
||||
assertExportRawBsonSafety,
|
||||
EXPORT_RAW_BSON_USAGE,
|
||||
parseExportRawBsonArgs,
|
||||
runCli,
|
||||
runExportRawBson,
|
||||
} from '../src/security-master/run-export-raw-bson';
|
||||
|
||||
function createBaseConfig(overrides: Partial<StockAppConfig['database']['mongodb']> = {}): StockAppConfig {
|
||||
return {
|
||||
environment: 'development',
|
||||
database: {
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'trading_bot',
|
||||
user: 'trading_user',
|
||||
password: 'pw',
|
||||
ssl: false,
|
||||
poolSize: 5,
|
||||
idleTimeout: 10000,
|
||||
connectionTimeout: 5000,
|
||||
},
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
|
||||
readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
|
||||
readOnly: true,
|
||||
host: 'localhost',
|
||||
port: 27017,
|
||||
database: 'stock',
|
||||
poolSize: 5,
|
||||
...overrides,
|
||||
},
|
||||
dragonfly: {
|
||||
enabled: false,
|
||||
host: 'localhost',
|
||||
port: 6380,
|
||||
},
|
||||
questdb: {
|
||||
enabled: false,
|
||||
host: 'localhost',
|
||||
port: 9100,
|
||||
},
|
||||
},
|
||||
} as unknown as StockAppConfig;
|
||||
}
|
||||
|
||||
describe('parseExportRawBsonArgs', () => {
|
||||
test('parses valid flags in both space-separated and equals forms', () => {
|
||||
const parsed1 = parseExportRawBsonArgs([
|
||||
'--out-dir',
|
||||
'./tmp/bson',
|
||||
'--collections',
|
||||
'eodPrices',
|
||||
'--eod-symbol',
|
||||
'CAD.FOREX',
|
||||
'--limit',
|
||||
'100',
|
||||
'--batch-size',
|
||||
'512',
|
||||
]);
|
||||
expect(parsed1).toEqual({
|
||||
help: false,
|
||||
outDir: './tmp/bson',
|
||||
collections: ['eodPrices'],
|
||||
eodSymbol: 'CAD.FOREX',
|
||||
limit: 100,
|
||||
batchSize: 512,
|
||||
});
|
||||
|
||||
const parsed2 = parseExportRawBsonArgs([
|
||||
'--out-dir=./tmp/te',
|
||||
'--collections=teMarketData',
|
||||
'--te-symbol=USDCAD',
|
||||
]);
|
||||
expect(parsed2).toEqual({
|
||||
help: false,
|
||||
outDir: './tmp/te',
|
||||
collections: ['teMarketData'],
|
||||
teSymbol: 'USDCAD',
|
||||
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
});
|
||||
|
||||
const parsedDefault = parseExportRawBsonArgs(['--out-dir', './tmp/all']);
|
||||
expect(parsedDefault).toEqual({
|
||||
help: false,
|
||||
outDir: './tmp/all',
|
||||
collections: [...RAW_BSON_EXPORT_COLLECTIONS],
|
||||
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
});
|
||||
|
||||
expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true });
|
||||
});
|
||||
|
||||
test('rejects unknown, duplicate, missing-value, positional, and malformed flags', () => {
|
||||
expect(() => parseExportRawBsonArgs([])).toThrow(/Missing required argument: --out-dir/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', '--bogus'])).toThrow(/Unknown argument/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', 'positional'])).toThrow(/Unknown argument/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--out-dir', './b'])).toThrow(/Duplicate flag/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--limit', '10', '--limit=20'])
|
||||
).toThrow(/Duplicate flag/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', '--collections', 'eodPrices'])).toThrow(
|
||||
/Missing value for --out-dir/
|
||||
);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir='])).toThrow(/Missing value for --out-dir/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '0'])).toThrow(/Invalid --limit/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '-5'])).toThrow(/Invalid --limit/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '1.5'])).toThrow(/Invalid --limit/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '0'])).toThrow(
|
||||
/Invalid --batch-size/
|
||||
);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '999999'])).toThrow(
|
||||
/Invalid --batch-size/
|
||||
);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,'])
|
||||
).toThrow(/Malformed --collections/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices'])
|
||||
).toThrow(/Duplicate collection/);
|
||||
});
|
||||
|
||||
test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => {
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M'])
|
||||
).toThrow(RawBsonExportError);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols'])
|
||||
).toThrow(RawBsonExportError);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX'])
|
||||
).toThrow(/--eod-symbol is only permitted/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs([
|
||||
'--out-dir',
|
||||
'./a',
|
||||
'--collections',
|
||||
'eodPrices,qmSplits',
|
||||
'--eod-symbol',
|
||||
'CAD.FOREX',
|
||||
])
|
||||
).toThrow(/--eod-symbol is only permitted/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--eod-symbol', 'CAD.FOREX'])
|
||||
).toThrow(/--eod-symbol is only permitted/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--te-symbol', 'USDCAD'])
|
||||
).toThrow(/--te-symbol is only permitted/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertExportRawBsonSafety', () => {
|
||||
test('allows read-only dev MongoDB even if Postgres config points to QA, and rejects disabled/writable/admin MongoDB', () => {
|
||||
expect(() => assertExportRawBsonSafety(createBaseConfig(), {})).not.toThrow();
|
||||
|
||||
expect(() => assertExportRawBsonSafety(createBaseConfig({ enabled: false }), {})).toThrow(
|
||||
/MongoDB is disabled/
|
||||
);
|
||||
expect(() => assertExportRawBsonSafety(createBaseConfig({ readOnly: false }), {})).toThrow(
|
||||
/read-only MongoDB configuration/
|
||||
);
|
||||
expect(() =>
|
||||
assertExportRawBsonSafety(
|
||||
createBaseConfig({
|
||||
readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin',
|
||||
readOnly: true,
|
||||
}),
|
||||
{}
|
||||
)
|
||||
).toThrow(/Safety guard/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runExportRawBson & runCli', () => {
|
||||
test('--help prints usage and performs zero config, Mongo, or fs I/O', async () => {
|
||||
const stdout: string[] = [];
|
||||
const initConfigMock = mock(() => {
|
||||
throw new Error('initializeConfig must not be called on --help');
|
||||
});
|
||||
const createClientMock = mock(() => {
|
||||
throw new Error('createMongoClient must not be called on --help');
|
||||
});
|
||||
|
||||
await runCli(['--help'], {
|
||||
initializeConfig: initConfigMock as never,
|
||||
createMongoClient: createClientMock,
|
||||
writeStdout: text => stdout.push(text),
|
||||
});
|
||||
|
||||
expect(stdout.join('')).toBe(`${EXPORT_RAW_BSON_USAGE}\n`);
|
||||
expect(initConfigMock).not.toHaveBeenCalled();
|
||||
expect(createClientMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('runCli initializes config with mongoReadOnly: true, issues strictly raw find(), calls zero write methods, and closes client', async () => {
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-cli-'));
|
||||
try {
|
||||
const sampleBytes = Uint8Array.from(
|
||||
BSON.serialize({ eodSearchCode: 'CAD.FOREX', date: '2025-01-02', close: 1.44 })
|
||||
);
|
||||
const findCalls: Array<{ collection: string; filter: unknown; options: unknown }> = [];
|
||||
const forbiddenWrite = mock(() => {
|
||||
throw new Error('Write/DDL method must never be called');
|
||||
});
|
||||
const closeMongoMock = mock(async () => {});
|
||||
const closeCursorMock = mock(async () => {});
|
||||
|
||||
const fakeClient: ReadOnlyMongoRawBsonClient & Record<string, unknown> = {
|
||||
isReadOnly: () => true,
|
||||
insertOne: forbiddenWrite,
|
||||
updateOne: forbiddenWrite,
|
||||
deleteMany: forbiddenWrite,
|
||||
createIndex: forbiddenWrite,
|
||||
dropCollection: forbiddenWrite,
|
||||
getCollection: (name: string) => ({
|
||||
find: (filter, options) => {
|
||||
findCalls.push({ collection: name, filter, options });
|
||||
return {
|
||||
close: closeCursorMock,
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield sampleBytes;
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const initCalls: Array<{ service: string; opts: unknown }> = [];
|
||||
const stdout: string[] = [];
|
||||
|
||||
await runCli(
|
||||
[
|
||||
'--out-dir',
|
||||
outDir,
|
||||
'--collections',
|
||||
'eodPrices',
|
||||
'--eod-symbol',
|
||||
'CAD.FOREX',
|
||||
'--batch-size',
|
||||
'256',
|
||||
],
|
||||
{
|
||||
initializeConfig: ((service: string, opts?: unknown) => {
|
||||
initCalls.push({ service, opts });
|
||||
return createBaseConfig();
|
||||
}) as never,
|
||||
createMongoClient: async () => ({
|
||||
client: fakeClient,
|
||||
close: closeMongoMock,
|
||||
}),
|
||||
writeStdout: text => stdout.push(text),
|
||||
}
|
||||
);
|
||||
|
||||
expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]);
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
collection: 'eodPrices',
|
||||
filter: { eodSearchCode: 'CAD.FOREX' },
|
||||
options: { raw: true, batchSize: 256 },
|
||||
},
|
||||
]);
|
||||
expect(forbiddenWrite).not.toHaveBeenCalled();
|
||||
expect(closeCursorMock).toHaveBeenCalledTimes(1);
|
||||
expect(closeMongoMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
const written = Uint8Array.from(await readFile(join(outDir, 'eodPrices.bson')));
|
||||
expect(written).toEqual(sampleBytes);
|
||||
expect(stdout.join('')).toContain('eodPrices: docs=1');
|
||||
expect(stdout.join('')).toContain('sha256=');
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('runExportRawBson closes Mongo client on mid-stream export failure and preserves primary error', async () => {
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-fail-'));
|
||||
try {
|
||||
const closeMongoMock = mock(async () => {});
|
||||
const fakeClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield Uint8Array.from(BSON.serialize({ ok: 1 }));
|
||||
throw new Error('Mid-stream Mongo failure');
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
|
||||
await expect(
|
||||
runExportRawBson(
|
||||
{
|
||||
createMongoClient: () => ({ client: fakeClient, close: closeMongoMock }),
|
||||
writeStdout: () => {},
|
||||
},
|
||||
{
|
||||
outDir,
|
||||
collections: ['qmSplits'],
|
||||
}
|
||||
)
|
||||
).rejects.toThrow('Mid-stream Mongo failure');
|
||||
|
||||
expect(closeMongoMock).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('runExportRawBson rejects disallowed collections before calling assertSafety or createMongoClient', async () => {
|
||||
const assertSafetyMock = mock(() => {});
|
||||
const createClientMock = mock(() => {
|
||||
throw new Error('createMongoClient must not be called');
|
||||
});
|
||||
|
||||
await expect(
|
||||
runExportRawBson(
|
||||
{
|
||||
assertSafety: assertSafetyMock,
|
||||
createMongoClient: createClientMock,
|
||||
},
|
||||
{
|
||||
outDir: '/tmp/unused',
|
||||
collections: ['eodIntraday1M' as never],
|
||||
}
|
||||
)
|
||||
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' });
|
||||
|
||||
expect(assertSafetyMock).not.toHaveBeenCalled();
|
||||
expect(createClientMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue