import { randomUUID } from 'node:crypto'; import { copyFileSync, mkdtempSync, 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 { Pool } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { generateExchangeSeedFromMongo, ISO_EXCHANGE_SEEDS, type ExchangeSeedRow, type ReadOnlyExchangeMongoClient, } from '../../apps/stock/data-pipeline/src/security-master'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('security-master-exchange-seed-upgrade-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const initDir = fileURLToPath(new URL('../../database/postgres/init', import.meta.url)); const PRE_SEED_MASTER_FILES = [ '01-init-database.sql', '02-master-schema.sql', '03-initial-data.sql', '04-provider-exchange-mapping-schema.sql', '05-add-visible-column.sql', '34-security-master.sql', ]; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function createIsolatedFixture() { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Dedicated stock_bot_safety database required'); } const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); const pool = new Pool({ connectionString: url, options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => ({ connect: () => pool.connect(), }), }); return { pool, postgres }; } function makeTempDir(prefix: string): string { const dir = mkdtempSync(join(tmpdir(), prefix)); cleanup.push(() => rmSync(dir, { recursive: true, force: true })); return dir; } describe.skipIf(!url)('security master Pass 1 exchange seed upgrade and generated SQL', () => { test('upgrading a schema that already ran 34 applies only 35 and keeps pre-existing director data', async () => { const f = await createIsolatedFixture(); // Arrange: a database migrated before migration 35 existed. const preSeedDir = makeTempDir('pass1-pre-seed-migrations-'); for (const file of PRE_SEED_MASTER_FILES) { copyFileSync(join(initDir, file), join(preSeedDir, file)); } expect( await runPostgresMigrations(f.postgres, { track: 'master', migrationsDir: preSeedDir }) ).toEqual(PRE_SEED_MASTER_FILES); await f.pool.query( `INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) VALUES ('XNYS', 'XNYS', 'NYSE (director-curated)', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100')` ); await f.pool.query( `INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method, reviewed_by) VALUES ('eod', 'US', 'primary_venue', 'XNYS', 'US', 'director_override', 'director'), ('ceo', 'TSX', 'composite', NULL, NULL, 'stale_manual', NULL)` ); // Act: run the real master track. const applied = await runPostgresMigrations(f.postgres, { track: 'master' }); // Assert expect(applied).toEqual(['35-security-master-exchange-seed.sql']); const xnys = (await f.pool.query(`SELECT name FROM exchange WHERE mic = 'XNYS'`)).rows[0]; expect(xnys).toEqual({ name: 'NYSE (director-curated)' }); const micCount = (await f.pool.query('SELECT count(*)::int AS count FROM exchange')).rows[0] .count as number; expect(micCount).toBe(11); const reviewed = ( await f.pool.query( `SELECT role, mic, method, reviewed_by FROM exchange_source_map WHERE source = 'eod' AND source_code = 'US'` ) ).rows[0]; expect(reviewed).toEqual({ role: 'primary_venue', mic: 'XNYS', method: 'director_override', reviewed_by: 'director', }); const refreshed = ( await f.pool.query( `SELECT role, mic, country_iso, method, reviewed_by FROM exchange_source_map WHERE source = 'ceo' AND source_code = 'TSX'` ) ).rows[0]; expect(refreshed).toEqual({ role: 'primary_venue', mic: 'XTSE', country_iso: 'CA', method: 'explicit_rule', reviewed_by: null, }); const mappingCount = ( await f.pool.query('SELECT count(*)::int AS count FROM exchange_source_map') ).rows[0].count as number; expect(mappingCount).toBe(17); expect(await runPostgresMigrations(f.postgres, { track: 'master' })).toEqual([]); }); test('host-generator SQL from a fake read-only Mongo applies on top of migration 35, round-trips quoted names, and is idempotent', async () => { const f = await createIsolatedFixture(); await runPostgresMigrations(f.postgres, { track: 'master' }); const syntheticExchange: ExchangeSeedRow = { mic: 'XTST', operatingMic: 'XTST', name: "O'Brien \\ Test Exchange", countryIso: 'US', currency: 'USD', timezone: 'America/New_York', calendarCode: 'XNYS', boardLotPolicy: 'us_100', }; const fixtures: Record[]> = { eodExchanges: [ { Code: 'US', OperatingMIC: 'XNAS, XNYS' }, { Code: 'TO', OperatingMIC: 'XTSE' }, { Code: 'V', OperatingMIC: 'XTSX' }, { Code: 'LSE', OperatingMIC: 'XLON' }, ], ibExchanges: [ { id: 'IEX' }, { id: 'NYSE', OperatingMIC: 'XNYS' }, { id: 'TESTX', OperatingMIC: 'xtst' }, ], qmExchanges: [ { exchange: 'NGS', OperatingMIC: 'XNAS' }, { exchange: 'MULTI', OperatingMIC: 'XNAS/XNYS' }, ], ceoExchanges: [{ exchange: 'TSX' }, { exchange: 'AQL' }], }; const mongo: ReadOnlyExchangeMongoClient = { isReadOnly: () => true, find: async >(collection: string): Promise => (fixtures[collection] ?? []) as T[], }; const dir = makeTempDir('pass1-generated-sql-'); const output = await generateExchangeSeedFromMongo(mongo, { sqlOutPath: join(dir, 'generated.sql'), reportOutPath: join(dir, 'unresolved.md'), knownExchanges: [...ISO_EXCHANGE_SEEDS, syntheticExchange], }); const countRows = async () => ({ exchanges: (await f.pool.query('SELECT count(*)::int AS count FROM exchange')).rows[0] .count as number, mappings: (await f.pool.query('SELECT count(*)::int AS count FROM exchange_source_map')) .rows[0].count as number, }); await f.pool.query(output.sql); const afterFirst = await countRows(); await f.pool.query(output.sql); expect(await countRows()).toEqual(afterFirst); // 11 seeded + XTST; 17 baseline + eod TO, eod V, ib NYSE, ib TESTX, qm NGS. expect(afterFirst).toEqual({ exchanges: 12, mappings: 22 }); const name = (await f.pool.query(`SELECT name FROM exchange WHERE mic = 'XTST'`)).rows[0]; expect(name).toEqual({ name: "O'Brien \\ Test Exchange" }); const generated = ( await f.pool.query( `SELECT source, source_code, role, mic, method FROM exchange_source_map WHERE method = 'operating_mic' ORDER BY source, source_code` ) ).rows; expect(generated).toEqual([ { source: 'eod', source_code: 'TO', role: 'primary_venue', mic: 'XTSE', method: 'operating_mic', }, { source: 'eod', source_code: 'V', role: 'primary_venue', mic: 'XTSX', method: 'operating_mic', }, { source: 'ib', source_code: 'NYSE', role: 'primary_venue', mic: 'XNYS', method: 'operating_mic', }, { source: 'ib', source_code: 'TESTX', role: 'primary_venue', mic: 'XTST', method: 'operating_mic', }, { source: 'qm', source_code: 'NGS', role: 'primary_venue', mic: 'XNAS', method: 'operating_mic', }, ]); // Unresolved codes never reach the table. const leaked = ( await f.pool.query( `SELECT count(*)::int AS count FROM exchange_source_map WHERE (source, source_code) IN (('eod', 'LSE'), ('qm', 'MULTI'))` ) ).rows[0].count as number; expect(leaked).toBe(0); expect(output.reportMarkdown).toContain('| eod | LSE |'); expect(output.reportMarkdown).toContain('| qm | MULTI |'); // Explicit rule kept eod US as composite despite its multi-valued OperatingMIC. const us = ( await f.pool.query( `SELECT role, mic FROM exchange_source_map WHERE source = 'eod' AND source_code = 'US'` ) ).rows[0]; expect(us).toEqual({ role: 'composite', mic: null }); const orphans = ( await f.pool.query( `SELECT count(*)::int AS count FROM exchange_source_map m LEFT JOIN exchange e ON e.mic = m.mic WHERE m.mic IS NOT NULL AND e.mic IS NULL` ) ).rows[0].count as number; expect(orphans).toBe(0); }); });