import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { classifySourceExchanges, escapeSqlLiteral, EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, generateExchangeSeedFromMongo, generateExchangeSeedSql, generateUnresolvedExchangesMarkdown, ISO_EXCHANGE_SEEDS, normalizeRawExchangeDoc, parseGenerateExchangeSeedArgs, resolveReadOnlyMongoClientConfig, SOURCE_EXCHANGE_COLLECTIONS, type ExchangeSource, type ReadOnlyExchangeMongoClient, type SourceExchangeRecord, } from '../../apps/stock/data-pipeline/src/security-master'; const committedSeedPath = fileURLToPath( new URL('../../database/postgres/init/35-security-master-exchange-seed.sql', import.meta.url) ); const tempDirs: string[] = []; afterEach(() => { for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } }); describe('security master Pass 1 exchange classifier', () => { test('explicit rules take precedence over OperatingMIC', () => { const result = classifySourceExchanges([ { source: 'eod', code: 'US', operatingMic: 'XNYS', country: 'US' }, { source: 'eod', code: 'NMFQS', operatingMic: 'XNAS', country: 'US' }, { source: 'eod', code: 'FOREX', operatingMic: 'XNYS' }, { source: 'ib', code: 'IEX', operatingMic: 'IEXG', country: 'US' }, { source: 'ceo', code: 'TSX', operatingMic: 'XNYS', country: 'CA' }, ]); expect(result.unresolved).toEqual([]); expect(result.mapped).toEqual([ { source: 'ceo', sourceCode: 'TSX', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'explicit_rule', reviewedBy: null, }, { source: 'eod', sourceCode: 'FOREX', role: 'forex', mic: null, countryIso: null, method: 'explicit_rule', reviewedBy: null, }, { source: 'eod', sourceCode: 'NMFQS', role: 'excluded_fund', mic: null, countryIso: 'US', method: 'explicit_rule', reviewedBy: null, }, { source: 'eod', sourceCode: 'US', role: 'composite', mic: null, countryIso: 'US', method: 'explicit_rule', reviewedBy: null, }, { source: 'ib', sourceCode: 'IEX', role: 'ats_routing', mic: null, countryIso: 'US', method: 'explicit_rule', reviewedBy: null, }, ]); }); test('trims, uppercases, and collapses duplicate source codes deterministically', () => { const result = classifySourceExchanges([ { source: 'ceo', code: ' tsx ' }, { source: 'ceo', code: 'TSX' }, { source: 'eod', code: ' to ', operatingMic: ' xtse ' }, { source: 'eod', code: 'TO', operatingMic: 'XTSE' }, { source: 'eod', code: 'to', operatingMic: null }, ]); expect(result.unresolved).toEqual([]); expect(result.mapped).toEqual([ { source: 'ceo', sourceCode: 'TSX', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'explicit_rule', reviewedBy: null, }, { source: 'eod', sourceCode: 'TO', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'operating_mic', reviewedBy: null, }, ]); }); test('resolves valid single OperatingMIC to primary_venue with exchange countryIso', () => { const result = classifySourceExchanges([ { source: 'eod', code: 'NASDAQ', operatingMic: 'xnas', country: 'USA' }, { source: 'qm', code: 'TSV', operatingMic: 'XTSX', country: 'Canada' }, ]); expect(result.unresolved).toEqual([]); expect(result.mapped).toEqual([ { source: 'eod', sourceCode: 'NASDAQ', role: 'primary_venue', mic: 'XNAS', countryIso: 'US', method: 'operating_mic', reviewedBy: null, }, { source: 'qm', sourceCode: 'TSV', role: 'primary_venue', mic: 'XTSX', countryIso: 'CA', method: 'operating_mic', reviewedBy: null, }, ]); }); test('routes empty codes, missing/unknown/malformed/multi-valued/conflicting MICs to unresolved without guessing', () => { const result = classifySourceExchanges([ { source: 'eod', code: ' ', name: 'Blank' }, { source: 'qm', code: 'MYSTERY', name: 'No MIC' }, { source: 'eod', code: 'LSE', operatingMic: 'XLON', country: 'GB' }, { source: 'eod', code: 'BADFMT', operatingMic: 'XN-Y' }, { source: 'eod', code: 'MULTI_COMMA', operatingMic: 'XNAS, XNYS' }, { source: 'eod', code: 'MULTI_SEMI', operatingMic: 'XNYS;XNAS' }, { source: 'eod', code: 'MULTI_SPACE', operatingMic: 'XNAS XNYS' }, { source: 'eod', code: 'MULTI_SLASH', operatingMic: 'XNAS/XNYS' }, { source: 'eod', code: 'MULTI_PIPE', operatingMic: 'XNAS|XNYS' }, { source: 'ib', code: 'CONFLICT', operatingMic: 'XNYS' }, { source: 'ib', code: 'conflict', operatingMic: 'XNAS' }, ]); expect(result.mapped).toEqual([]); expect(result.unresolved.map(row => [row.source, row.sourceCode, row.reason])).toEqual([ ['eod', '', 'empty_code'], ['eod', 'BADFMT', 'invalid_operating_mic_format'], ['eod', 'LSE', 'unknown_operating_mic'], ['eod', 'MULTI_COMMA', 'multi_valued_operating_mic'], ['eod', 'MULTI_PIPE', 'multi_valued_operating_mic'], ['eod', 'MULTI_SEMI', 'multi_valued_operating_mic'], ['eod', 'MULTI_SLASH', 'multi_valued_operating_mic'], ['eod', 'MULTI_SPACE', 'multi_valued_operating_mic'], ['ib', 'CONFLICT', 'multi_valued_operating_mic'], ['qm', 'MYSTERY', 'missing_operating_mic'], ]); }); test('throws an error naming both source and code on unknown source', () => { expect(() => classifySourceExchanges([ { source: 'yahoo' as unknown as ExchangeSource, code: 'NYSE', operatingMic: 'XNYS' }, ]) ).toThrow(/yahoo.*NYSE/); }); test('normalizes observed raw MongoDB field spellings across all four provider collections', () => { expect( normalizeRawExchangeDoc('eod', { Code: 'TO', Name: 'Toronto Exchange', CountryISO2: 'CA', OperatingMIC: 'XTSE', Currency: 'CAD', }) ).toEqual({ source: 'eod', code: 'TO', name: 'Toronto Exchange', country: 'CA', operatingMic: 'XTSE', currency: 'CAD', }); expect( normalizeRawExchangeDoc('ib', { id: 'DRCTEDGE', description: 'Direct Edge', country_code: 'US', }) ).toEqual({ source: 'ib', code: 'DRCTEDGE', name: 'Direct Edge', country: 'US', operatingMic: null, currency: null, }); expect( normalizeRawExchangeDoc('ib', { exchange_id: 'AEQLIT', name: 'Aequitas NEO', countryCode: 'CA', }) ).toEqual({ source: 'ib', code: 'AEQLIT', name: 'Aequitas NEO', country: 'CA', operatingMic: null, currency: null, }); expect( normalizeRawExchangeDoc('qm', { exchange: 'TSX', exchangeName: 'Toronto Stock Exchange', countryCode: 'CA', OperatingMIC: 'XTSE', }) ).toEqual({ source: 'qm', code: 'TSX', name: 'Toronto Stock Exchange', country: 'CA', operatingMic: 'XTSE', currency: null, }); expect( normalizeRawExchangeDoc('qm', { exchangeCode: 'NGS', exchangeShortName: 'NASDAQ', country_code: 'US', }) ).toEqual({ source: 'qm', code: 'NGS', name: 'NASDAQ', country: 'US', operatingMic: null, currency: null, }); expect( normalizeRawExchangeDoc('ceo', { exchange: 'CDX', name: 'TSX Venture', country: 'CA', }) ).toEqual({ source: 'ceo', code: 'CDX', name: 'TSX Venture', country: 'CA', operatingMic: null, currency: null, }); }); }); describe('security master Pass 1 SQL and Markdown generator', () => { test('escapes single quotes and rejects NUL bytes in SQL literals', () => { expect(escapeSqlLiteral(null)).toBe('NULL'); expect(escapeSqlLiteral(undefined)).toBe('NULL'); expect(escapeSqlLiteral("O'Hare's Exchange")).toBe("'O''Hare''s Exchange'"); expect(() => escapeSqlLiteral('BAD\0VALUE')).toThrow(/NUL/); }); test('produces byte-identical SQL and Markdown for shuffled inputs sorted by mic and (source, source_code)', () => { const recordsA: SourceExchangeRecord[] = [ { source: 'ib', code: 'PSX' }, { source: 'ceo', code: 'TSX' }, { source: 'eod', code: 'TO', operatingMic: 'XTSE' }, { source: 'eod', code: 'US' }, { source: 'qm', code: 'UNK_B', name: 'Pipe | Name\nLine2' }, { source: 'eod', code: 'UNK_A', operatingMic: 'XLON' }, ]; const recordsB: SourceExchangeRecord[] = [ recordsA[5]!, recordsA[2]!, recordsA[0]!, recordsA[4]!, recordsA[3]!, recordsA[1]!, ]; const resA = classifySourceExchanges(recordsA); const resB = classifySourceExchanges(recordsB); const sqlA = generateExchangeSeedSql({ exchanges: ISO_EXCHANGE_SEEDS, mappings: resA.mapped, }); const sqlB = generateExchangeSeedSql({ exchanges: [...ISO_EXCHANGE_SEEDS].reverse(), mappings: [...resB.mapped].reverse(), }); expect(sqlA).toBe(sqlB); expect(sqlA.indexOf("('ceo', 'TSX'")).toBeLessThan(sqlA.indexOf("('eod', 'TO'")); expect(sqlA.indexOf("('eod', 'TO'")).toBeLessThan(sqlA.indexOf("('eod', 'US'")); expect(sqlA.indexOf("('eod', 'US'")).toBeLessThan(sqlA.indexOf("('ib', 'PSX'")); const mdA = generateUnresolvedExchangesMarkdown(resA); const mdB = generateUnresolvedExchangesMarkdown(resB); expect(mdA).toBe(mdB); expect(mdA).toContain('Pipe \\| Name Line2'); }); test('breaks ties on country and currency for shuffled missing-code records with identical name and MIC', () => { const recordsA: SourceExchangeRecord[] = [ { source: 'qm', code: '', name: 'Unnamed Venue', operatingMic: null, country: 'US', currency: 'USD' }, { source: 'qm', code: '', name: 'Unnamed Venue', operatingMic: null, country: 'US', currency: 'CAD' }, { source: 'qm', code: '', name: 'Unnamed Venue', operatingMic: null, country: 'CA', currency: 'CAD' }, ]; const recordsB: SourceExchangeRecord[] = [recordsA[2]!, recordsA[0]!, recordsA[1]!]; const resA = classifySourceExchanges(recordsA); const resB = classifySourceExchanges(recordsB); expect(resA.unresolved).toEqual(resB.unresolved); expect(resA.unresolved.map(row => [row.country, row.currency])).toEqual([ ['CA', 'CAD'], ['US', 'CAD'], ['US', 'USD'], ]); const mdA = generateUnresolvedExchangesMarkdown(resA); const mdB = generateUnresolvedExchangesMarkdown(resB); expect(mdA).toBe(mdB); expect(mdA.indexOf('| CA | CAD |')).toBeLessThan(mdA.indexOf('| US | CAD |')); expect(mdA.indexOf('| US | CAD |')).toBeLessThan(mdA.indexOf('| US | USD |')); }); test('escapes single quotes in generated SQL values', () => { const sql = generateExchangeSeedSql({ exchanges: [ { mic: 'XTST', operatingMic: 'XTST', name: "O'Connor's Venue", countryIso: 'US', currency: 'USD', timezone: 'America/New_York', calendarCode: 'XNYS', boardLotPolicy: 'us_100', }, ], mappings: [], }); expect(sql).toContain("'O''Connor''s Venue'"); }); test('generated SQL for baseline seeds matches committed 35-security-master-exchange-seed.sql byte-for-byte', () => { const generated = generateExchangeSeedSql({ exchanges: ISO_EXCHANGE_SEEDS, mappings: EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, }); const committed = readFileSync(committedSeedPath, 'utf8'); expect(generated).toBe(committed); }); }); describe('security master Pass 1 read-only MongoDB generator wrapper', () => { test('only calls isReadOnly and find on the four exchange collections and fails loudly on write methods', async () => { const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-gen-')); tempDirs.push(dir); const sqlOutPath = join(dir, 'out', 'seed.sql'); const reportOutPath = join(dir, 'out', 'unresolved.md'); const fixtures: Record[]> = { [SOURCE_EXCHANGE_COLLECTIONS.eod]: [ { Code: 'US', Name: 'USA Stocks', CountryISO2: 'US', OperatingMIC: 'XNAS, XNYS' }, { Code: 'TO', Name: 'Toronto', CountryISO2: 'CA', OperatingMIC: 'XTSE' }, { Code: 'LSE', Name: 'London', CountryISO2: 'GB', OperatingMIC: 'XLON' }, ], [SOURCE_EXCHANGE_COLLECTIONS.ib]: [ { id: 'IEX', name: 'IEX Routing', country_code: 'US' }, ], [SOURCE_EXCHANGE_COLLECTIONS.qm]: [ { exchange: 'NGS', exchangeName: 'NASDAQ Global Select', OperatingMIC: 'XNAS' }, ], [SOURCE_EXCHANGE_COLLECTIONS.ceo]: [ { exchange: 'TSX', name: 'Toronto Stock Exchange', country: 'CA' }, ], }; const calls: Array<{ method: string; collection?: string }> = []; const readOnlyFake = new Proxy( {}, { get(_target, prop) { if (prop === 'isReadOnly') { return () => { calls.push({ method: 'isReadOnly' }); return true; }; } if (prop === 'find') { return async (collectionName: string, filter?: Record) => { expect(filter).toEqual({}); calls.push({ method: 'find', collection: collectionName }); return fixtures[collectionName] ?? []; }; } return () => { throw new Error(`Forbidden MongoDB method invoked: ${String(prop)}`); }; }, } ) as ReadOnlyExchangeMongoClient & { insertOne: () => void }; expect(() => readOnlyFake.insertOne()).toThrow(/Forbidden MongoDB method invoked: insertOne/); const output = await generateExchangeSeedFromMongo(readOnlyFake, { sqlOutPath, reportOutPath, }); expect(calls).toEqual([ { method: 'isReadOnly' }, { method: 'find', collection: 'eodExchanges' }, { method: 'find', collection: 'ibExchanges' }, { method: 'find', collection: 'qmExchanges' }, { method: 'find', collection: 'ceoExchanges' }, ]); expect(output.countsByCollection).toEqual({ eod: 3, ib: 1, qm: 1, ceo: 1 }); expect(output.classification.mapped).toHaveLength(5); expect(output.classification.unresolved).toHaveLength(1); expect(output.classification.unresolved[0]?.sourceCode).toBe('LSE'); expect(readFileSync(sqlOutPath, 'utf8')).toBe(output.sql); expect(readFileSync(reportOutPath, 'utf8')).toBe(output.reportMarkdown); }); test('rejects a non-read-only MongoDB client before calling find', async () => { const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-nonro-')); tempDirs.push(dir); let findCalled = false; const nonReadOnlyFake: ReadOnlyExchangeMongoClient = { isReadOnly: () => false, find: async () => { findCalled = true; return []; }, }; await expect( generateExchangeSeedFromMongo(nonReadOnlyFake, { sqlOutPath: join(dir, 'seed.sql'), reportOutPath: join(dir, 'report.md'), }) ).rejects.toThrow(/read-only/i); expect(findCalled).toBe(false); }); test('parses CLI arguments and resolves read-only MongoDB config from readUri', () => { expect(parseGenerateExchangeSeedArgs([])).toEqual({ sqlOutPath: './tmp/35-security-master-exchange-seed.generated.sql', reportOutPath: './tmp/pass1-unresolved-exchanges.md', }); expect( parseGenerateExchangeSeedArgs(['--sql-out', '/tmp/a.sql', '--report-out=/tmp/b.md']) ).toEqual({ sqlOutPath: '/tmp/a.sql', reportOutPath: '/tmp/b.md', }); expect(() => parseGenerateExchangeSeedArgs(['--unknown'])).toThrow(/Unknown argument/); expect(() => parseGenerateExchangeSeedArgs(['--sql-out'])).toThrow(/Missing value/); const resolved = resolveReadOnlyMongoClientConfig({ database: { mongodb: { enabled: true, host: 'localhost', port: 27018, database: 'stock_dev', uri: 'mongodb://localhost:27018/stock_dev', readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', readOnly: false, poolSize: 10, }, postgres: {} as never, questdb: {} as never, dragonfly: {} as never, }, }); expect(resolved.readOnly).toBe(true); expect(resolved.uri).toBe( 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock' ); expect(resolved.database).toBe('stock'); }); });