345 lines
11 KiB
TypeScript
345 lines
11 KiB
TypeScript
import { getLogger } from '@stock-bot/logger';
|
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
|
import {
|
|
assertEnvironmentSafety,
|
|
initializeStockConfig,
|
|
type StockAppConfig,
|
|
} from '@stock-bot/stock-config';
|
|
import {
|
|
CURATE_INPUT_FILES,
|
|
DEFAULT_DELISTING_MAPPING_SOURCE,
|
|
DEFAULT_EXPORT_CHUNK_SIZE,
|
|
exportCurateInputs,
|
|
MAX_EXPORT_CHUNK_SIZE,
|
|
type ExportCurateInputsFsHooks,
|
|
type ExportCurateInputsResult,
|
|
} from './export-curate-inputs';
|
|
import type { SecurityMasterQueryable, SecurityMasterQueryResult } from './persist';
|
|
import type { SecurityMasterPostgresHandle } from './run-security-master';
|
|
|
|
export const EXPORT_CURATE_INPUTS_USAGE = [
|
|
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir <dir> [--chunk-size <n>] [--help]',
|
|
'',
|
|
'Options:',
|
|
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`,
|
|
` --chunk-size <n> Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`,
|
|
' --help Show this help message and exit.',
|
|
].join('\n');
|
|
|
|
export type ParsedExportCurateInputsArgs =
|
|
| { readonly help: true }
|
|
| {
|
|
readonly help: false;
|
|
readonly outDir: string;
|
|
readonly chunkSize: number;
|
|
};
|
|
|
|
export interface RunExportCurateInputsDeps {
|
|
readonly assertSafety?: () => void;
|
|
readonly createPostgresClient: () =>
|
|
| Promise<SecurityMasterPostgresHandle>
|
|
| SecurityMasterPostgresHandle;
|
|
readonly exportFn?: typeof exportCurateInputs;
|
|
readonly writeStdout?: (text: string) => void;
|
|
}
|
|
|
|
export interface RunExportCurateInputsOptions {
|
|
readonly outDir: string;
|
|
readonly chunkSize?: number;
|
|
readonly delistingMappingSource?: string;
|
|
readonly fs?: ExportCurateInputsFsHooks;
|
|
}
|
|
|
|
export interface RunExportCurateInputsOutput {
|
|
readonly result: ExportCurateInputsResult;
|
|
readonly summary: string;
|
|
}
|
|
|
|
const STRICT_INT_PATTERN = /^-?\d+$/;
|
|
|
|
function usageError(message: string): Error {
|
|
return new Error(`${message}\n\n${EXPORT_CURATE_INPUTS_USAGE}`);
|
|
}
|
|
|
|
function parseChunkSizeArg(raw: string): number {
|
|
if (!STRICT_INT_PATTERN.test(raw)) {
|
|
throw usageError(
|
|
`Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}`
|
|
);
|
|
}
|
|
const parsed = Number(raw);
|
|
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_EXPORT_CHUNK_SIZE) {
|
|
throw usageError(
|
|
`Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}`
|
|
);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
export function parseExportCurateInputsArgs(
|
|
argv: readonly string[]
|
|
): ParsedExportCurateInputsArgs {
|
|
let help = false;
|
|
let outDir: string | undefined;
|
|
let chunkSize = DEFAULT_EXPORT_CHUNK_SIZE;
|
|
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const arg = argv[i];
|
|
if (arg === '--help') {
|
|
help = true;
|
|
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.trim();
|
|
i += 1;
|
|
continue;
|
|
}
|
|
if (arg?.startsWith('--out-dir=')) {
|
|
const value = arg.slice('--out-dir='.length).trim();
|
|
if (value.length === 0) {
|
|
throw usageError('Missing value for --out-dir');
|
|
}
|
|
outDir = value;
|
|
continue;
|
|
}
|
|
if (arg === '--chunk-size') {
|
|
const value = argv[i + 1];
|
|
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
|
throw usageError('Missing value for --chunk-size');
|
|
}
|
|
chunkSize = parseChunkSizeArg(value.trim());
|
|
i += 1;
|
|
continue;
|
|
}
|
|
if (arg?.startsWith('--chunk-size=')) {
|
|
const value = arg.slice('--chunk-size='.length).trim();
|
|
if (value.length === 0) {
|
|
throw usageError('Missing value for --chunk-size');
|
|
}
|
|
chunkSize = parseChunkSizeArg(value);
|
|
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>');
|
|
}
|
|
|
|
return {
|
|
help: false,
|
|
outDir,
|
|
chunkSize,
|
|
};
|
|
}
|
|
|
|
export function assertExportCurateInputsSafety(
|
|
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 export curate-etl inputs');
|
|
}
|
|
|
|
const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env;
|
|
const pgOnlyConfig: StockAppConfig = {
|
|
...config,
|
|
database: {
|
|
...config.database,
|
|
mongodb: {
|
|
...config.database.mongodb,
|
|
enabled: false,
|
|
},
|
|
},
|
|
};
|
|
assertEnvironmentSafety(pgOnlyConfig, 'dataPipeline', safeEnv);
|
|
}
|
|
|
|
export function formatExportCurateInputsSummary(result: ExportCurateInputsResult): string {
|
|
const d = result.delistings.stats;
|
|
const s = d.skipped;
|
|
const lines = [
|
|
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`,
|
|
` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`,
|
|
` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`,
|
|
` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`,
|
|
` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`,
|
|
];
|
|
for (const warning of result.cleanupWarnings) {
|
|
lines.push(` warning: ${warning}`);
|
|
}
|
|
return `${lines.join('\n')}\n`;
|
|
}
|
|
|
|
export async function runExportCurateInputs(
|
|
deps: RunExportCurateInputsDeps,
|
|
options: RunExportCurateInputsOptions
|
|
): Promise<RunExportCurateInputsOutput> {
|
|
if (deps.assertSafety) {
|
|
deps.assertSafety();
|
|
}
|
|
|
|
const pgHandle = await deps.createPostgresClient();
|
|
let result: ExportCurateInputsResult;
|
|
let closeError: unknown = null;
|
|
try {
|
|
const exportFn = deps.exportFn ?? exportCurateInputs;
|
|
result = await exportFn(pgHandle.queryable, {
|
|
outDir: options.outDir,
|
|
chunkSize: options.chunkSize,
|
|
delistingMappingSource: options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE,
|
|
fs: options.fs,
|
|
});
|
|
} finally {
|
|
try {
|
|
await pgHandle.close();
|
|
} catch (error) {
|
|
closeError = error;
|
|
}
|
|
}
|
|
|
|
if (closeError !== null) {
|
|
throw closeError;
|
|
}
|
|
|
|
const summary = formatExportCurateInputsSummary(result);
|
|
const writeStdout =
|
|
deps.writeStdout ??
|
|
((text: string) => {
|
|
process.stdout.write(text);
|
|
});
|
|
writeStdout(summary);
|
|
|
|
return { result, summary };
|
|
}
|
|
|
|
export async function runCli(
|
|
argv: readonly string[] = process.argv.slice(2),
|
|
overrides?: Partial<RunExportCurateInputsDeps>
|
|
): Promise<void> {
|
|
const parsed = parseExportCurateInputsArgs(argv);
|
|
if (parsed.help) {
|
|
const writeStdout =
|
|
overrides?.writeStdout ??
|
|
((text: string) => {
|
|
process.stdout.write(text);
|
|
});
|
|
writeStdout(`${EXPORT_CURATE_INPUTS_USAGE}\n`);
|
|
return;
|
|
}
|
|
|
|
const logger = getLogger('security-master-export-curate-inputs-cli');
|
|
const config = initializeStockConfig('dataPipeline', { postgresOnly: true });
|
|
|
|
const assertSafety = (): void => {
|
|
assertExportCurateInputsSafety(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 runExportCurateInputs(
|
|
{
|
|
assertSafety: overrides?.assertSafety ?? assertSafety,
|
|
createPostgresClient: overrides?.createPostgresClient ?? createPostgresClient,
|
|
exportFn: overrides?.exportFn,
|
|
writeStdout: overrides?.writeStdout,
|
|
},
|
|
{
|
|
outDir: parsed.outDir,
|
|
chunkSize: parsed.chunkSize,
|
|
}
|
|
);
|
|
}
|
|
|
|
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);
|
|
});
|
|
}
|