import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres" import type { PoolClient } from "pg" import * as schema from "../db/schema.js" import { assertDatabaseRestoreQuarantineOpen, databaseRestoreQuarantineEnabled } from "../db/database-restore-quarantine.js" // Independent of the optional trigger proposal/migration and maintenance // runtime: collectors can acquire this key before their first relation access. export const PARTITION_WRITER_ADVISORY_KEY = 8723110 const admittedClients = new WeakMap boolean>() /** Identity proof for the guarded client owned by this module. A caller's * query property or serialized marker can never manufacture this capability. */ export function isPartitionWriteClient(value: unknown): value is PoolClient { return !!value && typeof value === "object" && admittedClients.get(value)?.() === true } export interface PartitionWriteOptions { authorize?: () => Promise signal?: AbortSignal deadlineAt?: number connect?: () => Promise } export interface PartitionWriteOwner { client: PoolClient; db: NodePgDatabase } export class PartitionWriterBusy extends Error { constructor() { super("Partition writer lock is busy") } } export class PartitionWriteError extends Error { readonly automaticReplay = false readonly code: "PARTITION_WRITE_UNAVAILABLE" | "PARTITION_WRITE_UNKNOWN" constructor(readonly outcomeUnknown = false) { super(outcomeUnknown ? "Partition write outcome unknown; automatic replay forbidden" : "Partition write transaction unavailable or closed") this.code = outcomeUnknown ? "PARTITION_WRITE_UNKNOWN" : "PARTITION_WRITE_UNAVAILABLE" } } export const isPartitionWriteOutcomeUnknown = (error: unknown): error is PartitionWriteError => error instanceof PartitionWriteError && error.outcomeUnknown type PartitionWriteStage = "checkout" | "begin" | "admission" | "work" | "commit" const failureDiagnostics = new WeakMap() export function partitionWriteFailureDiagnostic(error: unknown) { return error instanceof PartitionWriteError ? failureDiagnostics.get(error) : undefined } function safeSqlState(error: unknown): string | undefined { if (!(error instanceof Error)) return undefined const code = Object.getOwnPropertyDescriptor(error, "code")?.value // SQLSTATE excludes transport codes such as EPIPE and ECONNRESET. return typeof code === "string" && /^[0-9A-Z]{5}$/.test(code) && /[0-9]/.test(code) ? code : undefined } const boundary = /^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE|START\s+TRANSACTION|PREPARE\s+TRANSACTION)\b/i function settings(options: PartitionWriteOptions) { const now = Date.now(), deadlineAt = options.deadlineAt ?? now + 30000 if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= now || deadlineAt - now > 120000 || options.signal?.aborted) throw new PartitionWriteError() return { ...options, deadlineAt } } function remaining(deadlineAt: number) { const value = deadlineAt - Date.now() if (value <= 0) throw new PartitionWriteError() return Math.max(1, Math.min(5000, value)) } /** Caller MUST already own an open SQL transaction on this exact backend and * MUST call before any partition/table query or secondary writer lock. This * helper never starts/commits a caller's transaction and never retries SQL. * Its bounded server timeout also applies when a surrounding Drizzle tx owns * the lifecycle. The surrounding owner must roll back/destroy on rejection. */ type PartitionAdmissionClient = { query(text: string, values?: [number]): Promise } async function acquirePartitionWriter(client: PartitionAdmissionClient, options: Omit, acquire: () => Promise) { const current = settings(options) const check = async () => { if (current.signal?.aborted) throw new PartitionWriteError() remaining(current.deadlineAt); await current.authorize?.() if (current.signal?.aborted) throw new PartitionWriteError() remaining(current.deadlineAt) } await check() await client.query(`SET LOCAL lock_timeout='${remaining(current.deadlineAt)}ms'`) await check() await client.query(`SET LOCAL statement_timeout='${remaining(current.deadlineAt)}ms'`) await check() const acquired = await acquire() if (acquired && databaseRestoreQuarantineEnabled()) { await assertDatabaseRestoreQuarantineOpen({ query: text => client.query(text) }) } if (acquired && process.env.DATABASE_RUNTIME_ACTIVATION_DIRECTORY !== undefined) { const { assertRuntimeDatabaseActivationCurrent } = await import("../db/index.js") assertRuntimeDatabaseActivationCurrent() } await check() return acquired } export async function admitPartitionWriter(client: PartitionAdmissionClient, options: Omit = {}): Promise { await acquirePartitionWriter(client, options, async () => { await client.query("SELECT pg_advisory_xact_lock_shared($1::bigint)", [PARTITION_WRITER_ADVISORY_KEY]) return true }) } export function tryAdmitPartitionWriter(client: Pick, options: Omit = {}): Promise { return acquirePartitionWriter(client, options, async () => { const { rows } = await client.query<{ acquired: boolean }>( "SELECT pg_catalog.pg_try_advisory_xact_lock_shared($1::bigint) AS acquired", [PARTITION_WRITER_ADVISORY_KEY]) if (rows.length !== 1 || typeof rows[0].acquired !== "boolean") throw new PartitionWriteError() return rows[0].acquired }) } /** Owns exactly one checked-out backend for raw SQL AND Drizzle. Admission is * BEGIN → bounded LOCAL timeouts → shared writer key → target relation SQL. * Query handles expire before COMMIT; detached work cannot use a pooled client * after release. Any failed/uncertain boundary destroys the owner. No retries * and no ROLLBACK is sent after an uncertain BEGIN/COMMIT acknowledgement. */ async function runPartitionWrite(work: (owner: PartitionWriteOwner) => Promise, options: PartitionWriteOptions, deferIfBusy: boolean): Promise { const current = settings(options) let client: PoolClient | undefined, released = false, active = false, accepting = false let beginSent = false, beginAcknowledged = false, commitSent = false, committed = false, ended = false let queryFailed = false let stage: PartitionWriteStage = "checkout" let querySqlState: string | undefined const inflight = new Set>() const release = (destroy: boolean) => { active = false; accepting = false; if (client && !released) { released = true; client.release(destroy) } } const check = async () => { if (ended || current.signal?.aborted) throw new PartitionWriteError(beginSent && !beginAcknowledged || commitSent) remaining(current.deadlineAt); await Promise.race([current.authorize?.() ?? Promise.resolve(), stopped]) if (ended || current.signal?.aborted) throw new PartitionWriteError(beginSent && !beginAcknowledged || commitSent) remaining(current.deadlineAt) } let stop!: (error: PartitionWriteError) => void const stopped = new Promise((_resolve, reject) => { stop = reject }) void stopped.catch(() => {}) const destroy = () => { ended = true; release(true); stop(new PartitionWriteError(beginSent && !beginAcknowledged || commitSent)) } const timer = setTimeout(destroy, Math.max(1, current.deadlineAt - Date.now())) current.signal?.addEventListener("abort", destroy, { once: true }) try { const connect = current.connect ?? (async () => (await import("../db/index.js")).pool.connect()) const pending = connect() client = await Promise.race([pending, stopped, new Promise((_resolve, reject) => { const admissionTimer = setTimeout(() => reject(new PartitionWriteError()), Math.min(5000, remaining(current.deadlineAt))) pending.finally(() => clearTimeout(admissionTimer)).catch(() => {}) })]).catch(error => { ended = true; void pending.then(late => late.release(true), () => {}); throw error }) if (ended) { release(true); throw new PartitionWriteError() } await check() stage = "begin" beginSent = true await Promise.race([client.query("BEGIN"), stopped]) beginAcknowledged = true stage = "admission" await check() if (deferIfBusy) { const acquired = await Promise.race([tryAdmitPartitionWriter(client, current), stopped]) if (!acquired) { const rollback = await Promise.race([client.query("ROLLBACK"), stopped]) if (rollback.command !== "ROLLBACK") throw new PartitionWriteError() await check() release(false) throw new PartitionWriterBusy() } } else await Promise.race([admitPartitionWriter(client, current), stopped]) stage = "work" active = true; accepting = true const rawClient = client const guardedQuery = (...args: unknown[]) => { const callback = typeof args.at(-1) === "function" ? args.pop() as (error: Error | null, value?: unknown) => void : undefined const run = async () => { if (!active || !accepting || released) throw new PartitionWriteError() const text = typeof args[0] === "string" ? args[0] : args[0] && typeof args[0] === "object" && "text" in args[0] ? String(args[0].text) : "" // Scope clients only run application statements. The owner keeps all // transaction boundaries and cannot be escaped through Drizzle SQL. const statement = text.replace(/\/\*[\s\S]*?\*\/|--[^\r\n]*/g, " ").trim() if (!statement || boundary.test(statement) || /;\s*\S/.test(statement)) throw new PartitionWriteError() await check() if (!active || !accepting || released) throw new PartitionWriteError() let result: unknown try { result = await Reflect.apply(rawClient.query, rawClient, args) } catch (error) { querySqlState ??= safeSqlState(error); throw error } await check() return result } const pending = run(); inflight.add(pending) void pending.then(() => inflight.delete(pending), () => { queryFailed = true; inflight.delete(pending) }) if (callback) { void pending.then(value => callback(null, value), error => callback(error)); return } return pending } const guarded = new Proxy(rawClient, { get(target, property) { if (property === "query") return guardedQuery if (property === "release" || property === "end" || property === "connect" || property === "connection") throw new PartitionWriteError() const value = Reflect.get(target, property, target) return typeof value === "function" ? value.bind(target) : value } }) const owner: PartitionWriteOwner = { client: guarded, db: drizzle(guarded, { schema }) } admittedClients.set(guarded, () => active && accepting && !released && !ended && current.deadlineAt > Date.now() && !current.signal?.aborted) const result = await Promise.race([work(owner), stopped]) accepting = false // Await already-started work, then close both SQL handles BEFORE COMMIT. await Promise.race([Promise.all([...inflight]), stopped]); active = false if (queryFailed) throw new PartitionWriteError() await check(); stage = "commit"; commitSent = true const commitResult = await Promise.race([client.query("COMMIT"), stopped]) if (commitResult.command !== "COMMIT") throw new PartitionWriteError(true) committed = true await check(); release(false) return result } catch (error) { if (error instanceof PartitionWriterBusy && released && stage === "admission") throw error const unknown = beginSent && !beginAcknowledged || commitSent || committed destroy() const failure = error instanceof PartitionWriteError && error.outcomeUnknown === unknown ? error : new PartitionWriteError(unknown) failureDiagnostics.set(failure, { stage, sqlState: querySqlState ?? safeSqlState(error) }) throw failure } finally { clearTimeout(timer); current.signal?.removeEventListener("abort", destroy) if (!released) release(true) } } export function withPartitionWrite(work: (owner: PartitionWriteOwner) => Promise, options: PartitionWriteOptions = {}): Promise { return runPartitionWrite(work, options, false) } /** Defer scheduled maintenance only on a definite negative lock result. */ export function withBackgroundPartitionWrite(work: (owner: PartitionWriteOwner) => Promise, options: PartitionWriteOptions = {}): Promise { return runPartitionWrite(work, options, true) }