T-116: M1.2af — data-pipeline: read-only security-master → curate-etl input exporter (provider_mapping.tsv, listing_currencies.tsv, Pass 6 delistings.tsv from PostgreSQL) with tests and local benchmark
This commit is contained in:
parent
88b7f1f020
commit
7c55c97c44
8 changed files with 576 additions and 26 deletions
|
|
@ -25,9 +25,12 @@ export const CURATE_INPUT_FILES = Object.freeze({
|
|||
|
||||
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;
|
||||
|
|
@ -55,6 +58,7 @@ export type CurateInputExportErrorCode =
|
|||
| 'SELF_SUCCESSOR_CONTINUITY'
|
||||
| 'DUPLICATE_OTC_CONTINUITY'
|
||||
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
|
||||
| 'PUBLISH_LOCK_TIMEOUT'
|
||||
| 'PUBLISH_ROLLBACK_FAILED';
|
||||
|
||||
export interface CurateInputExportErrorOptions {
|
||||
|
|
@ -168,6 +172,7 @@ export interface ExportCurateInputsOptions {
|
|||
readonly outDir: string;
|
||||
readonly chunkSize?: number;
|
||||
readonly delistingMappingSource?: string;
|
||||
readonly publishLockTimeoutMs?: number;
|
||||
readonly fs?: ExportCurateInputsFsHooks;
|
||||
}
|
||||
|
||||
|
|
@ -1132,6 +1137,47 @@ async function writeAll(handle: FileHandle, buf: Buffer): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
async function acquirePublishLock(
|
||||
lockPath: string,
|
||||
outDir: string,
|
||||
runTag: string,
|
||||
timeoutMs: number,
|
||||
fsOpen: typeof open
|
||||
): Promise<void> {
|
||||
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;
|
||||
try {
|
||||
handle = await fsOpen(lockPath, 'wx');
|
||||
await writeAll(handle, payload);
|
||||
await handle.close();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (handle !== null) {
|
||||
await handle.close().catch(() => {});
|
||||
}
|
||||
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 `<outDir>/current`
|
||||
* before a consumer opens any TSV file. All three returned paths belong to the same atomic
|
||||
|
|
@ -1196,6 +1242,20 @@ export async function exportCurateInputs(
|
|||
|
||||
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',
|
||||
|
|
@ -1225,6 +1285,7 @@ export async function exportCurateInputs(
|
|||
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),
|
||||
|
|
@ -1271,6 +1332,7 @@ export async function exportCurateInputs(
|
|||
const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings'];
|
||||
|
||||
let stagingCreated = false;
|
||||
let publishLockAcquired = false;
|
||||
let generationMoved = false;
|
||||
let currentTempCreated = false;
|
||||
const backedUp = new Set<PublishKey>();
|
||||
|
|
@ -1784,7 +1846,13 @@ export async function exportCurateInputs(
|
|||
await delistingsHandle.close();
|
||||
delistingsHandle = null;
|
||||
|
||||
// 6. Promote staging directory to an immutable generation and prepare top-level links.
|
||||
// 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);
|
||||
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);
|
||||
|
|
@ -1837,7 +1905,7 @@ export async function exportCurateInputs(
|
|||
}
|
||||
}
|
||||
|
||||
// Roll back any backed-up targets or newly created top-level links.
|
||||
// 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;
|
||||
|
|
@ -1877,6 +1945,11 @@ export async function exportCurateInputs(
|
|||
}
|
||||
await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {});
|
||||
|
||||
if (publishLockAcquired) {
|
||||
await safeUnlink(fsUnlink, publishLockPath).catch(() => {});
|
||||
publishLockAcquired = false;
|
||||
}
|
||||
|
||||
if (restoreFailures.length > 0) {
|
||||
const originalMessage = error instanceof Error ? error.message : String(error);
|
||||
const failureSummary = restoreFailures
|
||||
|
|
@ -1894,8 +1967,20 @@ export async function exportCurateInputs(
|
|||
throw error;
|
||||
}
|
||||
|
||||
// 8. Post-commit backup cleanup (outside rollback scope: publication is already committed).
|
||||
// 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]);
|
||||
|
|
|
|||
|
|
@ -52,9 +52,11 @@ export {
|
|||
CURATE_INPUT_CURRENT_LINK,
|
||||
CURATE_INPUT_FILES,
|
||||
CURATE_INPUT_GENERATIONS_DIR,
|
||||
CURATE_INPUT_PUBLISH_LOCK,
|
||||
CurateInputExportError,
|
||||
DEFAULT_DELISTING_MAPPING_SOURCE,
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
DEFAULT_PUBLISH_LOCK_TIMEOUT_MS,
|
||||
exportCurateInputs,
|
||||
formatDelistingsTsv,
|
||||
formatListingCurrenciesTsv,
|
||||
|
|
|
|||
|
|
@ -168,7 +168,7 @@ export function formatExportCurateInputsSummary(result: ExportCurateInputsResult
|
|||
const d = result.delistings.stats;
|
||||
const s = d.skipped;
|
||||
const lines = [
|
||||
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId})`,
|
||||
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`,
|
||||
` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`,
|
||||
` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`,
|
||||
` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue