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, RawBsonExportError, validateRawBsonFrame, walkRawBsonFrames, type ExportRawBsonFsHooks, type ReadOnlyMongoRawBsonClient, type ReadOnlyRawBsonSource, } from '../src/security-master/export-raw-bson'; import { runExportRawBson } from '../src/security-master/run-export-raw-bson'; function sha256Hex(bytes: Uint8Array): string { return createHash('sha256').update(bytes).digest('hex'); } function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { const out = new Uint8Array(chunks.reduce((acc, c) => acc + c.byteLength, 0)); let offset = 0; for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; } return out; } function sourceOf(docs: readonly unknown[], onYield?: () => void): ReadOnlyRawBsonSource { return { isReadOnly: () => true, find: () => ({ async *[Symbol.asyncIterator]() { for (const doc of docs) { onYield?.(); yield doc; } }, }), }; } async function withTempDir(fn: (dir: string) => Promise): Promise { const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-qa-')); try { return await fn(dir); } finally { await rm(dir, { recursive: true, force: true }); } } /** * The mongodb 6.x driver returns `raw: true` documents as `subarray` views into the shared * wire-reply buffer (`OnDemandDocument.toBytes`), so frames have non-zero `byteOffset` and * neighbouring bytes belong to other documents / reply headers. */ function packAsReplyViews(docs: readonly Uint8Array[]): Uint8Array[] { const junk = new Uint8Array([0xde, 0xad, 0xbe, 0xef, 0x07]); const reply = concatBytes(docs.flatMap(d => [junk, d]).concat([junk])); const views: Uint8Array[] = []; let offset = 0; for (const doc of docs) { offset += junk.byteLength; views.push(Buffer.from(reply.buffer, reply.byteOffset + offset, doc.byteLength)); offset += doc.byteLength; } return views; } describe('exportRawBsonCollection (QA edge cases)', () => { test('writes only the frame bytes when raw documents are offset views into a shared reply buffer (buffered and direct-write paths, real fs)', async () => { const small = Array.from({ length: 40 }, (_, i) => Uint8Array.from(BSON.serialize({ eodSearchCode: `S${i}.US`, close: i + 0.5 })) ); const large = Uint8Array.from(BSON.serialize({ eodSearchCode: 'BIG.US', pad: 'z'.repeat(300) })); const originals = [...small.slice(0, 20), large, ...small.slice(20)]; const views = packAsReplyViews(originals); expect(views.every(v => v.byteOffset > 0)).toBe(true); const expected = concatBytes(originals); await withTempDir(async outDir => { const result = await exportRawBsonCollection(sourceOf(views), { collection: 'eodPrices', outDir, writeBufferBytes: 128, }); const fileBytes = Uint8Array.from(await readFile(result.outPath)); expect(fileBytes).toEqual(expected); expect(result.sha256).toBe(sha256Hex(expected)); expect(result.docsWritten).toBe(originals.length); expect(walkRawBsonFrames(fileBytes).map(f => BSON.deserialize(f))).toEqual( originals.map(o => BSON.deserialize(o)) ); }); }); test('flushes correctly when frames exactly fill the write buffer', async () => { const doc = Uint8Array.from(BSON.serialize({ k: 'v' })); const writeBufferBytes = Math.max(64, doc.byteLength * 4); const perBuffer = Math.floor(writeBufferBytes / doc.byteLength); const docs = Array.from({ length: perBuffer * 3 }, () => doc); const writes: number[] = []; await withTempDir(async outDir => { const fsHooks: ExportRawBsonFsHooks = { open: async () => ({ write: async (_b, _o, len) => { writes.push(len ?? 0); return { bytesWritten: len ?? 0 }; }, sync: async () => {}, close: async () => {}, }), rename: async () => {}, unlink: async () => {}, }; const result = await exportRawBsonCollection(sourceOf(docs), { collection: 'qmEarnings', outDir, writeBufferBytes, fs: fsHooks, }); expect(result.bytesWritten).toBe(doc.byteLength * docs.length); expect(writes.reduce((a, b) => a + b, 0)).toBe(result.bytesWritten); expect(writes.every(w => w <= writeBufferBytes)).toBe(true); expect(writes).toHaveLength(3); }); }); test('completes partial writes by continuing from the reported offset', async () => { const docs = Array.from({ length: 10 }, (_, i) => Uint8Array.from(BSON.serialize({ i }))); const expected = concatBytes(docs); const received: Uint8Array[] = []; await withTempDir(async outDir => { const fsHooks: ExportRawBsonFsHooks = { open: async () => ({ write: async (buf, off, len) => { const start = off ?? 0; const n = Math.min(len ?? 0, 7); received.push(Uint8Array.from(buf.subarray(start, start + n))); return { bytesWritten: n }; }, sync: async () => {}, close: async () => {}, }), rename: async () => {}, unlink: async () => {}, }; const result = await exportRawBsonCollection(sourceOf(docs), { collection: 'qmSplits', outDir, writeBufferBytes: 64, fs: fsHooks, }); expect(concatBytes(received)).toEqual(expected); expect(result.sha256).toBe(sha256Hex(expected)); }); }); test('stops pulling from the source once limit is reached', async () => { const docs = Array.from({ length: 50 }, (_, i) => Uint8Array.from(BSON.serialize({ i }))); let pulled = 0; await withTempDir(async outDir => { const result = await exportRawBsonCollection( sourceOf(docs, () => { pulled += 1; }), { collection: 'eodPrices', outDir, limit: 3 } ); expect(result.docsWritten).toBe(3); expect(pulled).toBe(3); expect(Uint8Array.from(await readFile(result.outPath))).toEqual(concatBytes(docs.slice(0, 3))); }); }); test('creates a missing nested out-dir and leaves no temp files after success', async () => { await withTempDir(async root => { const outDir = join(root, 'a', 'b'); const doc = Uint8Array.from(BSON.serialize({ x: 1 })); const result = await exportRawBsonCollection(sourceOf([doc]), { collection: 'qmFilings', outDir }); expect(await readdir(outDir)).toEqual(['qmFilings.bson']); expect(result.outPath).toBe(join(outDir, 'qmFilings.bson')); }); }); test('rejects frames whose length prefix has the sign bit set (negative int32)', () => { const frame = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0x00]); expect(() => validateRawBsonFrame(frame, 'eodPrices', 7)).toThrow(RawBsonExportError); expect(() => walkRawBsonFrames(frame)).toThrow(/corrupt BSON document length -1/); }); test('walkRawBsonFrames rejects truncated trailing bytes like curate-etl iter_raw_bson_docs', () => { const doc = Uint8Array.from(BSON.serialize({ a: 1 })); expect(() => walkRawBsonFrames(concatBytes([doc, new Uint8Array([1, 2])]))).toThrow( /truncated BSON length prefix/ ); expect(() => walkRawBsonFrames(concatBytes([doc, doc.subarray(0, doc.byteLength - 1)]))).toThrow( /truncated BSON document/ ); expect(walkRawBsonFrames(new Uint8Array())).toEqual([]); }); test('rejects out-of-range writeBufferBytes, batchSize and limit before any fs or source call', async () => { const openMock = mock(async () => { throw new Error('open must not be called'); }); const findMock = mock(() => { throw new Error('find must not be called'); }); const source: ReadOnlyRawBsonSource = { isReadOnly: () => true, find: findMock }; const bad = [ { writeBufferBytes: 63 }, { writeBufferBytes: 64 * 1024 * 1024 + 1 }, { writeBufferBytes: 100.5 }, { batchSize: 0 }, { batchSize: 100_001 }, { limit: 0 }, { limit: -1 }, { maxDocBytes: 4 }, { eodSymbol: ' ' }, ]; for (const opts of bad) { await expect( exportRawBsonCollection(source, { collection: 'eodPrices', outDir: '/tmp/unused', fs: { open: openMock }, ...opts }) ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); } await expect( exportRawBsonCollection(source, { collection: 'eodPrices', outDir: ' ', fs: { open: openMock } }) ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); expect(openMock).not.toHaveBeenCalled(); expect(findMock).not.toHaveBeenCalled(); }); }); describe('runExportRawBson multi-collection (QA edge cases)', () => { test('a failure in a later collection keeps earlier published files, preserves that collection\'s previous output, and closes the client once', async () => { await withTempDir(async outDir => { const splitsDoc = Uint8Array.from(BSON.serialize({ split: '2:1' })); const previousDividends = Uint8Array.from(BSON.serialize({ previous: true })); await writeFile(join(outDir, 'qmDividends.bson'), previousDividends); const closeMongo = mock(async () => {}); const findCalls: string[] = []; const client: ReadOnlyMongoRawBsonClient = { isReadOnly: () => true, getCollection: name => ({ find: () => { findCalls.push(name); return { async *[Symbol.asyncIterator]() { if (name === 'qmSplits') { yield splitsDoc; return; } yield new Uint8Array([9, 0, 0, 0, 0]); }, }; }, }), }; await expect( runExportRawBson( { createMongoClient: () => ({ client, close: closeMongo }), writeStdout: () => {} }, { outDir, collections: ['qmSplits', 'qmDividends', 'qmEarnings'] } ) ).rejects.toMatchObject({ code: 'INVALID_BSON_FRAME', collection: 'qmDividends', docOrdinal: 0 }); expect(findCalls).toEqual(['qmSplits', 'qmDividends']); expect(closeMongo).toHaveBeenCalledTimes(1); expect((await readdir(outDir)).sort()).toEqual(['qmDividends.bson', 'qmSplits.bson']); expect(Uint8Array.from(await readFile(join(outDir, 'qmSplits.bson')))).toEqual(splitsDoc); expect(Uint8Array.from(await readFile(join(outDir, 'qmDividends.bson')))).toEqual(previousDividends); }); }); test('createReadOnlyMongoRawBsonSource re-checks read-only mode at find time', () => { let readOnly = true; const getCollection = mock(() => ({ find: () => ({ async *[Symbol.asyncIterator]() {} }), })); const source = createReadOnlyMongoRawBsonSource({ isReadOnly: () => readOnly, getCollection }); readOnly = false; expect(() => source.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError); expect(getCollection).not.toHaveBeenCalled(); }); });