stock-bot/apps/stock/data-pipeline/src/security-master/run-security-master.ts

677 lines
21 KiB
TypeScript

import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import { PostgreSQLClient } from '@stock-bot/postgres';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import {
computeBarSpans,
normalizeBarDate,
type BarSpanAggregateReader,
type ComputeBarSpansOptions,
type ComputeBarSpansResult,
} from '../normalization/bar-spans';
import {
classifySourceExchanges,
compareAscii,
EXCHANGE_SOURCES,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
type ExchangeClassificationResult,
type ExchangeSource,
type SourceExchangeRecord,
} from './exchange-pass1';
import {
resolveReadOnlyMongoClientConfig,
SOURCE_EXCHANGE_COLLECTIONS,
} from './generate-exchange-seed';
import {
canonicalizeJsonValue,
persistSecurityMaster,
type PersistSecurityMasterResult,
type SecurityMasterQueryable,
type SecurityMasterQueryResult,
} from './persist';
import { composeSecurityMasterRun, type ComposeSecurityMasterRunResult } from './run';
import {
createExchangeSourceLookup,
createReadOnlyMongoSourceSymbolReader,
readSecurityMasterSources,
type ExchangeSourceLookup,
type ReadOnlyMongoCollectionClient,
type SecurityMasterSourcesResult,
} from './source-symbol-readers';
export const SECURITY_MASTER_OUTPUT_FILES = Object.freeze({
matchReport: 'match-report.md',
conflictsCsv: 'conflicts.csv',
overrideTemplateSql: 'override-template.sql',
runStatsJson: 'run-stats.json',
} as const);
export const RUN_SECURITY_MASTER_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of <YYYY-MM-DD> --out-dir <dir> [--persist] [--help]',
'',
'Options:',
' --as-of <YYYY-MM-DD> Required. Calendar reference date for Pass 6 delisting classification.',
' --out-dir <dir> Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.',
' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).',
' --help Show this help message and exit.',
].join('\n');
export type ParsedRunSecurityMasterArgs =
| { readonly help: true }
| {
readonly help: false;
readonly asOfDate: string;
readonly outDir: string;
readonly persist: boolean;
};
export interface SecurityMasterPostgresHandle {
readonly queryable: SecurityMasterQueryable;
close(): Promise<void> | void;
}
export interface RunSecurityMasterDeps {
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
readonly barSpanReader: BarSpanAggregateReader;
readonly closeMongo?: () => Promise<void> | void;
readonly exchangeClassification?: ExchangeClassificationResult;
readonly exchangeLookup?: ExchangeSourceLookup;
readonly assertSafety?: () => void;
readonly createPostgresClient?: () =>
| Promise<SecurityMasterPostgresHandle>
| SecurityMasterPostgresHandle;
readonly persistFn?: typeof persistSecurityMaster;
readonly writeFile?: (filePath: string, content: string) => Promise<void> | void;
readonly writeStdout?: (text: string) => void;
}
export interface RunSecurityMasterOptions {
readonly asOfDate: string;
readonly outDir: string;
readonly persist?: boolean;
readonly countries?: readonly string[] | null;
readonly batchSize?: number;
readonly barSpans?: Omit<ComputeBarSpansOptions, 'sourceIdsBySource'>;
}
export interface RunSecurityMasterOutput {
readonly asOfDate: string;
readonly outDir: string;
readonly persist: boolean;
readonly filesWritten: readonly string[];
readonly exchanges: ExchangeClassificationResult;
readonly exchangeCountsByCollection: Readonly<Record<ExchangeSource, number>>;
readonly sources: SecurityMasterSourcesResult;
readonly barSpans: ComputeBarSpansResult;
readonly composed: ComposeSecurityMasterRunResult;
readonly persistResult: PersistSecurityMasterResult | null;
readonly runStatsJson: string;
readonly summary: string;
}
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
function isValidAsOfDate(value: string): boolean {
return EXACT_YMD_PATTERN.test(value) && normalizeBarDate(value) === value;
}
function usageError(message: string): Error {
return new Error(`${message}\n\n${RUN_SECURITY_MASTER_USAGE}`);
}
function wrapStepError(step: string, error: unknown): Error {
const detail = error instanceof Error ? error.message : String(error);
return new Error(`Security master step "${step}" failed: ${detail}`, { cause: error });
}
function collectSortedUniqueIds(ids: readonly string[]): string[] {
const unique = new Set<string>();
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
if (typeof id === 'string' && id.length > 0) {
unique.add(id);
}
}
return Array.from(unique).sort(compareAscii);
}
async function defaultWriteFile(filePath: string, content: string): Promise<void> {
await mkdir(dirname(filePath), { recursive: true });
await writeFile(filePath, content, 'utf8');
}
export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSecurityMasterArgs {
let help = false;
let asOfDate: string | undefined;
let outDir: string | undefined;
let persist = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--help') {
help = true;
continue;
}
if (arg === '--persist') {
persist = true;
continue;
}
if (arg === '--as-of') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --as-of');
}
asOfDate = value;
i += 1;
continue;
}
if (arg?.startsWith('--as-of=')) {
const value = arg.slice('--as-of='.length);
if (value.trim().length === 0) {
throw usageError('Missing value for --as-of');
}
asOfDate = value;
continue;
}
if (arg === '--out-dir') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --out-dir');
}
outDir = value;
i += 1;
continue;
}
if (arg?.startsWith('--out-dir=')) {
const value = arg.slice('--out-dir='.length);
if (value.trim().length === 0) {
throw usageError('Missing value for --out-dir');
}
outDir = value;
continue;
}
throw usageError(`Unknown argument: ${String(arg)}`);
}
if (help) {
return { help: true };
}
if (asOfDate === undefined) {
throw usageError('Missing required argument: --as-of <YYYY-MM-DD>');
}
if (!isValidAsOfDate(asOfDate)) {
throw usageError(
`Invalid --as-of date "${asOfDate}": expected a valid calendar date in YYYY-MM-DD format`
);
}
if (outDir === undefined || outDir.trim().length === 0) {
throw usageError('Missing required argument: --out-dir <dir>');
}
return {
help: false,
asOfDate,
outDir,
persist,
};
}
export function assertSecurityMasterPersistSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
const pg = config.database.postgres;
if (!pg.enabled) {
throw new Error('PostgreSQL is disabled in configuration; cannot run with --persist');
}
const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env;
assertEnvironmentSafety(config, 'dataPipeline', safeEnv);
if (config.environment !== 'development') {
throw new Error(
`Security master --persist is restricted to NODE_ENV=development targeting isolated dev PostgreSQL ` +
`(got environment "${config.environment}", target ${pg.host}:${pg.port}/${pg.database}).`
);
}
if (pg.database === 'trading_bot' || pg.port === 5432) {
throw new Error(
`Security master --persist cannot target QA PostgreSQL (${pg.host}:${pg.port}/${pg.database}); ` +
'configure isolated dev PostgreSQL (localhost:5433/trading_bot_dev).'
);
}
if (!pg.database.endsWith('_dev') && !pg.database.startsWith('stock_bot_safety')) {
throw new Error(
`Security master --persist requires an isolated dev PostgreSQL database ` +
`(ending in "_dev" or "stock_bot_safety*"), got "${pg.database}".`
);
}
}
export function formatRunSecurityMasterSummary(
params: Pick<
RunSecurityMasterOutput,
'asOfDate' | 'outDir' | 'persist' | 'filesWritten' | 'composed'
>
): string {
const { asOfDate, outDir, persist, composed } = params;
const resolutionParts = composed.report.resolutionBySource.map(row => {
const pct =
row.eligibleResolvedPct === null
? 'n/a'
: `${(row.eligibleResolvedPct * 100).toFixed(1)}%`;
return `${row.source}=${pct} (${row.matched}/${row.eligibleTotal})`;
});
const fileNames = [
SECURITY_MASTER_OUTPUT_FILES.matchReport,
SECURITY_MASTER_OUTPUT_FILES.conflictsCsv,
SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql,
SECURITY_MASTER_OUTPUT_FILES.runStatsJson,
];
const lines = [
`Security master run complete (as-of ${asOfDate})`,
` Instruments: ${composed.stageA.instruments.length} | Listings: ${composed.stageB.listings.length} | Conflicts: ${composed.report.conflicts.length}`,
` Resolution (eligible): ${resolutionParts.length > 0 ? resolutionParts.join(', ') : 'none'}`,
` Pass 4 price cross-check: ${composed.stats.pass4.status} (sample closes not yet wired)`,
` Files written (${outDir}): ${fileNames.join(', ')}`,
` Persisted: ${persist ? 'yes' : 'no (dry-run)'}`,
];
return `${lines.join('\n')}\n`;
}
export async function runSecurityMaster(
deps: RunSecurityMasterDeps,
options: RunSecurityMasterOptions
): Promise<RunSecurityMasterOutput> {
const persist = options.persist === true;
let mongoCloseError: unknown = null;
let output: RunSecurityMasterOutput;
try {
if (!isValidAsOfDate(options.asOfDate)) {
throw wrapStepError(
'validate-options',
new Error(
`Invalid asOfDate "${options.asOfDate}": expected a valid calendar date in YYYY-MM-DD format`
)
);
}
if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) {
throw wrapStepError('validate-options', new Error('outDir must be a non-empty string'));
}
// Step 1: Environment safety check before opening PostgreSQL or reading Mongo when --persist is requested.
if (persist) {
try {
if (typeof deps.assertSafety !== 'function') {
throw new Error(
'Persisting security master requires an assertSafety guard to be configured'
);
}
if (typeof deps.createPostgresClient !== 'function') {
throw new Error(
'Persisting security master requires a createPostgresClient factory to be configured'
);
}
deps.assertSafety();
} catch (error) {
throw wrapStepError('env-safety', error);
}
}
// Step 2: Read-only exchange classification (Pass 1) and lookup construction.
let sourceReader: ReturnType<typeof createReadOnlyMongoSourceSymbolReader>;
let exchanges: ExchangeClassificationResult;
let exchangeLookup: ExchangeSourceLookup;
const exchangeCountsByCollection: Record<ExchangeSource, number> = {
eod: 0,
ib: 0,
qm: 0,
ceo: 0,
};
try {
sourceReader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient);
if (deps.exchangeClassification !== undefined) {
exchanges = deps.exchangeClassification;
} else {
const normalizedRecords: SourceExchangeRecord[] = [];
for (const source of EXCHANGE_SOURCES) {
const collectionName = SOURCE_EXCHANGE_COLLECTIONS[source];
const cursor = await sourceReader.find<Record<string, unknown>>(collectionName, {});
let count = 0;
for await (const doc of cursor) {
count += 1;
normalizedRecords.push(normalizeRawExchangeDoc(source, doc));
}
exchangeCountsByCollection[source] = count;
}
exchanges = classifySourceExchanges(normalizedRecords, {
knownExchanges: ISO_EXCHANGE_SEEDS,
});
}
exchangeLookup = deps.exchangeLookup ?? createExchangeSourceLookup(exchanges.mapped);
} catch (error) {
throw wrapStepError('read-exchanges', error);
}
// Step 3: Stream read-only symbol collections into Stage A / Stage B inputs.
let sources: SecurityMasterSourcesResult;
try {
sources = await readSecurityMasterSources(sourceReader, {
exchangeLookup,
countries: options.countries,
batchSize: options.batchSize,
});
} catch (error) {
throw wrapStepError('read-sources', error);
}
// Step 4: Compute targeted observed bar spans for in-scope EOD and QM listings.
let barSpans: ComputeBarSpansResult;
try {
const eodIds = collectSortedUniqueIds(
sources.stageBInput.eodListings.map(entry => entry.sourceId)
);
const qmIds = collectSortedUniqueIds(
sources.stageBInput.tickerSources
.filter(entry => entry.source === 'qm')
.map(entry => entry.sourceId)
);
barSpans = await computeBarSpans(deps.barSpanReader, {
sources: ['eod', 'qm'],
...options.barSpans,
sourceIdsBySource: {
eod: eodIds,
qm: qmIds,
},
});
} catch (error) {
throw wrapStepError('compute-bar-spans', error);
}
// Step 5: Compose Stage A -> Stage B -> Pass 6 -> Report + PersistInput (Pass 4 omitted).
let composed: ComposeSecurityMasterRunResult;
try {
composed = composeSecurityMasterRun(
{
sources,
barSpans,
exchanges,
},
{
asOfDate: options.asOfDate,
}
);
} catch (error) {
throw wrapStepError('compose', error);
}
// Step 6: Write deterministic artifacts into outDir.
const statsArtifact = {
asOfDate: options.asOfDate,
pass4Wired: false,
exchanges: {
countsByCollection: exchangeCountsByCollection,
mapped: exchanges.mapped.length,
unresolved: exchanges.unresolved.length,
total: exchanges.mapped.length + exchanges.unresolved.length,
},
readers: sources.stats,
securityTypes: {
stats: sources.securityTypeStats,
loaderStats: sources.securityTypeLoaderStats,
unknownCount: sources.unknownSecurityTypes.length,
conflictCount: sources.securityTypeConflicts.length,
},
barSpans: {
bySource: barSpans.bySource,
skipped: barSpans.skipped,
totalRowsRead: barSpans.totalRowsRead,
totalSpans: barSpans.totalSpans,
},
compose: composed.stats,
reportSummary: {
instruments: composed.stageA.instruments.length,
listings: composed.stageB.listings.length,
providerMappings: composed.stageB.providerMappings.length,
conflicts: composed.report.conflicts.length,
exchangeCoverage: composed.report.exchangeCoverage,
resolutionBySource: composed.report.resolutionBySource,
resolutionByCountry: composed.report.resolutionByCountry,
meetsExitThresholds: composed.report.meetsExitThresholds,
},
};
const runStatsJson = `${JSON.stringify(canonicalizeJsonValue(statsArtifact), null, 2)}\n`;
const writer = deps.writeFile ?? defaultWriteFile;
const filesToWrite: ReadonlyArray<readonly [string, string]> = [
[join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), composed.reportMarkdown],
[join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), composed.conflictsCsv],
[
join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql),
composed.overrideTemplateSql,
],
[join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), runStatsJson],
];
const filesWritten = filesToWrite.map(([filePath]) => filePath);
try {
for (const [filePath, content] of filesToWrite) {
await writer(filePath, content);
}
} catch (error) {
throw wrapStepError('write-files', error);
}
// Step 7: Optional persistence to PostgreSQL (only when --persist is enabled).
let persistResult: PersistSecurityMasterResult | null = null;
if (persist) {
try {
const createPg = deps.createPostgresClient;
if (typeof createPg !== 'function') {
throw new Error(
'Persisting security master requires a createPostgresClient factory to be configured'
);
}
const pgHandle = await createPg();
let pgCloseError: unknown = null;
try {
const persistFn = deps.persistFn ?? persistSecurityMaster;
persistResult = await persistFn(pgHandle.queryable, composed.persistInput);
} finally {
try {
await pgHandle.close();
} catch (closeError) {
pgCloseError = closeError;
}
}
if (pgCloseError !== null) {
throw pgCloseError;
}
} catch (error) {
throw wrapStepError('persist', error);
}
}
// Step 8: Build concise one-screen summary (emitted only after cleanup succeeds).
const summary = formatRunSecurityMasterSummary({
asOfDate: options.asOfDate,
outDir: options.outDir,
persist,
filesWritten,
composed,
});
output = {
asOfDate: options.asOfDate,
outDir: options.outDir,
persist,
filesWritten,
exchanges,
exchangeCountsByCollection,
sources,
barSpans,
composed,
persistResult,
runStatsJson,
summary,
};
} finally {
if (deps.closeMongo) {
try {
await deps.closeMongo();
} catch (closeError) {
mongoCloseError = closeError;
}
}
}
if (mongoCloseError !== null) {
throw wrapStepError('close-mongo', mongoCloseError);
}
const writeStdout =
deps.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(output.summary);
return output;
}
export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise<void> {
const parsed = parseRunSecurityMasterArgs(argv);
if (parsed.help) {
process.stdout.write(`${RUN_SECURITY_MASTER_USAGE}\n`);
return;
}
const logger = getLogger('security-master-run-cli');
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
const assertSafety = (): void => {
assertSecurityMasterPersistSafety(config, process.env);
};
const createPostgresClient = async (): Promise<SecurityMasterPostgresHandle> => {
const pg = config.database.postgres;
const pgClient = new PostgreSQLClient(
{
host: pg.host,
port: pg.port,
database: pg.database,
username: pg.user,
password: pg.password,
poolSettings: {
min: 1,
max: Math.max(1, pg.poolSize),
idleTimeoutMillis: pg.idleTimeout,
},
ssl: {
enabled: pg.ssl,
rejectUnauthorized: true,
},
timeouts: {
connection: pg.connectionTimeout,
},
},
logger
);
await pgClient.connect();
try {
const pool = pgClient.connectionPool;
if (!pool) {
throw new Error('PostgreSQL connection pool was not initialized after connect()');
}
const poolClient = await pool.connect();
const queryable: SecurityMasterQueryable = {
query<Row = Record<string, unknown>>(
text: string,
values?: readonly unknown[]
): Promise<SecurityMasterQueryResult<Row>> {
return poolClient.query(
text,
values === undefined ? undefined : [...values]
) as unknown as Promise<SecurityMasterQueryResult<Row>>;
},
release: () => {
poolClient.release();
},
};
let closed = false;
return {
queryable,
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
let releaseError: unknown = null;
try {
poolClient.release();
} catch (error) {
releaseError = error;
}
try {
await pgClient.disconnect();
} catch (disconnectError) {
if (releaseError === null) {
throw disconnectError;
}
}
if (releaseError !== null) {
throw releaseError;
}
},
};
} catch (error) {
await pgClient.disconnect().catch(() => {});
throw error;
}
};
await runSecurityMaster(
{
mongoCollectionClient: mongo,
barSpanReader: mongo,
closeMongo: () => mongo.disconnect(),
assertSafety,
createPostgresClient,
},
{
asOfDate: parsed.asOfDate,
outDir: parsed.outDir,
persist: parsed.persist,
}
);
}
if (import.meta.main) {
runCli().catch(error => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`Error: ${message}\n`);
process.exit(1);
});
}