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

478 lines
15 KiB
TypeScript

import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import {
createReadOnlyMongoRawBsonSource,
DEFAULT_RAW_BSON_BATCH_SIZE,
exportRawBsonCollection,
isRawBsonExportCollection,
MAX_RAW_BSON_BATCH_SIZE,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
type ExportRawBsonCollectionResult,
type ExportRawBsonFsHooks,
type RawBsonExportCollection,
type ReadOnlyMongoRawBsonClient,
} from './export-raw-bson';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety';
/**
* Default collection set when `--collections` is omitted. Preserves the bounded
* M1 set so omitting `--collections` does not trigger an unbounded dump of M2
* collections (e.g. `eodIntraday1M`). All 14 M1+M2 collections remain
* selectable via `--collections`.
*/
export const DEFAULT_RAW_BSON_EXPORT_COLLECTIONS: readonly RawBsonExportCollection[] =
Object.freeze([
'eodPrices',
'qmSplits',
'qmDividends',
'qmPrices',
'teMarketData',
'ceoShorts',
'qmFilings',
'qmEarnings',
] as const);
export const EXPORT_RAW_BSON_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
'',
'Options:',
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${DEFAULT_RAW_BSON_EXPORT_COLLECTIONS.join(',')}; M2 collections require explicit selection: qmFinancials,qmFinancials-old,ceoPosts,teData,eodIntraday1M,qmIntraday).`,
' --eod-symbol <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
` --batch-size <n> Optional. MongoDB cursor batchSize (1..${MAX_RAW_BSON_BATCH_SIZE}, default: ${DEFAULT_RAW_BSON_BATCH_SIZE}).`,
' --help Show this help message and exit.',
].join('\n');
export type ParsedExportRawBsonArgs =
| { readonly help: true }
| {
readonly help: false;
readonly outDir: string;
readonly collections: readonly RawBsonExportCollection[];
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize: number;
};
export interface RawBsonMongoHandle {
readonly client: ReadOnlyMongoRawBsonClient;
readonly close: () => Promise<void> | void;
}
export interface RunExportRawBsonDeps {
readonly assertSafety?: () => void;
readonly createMongoClient: () => Promise<RawBsonMongoHandle> | RawBsonMongoHandle;
readonly exportFn?: typeof exportRawBsonCollection;
readonly writeStdout?: (text: string) => void;
}
export interface RunExportRawBsonCliOverrides extends Partial<RunExportRawBsonDeps> {
readonly initializeConfig?: typeof initializeStockConfig;
}
export interface RunExportRawBsonOptions {
readonly outDir: string;
readonly collections: readonly RawBsonExportCollection[];
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize?: number;
readonly writeBufferBytes?: number;
readonly maxDocBytes?: number;
readonly fs?: ExportRawBsonFsHooks;
}
export interface RunExportRawBsonOutput {
readonly results: readonly ExportRawBsonCollectionResult[];
readonly summary: string;
}
const STRICT_INT_PATTERN = /^-?\d+$/;
function usageError(message: string): Error {
return new Error(`${message}\n\n${EXPORT_RAW_BSON_USAGE}`);
}
function parsePositiveIntArg(flag: string, raw: string, max?: number): number {
if (!STRICT_INT_PATTERN.test(raw)) {
throw usageError(
max !== undefined
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
: `Invalid ${flag} value "${raw}": expected a positive integer`
);
}
const parsed = Number(raw);
if (
!Number.isSafeInteger(parsed) ||
parsed < 1 ||
(max !== undefined && parsed > max)
) {
throw usageError(
max !== undefined
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
: `Invalid ${flag} value "${raw}": expected a positive integer`
);
}
return parsed;
}
function parseCollectionsList(raw: string): RawBsonExportCollection[] {
const segments = raw.split(',');
const result: RawBsonExportCollection[] = [];
const seen = new Set<string>();
for (const segment of segments) {
const trimmed = segment.trim();
if (trimmed.length === 0) {
throw usageError(`Malformed --collections value "${raw}": empty collection entry`);
}
if (!isRawBsonExportCollection(trimmed)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: trimmed,
detail: `collection "${trimmed}" is not in the M1+M2 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
});
}
if (seen.has(trimmed)) {
throw usageError(`Duplicate collection "${trimmed}" in --collections`);
}
seen.add(trimmed);
result.push(trimmed);
}
if (result.length === 0) {
throw usageError('Missing value for --collections');
}
return result;
}
function readFlagValue(
argv: readonly string[],
index: number,
flag: string
): { value: string; nextIndex: number } {
const arg = argv[index] ?? '';
const eqPrefix = `${flag}=`;
if (arg.startsWith(eqPrefix)) {
const value = arg.slice(eqPrefix.length).trim();
if (value.length === 0) {
throw usageError(`Missing value for ${flag}`);
}
if (value.startsWith('--')) {
throw usageError(`Invalid value for ${flag}: "${value}" must not start with "--"`);
}
return { value, nextIndex: index };
}
const next = argv[index + 1];
const trimmedNext = next?.trim() ?? '';
if (trimmedNext.length === 0 || trimmedNext.startsWith('--')) {
throw usageError(`Missing value for ${flag}`);
}
return { value: trimmedNext, nextIndex: index + 1 };
}
export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRawBsonArgs {
let help = false;
let outDir: string | undefined;
let collections: RawBsonExportCollection[] | undefined;
let eodSymbol: string | undefined;
let teSymbol: string | undefined;
let limit: number | undefined;
let batchSize = DEFAULT_RAW_BSON_BATCH_SIZE;
const seenFlags = new Set<string>();
const markSeen = (flag: string): void => {
if (seenFlags.has(flag)) {
throw usageError(`Duplicate flag: ${flag}`);
}
seenFlags.add(flag);
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--help') {
markSeen('--help');
help = true;
continue;
}
if (arg === '--out-dir' || arg?.startsWith('--out-dir=')) {
markSeen('--out-dir');
const { value, nextIndex } = readFlagValue(argv, i, '--out-dir');
outDir = value;
i = nextIndex;
continue;
}
if (arg === '--collections' || arg?.startsWith('--collections=')) {
markSeen('--collections');
const { value, nextIndex } = readFlagValue(argv, i, '--collections');
collections = parseCollectionsList(value);
i = nextIndex;
continue;
}
if (arg === '--eod-symbol' || arg?.startsWith('--eod-symbol=')) {
markSeen('--eod-symbol');
const { value, nextIndex } = readFlagValue(argv, i, '--eod-symbol');
eodSymbol = value;
i = nextIndex;
continue;
}
if (arg === '--te-symbol' || arg?.startsWith('--te-symbol=')) {
markSeen('--te-symbol');
const { value, nextIndex } = readFlagValue(argv, i, '--te-symbol');
teSymbol = value;
i = nextIndex;
continue;
}
if (arg === '--limit' || arg?.startsWith('--limit=')) {
markSeen('--limit');
const { value, nextIndex } = readFlagValue(argv, i, '--limit');
limit = parsePositiveIntArg('--limit', value);
i = nextIndex;
continue;
}
if (arg === '--batch-size' || arg?.startsWith('--batch-size=')) {
markSeen('--batch-size');
const { value, nextIndex } = readFlagValue(argv, i, '--batch-size');
batchSize = parsePositiveIntArg('--batch-size', value, MAX_RAW_BSON_BATCH_SIZE);
i = nextIndex;
continue;
}
throw usageError(`Unknown argument: ${String(arg)}`);
}
if (help) {
return { help: true };
}
if (outDir === undefined || outDir.trim().length === 0) {
throw usageError('Missing required argument: --out-dir <dir>');
}
const resolvedCollections: readonly RawBsonExportCollection[] =
collections ?? [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS];
if (eodSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
throw usageError(
'--eod-symbol is only permitted when --collections is strictly "eodPrices"'
);
}
}
if (teSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'teMarketData') {
throw usageError(
'--te-symbol is only permitted when --collections is strictly "teMarketData"'
);
}
}
return {
help: false,
outDir,
collections: resolvedCollections,
...(eodSymbol !== undefined ? { eodSymbol } : {}),
...(teSymbol !== undefined ? { teSymbol } : {}),
...(limit !== undefined ? { limit } : {}),
batchSize,
};
}
export function assertExportRawBsonSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
assertReadOnlyMongoDiagnosticSafety(
config,
{
operationLabel: 'export raw BSON collections',
diagnosticLabel: 'Raw BSON exporter',
},
env
);
}
export function formatExportRawBsonSummary(
results: readonly ExportRawBsonCollectionResult[]
): string {
const lines = [`Raw BSON export complete (${results.length} collection(s))`];
for (const r of results) {
lines.push(
` ${r.collection}: docs=${r.docsWritten} bytes=${r.bytesWritten} elapsed_ms=${r.elapsedMs.toFixed(1)} sha256=${r.sha256} out=${r.outPath}`
);
}
return `${lines.join('\n')}\n`;
}
export async function runExportRawBson(
deps: RunExportRawBsonDeps,
options: RunExportRawBsonOptions
): Promise<RunExportRawBsonOutput> {
if (options.collections.length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: '*',
detail: 'At least one allowlisted collection must be specified',
});
}
for (const collection of options.collections) {
if (!isRawBsonExportCollection(collection)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: String(collection),
detail: `collection "${String(collection)}" is not in the M1+M2 allowlist`,
});
}
}
if (
options.eodSymbol !== undefined &&
(options.collections.length !== 1 || options.collections[0] !== 'eodPrices')
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: options.collections.join(','),
detail: '--eod-symbol is only permitted when exporting strictly "eodPrices"',
});
}
if (
options.teSymbol !== undefined &&
(options.collections.length !== 1 || options.collections[0] !== 'teMarketData')
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: options.collections.join(','),
detail: '--te-symbol is only permitted when exporting strictly "teMarketData"',
});
}
if (deps.assertSafety) {
deps.assertSafety();
}
const mongoHandle = await deps.createMongoClient();
const results: ExportRawBsonCollectionResult[] = [];
let primaryError: unknown = undefined;
let hasPrimaryError = false;
try {
const source = createReadOnlyMongoRawBsonSource(mongoHandle.client);
const exportFn = deps.exportFn ?? exportRawBsonCollection;
for (const collection of options.collections) {
const result = await exportFn(source, {
collection,
outDir: options.outDir,
...(options.eodSymbol !== undefined ? { eodSymbol: options.eodSymbol } : {}),
...(options.teSymbol !== undefined ? { teSymbol: options.teSymbol } : {}),
...(options.limit !== undefined ? { limit: options.limit } : {}),
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
...(options.writeBufferBytes !== undefined
? { writeBufferBytes: options.writeBufferBytes }
: {}),
...(options.maxDocBytes !== undefined ? { maxDocBytes: options.maxDocBytes } : {}),
...(options.fs !== undefined ? { fs: options.fs } : {}),
});
results.push(result);
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
try {
await mongoHandle.close();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
if (hasPrimaryError) {
throw primaryError;
}
const summary = formatExportRawBsonSummary(results);
const writeStdout =
deps.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(summary);
return { results, summary };
}
export async function runCli(
argv: readonly string[] = process.argv.slice(2),
overrides?: RunExportRawBsonCliOverrides
): Promise<void> {
const parsed = parseExportRawBsonArgs(argv);
if (parsed.help) {
const writeStdout =
overrides?.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(`${EXPORT_RAW_BSON_USAGE}\n`);
return;
}
const logger = getLogger('security-master-export-raw-bson-cli');
const initConfig = overrides?.initializeConfig ?? initializeStockConfig;
const config = initConfig('dataPipeline', { mongoReadOnly: true });
const assertSafety = (): void => {
assertExportRawBsonSafety(config, process.env);
};
const createMongoClient = async (): Promise<RawBsonMongoHandle> => {
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
let closed = false;
return {
client: mongo,
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
await mongo.disconnect();
},
};
};
await runExportRawBson(
{
assertSafety: overrides?.assertSafety ?? assertSafety,
createMongoClient: overrides?.createMongoClient ?? createMongoClient,
exportFn: overrides?.exportFn,
writeStdout: overrides?.writeStdout,
},
{
outDir: parsed.outDir,
collections: parsed.collections,
...(parsed.eodSymbol !== undefined ? { eodSymbol: parsed.eodSymbol } : {}),
...(parsed.teSymbol !== undefined ? { teSymbol: parsed.teSymbol } : {}),
...(parsed.limit !== undefined ? { limit: parsed.limit } : {}),
batchSize: parsed.batchSize,
}
);
}
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);
});
}