/** * @siax/access idempotency primitives — the universal SIAX contract for any * operation that must either happen exactly once or replay its receipt. * * This package is derived from the pattern proven in 0pt's durable upload * attempts (prepare -> claim -> dispatch -> store receipt -> replay), then * generalized so DOC0, N0D and future products can adopt the identical shape * instead of re-implementing it. * * Rules encoded here: * 1. An operation identity binds EVERY result-affecting input (tenant, * project, actor, payload version). A changed payload under the same key * is a CONFLICT, never a replay of someone else's receipt. * 2. One claimant per key: returning `false` from `start` means another * caller owns the dispatch, and only the stored receipt (or bounded * observation) may be answered. * 3. A stored receipt is replayed verbatim; the caller never invents one. * 4. Commit boundaries: NEVER write a network command before the claim is * durably persisted, and never lose the claim after the command may have * committed. */ import { createHash } from "node:crypto"; /** Stable JSON canonicalization (sorted array stays sorted; v-prefix bumped on contract change). */ export function operationFingerprint(parts: readonly unknown[], version = "siax-idempotency-v1"): string { return createHash("sha256") .update(JSON.stringify([version, ...parts])) .digest("hex"); } export interface OperationIdentity { tenantId: string; projectId: string; actorId: string; /** Client-generated, transport-level key (<=256 visible ASCII). */ idempotencyKey: string; /** Supply result-affecting inputs; the helper adds the scope fields itself. */ payload: readonly unknown[]; } export function operationIdentity(operation: OperationIdentity): { tenantId: string; projectId: string; actorId: string; idempotencyKey: string; fingerprint: string; } { if ( !operation || ![operation.tenantId, operation.projectId, operation.actorId, operation.idempotencyKey].every( (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._@:+-]{0,255}$/.test(value), ) || !Array.isArray(operation.payload) ) { throw new Error("Invalid idempotent operation identity"); } void operation.payload; return { tenantId: operation.tenantId, projectId: operation.projectId, actorId: operation.actorId, idempotencyKey: operation.idempotencyKey, fingerprint: operationFingerprint([ operation.tenantId, operation.projectId, operation.actorId, ...operation.payload, ]), }; } export type OperationOutcome = | { kind: "claimed"; execute: () => Promise } | { kind: "replayed"; receipt: R } | { kind: "conflict"; expected?: string }; /** Structural contract for an attempt store. Matched by Postgres adapters per product. */ export interface IdempotencyStore { /** Returns true when this caller won the right to dispatch; false = reuse replay path. */ start(identity: Identity, fingerprint: string): Promise; /** Persist after a verified downstream commit. Must never be called before. */ save(identity: Identity, fingerprint: string, receipt: Receipt): Promise; /** Load a stored receipt for replay (exact fingerprint match). */ receipt(identity: Identity, fingerprint: string): Promise; } export type IdempotentStoreItemIdentity = { identity: I; fingerprint: string; }; export async function runIdempotentOperation(input: { store: IdempotencyStore; identity: I; fingerprint: string; /** Must be safe to call exactly once; a second call is never attempted here. */ dispatch: () => Promise; }): Promise> { if (typeof input.dispatch !== "function") throw new Error("Dispatch is required"); try { const won = await input.store.start(input.identity, input.fingerprint); if (!won) { const stored = await input.store.receipt(input.identity, input.fingerprint); return stored !== undefined ? { kind: "replayed", receipt: stored } : { kind: "replayed", receipt: undefined as unknown as R }; } } catch (error) { return { kind: "conflict", expected: error instanceof Error ? error.message : "store_unavailable" }; } const receipt = await input.dispatch(); try { await input.store.save(input.identity, input.fingerprint, receipt); } catch { /* The downstream commit is real; a journal-write failure must not turn a real receipt into an error. The next retry replays via the stored receipt if the save ever succeeds before a downstream resend. */ } return { kind: "claimed", execute: async () => receipt }; }