stock-bot/apps/stock/data-pipeline/scripts/phase1-inventory.ts
2026-11-26 10:22:21 -05:00

528 lines
28 KiB
TypeScript

import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { parseArgs, parseEnv } from 'node:util';
import { MongoClient, type Db, type Document } from 'mongodb';
import { Client } from 'pg';
const sources = ['qm', 'eod', 'ib', 'ceo'] as const;
type Source = typeof sources[number];
type Entity = 'stock' | 'exchange' | 'country' | 'other' | 'unclassified';
const entities: Record<string, Entity> = {
qmSymbols: 'stock', eodSymbols: 'stock', ibSymbols: 'stock', ceoSymbols: 'stock',
qmExchanges: 'exchange', eodExchanges: 'exchange', ibExchanges: 'exchange', ceoExchanges: 'exchange',
teCountries: 'country', teIndicators: 'country', teData: 'country', teMarketData: 'country',
qmDividends: 'other', qmEarnings: 'other', qmFilings: 'other', qmFinancials: 'other',
'qmFinancials-old': 'other', qmIntraday: 'other', qmPrices: 'other', qmSplits: 'other',
eodFinancialsOLD: 'other', eodFundamentalsOLD: 'other', eodIntraday1H: 'other',
eodIntraday1M: 'other', eodIntraday5M: 'other', eodPrices: 'other', eodSymbolChange: 'other',
ceoPosts: 'other', ceoShorts: 'other', teUrls: 'other', ttFutures: 'other',
};
const fields = ['ticker', 'exchange', 'isin', 'figi', 'cusip', 'name', 'country', 'currency', 'mic', 'conid', 'priority'] as const;
type Field = typeof fields[number];
type Aliases = Partial<Record<Field, string[]>>;
const qmId = (field: string) => [
field, 'profile.' + field, 'profile.info.' + field, 'profile.details.' + field,
'symbolInfo.' + field, 'symbolInfo.' + field.toUpperCase(),
];
const aliases: Record<string, Aliases> = {
qmSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'],
isin: qmId('isin'), cusip: qmId('cusip'), figi: qmId('figi'), currency: qmId('currency') },
eodSymbols: { ticker: ['Code'], exchange: ['eodExchange', 'Exchange'], isin: ['Isin', 'ISIN'],
name: ['Name'], country: ['Country'], currency: ['Currency'], cusip: ['Cusip'], figi: ['FIGI', 'Figi'] },
ibSymbols: { ticker: ['localSymbol', 'symbol'], exchange: ['exchangeId', 'exchange_id'], isin: ['isin'],
cusip: ['cusip'], figi: ['figi'], conid: ['conid'], name: ['description'], country: ['country'], currency: ['currency'] },
ceoSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'],
currency: ['currency'], isin: ['isin'], cusip: ['cusip'], figi: ['figi'] },
qmExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'],
currency: ['currency'], mic: ['operatingMIC', 'mic'], priority: ['priority'] },
eodExchanges: { exchange: ['Code'], mic: ['OperatingMIC'], country: ['CountryISO2', 'Country'],
currency: ['Currency'], name: ['Name'] },
ibExchanges: { exchange: ['exchange_id', 'id'], country: ['country_code', 'country'], name: ['name'],
currency: ['currency'], mic: ['operatingMIC', 'mic'] },
ceoExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'],
currency: ['currency'], mic: ['operatingMIC', 'mic'] },
};
const requiredFields = fields.slice(0, 8);
const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
const upper = (value: string) => value.toUpperCase();
const sourceOf = (name: string) => /^(qm|eod|ib|ceo|te|tt)(?=[A-Z])/.exec(name)?.[1] ?? 'other';
const tupleKey = (...parts: string[]) => parts.join('\u0000');
const text = (value: unknown) => typeof value === 'string' ? value.trim() :
typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
function assertReadStages(value: unknown): void {
if (!value || typeof value !== 'object') return;
for (const [key, child] of Object.entries(value)) {
if (key === '$' + 'out' || key === '$' + 'merge') throw Error('Aggregation stage is forbidden');
assertReadStages(child);
}
}
function mongoReads(db: Db) {
return {
listCollections: () => db.listCollections({}, { nameOnly: true }).toArray(),
estimatedDocumentCount: (name: string) => db.collection(name).estimatedDocumentCount(),
countDocuments: (name: string) => db.collection(name).countDocuments({}),
find: (name: string, filter: Document = {}) => ({
limit: (n: number) => {
if (!Number.isSafeInteger(n) || n < 1 || n > 2) throw Error('Expected a bounded example query');
return db.collection(name).find(filter).sort({ _id: 1 }).limit(n).toArray();
},
}),
aggregate: (name: string, stages: Document[]) => {
assertReadStages(stages);
return db.collection(name).aggregate(stages, { batchSize: 2_000 });
},
listIndexes: (name: string) => db.collection(name).listIndexes().toArray(),
runCommand: (command: { usersInfo: 1 }) => {
if (Object.keys(command).length !== 1 || command.usersInfo !== 1) throw Error('Expected usersInfo');
return db.command(command, { readPreference: 'primary' });
},
};
}
type MongoReads = ReturnType<typeof mongoReads>;
type User = { user: string; db: string; roles: { role: string; db: string }[] };
const readOnly = (user: User) => user.roles.length > 0 &&
user.roles.every(({ role }) => role === 'read' || role === 'readAnyDatabase');
const canRead = (user: User, db: string) => user.roles.some(role => role.role === 'readAnyDatabase' || role.db === db);
async function mongoUsers(client: MongoClient, name: string) {
const results = await Promise.all(['admin', name].map(db => mongoReads(client.db(db)).runCommand({ usersInfo: 1 })));
const users: User[] = results.flatMap(result => result.users.map(({ user, db, roles }: User) => ({ user, db, roles })));
return [...new Map(users.map(user => [tupleKey(user.db, user.user), user])).values()]
.sort((a, b) => cmp(tupleKey(a.db, a.user), tupleKey(b.db, b.user)));
}
function safeMongoUri(raw: string) {
const uri = new URL(raw);
if (!['localhost', '127.0.0.1', '[::1]'].includes(uri.hostname)) throw Error('Expected a local MongoDB host');
return uri;
}
async function mongoReadUri(rootUri: string, name: string, users: User[], env: Partial<Record<string, string>>) {
const available = users.filter(user => readOnly(user) && canRead(user, name));
if (!available.length) return rootUri;
const studioEnv = Bun.file(join(homedir(), '.studio', 'test-env', 'stock-bot.env'));
const candidates = [env.PHASE1_MONGO_READ_URI, rootUri, await studioEnv.exists()
? parseEnv(await studioEnv.text()).MONGODB_URI : undefined];
for (const raw of candidates) {
if (!raw) continue;
const uri = safeMongoUri(raw), username = decodeURIComponent(uri.username);
const authDb = uri.searchParams.get('authSource') ?? (uri.pathname.slice(1) || 'admin');
if (available.some(user => user.user === username && user.db === authDb)) return raw;
}
throw Error('A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI');
}
function trimmed(doc: Document) {
return Object.fromEntries(Object.entries(doc).map(([key, value]) => {
if (Array.isArray(value)) return [key, { length: value.length, keys: [...new Set(value.slice(0, 5).flatMap(v =>
v && typeof v === 'object' ? Object.keys(v) : []))].sort(cmp) }];
if (value && Object.getPrototypeOf(value) === Object.prototype) return [key, { keys: Object.keys(value).sort(cmp) }];
return [key, typeof value === 'string' && value.length > 180 ? value.slice(0, 180) + '…' : value];
}));
}
function expression(path: string) {
return { $trim: { input: { $convert: { input: '$' + path, to: 'string', onError: '', onNull: '' } } } };
}
const limitStages = (limit: number | null) => limit === null ? [] : [{ $limit: limit }];
async function fieldCoverage(mongo: MongoReads, name: string, mapping: Aliases, limit: number | null) {
const names = fields.filter(field => requiredFields.includes(field) || mapping[field]);
const group = Object.fromEntries(names.map(field => [field, { $sum: { $cond: [
mapping[field]?.length ? { $or: mapping[field]!.map(path => ({ $ne: [expression(path), ''] })) } : false, 1, 0,
] } }]));
const [counts] = await mongo.aggregate(name, [...limitStages(limit),
{ $group: { _id: null, total: { $sum: 1 }, ...group } }]).toArray();
const total = Number(counts?.total ?? 0);
return { total, aliases: mapping, fields: Object.fromEntries(names.map(field => {
const filled = Number(counts?.[field] ?? 0);
return [field, { filled, fraction: total ? filled / total : 0 }];
})) };
}
async function inventory(mongo: MongoReads, limit: number | null, sampleMemory: () => void) {
const collections = [];
const fillRates: Record<string, Awaited<ReturnType<typeof fieldCoverage>>> = {};
const examples: Partial<Record<Entity, { collection: string; document: Document }[]>> = {};
const group: Record<string, string[]> = {};
for (const row of (await mongo.listCollections()).sort((a, b) => cmp(a.name, b.name))) {
const name = row.name, source = sourceOf(name), entity = entities[name] ?? 'unclassified';
const estimatedDocumentCount = await mongo.estimatedDocumentCount(name);
const countDocuments = estimatedDocumentCount < 1_000_000 ? await mongo.countDocuments(name) : null;
const indexes = (await mongo.listIndexes(name)).map(index => String(index.name)).sort(cmp);
const keyRows = await mongo.aggregate(name, [
{ $sample: { size: 200 } },
{ $project: { _id: 0, keys: { $map: { input: { $objectToArray: '$$ROOT' }, as: 'field', in: '$$field.k' } } } },
]).toArray();
const topLevelKeys = [...new Set<string>(keyRows.flatMap(value => value.keys))].sort(cmp);
(group[source] ??= []).push(name);
collections.push({ name, source, entity, estimatedDocumentCount, countDocuments, indexes, topLevelKeys });
const seen = examples[entity] ??= [];
if (seen.length < 2 && estimatedDocumentCount) {
for (const document of await mongo.find(name).limit(2 - seen.length)) seen.push({ collection: name, document: trimmed(document) });
}
if (aliases[name]) fillRates[name] = await fieldCoverage(mongo, name, aliases[name], limit);
sampleMemory();
console.error('Inspected ' + name);
}
return { collections, groups: group, examples, fillRates };
}
const tables = [
'exchanges', 'symbols', 'provider_mappings', 'provider_exchange_mappings', 'sync_status',
'master_exchanges', 'master_symbols', 'provider_symbol_mappings',
] as const;
type Mapping = { provider: string; code: string; master: string | null; verified: boolean | null; auto: boolean | null };
async function readPostgres(client: Client) {
await client.connect();
await client.query('BEGIN TRANSACTION READ ONLY');
try {
const counts: Record<string, number | 'missing'> = {};
for (const table of tables) {
const { rows: [row] } = await client.query('SELECT to_regclass($1) IS NOT NULL AS present', ['public.' + table]);
counts[table] = row.present
? Number((await client.query('SELECT count(*) AS total FROM public.' + table)).rows[0].total) : 'missing';
}
const present = (table: string) => counts[table] !== 'missing';
const rows = async (sql: string) => (await client.query(sql)).rows;
const exchangeStatus = present('provider_exchange_mappings') ? await rows(`
SELECT provider, master_exchange_id IS NOT NULL AS mapped, verified, active, auto_mapped, count(*)::int AS total
FROM public.provider_exchange_mappings GROUP BY 1,2,3,4,5 ORDER BY 1,2,3,4,5`) : [];
const symbolStatus = present('provider_mappings') ? await rows(`
SELECT provider, verified, count(*)::int AS total
FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : [];
const confidence = present('provider_mappings') ? await rows(`
SELECT provider, confidence, count(*)::int AS total
FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : [];
const mapping: Mapping[] = present('provider_exchange_mappings') ? await rows(`
SELECT provider, provider_exchange_code AS code, master_exchange_id AS master,
verified, auto_mapped AS auto FROM public.provider_exchange_mappings
ORDER BY provider, provider_exchange_code`) : [];
return { counts, exchangeStatus, symbolStatus, confidence, mapping };
} finally {
await client.query('ROLLBACK');
}
}
function mappingIndex(mapping: Mapping[]) {
const result = new Map<string, Mapping>();
for (const row of mapping) {
const key = tupleKey(row.provider.toLowerCase(), upper(row.code.trim())), previous = result.get(key);
if (previous?.master && row.master && previous.master !== row.master)
throw Error('Conflicting master exchange mappings for a normalized provider code');
if (!previous || row.master) result.set(key, row);
}
return result;
}
function pathValue(document: Document, path: string): unknown {
return path.split('.').reduce<unknown>((parent, key) =>
parent && typeof parent === 'object' ? (parent as Document)[key] : undefined, document);
}
function identifiers(document: Document, mapping: Aliases) {
return Object.fromEntries(fields.map(field => [field, mapping[field]?.map(path => text(pathValue(document, path))).find(Boolean) ?? ''])) as Record<Field, string>;
}
function projection(mapping: Aliases) {
return Object.fromEntries(Object.values(mapping).flat().map(path => [path, 1]));
}
function validIsin(value: string) {
if (!/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/.test(value)) return false;
const digits = value.replace(/[A-Z]/g, letter => String(letter.charCodeAt(0) - 55));
let total = 0;
for (let i = digits.length - 1; i >= 0; i--) {
const n = Number(digits[i]) * ((digits.length - i) % 2 ? 1 : 2);
total += n > 9 ? n - 9 : n;
}
return total % 10 === 0;
}
const venues = 'US|CA|NASDAQ|NYSE|AMEX|NYSEARCA|TSX|TSE|TSXV|CSE|OTC';
const prefix = new RegExp('^(?:' + venues + '):');
const suffix = new RegExp(':(?:' + venues + ')$');
function tickerKey(raw: string) {
const rules: string[] = [];
let key = raw;
for (const [rule, pattern, replacement] of [
['case', /[a-z]/, upper(key)],
['venue_prefix', prefix, ''],
['venue_suffix', suffix, ''],
['us_dot_suffix', /\.US$/, ''],
['share_class_separator', /^([A-Z0-9]+)[ /-]([A-Z])$/, '$1.$2'],
['share_class_dot', /^[A-Z0-9]+\.[A-Z]$/, null],
] as const) {
if (!pattern.test(key)) continue;
rules.push(rule);
if (replacement !== null) key = rule === 'case' ? replacement : key.replace(pattern, replacement);
}
return { key, rules };
}
function countryKey(value: string) {
const code = upper(value);
return ({ USA: 'US', 'UNITED STATES': 'US', 'UNITED STATES OF AMERICA': 'US', CAN: 'CA', CANADA: 'CA',
GBR: 'GB', UK: 'GB', 'UNITED KINGDOM': 'GB', AUS: 'AU', AUSTRALIA: 'AU' } as Record<string, string>)[code] ?? code;
}
const words = (name: string) => new Set(name.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) ?? []);
function similar(a: string, b: string) {
if (!a || !b) return false;
if (a === b) return true;
const one = words(a), two = words(b);
let common = 0;
for (const token of one) if (two.has(token)) common++;
return common > 0 && common / (one.size + two.size - common) >= 0.8;
}
type Stock = [source: Source, id: unknown, exact: string, ticker: string, exchange: string, master: string,
rawIsin: string, isin: string, cusip: string, figi: string, name: string, country: string, currency: string];
type Index = Map<string, number[]>;
const add = (index: Index, key: string, id: number) => {
if (!key) return;
const ids = index.get(key);
if (ids) ids.push(id);
else index.set(key, [id]);
};
const marketKey = (ticker: string, market: string) => ticker && market ? tupleKey(ticker, market) : '';
const stocksFor = (source: Source) => source + 'Symbols';
const exchangeFor = (source: Source) => source + 'Exchanges';
async function gatherStocks(mongo: MongoReads, names: Set<string>, mapping: Map<string, Mapping>, limit: number | null, memory: () => void) {
const records: Stock[] = [];
const indices = { isin: new Map() as Index, cusip: new Map() as Index, figi: new Map() as Index,
markets: new Map() as Index, rawMarkets: new Map() as Index, currency: new Map() as Index, rawCurrency: new Map() as Index,
tickers: new Map() as Index };
const counts = Object.fromEntries(sources.map(source => [source, {
noExchangeCode: 0, mappingMissing: 0, mappingHasNullMaster: 0, hasMaster: 0,
normalizations: {} as Record<string, number>,
}])) as Record<Source, { noExchangeCode: number; mappingMissing: number; mappingHasNullMaster: number; hasMaster: number; normalizations: Record<string, number> }>;
for (const source of sources) {
const name = stocksFor(source);
if (!names.has(name)) continue;
const rules = aliases[name], stats = counts[source];
for await (const row of mongo.aggregate(name, [{ $project: projection(rules) }, ...limitStages(limit)])) {
const id = identifiers(row, rules), rawIsin = upper(id.isin);
const isin = validIsin(rawIsin) ? rawIsin : '';
const cusip = /^[0-9A-Z*@#]{9}$/.test(upper(id.cusip)) ? upper(id.cusip) : /^(US|CA)/.test(isin) ? isin.slice(2, 11) : '';
const figi = /^[A-Z0-9]{12}$/.test(upper(id.figi)) ? upper(id.figi) : '';
const exchange = upper(id.exchange), mapped = mapping.get(tupleKey(source, exchange));
if (!exchange) stats.noExchangeCode++;
else if (!mapped) stats.mappingMissing++;
else if (!mapped.master) stats.mappingHasNullMaster++;
else stats.hasMaster++;
const { key: ticker, rules: applied } = tickerKey(id.ticker);
for (const rule of applied) stats.normalizations[rule] = (stats.normalizations[rule] ?? 0) + 1;
const master = mapped?.master ?? '', currency = upper(id.currency);
const n = records.length;
records.push([source, row._id, id.ticker, ticker, exchange, master, rawIsin, isin, cusip, figi, id.name, countryKey(id.country), currency]);
add(indices.isin, isin, n);
add(indices.cusip, cusip, n);
add(indices.figi, figi, n);
add(indices.tickers, ticker, n);
add(indices.markets, marketKey(ticker, master), n);
add(indices.rawMarkets, marketKey(id.ticker, master), n);
if (master && id.name) {
add(indices.currency, marketKey(ticker, currency), n);
add(indices.rawCurrency, marketKey(id.ticker, currency), n);
}
if (n % 2048 === 0) memory();
}
console.error('Projected ' + name);
}
return { records, indices, counts };
}
type StockData = Awaited<ReturnType<typeof gatherStocks>>;
const tally = () => ({ total: 0, strong: 0, weak_only: 0, unmatched: 0, exact_after_trim: 0, normalized: 0 });
type Tally = ReturnType<typeof tally>;
const sourceBit = Object.fromEntries(sources.map((source, n) => [source, 1 << n])) as Record<Source, number>;
function hitBits(records: Stock[], ids: number[] | undefined, source: Source, predicate?: (record: Stock) => boolean) {
let bits = 0;
for (const id of ids ?? []) {
const other = records[id];
if (other[0] !== source && (!predicate || predicate(other))) bits |= sourceBit[other[0]];
}
return bits;
}
function countRecord(counts: Tally, mask: number, strong: number, exact: number, normal: number) {
counts.total++;
if (strong & mask) { counts.strong++; return; }
if (exact & mask) counts.exact_after_trim++;
if (normal & mask) counts.normalized++;
if ((exact | normal) & mask) counts.weak_only++;
else counts.unmatched++;
}
function measureStocks(data: StockData, memory: () => void) {
const { records, indices, counts: coverage } = data;
const bySource = Object.fromEntries(sources.map(source => [source, tally()])) as Record<Source, Tally>;
const byPair: Record<string, Tally> = {};
for (const source of sources) for (const target of sources) if (source !== target) byPair[source + '→' + target] = tally();
for (let i = 0; i < records.length; i++) {
const [source, , raw, ticker, , master, , isin, cusip, figi, name, , currency] = records[i];
const hits = (index: Index, key: string) => key ? hitBits(records, index.get(key), source) : 0;
const strong = hits(indices.isin, isin) | hits(indices.cusip, cusip) | hits(indices.figi, figi);
const compareName = (row: Stock) => similar(name, row[10]);
const nameHits = (index: Index, ticker: string) => master && name && ticker && currency
? hitBits(records, index.get(marketKey(ticker, currency)), source, compareName) : 0;
const exact = hits(indices.rawMarkets, marketKey(raw, master)) | nameHits(indices.rawCurrency, raw);
const normal = hits(indices.markets, marketKey(ticker, master)) | nameHits(indices.currency, ticker);
countRecord(bySource[source], 15, strong, exact, normal);
for (const target of sources) if (source !== target)
countRecord(byPair[source + '→' + target], sourceBit[target], strong, exact, normal);
if (i % 2048 === 0) memory();
}
return { bySource, byPair, mappingCoverage: coverage };
}
async function measureExchanges(mongo: MongoReads, names: Set<string>, mapping: Map<string, Mapping>, limit: number | null) {
const codes = new Map<string, { source: Source; code: string; mic: string; country: string; name: string }>();
for (const source of sources) {
const collection = exchangeFor(source), rules = aliases[collection];
if (!names.has(collection)) continue;
for await (const row of mongo.aggregate(collection, [{ $project: projection(rules) }, ...limitStages(limit)])) {
const fields = identifiers(row, rules), code = upper(fields.exchange);
if (code) codes.set(tupleKey(source, code),
{ source, code, mic: upper(fields.mic), country: countryKey(fields.country), name: fields.name });
}
}
const rows = [...codes.values()];
return Object.fromEntries(sources.map(source => {
const counts = { total: 0, strong: 0, mappedVerified: 0, mappedAuto: 0, mappedOther: 0, weak_only: 0, unmatched: 0 };
for (const row of rows.filter(value => value.source === source)) {
counts.total++;
const mapped = mapping.get(tupleKey(source, row.code));
if (mapped?.master) {
counts.strong++;
if (mapped.verified) counts.mappedVerified++;
else if (mapped.auto) counts.mappedAuto++;
else counts.mappedOther++;
} else if (rows.some(peer => peer.source !== source &&
((row.mic && !/^(X{4}|N\/A|-)$/.test(row.mic) && peer.mic === row.mic) ||
(row.country && peer.country === row.country && similar(row.name, peer.name))))) counts.weak_only++;
else counts.unmatched++;
}
return [source, counts];
}));
}
type Pair = [number, number];
type Case = { bucket: string; key: string; ids: number[] };
const different = (a: string, b: string) => !!a && !!b && a !== b;
function trickySelection({ records, indices }: StockData) {
const cases: Case[] = [];
const idOrder = (a: number, b: number) => cmp(records[a][0], records[b][0]) || cmp(String(records[a][1]), String(records[b][1]));
const pair = (list: number[], test: (a: Stock, b: Stock) => boolean): Pair | undefined => {
if (list.length < 2) return;
const ordered = [...list].sort(idOrder);
for (let i = 0; i < ordered.length; i++) for (let j = i + 1; j < ordered.length; j++) {
const a = ordered[i], b = ordered[j];
if (records[a][0] !== records[b][0] && test(records[a], records[b])) return [a, b];
}
};
const grouped = (bucket: string, index: Index, test: (a: Stock, b: Stock) => boolean) => {
let count = 0;
for (const key of [...index.keys()].sort(cmp)) {
const ids = pair(index.get(key)!, test);
if (!ids) continue;
cases.push({ bucket, key: key.replaceAll('\u0000', ' / '), ids });
if (++count === 5) break;
}
};
grouped('isin_currency_or_country_conflict', indices.isin, (a, b) => different(a[11], b[11]) || different(a[12], b[12]));
grouped('isin_ticker_variation', indices.isin, (a, b) => different(a[2], b[2]));
grouped('share_class_format', indices.tickers, (a, b) =>
/^[A-Z0-9]+\.[A-Z]$/.test(a[3]) && different(a[2], b[2]) && [a[2], b[2]].some(value => /[ /-][A-Z]$/i.test(value)));
grouped('dual_master_exchanges', indices.isin, (a, b) => different(a[5], b[5]));
grouped('ticker_exchange_conflicting_isins', indices.markets, (a, b) => different(a[7], b[7]));
const invalid = records.flatMap((row, id) => row[6] && !row[7] ? [id] : [])
.sort((a, b) => cmp(records[a][6], records[b][6]) || cmp(records[a][2], records[b][2]) || idOrder(a, b));
for (const id of invalid.slice(0, 5)) cases.push({ bucket: 'invalid_isin', key: records[id][6], ids: [id] });
return cases;
}
async function trickyDocuments(mongo: MongoReads, data: StockData) {
const output = [];
for (const { bucket, key, ids } of trickySelection(data)) {
const documents = [];
for (const i of ids) {
const [source, _id, ticker, normalizedTicker, , master] = data.records[i], collection = stocksFor(source);
const [doc] = await mongo.find(collection, { _id }).limit(1);
if (!doc) throw Error('A selected fixture disappeared during the inventory');
documents.push({ collection, _id, ticker, normalizedTicker, resolvedMasterExchangeId: master || null, document: trimmed(doc) });
}
output.push({ bucket, key, documents });
}
return output;
}
async function main() {
const started = performance.now(), generatedAt = new Date().toISOString();
let peakRSS = 0;
const memory = () => { peakRSS = Math.max(peakRSS, process.memoryUsage.rss(), process.resourceUsage().maxRSS * 1024); };
memory();
const args = parseArgs({ options: { 'sample-limit': { type: 'string' } } });
const limit = args.values['sample-limit'] === undefined ? null : Number(args.values['sample-limit']);
if (limit !== null && (!Number.isSafeInteger(limit) || limit < 1)) throw Error('Expected a positive sample limit');
const env = parseEnv(await Bun.file(resolve(import.meta.dir, '../../../../.env')).text());
const rootUri = env.MONGODB_URI;
if (!rootUri) throw Error('Missing MONGODB_URI');
const parsed = safeMongoUri(rootUri), name = env.MONGODB_DATABASE || parsed.pathname.slice(1) || 'stock';
const host = env.POSTGRES_HOST;
if (!host || !['localhost', '127.0.0.1', '::1'].includes(host)) throw Error('Expected a local Postgres host');
const metadata = new MongoClient(rootUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 });
const pg = new Client({
host, port: Number(env.POSTGRES_PORT || 5432), database: env.POSTGRES_DATABASE,
user: env.POSTGRES_USERNAME, password: env.POSTGRES_PASSWORD, connectionTimeoutMillis: 5_000,
});
let reader: MongoClient | undefined;
try {
await metadata.connect();
const users = await mongoUsers(metadata, name);
const readUri = await mongoReadUri(rootUri, name, users, env), active = safeMongoUri(readUri);
let dbClient = metadata;
if (readUri !== rootUri) {
reader = new MongoClient(readUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 });
await reader.connect();
dbClient = reader;
}
const mongo = mongoReads(dbClient.db(name));
const { mapping: rows, ...postgres } = await readPostgres(pg);
const mapping = mappingIndex(rows);
const { collections, groups, examples, fillRates } = await inventory(mongo, limit, memory);
const names = new Set(collections.map(collection => collection.name));
const data = await gatherStocks(mongo, names, mapping, limit, memory);
const stocks = measureStocks(data, memory);
const exchanges = await measureExchanges(mongo, names, mapping, limit);
const trickyCases = await trickyDocuments(mongo, data);
memory();
console.log(JSON.stringify({
generatedAt,
mongo: { uriMasked: active.protocol + '//***:***@' + active.host + '/' + name,
db: name, users, readOnlyUserExists: users.some(readOnly), collectionLogin: readUri === rootUri ? 'configured' : 'read-only' },
collections, sources: { collections: groups, examples }, fillRates, postgres, matching: { stocks, exchanges },
trickyCases, sampleLimit: limit, runtimeMs: Math.round(performance.now() - started), peakRssMb: Math.round(peakRSS / 1048576),
}));
} finally {
await Promise.allSettled([metadata.close(), pg.end(), reader?.close()]);
}
}
await main().catch(error => {
const safeMessages = ['Aggregation stage is forbidden', 'Expected a bounded example query', 'Expected usersInfo',
'Expected a local MongoDB host', 'Expected a local Postgres host', 'Missing MONGODB_URI', 'Expected a positive sample limit',
'A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI',
'Conflicting master exchange mappings for a normalized provider code', 'A selected fixture disappeared during the inventory'];
console.error('Inventory failed: ' + (safeMessages.includes(error?.message) ? error.message :
String(error?.name || 'Error') + (error?.code ? ' (' + String(error.code) + ')' : '')));
process.exitCode = 1;
});