T-211: M2.2v — Export listing_venues.tsv and extend field-shape probe & BSON fixture exporter for M2 collections

This commit is contained in:
Studio 2026-12-04 14:33:13 -05:00
parent 12da9aa899
commit ba20f9a2e5
8 changed files with 345 additions and 63 deletions

View file

@ -87,7 +87,8 @@ export type CurateInputExportErrorCode =
| 'DUPLICATE_OTC_CONTINUITY'
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
| 'PUBLISH_LOCK_TIMEOUT'
| 'PUBLISH_ROLLBACK_FAILED';
| 'PUBLISH_ROLLBACK_FAILED'
| 'INCOMPLETE_SNAPSHOT';
export interface CurateInputExportErrorOptions {
readonly code: CurateInputExportErrorCode;
@ -1319,7 +1320,7 @@ async function acquirePublishLock(
*/
export async function pinCurateInputSnapshot(
outDir: string,
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath'>
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath' | 'access'>
): Promise<PinnedCurateInputSnapshot> {
if (typeof outDir !== 'string' || outDir.trim().length === 0) {
throw new CurateInputExportError({
@ -1332,17 +1333,41 @@ export async function pinCurateInputSnapshot(
}
const normalizedOutDir = outDir.trim();
const fsRealpath = fsHooks?.realpath ?? realpath;
const fsAccess = fsHooks?.access ?? access;
const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK);
const generationDir = await fsRealpath(currentLink);
const generationId = basename(generationDir);
const providerMapping = join(generationDir, CURATE_INPUT_FILES.providerMapping);
const listingCurrencies = join(generationDir, CURATE_INPUT_FILES.listingCurrencies);
const listingVenues = join(generationDir, CURATE_INPUT_FILES.listingVenues);
const delistings = join(generationDir, CURATE_INPUT_FILES.delistings);
try {
await fsAccess(listingVenues);
} catch (error) {
if ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') {
throw new CurateInputExportError({
code: 'INCOMPLETE_SNAPSHOT',
table: 'publish',
key: generationId,
field: CURATE_INPUT_FILES.listingVenues,
detail:
`generation "${generationId}" under "${normalizedOutDir}" is missing ${CURATE_INPUT_FILES.listingVenues} ` +
'(legacy M1 three-file snapshot); re-run exportCurateInputs to refresh the export',
cause: error,
});
}
throw error;
}
return {
outDir: normalizedOutDir,
generationId,
generationDir,
providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping),
listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies),
listingVenues: join(generationDir, CURATE_INPUT_FILES.listingVenues),
delistings: join(generationDir, CURATE_INPUT_FILES.delistings),
providerMapping,
listingCurrencies,
listingVenues,
delistings,
};
}

View file

@ -134,6 +134,7 @@ export {
export {
assertExportRawBsonSafety,
DEFAULT_RAW_BSON_EXPORT_COLLECTIONS,
EXPORT_RAW_BSON_USAGE,
formatExportRawBsonSummary,
parseExportRawBsonArgs,
@ -147,6 +148,11 @@ export {
type RunExportRawBsonOutput,
} from './run-export-raw-bson';
export {
assertReadOnlyMongoDiagnosticSafety,
type ReadOnlyMongoDiagnosticSafetyOptions,
} from './read-only-mongo-safety';
export {
escapeSqlLiteral,
generateExchangeSeedSql,

View file

@ -2,12 +2,9 @@ import { mkdir, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety';
import {
DEFAULT_FIELD_SHAPE_LIMIT,
FIELD_SHAPE_PROBE_COLLECTIONS,
@ -280,28 +277,14 @@ export function assertProbeSourceFieldShapesSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
const mongo = config.database.mongodb;
if (!mongo.enabled) {
throw new Error('MongoDB is disabled in configuration; cannot probe source field shapes');
}
if (mongo.readOnly !== true) {
throw new Error(
'Source field-shape probe requires read-only MongoDB configuration (database.mongodb.readOnly === true)'
);
}
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
const mongoOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
postgres: {
...config.database.postgres,
enabled: false,
},
assertReadOnlyMongoDiagnosticSafety(
config,
{
operationLabel: 'probe source field shapes',
diagnosticLabel: 'Source field-shape probe',
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
env
);
}
export async function runCli(

View file

@ -0,0 +1,82 @@
import { assertEnvironmentSafety, type StockAppConfig } from '@stock-bot/stock-config';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
export interface ReadOnlyMongoDiagnosticSafetyOptions {
readonly operationLabel: string;
readonly diagnosticLabel: string;
}
/**
* Shared safety guard for strictly read-only MongoDB diagnostic CLIs
* (`probe-source-field-shapes` and `run-export-raw-bson`).
*
* Enforces:
* 1. MongoDB is enabled and configured with `readOnly === true`.
* 2. Environment safety for `dataPipeline` (with PostgreSQL disabled and
* `STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE` stripped).
* 3. The exact effective URI resolved by `resolveReadOnlyMongoClientConfig`
* (falling back from unset/blank `readUri` to `uri`) cannot target QA
* MongoDB with admin credentials (`trading_admin`), regardless of `NODE_ENV`.
*/
export function assertReadOnlyMongoDiagnosticSafety(
config: StockAppConfig,
options: ReadOnlyMongoDiagnosticSafetyOptions,
env: Record<string, string | undefined> = process.env
): void {
const mongo = config.database.mongodb;
if (!mongo.enabled) {
throw new Error(`MongoDB is disabled in configuration; cannot ${options.operationLabel}`);
}
if (mongo.readOnly !== true) {
throw new Error(
`${options.diagnosticLabel} requires read-only MongoDB configuration (database.mongodb.readOnly === true)`
);
}
const effectiveMongoConfig = resolveReadOnlyMongoClientConfig(config);
const effectiveUri = effectiveMongoConfig.uri;
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
const mongoOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
postgres: {
...config.database.postgres,
enabled: false,
},
mongodb: {
...mongo,
uri: effectiveUri ?? mongo.uri,
readUri: effectiveUri,
},
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
if (mongoOnlyConfig.environment !== 'development') {
try {
assertEnvironmentSafety(
{
...mongoOnlyConfig,
environment: 'development',
},
'dataPipeline',
safeEnv
);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
if (detail.includes('development data-pipeline')) {
throw new Error(
detail.replace(
'development data-pipeline',
`${config.environment} ${options.diagnosticLabel}`
),
{ cause: error }
);
}
throw error;
}
}
}

View file

@ -1,10 +1,6 @@
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import {
createReadOnlyMongoRawBsonSource,
DEFAULT_RAW_BSON_BATCH_SIZE,
@ -19,13 +15,32 @@ import {
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: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`,
` --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).',
@ -242,7 +257,7 @@ export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRaw
}
const resolvedCollections: readonly RawBsonExportCollection[] =
collections ?? [...RAW_BSON_EXPORT_COLLECTIONS];
collections ?? [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS];
if (eodSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
@ -275,28 +290,14 @@ export function assertExportRawBsonSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
const mongo = config.database.mongodb;
if (!mongo.enabled) {
throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections');
}
if (mongo.readOnly !== true) {
throw new Error(
'Raw BSON exporter requires read-only MongoDB configuration (database.mongodb.readOnly === true)'
);
}
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
const mongoOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
postgres: {
...config.database.postgres,
enabled: false,
},
assertReadOnlyMongoDiagnosticSafety(
config,
{
operationLabel: 'export raw BSON collections',
diagnosticLabel: 'Raw BSON exporter',
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
env
);
}
export function formatExportRawBsonSummary(