Postgres: many requests at once no longer stop the site
Each Payload transaction holds a pool connection; code inside it that runs without its req needs a second one (Payload's own forgotPassword, the mail adapter's settings read and status write, payload.kv). With the default pool of 10, ten form submissions or ten "forgot password" requests at once held every connection and waited for good. - connectionReserve (default on): at most pool size − reserve transactions open at once; a waiter older than a second may use all but the last connection. Building blocks in modules/database/transactions.ts. - Form e-mails go out right after the submission's transaction commits, in the same request (forms.emailsInTransaction: true = the old way). - recordIntegrationStatus merges identical writes and does not hold its caller while the pool is busy. - SMTP time-outs: 10 s connect, 30 s greeting, 60 s silence (smtp.timeouts). Tests on Postgres 17: 30 submissions, 30 forgot-password, and both against an SMTP server that never answers, finish while a page answers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
acfcf72c03
commit
32bb542e8e
@@ -0,0 +1,227 @@
|
||||
import type { BasePayload, PayloadRequest } from 'payload'
|
||||
|
||||
/**
|
||||
* 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 that has waited a second (ESCAPE_MS) may use the reserve too, all but its last
|
||||
* connection — so a transaction begun inside another one (a hook that calls the Local API without `req`)
|
||||
* does not wait for ever on its own caller, and one connection is never held by a transaction.
|
||||
*
|
||||
* `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> | void)[] }
|
||||
type Waiter = { resolve: () => void; since: number }
|
||||
type Watch = {
|
||||
active: number
|
||||
/** Open transactions begun through this watch, by id. */
|
||||
open: Map<TransactionID, Entry>
|
||||
queue: Waiter[]
|
||||
/** Connections kept free; `null` = no limit (not Postgres, or switched off). */
|
||||
reserve: null | number
|
||||
timer?: ReturnType<typeof setTimeout>
|
||||
}
|
||||
type WatchedDb = {
|
||||
beginTransaction?: (...args: unknown[]) => Promise<null | TransactionID>
|
||||
commitTransaction?: (id: Promise<TransactionID> | TransactionID) => Promise<void>
|
||||
pool?: { options?: { max?: number } }
|
||||
rollbackTransaction?: (id: Promise<TransactionID> | TransactionID) => Promise<void>
|
||||
[WATCH]?: Watch
|
||||
}
|
||||
|
||||
const WATCH = Symbol.for('iapl.transactionWatch')
|
||||
/** After this long in the queue a transaction may use the reserve (all but one connection). */
|
||||
export const RESERVE_ESCAPE_MS = 1000
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
function drain(payload: BasePayload, watch: Watch): void {
|
||||
const size = poolSize(payload) ?? Infinity
|
||||
const limit = watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve)
|
||||
const escapeLimit = Math.max(limit, size - 1)
|
||||
const now = Date.now()
|
||||
// First come, first served; a waiter that has waited ESCAPE_MS may use the reserve but the last connection.
|
||||
while (watch.queue.length) {
|
||||
const waiter = watch.queue[0]
|
||||
const room = now - waiter.since >= RESERVE_ESCAPE_MS ? escapeLimit : limit
|
||||
if (watch.active >= room) {break}
|
||||
watch.queue.shift()
|
||||
watch.active += 1
|
||||
waiter.resolve()
|
||||
}
|
||||
if (watch.queue.length && !watch.timer) {
|
||||
const wait = Math.max(1, watch.queue[0].since + RESERVE_ESCAPE_MS - now)
|
||||
watch.timer = setTimeout(() => {
|
||||
watch.timer = undefined
|
||||
drain(payload, watch)
|
||||
}, wait)
|
||||
watch.timer.unref?.()
|
||||
}
|
||||
}
|
||||
|
||||
function acquire(payload: BasePayload, watch: Watch): Promise<void> | undefined {
|
||||
let resolve = () => {}
|
||||
const done = new Promise<void>((r) => (resolve = r))
|
||||
const waiter: Waiter = { 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): void {
|
||||
watch.active = Math.max(0, watch.active - 1)
|
||||
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)
|
||||
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, open: new Map(), queue: [], reserve: wanted }
|
||||
db[WATCH] = watch
|
||||
|
||||
const begin = db.beginTransaction
|
||||
const commit = db.commitTransaction
|
||||
const rollback = db.rollbackTransaction
|
||||
|
||||
db.beginTransaction = async function (this: unknown, ...args: unknown[]) {
|
||||
const waiting = acquire(payload, watch)
|
||||
if (waiting) {await waiting}
|
||||
let id: null | TransactionID
|
||||
try {
|
||||
id = await begin.apply(this, args)
|
||||
} catch (err) {
|
||||
release(payload, watch)
|
||||
throw err
|
||||
}
|
||||
if (id === null || id === undefined) {
|
||||
release(payload, watch)
|
||||
return id
|
||||
}
|
||||
watch.open.set(id, { after: [] })
|
||||
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<PayloadRequest, 'payload' | 'transactionID'>, fn: () => Promise<void> | 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<PayloadRequest, 'payload' | 'transactionID'>): 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; reserve: null | number; waiting: number } | null {
|
||||
const watch = dbOf(payload)[WATCH]
|
||||
return watch ? { active: watch.active, reserve: watch.reserve, waiting: watch.queue.length } : null
|
||||
}
|
||||
Reference in New Issue
Block a user