Files
0pt/src/ingestion/envelope.ts
T

88 lines
3.4 KiB
TypeScript

/**
* src/ingestion/envelope.ts
* ==========================
* P062: the one place a ConnectorRecord becomes an IngestionEnvelope. Every
* connector, every mode, one function — that is what "normalize all ingestion
* to a common envelope" means operationally.
*
* `hashPayload` is the stable content hash the idempotency ledger (P068) and
* the deterministic `envelope_id` are both built on. Key order must not
* change the hash — two connectors reading the same record can serialize the
* same object with different key order — so keys are sorted recursively.
* Undefined values are dropped (JSON has no undefined); null is kept, because
* "field explicitly null" is different data from "field absent".
*/
import crypto from "crypto";
import type { ConnectorRecord } from "../connectors/connector";
import type { EnvelopeOperation, IngestionEnvelope, IngestionMode } from "../types/ingestion";
/** Recursively key-sorted JSON — stable across key insertion order. */
export function stableStringify(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
if (typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
/** Content hash of an envelope payload. A delete (null payload) hashes as "deleted". */
export function hashPayload(payload: Record<string, unknown> | null): string {
if (payload === null) return "sha256:deleted";
return `sha256:${crypto.createHash("sha256").update(stableStringify(payload)).digest("hex")}`;
}
export interface BuildEnvelopeInput {
record: ConnectorRecord;
source_id: string;
tenant_id: string;
project_id: string;
mode: IngestionMode;
partition_key: string;
schema_version: number;
sequence: number;
connector_id: string;
connector_version: string;
run_id: string;
/** Cursor covering this record, when the connector reports one. */
cursor?: string;
now?: string;
}
export function buildEnvelope(input: BuildEnvelopeInput): IngestionEnvelope {
const operation: EnvelopeOperation = input.record.operation ?? "upsert";
const payload = operation === "delete" ? null : input.record.payload;
const contentHash = hashPayload(payload);
return {
// Deterministic: the same record with the same content re-read after a
// crash produces the same envelope_id, so a downstream sink that dedups
// by id sees a retry, not a new record.
envelope_id: `env_${crypto
.createHash("sha256")
.update(`${input.source_id}|${input.partition_key}|${input.record.record_key}|${contentHash}`)
.digest("hex")
.slice(0, 32)}`,
source_id: input.source_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
mode: input.mode,
operation,
partition_key: input.partition_key,
record_key: input.record.record_key,
schema_version: input.schema_version,
sequence: input.sequence,
occurred_at: input.record.occurred_at,
ingested_at: input.now ?? new Date().toISOString(),
payload,
provenance: {
connector_id: input.connector_id,
connector_version: input.connector_version,
run_id: input.run_id,
cursor: input.cursor ?? input.record.cursor,
},
};
}