import { randomUUID } from 'node:crypto'; import { afterEach, describe, expect, test } from 'bun:test'; import { Pool } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; import type { MongoDBClient } from '@stock-bot/services'; import { clearPostgreSQLData } from '../../apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations'; import { syncAllExchanges } from '../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations'; import { syncQMProviderMappings } from '../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations'; import { syncSymbolsFromProvider } from '../../apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations'; import { PipelineSyncRepository } from '../../apps/stock/data-pipeline/src/repositories/PipelineSyncRepository'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('pipeline-postgres-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); async function fixture() { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) throw new Error('A dedicated stock_bot_safety database is 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}` }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); await pool.query(` CREATE TABLE exchanges (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), code text UNIQUE NOT NULL, name text, country char(2), currency char(3), active boolean DEFAULT true); CREATE TABLE symbols (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), symbol text, exchange_id uuid REFERENCES exchanges, company_name text, country char(2), currency char(3), updated_at timestamptz, UNIQUE(symbol, exchange_id)); CREATE TABLE provider_exchange_mappings (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), provider text, provider_exchange_code text, provider_exchange_name text, master_exchange_id uuid REFERENCES exchanges, country_code text, currency text, confidence numeric, active boolean, auto_mapped boolean, UNIQUE(provider, provider_exchange_code)); CREATE TABLE provider_mappings (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), symbol_id uuid REFERENCES symbols, provider text, provider_symbol text, provider_exchange text, verified boolean DEFAULT false, last_seen timestamptz, UNIQUE(provider, provider_symbol)); CREATE TABLE sync_status (provider text, data_type text, last_sync_at timestamptz, last_sync_count integer, sync_errors text, updated_at timestamptz, UNIQUE(provider, data_type)); INSERT INTO exchanges (code,name,country,currency) VALUES ('TSX','Manually curated','CA','CAD'); INSERT INTO provider_exchange_mappings (provider,provider_exchange_code,master_exchange_id,active,auto_mapped) SELECT 'eod','TO',id,true,false FROM exchanges; INSERT INTO symbols (symbol,exchange_id,company_name,country,currency) SELECT 'KEEP',id,'Original company','CA','CAD' FROM exchanges; INSERT INTO provider_mappings (provider,provider_symbol,symbol_id,verified) SELECT 'eod','KEEP.TO',id,true FROM symbols; `); const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); const documents: Record[]> = { eodExchanges: [], ibExchanges: [], eodSymbols: [], qmSymbols: [], }; const mongodb = { async find(collection: string) { return documents[collection] ?? []; }, getDatabase() { return { collection(name: string) { return { find() { return { async toArray() { return documents[name] ?? []; }, }; }, aggregate() { return { async toArray() { return documents[name] ?? []; }, }; }, }; }, }; }, } as unknown as MongoDBClient; const services = { logger, postgres, mongodb }; const snapshot = async () => { const result: Record = {}; for (const table of [ 'exchanges', 'symbols', 'provider_mappings', 'provider_exchange_mappings', 'sync_status', ]) { result[table] = (await pool.query(`SELECT * FROM ${table} ORDER BY 1`)).rows; } return result; }; return { services, pool, postgres, documents, snapshot }; } describe.skipIf(!url)('pipeline safety on real PostgreSQL', () => { test('default and false syncs preserve IDs and manual mappings; replay is idempotent', async () => { const f = await fixture(); const before = await f.snapshot(); f.documents.eodExchanges = [ { Code: 'TO', Name: 'Provider name', CountryISO2: 'CA', Currency: 'CAD' }, { Code: 'NEW', Name: 'New', CountryISO2: 'US', Currency: 'USD' }, ]; expect((await syncAllExchanges({}, f.services)).created).toBe(1); expect((await syncAllExchanges({ clearFirst: false }, f.services)).created).toBe(0); const after = await f.snapshot(); expect(after.symbols).toEqual(before.symbols); expect(after.provider_mappings).toEqual(before.provider_mappings); expect((await f.pool.query("SELECT name FROM exchanges WHERE code = 'TSX'")).rows[0].name).toBe( 'Manually curated' ); await expect(syncAllExchanges({ clearFirst: true }, f.services)).rejects.toThrow( 'non-destructive' ); }); test('a failure after an earlier exchange write rolls back data and status', async () => { const f = await fixture(); const before = await f.snapshot(); f.documents.eodExchanges = [ { Code: 'NEW', Name: 'New', CountryISO2: 'US' }, { Code: 'BAD', Name: 'Bad', CountryISO2: 'INVALID' }, ]; await expect(syncAllExchanges({}, f.services)).rejects.toThrow(); expect(await f.snapshot()).toEqual(before); }); test('symbol updates, mappings, and status roll back together on a later failure', async () => { const f = await fixture(); const before = await f.snapshot(); f.documents.eodSymbols = [ { Code: 'KEEP', Exchange: 'TO', eodSearchCode: 'KEEP.TO', Name: 'Changed', Currency: 'CAD' }, { Code: 'BAD', Exchange: 'TO', Currency: 'TOO LONG' }, ]; await expect(syncSymbolsFromProvider({ provider: 'eod' }, f.services)).rejects.toThrow(); expect(await f.snapshot()).toEqual(before); await expect( syncSymbolsFromProvider({ provider: 'eod', clearFirst: true }, f.services) ).rejects.toThrow('non-destructive'); }); test('QM mapping writes also roll back as one transaction', async () => { const f = await fixture(); const before = await f.snapshot(); f.documents.qmSymbols = [ { exchangeCode: 'NEW', countryCode: 'US' }, { exchangeCode: 'BAD', countryCode: 'INVALID' }, ]; await expect(syncQMProviderMappings({}, f.services)).rejects.toThrow(); expect(await f.snapshot()).toEqual(before); }); test('unconfirmed reset does nothing; FK failure rolls back earlier deletes', async () => { const f = await fixture(); const before = await f.snapshot(); await expect(clearPostgreSQLData({}, f.services)).rejects.toThrow('confirmation'); await expect( clearPostgreSQLData( { type: 'all', confirmation: 'DELETE STOCK REFERENCE DATA:exchanges' }, f.services ) ).rejects.toThrow('confirmation'); await expect( clearPostgreSQLData( { type: 'exchanges', confirmation: 'DELETE STOCK REFERENCE DATA:exchanges' }, f.services ) ).rejects.toThrow(); expect(await f.snapshot()).toEqual(before); }); test('confirmed mapping-only reset respects scope; all reset respects FK ordering', async () => { const f = await fixture(); const mappingOnly = await clearPostgreSQLData( { type: 'provider_mappings', confirmation: 'DELETE STOCK REFERENCE DATA:provider_mappings' }, f.services ); expect(mappingOnly.mappingsCleared).toBe(1); expect((await f.pool.query('SELECT * FROM symbols')).rows).toHaveLength(1); const all = await clearPostgreSQLData( { type: 'all', confirmation: 'DELETE STOCK REFERENCE DATA:all' }, f.services ); expect(all).toMatchObject({ exchangesCleared: 1, symbolsCleared: 1, exchangeMappingsCleared: 1, }); }); test('competing sync/reset transactions serialize on the same advisory lock', async () => { const f = await fixture(); let entered!: () => void; let release!: () => void; const ready = new Promise(resolve => { entered = resolve; }); const gate = new Promise(resolve => { release = resolve; }); const first = PipelineSyncRepository.transaction(f.postgres, async () => { entered(); await gate; }); await ready; let secondEntered = false; const second = PipelineSyncRepository.transaction(f.postgres, async () => { secondEntered = true; }); await new Promise(resolve => setTimeout(resolve, 50)); expect(secondEntered).toBe(false); release(); await Promise.all([first, second]); expect(secondEntered).toBe(true); }); });