import { randomUUID } from 'node:crypto'; import { access, lstat, mkdir, open, readlink, realpath, rename, rm, rmdir, symlink, unlink, type FileHandle, } from 'node:fs/promises'; import { basename, join } from 'node:path'; import { compareAscii } from './exchange-pass1'; import type { SecurityMasterQueryable } from './persist'; export const CURATE_INPUT_FILES = Object.freeze({ providerMapping: 'provider_mapping.tsv', listingCurrencies: 'listing_currencies.tsv', listingVenues: 'listing_venues.tsv', delistings: 'delistings.tsv', } as const); export const LISTING_STATUTORY_LAG_VENUES = Object.freeze(['us_tsx', 'tsxv_cse'] as const); export type ListingStatutoryLagVenue = (typeof LISTING_STATUTORY_LAG_VENUES)[number]; /** * Maps ISO 10383 exchange MICs in `ISO_EXCHANGE_SEEDS` to `curate-fundamentals` statutory-lag * classes (`us_tsx`: +45d quarterly / +90d annual; `tsxv_cse`: +60d quarterly / +120d annual). */ export const LISTING_VENUE_BY_MIC: Readonly> = Object.freeze( { ARCX: 'us_tsx', BATS: 'us_tsx', IEXG: 'us_tsx', NEOE: 'us_tsx', OTCM: 'us_tsx', XASE: 'us_tsx', XCNQ: 'tsxv_cse', XNAS: 'us_tsx', XNYS: 'us_tsx', XTSE: 'us_tsx', XTSX: 'tsxv_cse', } ); export const CURATE_INPUT_GENERATIONS_DIR = 'generations'; export const CURATE_INPUT_CURRENT_LINK = 'current'; export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock'; export const DEFAULT_EXPORT_CHUNK_SIZE = 5000; export const MAX_EXPORT_CHUNK_SIZE = 5000; export const DEFAULT_DELISTING_MAPPING_SOURCE = 'qm'; export const DEFAULT_PUBLISH_LOCK_TIMEOUT_MS = 30_000; const PUBLISH_LOCK_RETRY_MS = 5; const PROVIDER_MAPPING_CURSOR_NAME = 'curate_export_pm_cursor'; const MAX_PG_INT4 = 2_147_483_647; const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; const STRICT_DECIMAL_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; export type CurateInputExportErrorCode = | 'INVALID_OPTION' | 'INVALID_CLIENT' | 'FORBIDDEN_CONTROL_CHAR' | 'BLANK_FIELD' | 'INVALID_LISTING_ID' | 'INVALID_DATE' | 'INVALID_DATE_RANGE' | 'DUPLICATE_PROVIDER_MAPPING' | 'OVERLAPPING_PROVIDER_MAPPING' | 'UNSORTED_PROVIDER_MAPPING_STREAM' | 'DUPLICATE_LISTING_CURRENCY' | 'UNKNOWN_LISTING_MIC' | 'INVALID_LISTING_VENUE' | 'DUPLICATE_LISTING_VENUE' | 'UNSORTED_LISTING_STREAM' | 'INVALID_TERMINAL_RETURN' | 'INVALID_DELISTING_OUTCOME' | 'MISSING_FROM_LISTING_ID' | 'ACTIVE_LISTING_WITH_OUTCOME' | 'SELF_SUCCESSOR_CONTINUITY' | 'DUPLICATE_OTC_CONTINUITY' | 'OUT_OF_ORDER_CONTINUITY_STREAM' | 'PUBLISH_LOCK_TIMEOUT' | 'PUBLISH_ROLLBACK_FAILED' | 'INCOMPLETE_SNAPSHOT'; export interface CurateInputExportErrorOptions { readonly code: CurateInputExportErrorCode; readonly table: string; readonly key: string; readonly field?: string; readonly detail: string; readonly cause?: unknown; } export class CurateInputExportError extends Error { readonly code: CurateInputExportErrorCode; readonly table: string; readonly key: string; readonly field?: string; constructor(options: CurateInputExportErrorOptions) { const fieldPart = options.field !== undefined ? ` field=${options.field}` : ''; super( `[${options.code}] ${options.table} (${options.key})${fieldPart}: ${options.detail}`, options.cause !== undefined ? { cause: options.cause } : undefined ); this.name = 'CurateInputExportError'; this.code = options.code; this.table = options.table; this.key = options.key; if (options.field !== undefined) { this.field = options.field; } } } export interface ProviderMappingExportRow { readonly source: string; readonly sourceId: string; readonly validFrom: string; readonly validTo: string | null; readonly listingId: number; } export interface ListingCurrencyExportRow { readonly listingId: number; readonly currency: string; } export interface ListingVenueExportRow { readonly listingId: number; readonly venue: ListingStatutoryLagVenue; } export interface DelistingExportRow { readonly sourceId: string; readonly delistDate: string; readonly fromListingId: number | null; readonly successorSourceId: string | null; readonly terminalReturn: number | string | null; } export interface ListingDelistingSourceRow { readonly listingId: number; readonly listedTo: string | null; readonly delistReason: string | null; readonly terminalReturn: number | string | null; } export interface ContinuityExportSourceRow { readonly fromListingId: number; readonly toListingId: number; readonly effectiveDate: string; readonly kind: string; } export interface BuildDelistingExportRowsOptions { readonly mappingSource?: string; } export interface DelistingExportSkippedByReason { readonly active: number; readonly noOutcome: number; readonly missingListedTo: number; readonly missingOutgoingQmMapping: number; readonly missingSuccessorQmMapping: number; readonly nonOtcContinuity: number; } export interface DelistingExportStats { readonly rowsIn: number; readonly rowsOut: number; readonly otcTransfersOut: number; readonly terminalDelistingsOut: number; readonly skippedTotal: number; readonly skipped: DelistingExportSkippedByReason; } export interface BuildDelistingExportRowsResult { readonly rows: readonly DelistingExportRow[]; readonly stats: DelistingExportStats; } export interface ExportCurateInputsFsHooks { readonly mkdir?: typeof mkdir; readonly open?: typeof open; readonly rename?: typeof rename; readonly unlink?: typeof unlink; readonly access?: typeof access; readonly lstat?: typeof lstat; readonly readlink?: typeof readlink; readonly symlink?: typeof symlink; readonly realpath?: typeof realpath; readonly rm?: typeof rm; readonly rmdir?: typeof rmdir; } export interface ExportCurateInputsOptions { readonly outDir: string; readonly chunkSize?: number; readonly delistingMappingSource?: string; readonly publishLockTimeoutMs?: number; readonly fs?: ExportCurateInputsFsHooks; } export interface ExportCurateInputsFileStats { readonly path: string; readonly rowsIn: number; readonly rowsOut: number; readonly bytesWritten: number; } export interface PinnedCurateInputSnapshot { readonly outDir: string; readonly generationId: string; readonly generationDir: string; readonly providerMapping: string; readonly listingCurrencies: string; readonly listingVenues: string; readonly delistings: string; } export interface ExportCurateInputsResult { readonly outDir: string; readonly generationId: string; readonly generationDir: string; readonly currentLink: string; readonly chunkSize: number; readonly delistingMappingSource: string; readonly providerMapping: ExportCurateInputsFileStats; readonly listingCurrencies: ExportCurateInputsFileStats; readonly listingVenues: ExportCurateInputsFileStats; readonly delistings: ExportCurateInputsFileStats & { readonly stats: DelistingExportStats; }; readonly totalBytesWritten: number; readonly cleanupWarnings: readonly string[]; } interface QmListingMappingRange { readonly sourceId: string; readonly validFrom: string; readonly validTo: string | null; readonly listingId: number; } interface ValidatedDelistingRow { readonly sourceId: string; readonly delistDate: string; readonly fromListingId: number | null; readonly successorSourceId: string | null; readonly formattedTerminalReturn: string; } interface DbContinuityRow { from_listing_id: number; to_listing_id: number; effective_date: string; kind: string; } interface DbListingRow { listing_id: number; mic: string | null; currency: string | null; listed_to: string | null; delist_reason: string | null; terminal_return: string | null; } interface DbProviderMappingRow { source: string | null; source_id: string | null; valid_from: string | null; valid_to: string | null; listing_id: number; } function isLeapYear(year: number): boolean { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } export function isValidStrictYmd(value: string): boolean { if (!EXACT_YMD_PATTERN.test(value)) { return false; } const year = (value.charCodeAt(0) - 48) * 1000 + (value.charCodeAt(1) - 48) * 100 + (value.charCodeAt(2) - 48) * 10 + (value.charCodeAt(3) - 48); const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); if (year < 1 || year > 9999 || month < 1 || month > 12) { return false; } const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); return day >= 1 && day <= maxDay; } function assertNoTsvControlChars( value: string, table: string, key: string, field: string ): void { if (value.includes('\t') || value.includes('\n') || value.includes('\r')) { throw new CurateInputExportError({ code: 'FORBIDDEN_CONTROL_CHAR', table, key, field, detail: `${field} must not contain tab, newline, or carriage return characters`, }); } } function assertNonBlankVerbatim( value: unknown, table: string, key: string, field: string ): string { if (typeof value !== 'string') { throw new CurateInputExportError({ code: 'BLANK_FIELD', table, key, field, detail: `${field} must be a non-blank string`, }); } assertNoTsvControlChars(value, table, key, field); if (value.trim().length === 0) { throw new CurateInputExportError({ code: 'BLANK_FIELD', table, key, field, detail: `${field} must not be empty or whitespace-only`, }); } return value; } function assertStrictYmd(value: unknown, table: string, key: string, field: string): string { if (typeof value !== 'string') { throw new CurateInputExportError({ code: 'INVALID_DATE', table, key, field, detail: `${field} must be a strict Gregorian YYYY-MM-DD string`, }); } assertNoTsvControlChars(value, table, key, field); if (!isValidStrictYmd(value)) { throw new CurateInputExportError({ code: 'INVALID_DATE', table, key, field, detail: `invalid ${field} "${value}" (expected strict Gregorian YYYY-MM-DD)`, }); } return value; } function assertPositiveI32(value: unknown, table: string, key: string, field: string): number { if ( typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > MAX_PG_INT4 ) { throw new CurateInputExportError({ code: 'INVALID_LISTING_ID', table, key, field, detail: `invalid ${field} "${String(value)}" (expected integer in 1..=${MAX_PG_INT4})`, }); } return value; } /** * Formats a finite JS number as a plain base-10 decimal string without scientific notation. * Normalizes `-0` to `"0"`. */ export function formatPlainDecimal(value: number): string { if (value === 0) { return '0'; } const raw = String(value); const expIdx = raw.search(/[eE]/); if (expIdx === -1) { return raw; } const sign = raw.startsWith('-') ? '-' : ''; const unsigned = sign.length > 0 ? raw.slice(1, expIdx) : raw.slice(0, expIdx); const exponent = Number(raw.slice(expIdx + 1)); const dotIdx = unsigned.indexOf('.'); const digits = dotIdx === -1 ? unsigned : unsigned.slice(0, dotIdx) + unsigned.slice(dotIdx + 1); const integerLen = dotIdx === -1 ? unsigned.length : dotIdx; const decimalPos = integerLen + exponent; if (decimalPos <= 0) { return `${sign}0.${'0'.repeat(-decimalPos)}${digits}`; } if (decimalPos >= digits.length) { return `${sign}${digits}${'0'.repeat(decimalPos - digits.length)}`; } return `${sign}${digits.slice(0, decimalPos)}.${digits.slice(decimalPos)}`; } function normalizeAndFormatTerminalReturn( value: number | string, table: string, key: string, field: string ): string { let num: number; if (typeof value === 'string') { assertNoTsvControlChars(value, table, key, field); if (value.length === 0 || value.trim() !== value || !STRICT_DECIMAL_PATTERN.test(value)) { throw new CurateInputExportError({ code: 'INVALID_TERMINAL_RETURN', table, key, field, detail: `invalid ${field} "${value}" (expected finite decimal in [-1, 0])`, }); } num = Number(value); } else if (typeof value === 'number') { num = value; } else { throw new CurateInputExportError({ code: 'INVALID_TERMINAL_RETURN', table, key, field, detail: `invalid ${field} "${String(value)}" (expected finite decimal in [-1, 0])`, }); } if (!Number.isFinite(num) || num < -1 || num > 0) { throw new CurateInputExportError({ code: 'INVALID_TERMINAL_RETURN', table, key, field, detail: `invalid ${field} "${String(value)}" (must be finite and in [-1, 0])`, }); } const normalized = num === 0 ? 0 : num; return formatPlainDecimal(normalized); } function compareNullableAscii(a: string | null, b: string | null): number { if (a === b) { return 0; } if (a === null) { return 1; } if (b === null) { return -1; } return compareAscii(a, b); } function joinLinesInChunks(lines: readonly string[], chunkSize = DEFAULT_EXPORT_CHUNK_SIZE): string { if (lines.length === 0) { return ''; } if (lines.length <= chunkSize) { return `${lines.join('\n')}\n`; } const chunks: string[] = []; for (let offset = 0; offset < lines.length; offset += chunkSize) { chunks.push(lines.slice(offset, offset + chunkSize).join('\n')); } return `${chunks.join('\n')}\n`; } function validateProviderMappingRow( row: ProviderMappingExportRow, index: number ): ProviderMappingExportRow { const fallbackKey = `row#${index}`; const source = assertNonBlankVerbatim(row.source, 'provider_mapping', fallbackKey, 'source'); const sourceId = assertNonBlankVerbatim( row.sourceId, 'provider_mapping', `${source}:${fallbackKey}`, 'source_id' ); const key = `${source}:${sourceId}:${String(row.validFrom)}`; const validFrom = assertStrictYmd(row.validFrom, 'provider_mapping', key, 'valid_from'); let validTo: string | null = null; if (row.validTo !== null && row.validTo !== undefined) { validTo = assertStrictYmd(row.validTo, 'provider_mapping', key, 'valid_to'); if (validTo < validFrom) { throw new CurateInputExportError({ code: 'INVALID_DATE_RANGE', table: 'provider_mapping', key: `${source}:${sourceId}:${validFrom}`, field: 'valid_to', detail: `valid_to "${validTo}" precedes valid_from "${validFrom}"`, }); } } const listingId = assertPositiveI32( row.listingId, 'provider_mapping', `${source}:${sourceId}:${validFrom}`, 'listing_id' ); return { source, sourceId, validFrom, validTo, listingId }; } /** * Validates, deterministically ASCII-sorts, overlap-checks, and formats `provider_mapping.tsv`. * Headerless 5-column TSV: `source\tsource_id\tvalid_from\tvalid_to\tlisting_id`. */ export function formatProviderMappingTsv(rows: readonly ProviderMappingExportRow[]): string { if (rows.length === 0) { return ''; } const validated: ProviderMappingExportRow[] = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; if (row === undefined) { continue; } validated.push(validateProviderMappingRow(row, i)); } validated.sort( (a, b) => compareAscii(a.source, b.source) || compareAscii(a.sourceId, b.sourceId) || compareAscii(a.validFrom, b.validFrom) || compareNullableAscii(a.validTo, b.validTo) || a.listingId - b.listingId ); const lines: string[] = []; let prev: ProviderMappingExportRow | undefined; for (const curr of validated) { if (prev !== undefined && prev.source === curr.source && prev.sourceId === curr.sourceId) { if (prev.validFrom === curr.validFrom) { throw new CurateInputExportError({ code: 'DUPLICATE_PROVIDER_MAPPING', table: 'provider_mapping', key: `${curr.source}:${curr.sourceId}:${curr.validFrom}`, detail: 'duplicate (source, source_id, valid_from) primary key', }); } if (prev.validTo === null || prev.validTo >= curr.validFrom) { throw new CurateInputExportError({ code: 'OVERLAPPING_PROVIDER_MAPPING', table: 'provider_mapping', key: `${curr.source}:${curr.sourceId}:${curr.validFrom}`, detail: `inclusive range [${prev.validFrom}, ${prev.validTo ?? '+inf'}] overlaps [${curr.validFrom}, ${curr.validTo ?? '+inf'}]`, }); } } lines.push( `${curr.source}\t${curr.sourceId}\t${curr.validFrom}\t${curr.validTo ?? ''}\t${curr.listingId}` ); prev = curr; } return joinLinesInChunks(lines); } /** * Validates, sorts by ascending `listing_id`, rejects duplicate `listing_id`s, and formats * `listing_currencies.tsv`. Headerless 2-column TSV: `listing_id\tcurrency`. */ export function formatListingCurrenciesTsv(rows: readonly ListingCurrencyExportRow[]): string { if (rows.length === 0) { return ''; } const validated: ListingCurrencyExportRow[] = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; if (row === undefined) { continue; } const listingId = assertPositiveI32(row.listingId, 'listing', `row#${i}`, 'listing_id'); const currency = assertNonBlankVerbatim( row.currency, 'listing', `listing_id=${listingId}`, 'currency' ); validated.push({ listingId, currency }); } validated.sort((a, b) => a.listingId - b.listingId); const lines: string[] = []; let prevListingId: number | undefined; for (const curr of validated) { if (prevListingId === curr.listingId) { throw new CurateInputExportError({ code: 'DUPLICATE_LISTING_CURRENCY', table: 'listing', key: `listing_id=${curr.listingId}`, field: 'listing_id', detail: `duplicate listing_id ${curr.listingId} in listing_currencies`, }); } lines.push(`${curr.listingId}\t${curr.currency}`); prevListingId = curr.listingId; } return joinLinesInChunks(lines); } /** * Resolves a persisted ISO 10383 `listing.mic` to its `curate-fundamentals` statutory-lag venue * class (`us_tsx` vs `tsxv_cse`). Fails closed on blank, control-character, whitespace-padded, * prototype-key, or unmapped MIC values. */ export function resolveListingVenueForMic( mic: unknown, table = 'listing', key = 'mic' ): ListingStatutoryLagVenue { const validatedMic = assertNonBlankVerbatim(mic, table, key, 'mic'); const venue = Object.hasOwn(LISTING_VENUE_BY_MIC, validatedMic) ? LISTING_VENUE_BY_MIC[validatedMic] : undefined; if (venue === undefined) { throw new CurateInputExportError({ code: 'UNKNOWN_LISTING_MIC', table, key, field: 'mic', detail: `unknown listing mic "${validatedMic}" (expected one of: ${Object.keys(LISTING_VENUE_BY_MIC).join(', ')})`, }); } return venue; } function assertListingVenue( value: unknown, table: string, key: string, field: string ): ListingStatutoryLagVenue { if (typeof value === 'string') { assertNoTsvControlChars(value, table, key, field); } if (value !== 'us_tsx' && value !== 'tsxv_cse') { throw new CurateInputExportError({ code: 'INVALID_LISTING_VENUE', table, key, field, detail: `invalid ${field} "${String(value)}" (expected one of: ${LISTING_STATUTORY_LAG_VENUES.join(', ')})`, }); } return value; } /** * Validates, sorts by ascending `listing_id`, rejects duplicate `listing_id`s, and formats * `listing_venues.tsv`. Headerless 2-column TSV: `listing_id\tvenue` (`us_tsx` | `tsxv_cse`), * matching `tools/curate-etl/src/run_curate_fundamentals.rs::load_listing_venues_tsv`. */ export function formatListingVenuesTsv(rows: readonly ListingVenueExportRow[]): string { if (rows.length === 0) { return ''; } const validated: ListingVenueExportRow[] = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; if (row === undefined) { continue; } const listingId = assertPositiveI32(row.listingId, 'listing', `row#${i}`, 'listing_id'); const venue = assertListingVenue(row.venue, 'listing', `listing_id=${listingId}`, 'venue'); validated.push({ listingId, venue }); } validated.sort((a, b) => a.listingId - b.listingId); const lines: string[] = []; let prevListingId: number | undefined; for (const curr of validated) { if (prevListingId === curr.listingId) { throw new CurateInputExportError({ code: 'DUPLICATE_LISTING_VENUE', table: 'listing', key: `listing_id=${curr.listingId}`, field: 'listing_id', detail: `duplicate listing_id ${curr.listingId} in listing_venues`, }); } lines.push(`${curr.listingId}\t${curr.venue}`); prevListingId = curr.listingId; } return joinLinesInChunks(lines); } function validateDelistingExportRow(row: DelistingExportRow, index: number): ValidatedDelistingRow { const fallbackKey = `row#${index}`; const sourceId = assertNonBlankVerbatim(row.sourceId, 'delistings', fallbackKey, 'source_id'); const rowKey = `${sourceId}:${String(row.delistDate)}`; const delistDate = assertStrictYmd(row.delistDate, 'delistings', rowKey, 'delist_date'); const fromListingId = row.fromListingId === null || row.fromListingId === undefined ? null : assertPositiveI32(row.fromListingId, 'delistings', rowKey, 'from_listing_id'); const successorSourceId = row.successorSourceId === null || row.successorSourceId === undefined ? null : assertNonBlankVerbatim( row.successorSourceId, 'delistings', rowKey, 'successor_source_id' ); const formattedTerminalReturn = row.terminalReturn === null || row.terminalReturn === undefined ? '' : normalizeAndFormatTerminalReturn(row.terminalReturn, 'delistings', rowKey, 'terminal_return'); const hasSuccessor = successorSourceId !== null; const hasTerminalReturn = formattedTerminalReturn.length > 0; if (hasSuccessor && hasTerminalReturn) { throw new CurateInputExportError({ code: 'INVALID_DELISTING_OUTCOME', table: 'delistings', key: rowKey, detail: 'delisting row must set exactly one of successor_source_id or terminal_return (got both)', }); } if (!hasSuccessor && !hasTerminalReturn) { throw new CurateInputExportError({ code: 'INVALID_DELISTING_OUTCOME', table: 'delistings', key: rowKey, detail: 'delisting row must set exactly one of successor_source_id or terminal_return (got neither)', }); } if (hasSuccessor && fromListingId === null) { throw new CurateInputExportError({ code: 'MISSING_FROM_LISTING_ID', table: 'delistings', key: rowKey, field: 'from_listing_id', detail: 'OTC delisting transfer row with successor_source_id requires from_listing_id', }); } return { sourceId, delistDate, fromListingId, successorSourceId, formattedTerminalReturn, }; } function compareValidatedDelistingRows(a: ValidatedDelistingRow, b: ValidatedDelistingRow): number { return ( compareAscii(a.sourceId, b.sourceId) || compareAscii(a.delistDate, b.delistDate) || (a.fromListingId ?? 0) - (b.fromListingId ?? 0) || compareAscii(a.successorSourceId ?? '', b.successorSourceId ?? '') || compareAscii(a.formattedTerminalReturn, b.formattedTerminalReturn) ); } /** * Validates, deterministically sorts, and formats Pass 6 `delistings.tsv`. * Headerless 5-column TSV: * `source_id\tdelist_date\tfrom_listing_id\tsuccessor_source_id\tterminal_return`. */ export function formatDelistingsTsv(rows: readonly DelistingExportRow[]): string { if (rows.length === 0) { return ''; } const validated: ValidatedDelistingRow[] = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; if (row === undefined) { continue; } validated.push(validateDelistingExportRow(row, i)); } validated.sort(compareValidatedDelistingRows); const lines: string[] = []; for (const row of validated) { lines.push( `${row.sourceId}\t${row.delistDate}\t${row.fromListingId === null ? '' : String(row.fromListingId)}\t${row.successorSourceId ?? ''}\t${row.formattedTerminalReturn}` ); } return joinLinesInChunks(lines); } /** * Deterministic tie-breaker when multiple `qm` mappings qualify for the same `listing_id`: * 1. `validFrom DESC` (most recently started mapping) * 2. `validTo DESC NULLS FIRST` (open-ended active mapping beats closed, then latest end date) * 3. `sourceId ASC` (ASCII) */ function compareQualifyingQmMappings(a: QmListingMappingRange, b: QmListingMappingRange): number { const fromCmp = compareAscii(b.validFrom, a.validFrom); if (fromCmp !== 0) { return fromCmp; } if (a.validTo !== b.validTo) { if (a.validTo === null) { return -1; } if (b.validTo === null) { return 1; } const toCmp = compareAscii(b.validTo, a.validTo); if (toCmp !== 0) { return toCmp; } } return compareAscii(a.sourceId, b.sourceId); } function selectQmMappingOnOrBefore( ranges: readonly QmListingMappingRange[] | undefined, date: string ): QmListingMappingRange | null { if (!ranges || ranges.length === 0) { return null; } let best: QmListingMappingRange | null = null; for (const candidate of ranges) { if (candidate.validFrom <= date) { if (best === null || compareQualifyingQmMappings(candidate, best) < 0) { best = candidate; } } } return best; } function selectQmMappingOnDate( ranges: readonly QmListingMappingRange[] | undefined, date: string ): QmListingMappingRange | null { if (!ranges || ranges.length === 0) { return null; } let best: QmListingMappingRange | null = null; for (const candidate of ranges) { if (candidate.validFrom <= date && (candidate.validTo === null || candidate.validTo >= date)) { if (best === null || compareQualifyingQmMappings(candidate, best) < 0) { best = candidate; } } } return best; } /** * Pure Pass 6 delistings builder turning `listing`, `corporate_action_continuity`, and * `provider_mapping` rows into `DelistingExportRow[]` plus exact skip-reason stats * (`rowsIn === rowsOut + skippedTotal`). * * Indexes `otc_delist_transfer` continuities strictly by `fromListingId` so OTC successor listings * (e.g. `SIVBQ`) still emit their own subsequent terminal delisting (e.g. bankruptcy `-1`). */ export function buildDelistingExportRows( listings: readonly ListingDelistingSourceRow[], continuities: readonly ContinuityExportSourceRow[], providerMappings: readonly ProviderMappingExportRow[], options: BuildDelistingExportRowsOptions = {} ): BuildDelistingExportRowsResult { const mappingSource = assertNonBlankVerbatim( options.mappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, 'options', 'mappingSource', 'mappingSource' ); let nonOtcContinuity = 0; const otcByFromListingId = new Map(); for (let i = 0; i < continuities.length; i++) { const raw = continuities[i]; if (raw === undefined) { continue; } if (raw.kind !== 'otc_delist_transfer') { nonOtcContinuity += 1; continue; } const fromListingId = assertPositiveI32( raw.fromListingId, 'corporate_action_continuity', `row#${i}`, 'from_listing_id' ); const toListingId = assertPositiveI32( raw.toListingId, 'corporate_action_continuity', `from_listing_id=${fromListingId}`, 'to_listing_id' ); const effectiveDate = assertStrictYmd( raw.effectiveDate, 'corporate_action_continuity', `from_listing_id=${fromListingId}`, 'effective_date' ); if (fromListingId === toListingId) { throw new CurateInputExportError({ code: 'SELF_SUCCESSOR_CONTINUITY', table: 'corporate_action_continuity', key: `from_listing_id=${fromListingId}@${effectiveDate}`, field: 'to_listing_id', detail: `otc_delist_transfer continuity cannot link listing ${fromListingId} to itself`, }); } if (otcByFromListingId.has(fromListingId)) { throw new CurateInputExportError({ code: 'DUPLICATE_OTC_CONTINUITY', table: 'corporate_action_continuity', key: `from_listing_id=${fromListingId}`, detail: `multiple otc_delist_transfer continuities found for from_listing_id=${fromListingId}`, }); } otcByFromListingId.set(fromListingId, { fromListingId, toListingId, effectiveDate, kind: raw.kind, }); } const qmMappingsByListingId = new Map(); for (let i = 0; i < providerMappings.length; i++) { const rawMapping = providerMappings[i]; if (rawMapping === undefined) { continue; } const validated = validateProviderMappingRow(rawMapping, i); if (validated.source !== mappingSource) { continue; } let list = qmMappingsByListingId.get(validated.listingId); if (list === undefined) { list = []; qmMappingsByListingId.set(validated.listingId, list); } list.push({ sourceId: validated.sourceId, validFrom: validated.validFrom, validTo: validated.validTo, listingId: validated.listingId, }); } let active = 0; let noOutcome = 0; let missingListedTo = 0; let missingOutgoingQmMapping = 0; let missingSuccessorQmMapping = 0; let otcTransfersOut = 0; let terminalDelistingsOut = 0; const seenListingIds = new Set(); const rows: DelistingExportRow[] = []; for (let i = 0; i < listings.length; i++) { const listing = listings[i]; if (listing === undefined) { continue; } const listingId = assertPositiveI32(listing.listingId, 'listing', `row#${i}`, 'listing_id'); const listingKey = `listing_id=${listingId}`; if (seenListingIds.has(listingId)) { throw new CurateInputExportError({ code: 'DUPLICATE_LISTING_CURRENCY', table: 'listing', key: listingKey, field: 'listing_id', detail: `duplicate listing_id ${listingId} in listings input`, }); } seenListingIds.add(listingId); const otc = otcByFromListingId.get(listingId); const hasTerminalReturn = listing.terminalReturn !== null && listing.terminalReturn !== undefined; if (listing.delistReason === 'active') { if (otc !== undefined || hasTerminalReturn) { throw new CurateInputExportError({ code: 'ACTIVE_LISTING_WITH_OUTCOME', table: 'listing', key: listingKey, field: 'delist_reason', detail: 'listing marked active cannot have an OTC continuity or terminal_return', }); } active += 1; continue; } if (otc !== undefined && hasTerminalReturn) { throw new CurateInputExportError({ code: 'INVALID_DELISTING_OUTCOME', table: 'listing', key: listingKey, detail: 'listing cannot have both an outgoing otc_delist_transfer and a terminal_return', }); } if (otc !== undefined) { const outgoing = selectQmMappingOnOrBefore( qmMappingsByListingId.get(listingId), otc.effectiveDate ); if (outgoing === null) { missingOutgoingQmMapping += 1; continue; } const successor = selectQmMappingOnDate( qmMappingsByListingId.get(otc.toListingId), otc.effectiveDate ); if (successor === null) { missingSuccessorQmMapping += 1; continue; } rows.push({ sourceId: outgoing.sourceId, delistDate: otc.effectiveDate, fromListingId: listingId, successorSourceId: successor.sourceId, terminalReturn: null, }); otcTransfersOut += 1; continue; } if (hasTerminalReturn) { const formattedReturn = normalizeAndFormatTerminalReturn( listing.terminalReturn as number | string, 'listing', listingKey, 'terminal_return' ); if (listing.listedTo === null || listing.listedTo === undefined) { missingListedTo += 1; continue; } const listedTo = assertStrictYmd(listing.listedTo, 'listing', listingKey, 'listed_to'); const outgoing = selectQmMappingOnDate(qmMappingsByListingId.get(listingId), listedTo); if (outgoing === null) { missingOutgoingQmMapping += 1; continue; } rows.push({ sourceId: outgoing.sourceId, delistDate: listedTo, fromListingId: listingId, successorSourceId: null, terminalReturn: formattedReturn, }); terminalDelistingsOut += 1; continue; } noOutcome += 1; } // Handle any OTC continuity whose fromListingId was absent from `listings` (pure caller input). const orphanOtcIds = Array.from(otcByFromListingId.keys()) .filter(id => !seenListingIds.has(id)) .sort((a, b) => a - b); for (const fromListingId of orphanOtcIds) { const otc = otcByFromListingId.get(fromListingId); if (otc === undefined) { continue; } const outgoing = selectQmMappingOnOrBefore( qmMappingsByListingId.get(fromListingId), otc.effectiveDate ); if (outgoing === null) { missingOutgoingQmMapping += 1; continue; } const successor = selectQmMappingOnDate( qmMappingsByListingId.get(otc.toListingId), otc.effectiveDate ); if (successor === null) { missingSuccessorQmMapping += 1; continue; } rows.push({ sourceId: outgoing.sourceId, delistDate: otc.effectiveDate, fromListingId, successorSourceId: successor.sourceId, terminalReturn: null, }); otcTransfersOut += 1; } rows.sort((a, b) => compareValidatedDelistingRows( { sourceId: a.sourceId, delistDate: a.delistDate, fromListingId: a.fromListingId, successorSourceId: a.successorSourceId, formattedTerminalReturn: a.terminalReturn === null ? '' : String(a.terminalReturn), }, { sourceId: b.sourceId, delistDate: b.delistDate, fromListingId: b.fromListingId, successorSourceId: b.successorSourceId, formattedTerminalReturn: b.terminalReturn === null ? '' : String(b.terminalReturn), } ) ); const rowsOut = otcTransfersOut + terminalDelistingsOut; const skippedTotal = active + noOutcome + missingListedTo + missingOutgoingQmMapping + missingSuccessorQmMapping + nonOtcContinuity; const rowsIn = rowsOut + skippedTotal; return { rows, stats: { rowsIn, rowsOut, otcTransfersOut, terminalDelistingsOut, skippedTotal, skipped: { active, noOutcome, missingListedTo, missingOutgoingQmMapping, missingSuccessorQmMapping, nonOtcContinuity, }, }, }; } function assertDedicatedQueryable(client: SecurityMasterQueryable): void { if (client === null || client === undefined || typeof client !== 'object') { throw new CurateInputExportError({ code: 'INVALID_CLIENT', table: 'connection', key: 'client', detail: 'exportCurateInputs requires a dedicated SecurityMasterQueryable client', }); } if (typeof client.query !== 'function') { throw new CurateInputExportError({ code: 'INVALID_CLIENT', table: 'connection', key: 'client', detail: 'exportCurateInputs client must expose a query() method', }); } const maybePool = client as unknown as { connect?: unknown; release?: unknown }; if (typeof maybePool.connect === 'function' && typeof maybePool.release !== 'function') { throw new CurateInputExportError({ code: 'INVALID_CLIENT', table: 'connection', key: 'client', detail: 'exportCurateInputs requires a dedicated single-session client (e.g. pg.PoolClient), not a Pool', }); } } function validateChunkSize(chunkSize: number | undefined): number { const resolved = chunkSize ?? DEFAULT_EXPORT_CHUNK_SIZE; if ( typeof resolved !== 'number' || !Number.isSafeInteger(resolved) || resolved < 1 || resolved > MAX_EXPORT_CHUNK_SIZE ) { throw new CurateInputExportError({ code: 'INVALID_OPTION', table: 'options', key: 'chunkSize', field: 'chunkSize', detail: `chunkSize must be an integer in 1..=${MAX_EXPORT_CHUNK_SIZE} (got ${String(resolved)})`, }); } return resolved; } async function safeUnlink(unlinkFn: typeof unlink, filePath: string): Promise { try { await unlinkFn(filePath); } catch (error) { if ((error as NodeJS.ErrnoException | undefined)?.code !== 'ENOENT') { throw error; } } } async function safeRmdirIfEmpty(rmdirFn: typeof rmdir, dirPath: string): Promise { try { await rmdirFn(dirPath); } catch (error) { const code = (error as NodeJS.ErrnoException | undefined)?.code; if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') { throw error; } } } async function writeAll(handle: FileHandle, buf: Buffer): Promise { let offset = 0; while (offset < buf.byteLength) { const { bytesWritten } = await handle.write(buf, offset, buf.byteLength - offset); if (bytesWritten <= 0) { throw new Error('Short write (0 bytes written) while streaming TSV chunk'); } offset += bytesWritten; } } async function acquirePublishLock( lockPath: string, outDir: string, runTag: string, timeoutMs: number, fsOpen: typeof open, fsUnlink: typeof unlink ): Promise { const deadline = Date.now() + timeoutMs; const payload = Buffer.from( `${JSON.stringify({ pid: process.pid, runTag, acquiredAtMs: Date.now() })}\n`, 'utf8' ); for (;;) { let handle: FileHandle | null = null; let created = false; try { handle = await fsOpen(lockPath, 'wx'); created = true; await writeAll(handle, payload); const toClose = handle; handle = null; await toClose.close(); return; } catch (error) { if (handle !== null) { await handle.close().catch(() => {}); } if (created) { await safeUnlink(fsUnlink, lockPath).catch(() => {}); throw error; } const code = (error as NodeJS.ErrnoException | undefined)?.code; if (code !== 'EEXIST') { throw error; } if (Date.now() >= deadline) { throw new CurateInputExportError({ code: 'PUBLISH_LOCK_TIMEOUT', table: 'publish', key: outDir, detail: `timed out after ${timeoutMs}ms waiting for publish lock ${lockPath}`, cause: error, }); } await new Promise(resolve => setTimeout(resolve, PUBLISH_LOCK_RETRY_MS)); } } } /** * Resolves and pins the currently active immutable generation directory via `/current` * before a consumer opens any TSV file. All four returned paths belong to the same atomic * PostgreSQL snapshot and remain immutable even if a concurrent export refreshes `/current`. */ export async function pinCurateInputSnapshot( outDir: string, fsHooks?: Pick ): Promise { if (typeof outDir !== 'string' || outDir.trim().length === 0) { throw new CurateInputExportError({ code: 'INVALID_OPTION', table: 'options', key: 'outDir', field: 'outDir', detail: 'outDir must be a non-empty string', }); } 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, listingCurrencies, listingVenues, delistings, }; } /** * Reads security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` * transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable * generation directory under `/generations/`, and atomically commits * `/current` (plus top-level symlinks `provider_mapping.tsv`, `listing_currencies.tsv`, * `listing_venues.tsv`, and `delistings.tsv` pointing through `current/`). */ export async function exportCurateInputs( queryable: SecurityMasterQueryable, options: ExportCurateInputsOptions ): Promise { assertDedicatedQueryable(queryable); if ( options === null || options === undefined || typeof options !== 'object' || typeof options.outDir !== 'string' || options.outDir.trim().length === 0 ) { throw new CurateInputExportError({ code: 'INVALID_OPTION', table: 'options', key: 'outDir', field: 'outDir', detail: 'outDir must be a non-empty string', }); } const outDir = options.outDir.trim(); const chunkSize = validateChunkSize(options.chunkSize); const publishLockTimeoutMs = options.publishLockTimeoutMs ?? DEFAULT_PUBLISH_LOCK_TIMEOUT_MS; if ( typeof publishLockTimeoutMs !== 'number' || !Number.isFinite(publishLockTimeoutMs) || publishLockTimeoutMs < 0 ) { throw new CurateInputExportError({ code: 'INVALID_OPTION', table: 'options', key: 'publishLockTimeoutMs', field: 'publishLockTimeoutMs', detail: `publishLockTimeoutMs must be a non-negative finite number (got ${String(publishLockTimeoutMs)})`, }); } const delistingMappingSource = assertNonBlankVerbatim( options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, 'options', 'delistingMappingSource', 'delistingMappingSource' ); const fsMkdir = options.fs?.mkdir ?? mkdir; const fsOpen = options.fs?.open ?? open; const fsRename = options.fs?.rename ?? rename; const fsUnlink = options.fs?.unlink ?? unlink; const fsLstat = options.fs?.lstat ?? lstat; const fsReadlink = options.fs?.readlink ?? readlink; const fsSymlink = options.fs?.symlink ?? symlink; const fsRm = options.fs?.rm ?? rm; const fsRmdir = options.fs?.rmdir ?? rmdir; await fsMkdir(outDir, { recursive: true }); const uniqueSuffix = randomUUID().slice(0, 8); const timestamp = Date.now(); const runTag = `${process.pid}-${timestamp}-${uniqueSuffix}`; const generationId = `gen-${timestamp}-${process.pid}-${uniqueSuffix}`; const generationsRoot = join(outDir, CURATE_INPUT_GENERATIONS_DIR); const stagingDir = join(outDir, `.staging-${runTag}`); const generationDir = join(generationsRoot, generationId); const relativeGenerationTarget = join(CURATE_INPUT_GENERATIONS_DIR, generationId); const currentLink = join(outDir, CURATE_INPUT_CURRENT_LINK); const currentTempLink = join(outDir, `.${CURATE_INPUT_CURRENT_LINK}.${runTag}.tmp`); const publishLockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); const targets = { providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies), listingVenues: join(outDir, CURATE_INPUT_FILES.listingVenues), delistings: join(outDir, CURATE_INPUT_FILES.delistings), }; const stagedFiles = { providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies), listingVenues: join(stagingDir, CURATE_INPUT_FILES.listingVenues), delistings: join(stagingDir, CURATE_INPUT_FILES.delistings), }; const generationFiles = { 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), }; const backups = { providerMapping: `${targets.providerMapping}.${runTag}.bak`, listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`, listingVenues: `${targets.listingVenues}.${runTag}.bak`, delistings: `${targets.delistings}.${runTag}.bak`, }; const linkTemps = { providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`, listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`, listingVenues: `${targets.listingVenues}.${runTag}.link.tmp`, delistings: `${targets.delistings}.${runTag}.link.tmp`, }; let providerMappingHandle: FileHandle | null = null; let listingCurrenciesHandle: FileHandle | null = null; let listingVenuesHandle: FileHandle | null = null; let delistingsHandle: FileHandle | null = null; let providerMappingRowsIn = 0; let providerMappingRowsOut = 0; let providerMappingBytes = 0; let listingCurrenciesRowsIn = 0; let listingCurrenciesRowsOut = 0; let listingCurrenciesBytes = 0; let listingVenuesRowsIn = 0; let listingVenuesRowsOut = 0; let listingVenuesBytes = 0; let delistingsBytes = 0; let delistingsStats!: DelistingExportStats; type PublishKey = 'providerMapping' | 'listingCurrencies' | 'listingVenues' | 'delistings'; const publishOrder: PublishKey[] = [ 'providerMapping', 'listingCurrencies', 'listingVenues', 'delistings', ]; let stagingCreated = false; let publishLockAcquired = false; let generationMoved = false; let currentTempCreated = false; const backedUp = new Set(); const createdLinks = new Set(); try { await fsMkdir(stagingDir, { recursive: false }); stagingCreated = true; providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx'); listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx'); listingVenuesHandle = await fsOpen(stagedFiles.listingVenues, 'wx'); delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx'); const otcByFromListingId = new Map(); const relevantDelistingListingIds = new Set(); const otcCandidates: Array<{ listingId: number; otc: ContinuityExportSourceRow }> = []; const terminalCandidates: Array<{ listingId: number; listedTo: string; formattedTerminalReturn: string; }> = []; const qmMappingsByListingId = new Map(); let skippedActive = 0; let skippedNoOutcome = 0; let skippedMissingListedTo = 0; await queryable.query('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); try { // 1. Keyset-paginated read of corporate_action_continuity (kind = 'otc_delist_transfer'). let lastContFromId: number | null = null; let lastContEffDate: string | null = null; for (;;) { const res = lastContFromId === null ? await queryable.query( `SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind FROM corporate_action_continuity WHERE kind = 'otc_delist_transfer' ORDER BY from_listing_id ASC, effective_date ASC LIMIT $1`, [chunkSize] ) : await queryable.query( `SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind FROM corporate_action_continuity WHERE kind = 'otc_delist_transfer' AND ( from_listing_id > $1 OR (from_listing_id = $1 AND effective_date > $2::date) ) ORDER BY from_listing_id ASC, effective_date ASC LIMIT $3`, [lastContFromId, lastContEffDate, chunkSize] ); if (res.rows.length === 0) { break; } for (const row of res.rows) { const fromListingId = assertPositiveI32( row.from_listing_id, 'corporate_action_continuity', `from_listing_id=${String(row.from_listing_id)}`, 'from_listing_id' ); const toListingId = assertPositiveI32( row.to_listing_id, 'corporate_action_continuity', `from_listing_id=${fromListingId}`, 'to_listing_id' ); const effectiveDate = assertStrictYmd( row.effective_date, 'corporate_action_continuity', `from_listing_id=${fromListingId}`, 'effective_date' ); if (lastContFromId !== null && lastContEffDate !== null) { if ( fromListingId < lastContFromId || (fromListingId === lastContFromId && effectiveDate <= lastContEffDate) ) { throw new CurateInputExportError({ code: 'OUT_OF_ORDER_CONTINUITY_STREAM', table: 'corporate_action_continuity', key: `from_listing_id=${fromListingId}@${effectiveDate}`, detail: 'corporate_action_continuity stream was not strictly ordered by (from_listing_id, effective_date)', }); } } if (fromListingId === toListingId) { throw new CurateInputExportError({ code: 'SELF_SUCCESSOR_CONTINUITY', table: 'corporate_action_continuity', key: `from_listing_id=${fromListingId}@${effectiveDate}`, field: 'to_listing_id', detail: `otc_delist_transfer continuity cannot link listing ${fromListingId} to itself`, }); } if (otcByFromListingId.has(fromListingId)) { throw new CurateInputExportError({ code: 'DUPLICATE_OTC_CONTINUITY', table: 'corporate_action_continuity', key: `from_listing_id=${fromListingId}`, detail: `multiple otc_delist_transfer continuities found for from_listing_id=${fromListingId}`, }); } otcByFromListingId.set(fromListingId, { fromListingId, toListingId, effectiveDate, kind: row.kind, }); relevantDelistingListingIds.add(fromListingId); relevantDelistingListingIds.add(toListingId); lastContFromId = fromListingId; lastContEffDate = effectiveDate; } if (res.rows.length < chunkSize) { break; } } // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv and listing_venues.tsv directly. let lastListingId: number | null = null; for (;;) { const res = lastListingId === null ? await queryable.query( `SELECT listing_id, mic, btrim(currency) AS currency, to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, terminal_return::text AS terminal_return FROM listing ORDER BY listing_id ASC LIMIT $1`, [chunkSize] ) : await queryable.query( `SELECT listing_id, mic, btrim(currency) AS currency, to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, terminal_return::text AS terminal_return FROM listing WHERE listing_id > $1 ORDER BY listing_id ASC LIMIT $2`, [lastListingId, chunkSize] ); if (res.rows.length === 0) { break; } const chunkLines: string[] = []; const venueChunkLines: string[] = []; for (const row of res.rows) { const listingId = assertPositiveI32( row.listing_id, 'listing', `listing_id=${String(row.listing_id)}`, 'listing_id' ); const listingKey = `listing_id=${listingId}`; if (lastListingId !== null) { if (listingId === lastListingId) { throw new CurateInputExportError({ code: 'DUPLICATE_LISTING_CURRENCY', table: 'listing', key: listingKey, field: 'listing_id', detail: `duplicate listing_id ${listingId} in listing stream`, }); } if (listingId < lastListingId) { throw new CurateInputExportError({ code: 'UNSORTED_LISTING_STREAM', table: 'listing', key: listingKey, field: 'listing_id', detail: `listing stream out of ascending listing_id order (${listingId} after ${lastListingId})`, }); } } const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency'); const venue = resolveListingVenueForMic(row.mic, 'listing', listingKey); chunkLines.push(`${listingId}\t${currency}`); venueChunkLines.push(`${listingId}\t${venue}`); listingCurrenciesRowsIn += 1; listingCurrenciesRowsOut += 1; listingVenuesRowsIn += 1; listingVenuesRowsOut += 1; const otc = otcByFromListingId.get(listingId); const hasTerminalReturn = row.terminal_return !== null && row.terminal_return !== undefined; if (row.delist_reason === 'active') { if (otc !== undefined || hasTerminalReturn) { throw new CurateInputExportError({ code: 'ACTIVE_LISTING_WITH_OUTCOME', table: 'listing', key: listingKey, field: 'delist_reason', detail: 'listing marked active cannot have an OTC continuity or terminal_return', }); } skippedActive += 1; } else if (otc !== undefined && hasTerminalReturn) { throw new CurateInputExportError({ code: 'INVALID_DELISTING_OUTCOME', table: 'listing', key: listingKey, detail: 'listing cannot have both an outgoing otc_delist_transfer and a terminal_return', }); } else if (otc !== undefined) { otcCandidates.push({ listingId, otc }); } else if (hasTerminalReturn) { const formattedTerminalReturn = normalizeAndFormatTerminalReturn( row.terminal_return as string, 'listing', listingKey, 'terminal_return' ); if (row.listed_to === null || row.listed_to === undefined) { skippedMissingListedTo += 1; } else { const listedTo = assertStrictYmd(row.listed_to, 'listing', listingKey, 'listed_to'); relevantDelistingListingIds.add(listingId); terminalCandidates.push({ listingId, listedTo, formattedTerminalReturn, }); } } else { skippedNoOutcome += 1; } lastListingId = listingId; } const chunkText = `${chunkLines.join('\n')}\n`; const buf = Buffer.from(chunkText, 'utf8'); await writeAll(listingCurrenciesHandle, buf); listingCurrenciesBytes += buf.byteLength; const venueChunkText = `${venueChunkLines.join('\n')}\n`; const venueBuf = Buffer.from(venueChunkText, 'utf8'); await writeAll(listingVenuesHandle, venueBuf); listingVenuesBytes += venueBuf.byteLength; if (res.rows.length < chunkSize) { break; } } // 3. Server-side NO SCROLL cursor read of provider_mapping -> stream provider_mapping.tsv // directly in bounded chunks without repeated per-page sorts on non-C DB collations. let lastSource: string | null = null; let lastSourceId: string | null = null; let lastValidFrom: string | null = null; let lastValidTo: string | null = null; await queryable.query( `DECLARE ${PROVIDER_MAPPING_CURSOR_NAME} NO SCROLL CURSOR FOR SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id FROM provider_mapping ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC` ); for (;;) { const res = await queryable.query( `FETCH FORWARD ${chunkSize} FROM ${PROVIDER_MAPPING_CURSOR_NAME}` ); if (res.rows.length === 0) { break; } const chunkLines: string[] = []; for (const row of res.rows) { const fallbackKey = `row#${providerMappingRowsIn}`; const source = assertNonBlankVerbatim(row.source, 'provider_mapping', fallbackKey, 'source'); const sourceId = assertNonBlankVerbatim( row.source_id, 'provider_mapping', `${source}:${fallbackKey}`, 'source_id' ); const key = `${source}:${sourceId}:${String(row.valid_from)}`; const validFrom = assertStrictYmd(row.valid_from, 'provider_mapping', key, 'valid_from'); let validTo: string | null = null; if (row.valid_to !== null && row.valid_to !== undefined) { validTo = assertStrictYmd(row.valid_to, 'provider_mapping', key, 'valid_to'); if (validTo < validFrom) { throw new CurateInputExportError({ code: 'INVALID_DATE_RANGE', table: 'provider_mapping', key: `${source}:${sourceId}:${validFrom}`, field: 'valid_to', detail: `valid_to "${validTo}" precedes valid_from "${validFrom}"`, }); } } const listingId = assertPositiveI32( row.listing_id, 'provider_mapping', `${source}:${sourceId}:${validFrom}`, 'listing_id' ); if (lastSource !== null && lastSourceId !== null && lastValidFrom !== null) { const pairCmp = compareAscii(source, lastSource) || compareAscii(sourceId, lastSourceId); if (pairCmp < 0) { throw new CurateInputExportError({ code: 'UNSORTED_PROVIDER_MAPPING_STREAM', table: 'provider_mapping', key: `${source}:${sourceId}:${validFrom}`, detail: `provider_mapping stream out of COLLATE "C" order ("${source}:${sourceId}" after "${lastSource}:${lastSourceId}")`, }); } if (pairCmp === 0) { const fromCmp = compareAscii(validFrom, lastValidFrom); if (fromCmp < 0) { throw new CurateInputExportError({ code: 'UNSORTED_PROVIDER_MAPPING_STREAM', table: 'provider_mapping', key: `${source}:${sourceId}:${validFrom}`, detail: `provider_mapping stream out of valid_from order ("${validFrom}" after "${lastValidFrom}")`, }); } if (fromCmp === 0) { throw new CurateInputExportError({ code: 'DUPLICATE_PROVIDER_MAPPING', table: 'provider_mapping', key: `${source}:${sourceId}:${validFrom}`, detail: 'duplicate (source, source_id, valid_from) primary key', }); } if (lastValidTo === null || lastValidTo >= validFrom) { throw new CurateInputExportError({ code: 'OVERLAPPING_PROVIDER_MAPPING', table: 'provider_mapping', key: `${source}:${sourceId}:${validFrom}`, detail: `inclusive range [${lastValidFrom}, ${lastValidTo ?? '+inf'}] overlaps [${validFrom}, ${validTo ?? '+inf'}]`, }); } } } if (source === delistingMappingSource && relevantDelistingListingIds.has(listingId)) { let list = qmMappingsByListingId.get(listingId); if (list === undefined) { list = []; qmMappingsByListingId.set(listingId, list); } list.push({ sourceId, validFrom, validTo, listingId }); } chunkLines.push( `${source}\t${sourceId}\t${validFrom}\t${validTo ?? ''}\t${listingId}` ); providerMappingRowsIn += 1; providerMappingRowsOut += 1; lastSource = source; lastSourceId = sourceId; lastValidFrom = validFrom; lastValidTo = validTo; } const chunkText = `${chunkLines.join('\n')}\n`; const buf = Buffer.from(chunkText, 'utf8'); await writeAll(providerMappingHandle, buf); providerMappingBytes += buf.byteLength; if (res.rows.length < chunkSize) { break; } } await queryable.query(`CLOSE ${PROVIDER_MAPPING_CURSOR_NAME}`); await queryable.query('COMMIT'); } catch (error) { try { await queryable.query('ROLLBACK'); } catch { // Preserve original error if ROLLBACK fails on a broken session. } throw error; } // 4. Assemble and chunk-write delistings.tsv. let skippedMissingOutgoingQmMapping = 0; let skippedMissingSuccessorQmMapping = 0; let otcTransfersOut = 0; let terminalDelistingsOut = 0; const delistingRows: ValidatedDelistingRow[] = []; for (const { listingId, otc } of otcCandidates) { const outgoing = selectQmMappingOnOrBefore( qmMappingsByListingId.get(listingId), otc.effectiveDate ); if (outgoing === null) { skippedMissingOutgoingQmMapping += 1; continue; } const successor = selectQmMappingOnDate( qmMappingsByListingId.get(otc.toListingId), otc.effectiveDate ); if (successor === null) { skippedMissingSuccessorQmMapping += 1; continue; } delistingRows.push({ sourceId: outgoing.sourceId, delistDate: otc.effectiveDate, fromListingId: listingId, successorSourceId: successor.sourceId, formattedTerminalReturn: '', }); otcTransfersOut += 1; } for (const { listingId, listedTo, formattedTerminalReturn } of terminalCandidates) { const outgoing = selectQmMappingOnDate(qmMappingsByListingId.get(listingId), listedTo); if (outgoing === null) { skippedMissingOutgoingQmMapping += 1; continue; } delistingRows.push({ sourceId: outgoing.sourceId, delistDate: listedTo, fromListingId: listingId, successorSourceId: null, formattedTerminalReturn, }); terminalDelistingsOut += 1; } delistingRows.sort(compareValidatedDelistingRows); for (let offset = 0; offset < delistingRows.length; offset += chunkSize) { const slice = delistingRows.slice(offset, offset + chunkSize); const chunkLines: string[] = []; for (const row of slice) { chunkLines.push( `${row.sourceId}\t${row.delistDate}\t${row.fromListingId === null ? '' : String(row.fromListingId)}\t${row.successorSourceId ?? ''}\t${row.formattedTerminalReturn}` ); } const buf = Buffer.from(`${chunkLines.join('\n')}\n`, 'utf8'); await writeAll(delistingsHandle, buf); delistingsBytes += buf.byteLength; } const delistingsRowsOut = otcTransfersOut + terminalDelistingsOut; const delistingsSkippedTotal = skippedActive + skippedNoOutcome + skippedMissingListedTo + skippedMissingOutgoingQmMapping + skippedMissingSuccessorQmMapping; delistingsStats = { rowsIn: delistingsRowsOut + delistingsSkippedTotal, rowsOut: delistingsRowsOut, otcTransfersOut, terminalDelistingsOut, skippedTotal: delistingsSkippedTotal, skipped: { active: skippedActive, noOutcome: skippedNoOutcome, missingListedTo: skippedMissingListedTo, missingOutgoingQmMapping: skippedMissingOutgoingQmMapping, missingSuccessorQmMapping: skippedMissingSuccessorQmMapping, nonOtcContinuity: 0, }, }; // 5. Sync and close all four staged files before atomic generation publish. await providerMappingHandle.sync(); await providerMappingHandle.close(); providerMappingHandle = null; await listingCurrenciesHandle.sync(); await listingCurrenciesHandle.close(); listingCurrenciesHandle = null; await listingVenuesHandle.sync(); await listingVenuesHandle.close(); listingVenuesHandle = null; await delistingsHandle.sync(); await delistingsHandle.close(); delistingsHandle = null; // 6. Acquire cross-process publish lock before touching shared top-level links or `current`. // The lock serializes link setup, backups, atomic `current` commit, and any rollback across // concurrent exporters targeting the same `outDir`. await acquirePublishLock( publishLockPath, outDir, runTag, publishLockTimeoutMs, fsOpen, fsUnlink ); publishLockAcquired = true; // Promote staging directory to an immutable generation and prepare top-level links. // Keep every backup until the single atomic commit point (`rename(currentTempLink, currentLink)`). await fsMkdir(generationsRoot, { recursive: true }); await fsRename(stagingDir, generationDir); generationMoved = true; stagingCreated = false; await fsSymlink(relativeGenerationTarget, currentTempLink); currentTempCreated = true; for (const key of publishOrder) { const expectedLinkTarget = join(CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES[key]); let existingStat: Awaited> | null = null; try { existingStat = await fsLstat(targets[key]); } catch (statErr) { if ((statErr as NodeJS.ErrnoException | undefined)?.code !== 'ENOENT') { throw statErr; } } if (existingStat === null) { await fsSymlink(expectedLinkTarget, linkTemps[key]); await fsRename(linkTemps[key], targets[key]); createdLinks.add(key); continue; } if (existingStat.isSymbolicLink()) { const currentTarget = await fsReadlink(targets[key]); if (currentTarget === expectedLinkTarget) { continue; } } // Pre-existing regular file or non-standard symlink: back it up and keep backup until commit. await fsRename(targets[key], backups[key]); backedUp.add(key); await fsSymlink(expectedLinkTarget, linkTemps[key]); await fsRename(linkTemps[key], targets[key]); } // 7. Single atomic commit point: atomically swap `/current` -> `generations/`. await fsRename(currentTempLink, currentLink); currentTempCreated = false; } catch (error) { // Close any still-open staged file handles. for (const handle of [ providerMappingHandle, listingCurrenciesHandle, listingVenuesHandle, delistingsHandle, ]) { if (handle !== null) { await handle.close().catch(() => {}); } } // Roll back any backed-up targets or newly created top-level links while still holding the publish lock. // Never unlink backups here: if a restore fails, retain the backup on disk and report it. const restoreFailures: Array<{ key: PublishKey; target: string; backup: string; message: string; }> = []; for (const key of [...publishOrder].reverse()) { if (backedUp.has(key)) { try { await fsRename(backups[key], targets[key]); } catch (restoreErr) { restoreFailures.push({ key, target: targets[key], backup: backups[key], message: restoreErr instanceof Error ? restoreErr.message : String(restoreErr), }); } } else if (createdLinks.has(key)) { await safeUnlink(fsUnlink, targets[key]).catch(() => {}); } } // Clean up uncommitted temporary artifacts (never backups). for (const key of publishOrder) { await safeUnlink(fsUnlink, linkTemps[key]).catch(() => {}); } if (currentTempCreated) { await safeUnlink(fsUnlink, currentTempLink).catch(() => {}); } if (stagingCreated) { await fsRm(stagingDir, { recursive: true, force: true }).catch(() => {}); } if (generationMoved) { await fsRm(generationDir, { recursive: true, force: true }).catch(() => {}); } if (publishLockAcquired) { await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {}); await safeUnlink(fsUnlink, publishLockPath).catch(() => {}); publishLockAcquired = false; } if (restoreFailures.length > 0) { const originalMessage = error instanceof Error ? error.message : String(error); const failureSummary = restoreFailures .map(f => `${f.key} (retained backup: ${f.backup}, target: ${f.target}): ${f.message}`) .join('; '); throw new CurateInputExportError({ code: 'PUBLISH_ROLLBACK_FAILED', table: 'publish', key: restoreFailures.map(f => f.key).join(','), detail: `export failed (${originalMessage}) and backup restoration failed; retained backups: ${failureSummary}`, cause: error, }); } throw error; } // 8. Post-commit lock release & backup cleanup (outside rollback scope: publication is already committed). const cleanupWarnings: string[] = []; if (publishLockAcquired) { try { await safeUnlink(fsUnlink, publishLockPath); publishLockAcquired = false; } catch (lockCleanupErr) { const msg = lockCleanupErr instanceof Error ? lockCleanupErr.message : String(lockCleanupErr); cleanupWarnings.push( `Failed to remove post-commit publish lock ${publishLockPath} (publication committed): ${msg}` ); } } for (const key of backedUp) { try { await safeUnlink(fsUnlink, backups[key]); } catch (cleanupErr) { const msg = cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr); cleanupWarnings.push( `Failed to remove post-commit backup ${backups[key]} (publication committed): ${msg}` ); } } return { outDir, generationId, generationDir, currentLink, chunkSize, delistingMappingSource, providerMapping: { path: generationFiles.providerMapping, rowsIn: providerMappingRowsIn, rowsOut: providerMappingRowsOut, bytesWritten: providerMappingBytes, }, listingCurrencies: { path: generationFiles.listingCurrencies, rowsIn: listingCurrenciesRowsIn, rowsOut: listingCurrenciesRowsOut, bytesWritten: listingCurrenciesBytes, }, listingVenues: { path: generationFiles.listingVenues, rowsIn: listingVenuesRowsIn, rowsOut: listingVenuesRowsOut, bytesWritten: listingVenuesBytes, }, delistings: { path: generationFiles.delistings, rowsIn: delistingsStats.rowsIn, rowsOut: delistingsStats.rowsOut, bytesWritten: delistingsBytes, stats: delistingsStats, }, totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + listingVenuesBytes + delistingsBytes, cleanupWarnings, }; }