T-211: M2.2v — Export listing_venues.tsv and extend field-shape probe & BSON fixture exporter for M2 collections
This commit is contained in:
parent
ba20f9a2e5
commit
f05259a1ae
4 changed files with 202 additions and 7 deletions
|
|
@ -33,6 +33,7 @@ interface BenchContinuityRow {
|
|||
interface BenchListingRow {
|
||||
listing_id: number;
|
||||
currency: string;
|
||||
mic: string;
|
||||
listed_to: string | null;
|
||||
delist_reason: string | null;
|
||||
terminal_return: string | null;
|
||||
|
|
@ -75,14 +76,21 @@ function buildSyntheticTables(): {
|
|||
};
|
||||
}
|
||||
|
||||
const cadMics = ['XTSE', 'XTSX', 'XCNQ', 'NEOE'] as const;
|
||||
const usdMics = ['XNYS', 'XNAS', 'ARCX', 'XASE', 'BATS', 'OTCM', 'IEXG'] as const;
|
||||
const listings = new Array<BenchListingRow>(LISTING_COUNT);
|
||||
for (let i = 0; i < LISTING_COUNT; i++) {
|
||||
const id = i + 1;
|
||||
const currency = id % 5 === 0 ? 'CAD' : 'USD';
|
||||
const mic =
|
||||
currency === 'CAD'
|
||||
? cadMics[Math.floor(id / 5) % cadMics.length]!
|
||||
: usdMics[i % usdMics.length]!;
|
||||
if (id <= OTC_CONTINUITY_COUNT) {
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
mic,
|
||||
listed_to: '2023-03-10',
|
||||
delist_reason: 'moved_to_otc',
|
||||
terminal_return: null,
|
||||
|
|
@ -92,6 +100,7 @@ function buildSyntheticTables(): {
|
|||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
mic,
|
||||
listed_to: '2024-11-07',
|
||||
delist_reason: 'bankruptcy_cancelled',
|
||||
terminal_return: '-1.000000',
|
||||
|
|
@ -100,6 +109,7 @@ function buildSyntheticTables(): {
|
|||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
mic,
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
|
|
@ -110,6 +120,7 @@ function buildSyntheticTables(): {
|
|||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
mic,
|
||||
listed_to: missingDate ? null : '2023-06-15',
|
||||
delist_reason: 'unknown_involuntary',
|
||||
terminal_return: '-0.300000',
|
||||
|
|
@ -118,6 +129,7 @@ function buildSyntheticTables(): {
|
|||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
mic,
|
||||
listed_to: '2022-12-30',
|
||||
delist_reason: null,
|
||||
terminal_return: null,
|
||||
|
|
@ -126,6 +138,7 @@ function buildSyntheticTables(): {
|
|||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
mic,
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
|
|
@ -266,7 +279,10 @@ async function main(): Promise<void> {
|
|||
}
|
||||
|
||||
const totalRowsExported =
|
||||
result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut;
|
||||
result.providerMapping.rowsOut +
|
||||
result.listingCurrencies.rowsOut +
|
||||
result.listingVenues.rowsOut +
|
||||
result.delistings.rowsOut;
|
||||
const rowsPerSec = totalRowsExported / (elapsedMs / 1000);
|
||||
// process.resourceUsage().maxRSS is reported in KiB on Linux.
|
||||
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
|
||||
|
|
@ -276,7 +292,7 @@ async function main(): Promise<void> {
|
|||
` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n`
|
||||
);
|
||||
process.stdout.write(
|
||||
` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n`
|
||||
` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} listing_venues=${result.listingVenues.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n`
|
||||
);
|
||||
process.stdout.write(
|
||||
` total_rows_out=${totalRowsExported} bytes_written=${result.totalBytesWritten} elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(rowsPerSec)} rows/s peak_rss=${peakRssMiB.toFixed(2)} MiB\n`
|
||||
|
|
|
|||
|
|
@ -6,17 +6,88 @@ export interface ReadOnlyMongoDiagnosticSafetyOptions {
|
|||
readonly diagnosticLabel: string;
|
||||
}
|
||||
|
||||
const FORBIDDEN_DIAGNOSTIC_MONGO_USERNAMES: ReadonlySet<string> = new Set(['trading_admin']);
|
||||
|
||||
function hasAsciiControlChar(value: string): boolean {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const code = value.charCodeAt(i);
|
||||
if (code <= 0x1f || code === 0x7f) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractMongoUsernameFromUri(uri: string): string | undefined {
|
||||
if (hasAsciiControlChar(uri)) {
|
||||
throw new Error(
|
||||
'Safety guard: MongoDB URI contains forbidden whitespace or control characters.'
|
||||
);
|
||||
}
|
||||
const trimmed = uri.trim();
|
||||
if (!trimmed || /\s/.test(trimmed)) {
|
||||
throw new Error('Safety guard: MongoDB URI is empty or contains forbidden whitespace.');
|
||||
}
|
||||
|
||||
const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/is.exec(trimmed);
|
||||
const rest = schemeMatch?.[2];
|
||||
if (!schemeMatch?.[1] || rest === undefined) {
|
||||
throw new Error('Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.');
|
||||
}
|
||||
|
||||
const delimiterMatch = /[/?]/.exec(rest);
|
||||
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
|
||||
if (!authority) {
|
||||
throw new Error('Safety guard: MongoDB URI authority is empty.');
|
||||
}
|
||||
if (authority.includes('#')) {
|
||||
throw new Error(
|
||||
'Safety guard: MongoDB URI authority cannot contain an unencoded "#" character.'
|
||||
);
|
||||
}
|
||||
|
||||
const firstAtIndex = authority.indexOf('@');
|
||||
if (firstAtIndex === 0) {
|
||||
throw new Error('Safety guard: MongoDB URI authority cannot have empty userinfo before "@".');
|
||||
}
|
||||
if (firstAtIndex !== -1 && authority.indexOf('@', firstAtIndex + 1) !== -1) {
|
||||
throw new Error(
|
||||
'Safety guard: MongoDB URI authority cannot contain multiple unencoded "@" characters.'
|
||||
);
|
||||
}
|
||||
if (firstAtIndex < 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const userinfo = authority.slice(0, firstAtIndex);
|
||||
const colonIndex = userinfo.indexOf(':');
|
||||
const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo;
|
||||
if (!rawUsername) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
return decodeURIComponent(rawUsername);
|
||||
} catch (error) {
|
||||
if (error instanceof URIError) {
|
||||
throw new Error('Safety guard: invalid percent-encoding in MongoDB URI username.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* 2. The exact effective URI resolved by `resolveReadOnlyMongoClientConfig`
|
||||
* (falling back from unset/blank `readUri` to `uri`) cannot authenticate
|
||||
* as the QA admin principal (`trading_admin`), regardless of hostname
|
||||
* (localhost, Compose service `mongodb`, or remote) or `NODE_ENV`.
|
||||
* 3. 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,
|
||||
|
|
@ -35,6 +106,17 @@ export function assertReadOnlyMongoDiagnosticSafety(
|
|||
|
||||
const effectiveMongoConfig = resolveReadOnlyMongoClientConfig(config);
|
||||
const effectiveUri = effectiveMongoConfig.uri;
|
||||
const effectiveUsername =
|
||||
(effectiveUri ? extractMongoUsernameFromUri(effectiveUri) : undefined) ??
|
||||
effectiveMongoConfig.username?.trim();
|
||||
|
||||
if (effectiveUsername && FORBIDDEN_DIAGNOSTIC_MONGO_USERNAMES.has(effectiveUsername)) {
|
||||
throw new Error(
|
||||
`Safety guard: ${config.environment} ${options.diagnosticLabel} cannot connect to MongoDB ` +
|
||||
`with admin credentials ("${effectiveUsername}"). ` +
|
||||
'Configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) and enable mongoReadOnly: true.'
|
||||
);
|
||||
}
|
||||
|
||||
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
|
||||
const mongoOnlyConfig: StockAppConfig = {
|
||||
|
|
|
|||
|
|
@ -279,6 +279,40 @@ describe('assertExportRawBsonSafety', () => {
|
|||
expect(() => assertExportRawBsonSafety(qaAdminNoReadUri, {})).toThrow(/Safety guard/);
|
||||
expect(() => assertExportRawBsonSafety(qaAdminBlankReadUri, {})).toThrow(/Safety guard/);
|
||||
expect(() => assertExportRawBsonSafety(qaWithReadUri, {})).not.toThrow();
|
||||
|
||||
// QA Compose hostname (`mongodb`) with trading_admin (plain or percent-encoded) must also
|
||||
// be rejected regardless of NODE_ENV, while studio_stock_bot_read@mongodb is permitted.
|
||||
const qaComposeAdminNoReadUri = {
|
||||
...createBaseConfig({
|
||||
uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: undefined,
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
const qaComposeEncodedAdmin = {
|
||||
...createBaseConfig({
|
||||
uri: 'mongodb://trading%5Fadmin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: undefined,
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
const qaComposeWithReadUri = {
|
||||
...createBaseConfig({
|
||||
uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: 'mongodb://studio_stock_bot_read:pw@mongodb:27017/stock?authSource=stock',
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
|
||||
expect(() => assertExportRawBsonSafety(qaComposeAdminNoReadUri, {})).toThrow(/Safety guard/);
|
||||
expect(() => assertExportRawBsonSafety(qaComposeEncodedAdmin, {})).toThrow(/Safety guard/);
|
||||
expect(() => assertExportRawBsonSafety(qaComposeWithReadUri, {})).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -480,7 +514,7 @@ describe('runExportRawBson & runCli', () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('runCli rejects QA profile with no MONGODB_READ_URI before connecting to MongoDB', async () => {
|
||||
test('runCli rejects QA profile with no MONGODB_READ_URI (localhost and Compose mongodb hostname) before connecting to MongoDB', async () => {
|
||||
const createClientMock = mock(() => {
|
||||
throw new Error('createMongoClient must not be called when QA admin credentials are active');
|
||||
});
|
||||
|
|
@ -492,6 +526,15 @@ describe('runExportRawBson & runCli', () => {
|
|||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
const qaComposeAdminNoReadUri = {
|
||||
...createBaseConfig({
|
||||
uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: undefined,
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
|
||||
await expect(
|
||||
runCli(['--out-dir', '/tmp/unused-qa-bson', '--collections', 'eodPrices'], {
|
||||
|
|
@ -500,6 +543,13 @@ describe('runExportRawBson & runCli', () => {
|
|||
})
|
||||
).rejects.toThrow(/Safety guard/);
|
||||
|
||||
await expect(
|
||||
runCli(['--out-dir', '/tmp/unused-qa-compose-bson', '--collections', 'eodPrices'], {
|
||||
initializeConfig: (() => qaComposeAdminNoReadUri) as never,
|
||||
createMongoClient: createClientMock,
|
||||
})
|
||||
).rejects.toThrow(/Safety guard/);
|
||||
|
||||
expect(createClientMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1038,12 +1038,59 @@ describe('CLI arg parsing and headless probe runner', () => {
|
|||
);
|
||||
expect(() => assertProbeSourceFieldShapesSafety(qaWithReadUri, {})).not.toThrow();
|
||||
|
||||
// QA Compose hostname (`mongodb`) with trading_admin (plain or percent-encoded) must also
|
||||
// be rejected regardless of NODE_ENV, while studio_stock_bot_read@mongodb is permitted.
|
||||
const qaComposeAdminNoReadUri = {
|
||||
...createConfig({
|
||||
uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: undefined,
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
const qaComposeEncodedAdmin = {
|
||||
...createConfig({
|
||||
uri: 'mongodb://trading%5Fadmin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: undefined,
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
const qaComposeWithReadUri = {
|
||||
...createConfig({
|
||||
uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin',
|
||||
readUri: 'mongodb://studio_stock_bot_read:pw@mongodb:27017/stock?authSource=stock',
|
||||
readOnly: true,
|
||||
host: 'mongodb',
|
||||
}),
|
||||
environment: 'qa',
|
||||
} as unknown as StockAppConfig;
|
||||
|
||||
expect(() => assertProbeSourceFieldShapesSafety(qaComposeAdminNoReadUri, {})).toThrow(
|
||||
/Safety guard/
|
||||
);
|
||||
expect(() => assertProbeSourceFieldShapesSafety(qaComposeEncodedAdmin, {})).toThrow(
|
||||
/Safety guard/
|
||||
);
|
||||
expect(() => assertProbeSourceFieldShapesSafety(qaComposeWithReadUri, {})).not.toThrow();
|
||||
|
||||
await expect(
|
||||
runProbeSourceFieldShapesCli(['--out', './tmp/qa-blocked.md', '--collections', 'ceoPosts'], {
|
||||
initializeConfig: (() => qaAdminNoReadUri) as never,
|
||||
createMongoClient: clientNeverMock,
|
||||
})
|
||||
).rejects.toThrow(/Safety guard/);
|
||||
await expect(
|
||||
runProbeSourceFieldShapesCli(
|
||||
['--out', './tmp/qa-compose-blocked.md', '--collections', 'ceoPosts'],
|
||||
{
|
||||
initializeConfig: (() => qaComposeAdminNoReadUri) as never,
|
||||
createMongoClient: clientNeverMock,
|
||||
}
|
||||
)
|
||||
).rejects.toThrow(/Safety guard/);
|
||||
expect(clientNeverMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue