stock-bot/apps/stock/data-pipeline/src/security-master/generate-exchange-seed.ts

247 lines
7.1 KiB
TypeScript

import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient, type MongoDBClientConfig } from '@stock-bot/mongodb';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import {
classifySourceExchanges,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
type ExchangeClassificationResult,
type ExchangeSeedRow,
type ExchangeSource,
type SourceExchangeRecord,
} from './exchange-pass1';
import {
generateExchangeSeedSql,
generateUnresolvedExchangesMarkdown,
} from './exchange-seed-sql';
export const SOURCE_EXCHANGE_COLLECTIONS: Readonly<Record<ExchangeSource, string>> = Object.freeze({
eod: 'eodExchanges',
ib: 'ibExchanges',
qm: 'qmExchanges',
ceo: 'ceoExchanges',
});
export interface ReadOnlyExchangeMongoClient {
isReadOnly(): boolean;
find<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
filter?: Record<string, unknown>
): Promise<T[]>;
}
export interface GenerateExchangeSeedOptions {
sqlOutPath: string;
reportOutPath: string;
knownExchanges?: readonly ExchangeSeedRow[];
}
export interface GenerateExchangeSeedOutput {
sqlPath: string;
reportPath: string;
sql: string;
reportMarkdown: string;
classification: ExchangeClassificationResult;
countsByCollection: Record<ExchangeSource, number>;
}
export interface ParsedGenerateExchangeSeedArgs {
sqlOutPath: string;
reportOutPath: string;
}
const DEFAULT_SQL_OUT_PATH = './tmp/35-security-master-exchange-seed.generated.sql';
const DEFAULT_REPORT_OUT_PATH = './tmp/pass1-unresolved-exchanges.md';
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
const trimmed = uri?.trim();
if (!trimmed) {
return undefined;
}
const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed);
const rest = schemeMatch?.[1];
if (!rest) {
return undefined;
}
const delimiterMatch = /[/?#]/.exec(rest);
if (!delimiterMatch || delimiterMatch[0] !== '/') {
return undefined;
}
const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? '';
const rawDb = pathPart.replace(/^\/+/, '').split('/')[0];
if (!rawDb) {
return undefined;
}
try {
return decodeURIComponent(rawDb);
} catch {
return rawDb;
}
}
export function resolveReadOnlyMongoClientConfig(
config: Pick<StockAppConfig, 'database'>
): MongoDBClientConfig {
const mongo = config.database.mongodb;
const resolvedUri = mongo.readUri?.trim() || mongo.uri;
const resolvedDatabase =
extractMongoDatabaseFromUri(mongo.readUri) ??
extractMongoDatabaseFromUri(resolvedUri) ??
mongo.database;
return {
host: mongo.host ?? 'localhost',
port: mongo.port ?? 27017,
database: resolvedDatabase,
username: mongo.user,
password: mongo.password,
authSource: mongo.authSource,
uri: resolvedUri,
readOnly: true,
poolSettings: {
maxPoolSize: mongo.poolSize,
minPoolSize: 1,
maxIdleTime: 30_000,
},
};
}
export function parseGenerateExchangeSeedArgs(
argv: readonly string[]
): ParsedGenerateExchangeSeedArgs {
let sqlOutPath = DEFAULT_SQL_OUT_PATH;
let reportOutPath = DEFAULT_REPORT_OUT_PATH;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--sql-out') {
const value = argv[i + 1];
if (!value || value.startsWith('--')) {
throw new Error('Missing value for --sql-out');
}
sqlOutPath = value;
i += 1;
continue;
}
if (arg?.startsWith('--sql-out=')) {
const value = arg.slice('--sql-out='.length);
if (!value) {
throw new Error('Missing value for --sql-out');
}
sqlOutPath = value;
continue;
}
if (arg === '--report-out') {
const value = argv[i + 1];
if (!value || value.startsWith('--')) {
throw new Error('Missing value for --report-out');
}
reportOutPath = value;
i += 1;
continue;
}
if (arg?.startsWith('--report-out=')) {
const value = arg.slice('--report-out='.length);
if (!value) {
throw new Error('Missing value for --report-out');
}
reportOutPath = value;
continue;
}
throw new Error(`Unknown argument: ${String(arg)}`);
}
return { sqlOutPath, reportOutPath };
}
export async function generateExchangeSeedFromMongo(
mongo: ReadOnlyExchangeMongoClient,
options: GenerateExchangeSeedOptions
): Promise<GenerateExchangeSeedOutput> {
if (!mongo.isReadOnly()) {
throw new Error(
'generateExchangeSeedFromMongo requires a read-only MongoDB client (isReadOnly() must be true)'
);
}
const orderedSources: readonly ExchangeSource[] = ['eod', 'ib', 'qm', 'ceo'];
const normalizedRecords: SourceExchangeRecord[] = [];
const countsByCollection: Record<ExchangeSource, number> = {
eod: 0,
ib: 0,
qm: 0,
ceo: 0,
};
for (const source of orderedSources) {
const collectionName = SOURCE_EXCHANGE_COLLECTIONS[source];
const docs = await mongo.find<Record<string, unknown>>(collectionName, {});
countsByCollection[source] = docs.length;
for (const doc of docs) {
normalizedRecords.push(normalizeRawExchangeDoc(source, doc));
}
}
const knownExchanges = options.knownExchanges ?? ISO_EXCHANGE_SEEDS;
const classification = classifySourceExchanges(normalizedRecords, { knownExchanges });
const sql = generateExchangeSeedSql({
exchanges: knownExchanges,
mappings: classification.mapped,
});
const reportMarkdown = generateUnresolvedExchangesMarkdown(classification);
mkdirSync(dirname(options.sqlOutPath), { recursive: true });
writeFileSync(options.sqlOutPath, sql, 'utf8');
mkdirSync(dirname(options.reportOutPath), { recursive: true });
writeFileSync(options.reportOutPath, reportMarkdown, 'utf8');
return {
sqlPath: options.sqlOutPath,
reportPath: options.reportOutPath,
sql,
reportMarkdown,
classification,
countsByCollection,
};
}
async function runCli(): Promise<void> {
const logger = getLogger('security-master-pass1-seed');
const args = parseGenerateExchangeSeedArgs(process.argv.slice(2));
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
try {
const result = await generateExchangeSeedFromMongo(mongo, {
sqlOutPath: args.sqlOutPath,
reportOutPath: args.reportOutPath,
});
logger.info('Generated Pass 1 security master exchange seed files', {
sqlPath: result.sqlPath,
reportPath: result.reportPath,
mappedCount: result.classification.mapped.length,
unresolvedCount: result.classification.unresolved.length,
countsByCollection: result.countsByCollection,
});
} finally {
await mongo.disconnect();
}
}
if (import.meta.main) {
runCli().catch(error => {
const logger = getLogger('security-master-pass1-seed');
logger.fatal('Failed to generate Pass 1 exchange seed SQL', { error });
process.exit(1);
});
}