import type { BasePayload, PayloadRequest } from 'payload' import { AsyncLocalStorage } from 'node:async_hooks' /** * Transactions and the Postgres pool. * * Payload holds one pool connection for the whole of a transaction. Code inside it that reads or writes * WITHOUT the transaction's `req` needs a second connection: Payload's own "forgot password" (it reserves * the request interval outside the transaction), an e-mail adapter reading its settings, the key-value * store, a project's hook that forgot `req`. With the default pool of 10, ten such requests at the same * moment hold all ten connections and each waits for an eleventh: the whole site stops, for good. * * `reserveConnections` keeps a few connections free of transactions: at most `pool size − reserve` * transactions are open at once, the next one waits for a free place (its request is slower, nothing * stops). * * A transaction begun INSIDE another one — a hook that calls the Local API without `req` writes in a * transaction of its own while its caller's stays open — is not queued: it takes no place and goes * straight to the pool, because its caller cannot finish without it. "Inside" is told by an * AsyncLocalStorage mark set when the outer one begins. In case the mark is lost on the way (Node 22 * keeps such a mark per callback, not per operation), a queue that has not moved for a second * (RESERVE_ESCAPE_MS) lets its NEWEST waiter — the one most likely begun by a waiting caller — use the * reserve, all but the last connection. * * `afterCommit(req, fn)` runs `fn` right after the transaction of `req` commits, before the operation that * began it returns — for work that must not hold a connection, such as sending e-mail. */ type TransactionID = number | string type Entry = { after: (() => Promise | void)[]; depth: number; slot: boolean } /** `depth`: 0 = an outer transaction, 1 = begun inside one, 2 = inside that, … */ type Waiter = { depth: number; resolve: () => void; since: number } type Watch = { /** Transactions holding one of the limited places. */ active: number /** When a place was last given back (or the watch started). */ moved: number /** Transactions begun inside another one: no place, straight to the pool. */ nested: number /** Open transactions begun through this watch, by id. */ open: Map queue: Waiter[] /** Connections kept free; `null` = no limit (not Postgres, or switched off). */ reserve: null | number timer?: ReturnType } type WatchedDb = { beginTransaction?: (...args: unknown[]) => Promise commitTransaction?: (id: Promise | TransactionID) => Promise pool?: { options?: { max?: number } } rollbackTransaction?: (id: Promise | TransactionID) => Promise [WATCH]?: Watch } const WATCH = Symbol.for('iapl.transactionWatch') /** A queue that has not moved this long lets its newest waiter use the reserve (all but one connection). */ export const RESERVE_ESCAPE_MS = 1000 /** The transaction the running code is inside: set in the caller's own continuation when it begins one. */ const current = new AsyncLocalStorage<{ depth: number; id?: TransactionID }>() const dbOf = (payload: BasePayload) => ((payload as { db?: unknown } | undefined)?.db ?? {}) as WatchedDb /** The size of the adapter's pool (pg's default is 10), or null for an adapter without one. */ export function poolSize(payload: BasePayload): null | number { const pool = dbOf(payload).pool if (!pool) {return null} const max = pool.options?.max return typeof max === 'number' && max > 0 ? max : 10 } /** Connections kept free by default: a fifth of the pool, at least 2 (1 in a pool of fewer than 4). */ export function defaultConnectionReserve(size: number): number { return size < 4 ? 1 : Math.max(2, Math.ceil(size / 5)) } const limitOf = (payload: BasePayload, watch: Watch) => { const size = poolSize(payload) ?? Infinity return { limit: watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve), size } } /** How many transactions may be open in all when one begun at nesting `depth` (1 = inside an outer one) is let in. */ const nestedRoom = (size: number, limit: number, depth: number) => Math.max(size - 2, limit) + depth function admit(watch: Watch, waiter: Waiter): void { watch.queue.splice(watch.queue.indexOf(waiter), 1) if (waiter.depth > 0) {watch.nested += 1} else {watch.active += 1} waiter.resolve() } function drain(payload: BasePayload, watch: Watch): void { const { limit, size } = limitOf(payload, watch) // No reserve (switched off, or an adapter without a pool): nobody waits. if (watch.reserve === null) { while (watch.queue.length) {admit(watch, watch.queue[0])} return } const open = () => watch.active + watch.nested // A transaction begun inside another one first, the deepest first: its caller holds a place and waits for it. // It may use the reserve but the last connection (a second level that one too; in a pool of 3 or 4, one place // past the limit per level), so that a connection is left for the queries that run outside transactions. for (const waiter of [...watch.queue].filter((w) => w.depth > 0).sort((a, b) => b.depth - a.depth)) { if (open() < nestedRoom(size, limit, waiter.depth)) {admit(watch, waiter)} } // Then first come, first served while there is a place. let head = watch.queue.find((w) => w.depth === 0) while (head && watch.active < limit && open() < size - 1) { admit(watch, head) head = watch.queue.find((w) => w.depth === 0) } if (!watch.queue.length) {return} const now = Date.now() // The queue has not moved for a second: the places may all be held by callers waiting for a transaction of // their own whose mark was lost. The newest waiter may use the reserve, all but the last connection. const oldest = Math.min(...watch.queue.map((w) => w.since)) if (now - Math.max(watch.moved, oldest) >= RESERVE_ESCAPE_MS && open() < size - 1) { admit(watch, watch.queue[watch.queue.length - 1]) watch.moved = now } if (watch.queue.length && !watch.timer) { const wait = Math.max(1, Math.max(watch.moved, oldest) + RESERVE_ESCAPE_MS - now) watch.timer = setTimeout(() => { watch.timer = undefined drain(payload, watch) }, wait) watch.timer.unref?.() } } function acquire(payload: BasePayload, watch: Watch, depth: number): Promise | undefined { let resolve = () => {} const done = new Promise((r) => (resolve = r)) const waiter: Waiter = { depth, resolve: () => resolve(), since: Date.now() } watch.queue.push(waiter) drain(payload, watch) return watch.queue.includes(waiter) ? done : undefined } function release(payload: BasePayload, watch: Watch, slot = true): void { if (slot) {watch.active = Math.max(0, watch.active - 1)} else {watch.nested = Math.max(0, watch.nested - 1)} watch.moved = Date.now() drain(payload, watch) } function finish(payload: BasePayload, watch: Watch, id: TransactionID): Entry | undefined { const entry = watch.open.get(id) if (!entry) {return undefined} watch.open.delete(id) release(payload, watch, entry.slot) return entry } /** * Wraps the adapter's begin / commit / rollback once (idempotent). `reserve`: connections kept free of * transactions (Postgres only), `false` = no limit; the watch for `afterCommit` is installed either way. * Returns the watch, or null when the adapter has no transactions to watch. */ export function watchTransactions(payload: BasePayload, reserve: false | number = defaultConnectionReserve(poolSize(payload) ?? 10)): null | Watch { const db = dbOf(payload) if (typeof db.beginTransaction !== 'function' || typeof db.commitTransaction !== 'function' || typeof db.rollbackTransaction !== 'function') {return null} const size = poolSize(payload) const wanted = reserve === false || size === null ? null : Number.isFinite(reserve) ? Math.max(0, Math.floor(reserve)) : defaultConnectionReserve(size) if (db[WATCH]) { db[WATCH].reserve = wanted drain(payload, db[WATCH]) return db[WATCH] } const watch: Watch = { active: 0, moved: Date.now(), nested: 0, open: new Map(), queue: [], reserve: wanted } db[WATCH] = watch const begin = db.beginTransaction const commit = db.commitTransaction const rollback = db.rollbackTransaction // Not `async`: the mark must be set in the caller's own (synchronous) part, so that what the caller does // next — its hooks, a Local API call without `req` — carries it. db.beginTransaction = function (this: unknown, ...args: unknown[]) { const outer = current.getStore() const outerEntry = outer?.id !== undefined ? watch.open.get(outer.id) : undefined const depth = outerEntry ? outerEntry.depth + 1 : 0 const mark: { depth: number; id?: TransactionID } = { depth } current.enterWith(mark) return (async () => { const waiting = acquire(payload, watch, depth) if (waiting) {await waiting} let id: null | TransactionID try { id = await begin.apply(this, args) } catch (err) { release(payload, watch, depth === 0) throw err } if (id === null || id === undefined) { release(payload, watch, depth === 0) return id } mark.id = id watch.open.set(id, { after: [], depth, slot: depth === 0 }) return id })() } db.commitTransaction = async function (this: unknown, incoming) { const id = incoming instanceof Promise ? await incoming : incoming try { await commit.call(this, id) } catch (err) { finish(payload, watch, id) throw err } const entry = finish(payload, watch, id) for (const fn of entry?.after ?? []) { try { await fn() } catch (err) { payload.logger.error({ err, msg: '[iapl] A step that runs after a transaction commits failed.' }) } } } db.rollbackTransaction = async function (this: unknown, incoming) { const id = incoming instanceof Promise ? await incoming : incoming try { await rollback.call(this, id) } finally { finish(payload, watch, id) } } return watch } /** * Keeps `reserve` pool connections free of transactions (Postgres; does nothing on an adapter without a * pool). `iapl()` calls it at start; a project that uses only the building blocks calls it in its own * `onInit`: * onInit: (payload) => { reserveConnections(payload) } * `reserve`: a number, or the default (a fifth of the pool, at least 2). Calling it again changes the number. */ export function reserveConnections(payload: BasePayload, reserve?: number): void { watchTransactions(payload, reserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)) } /** * Runs `fn` right after the transaction of `req` commits — still inside the operation that began it, so * that operation returns only once `fn` is done — and drops it when the transaction is rolled back. * Returns `false` when there is no transaction to wait for (none open, an adapter without transactions, * one this watch did not see begin): then nothing is scheduled and the caller does the work at once. * A caller's OUTER transaction counts: `fn` runs when that one commits. * An error thrown by `fn` is logged; it does not undo the commit. */ export function afterCommit(req: Pick, fn: () => Promise | void): boolean { const id = req.transactionID if (id === undefined || id === null || id instanceof Promise) {return false} const entry = dbOf(req.payload)[WATCH]?.open.get(id) if (!entry) {return false} entry.after.push(fn) return true } /** True when `req` is inside a transaction that `afterCommit` can wait for. */ export function inWatchedTransaction(req: Pick): boolean { const id = req.transactionID return id !== undefined && id !== null && !(id instanceof Promise) && Boolean(dbOf(req.payload)[WATCH]?.open.has(id)) } /** * True while every place for a transaction is taken or a transaction waits for one (Postgres with the * reserve on). Work that would open a transaction of its own and is not needed for the caller's answer — * the panel status of an integration — runs in the background then instead of holding its caller, which * may itself be inside a transaction. */ export function transactionsBusy(payload: BasePayload): boolean { const watch = dbOf(payload)[WATCH] if (!watch || watch.reserve === null) {return false} const size = poolSize(payload) ?? Infinity return watch.queue.length > 0 || watch.active >= Math.max(1, size - watch.reserve) } /** For tests and diagnostics: open transactions, waiting ones and the reserve in force. */ export function transactionWatchState(payload: BasePayload): { active: number; nested: number; reserve: null | number; waiting: number } | null { const watch = dbOf(payload)[WATCH] return watch ? { active: watch.active, nested: watch.nested, reserve: watch.reserve, waiting: watch.queue.length } : null }