Postgres pool, review round 1: nested transactions, account mail after commit
P-1: a transaction begun inside another one (a hook calling the Local API without req) no longer queues behind its caller. An AsyncLocalStorage mark set when a transaction begins lets the inner one through at once, without a place, but never into the last connection (a second level may take that one). If the mark is lost, a queue that has not moved for a second admits its newest waiter. connectionReserve: false now admits everything, as before. Measured on Postgres 17: 9, 12 and 30 such submissions finish (before: stuck from 9). P-2: Payload's "forgot password" and "verify your e-mail" through mailAdapter() go out right after their transaction commits (mail.accountMailAfterCommit, default on). With the relay hanging, 30 resets + 30 submissions finish in about 11 s instead of 43.5 s. P-3: Postgres tests for the "not confirmed" file result after commit, a caller's outer transaction rolled back or committed, the relay hanging, and the nested rows; deployment.md has the measured table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
32bb542e8e
commit
4efadb21d5
@@ -1,5 +1,7 @@
|
||||
import type { BasePayload, PayloadRequest } from 'payload'
|
||||
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
|
||||
/**
|
||||
* Transactions and the Postgres pool.
|
||||
*
|
||||
@@ -11,19 +13,31 @@ import type { BasePayload, PayloadRequest } from 'payload'
|
||||
*
|
||||
* `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.
|
||||
* 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> | void)[] }
|
||||
type Waiter = { resolve: () => void; since: number }
|
||||
type Entry = { after: (() => Promise<void> | 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<TransactionID, Entry>
|
||||
queue: Waiter[]
|
||||
@@ -40,9 +54,12 @@ type WatchedDb = {
|
||||
}
|
||||
|
||||
const WATCH = Symbol.for('iapl.transactionWatch')
|
||||
/** After this long in the queue a transaction may use the reserve (all but one connection). */
|
||||
/** 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. */
|
||||
@@ -58,22 +75,52 @@ 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 limitOf = (payload: BasePayload, watch: Watch) => {
|
||||
const size = poolSize(payload) ?? Infinity
|
||||
const limit = watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve)
|
||||
const escapeLimit = Math.max(limit, size - 1)
|
||||
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()
|
||||
// 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()
|
||||
// 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, watch.queue[0].since + RESERVE_ESCAPE_MS - now)
|
||||
const wait = Math.max(1, Math.max(watch.moved, oldest) + RESERVE_ESCAPE_MS - now)
|
||||
watch.timer = setTimeout(() => {
|
||||
watch.timer = undefined
|
||||
drain(payload, watch)
|
||||
@@ -82,17 +129,19 @@ function drain(payload: BasePayload, watch: Watch): void {
|
||||
}
|
||||
}
|
||||
|
||||
function acquire(payload: BasePayload, watch: Watch): Promise<void> | undefined {
|
||||
function acquire(payload: BasePayload, watch: Watch, depth: number): Promise<void> | undefined {
|
||||
let resolve = () => {}
|
||||
const done = new Promise<void>((r) => (resolve = r))
|
||||
const waiter: Waiter = { resolve: () => resolve(), since: Date.now() }
|
||||
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): void {
|
||||
watch.active = Math.max(0, watch.active - 1)
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -100,7 +149,7 @@ function finish(payload: BasePayload, watch: Watch, id: TransactionID): Entry |
|
||||
const entry = watch.open.get(id)
|
||||
if (!entry) {return undefined}
|
||||
watch.open.delete(id)
|
||||
release(payload, watch)
|
||||
release(payload, watch, entry.slot)
|
||||
return entry
|
||||
}
|
||||
|
||||
@@ -119,29 +168,39 @@ export function watchTransactions(payload: BasePayload, reserve: false | number
|
||||
drain(payload, db[WATCH])
|
||||
return db[WATCH]
|
||||
}
|
||||
const watch: Watch = { active: 0, open: new Map(), queue: [], reserve: wanted }
|
||||
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
|
||||
|
||||
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)
|
||||
// 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
|
||||
}
|
||||
watch.open.set(id, { after: [] })
|
||||
return id
|
||||
})()
|
||||
}
|
||||
|
||||
db.commitTransaction = async function (this: unknown, incoming) {
|
||||
@@ -221,7 +280,7 @@ export function transactionsBusy(payload: BasePayload): boolean {
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
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, reserve: watch.reserve, waiting: watch.queue.length } : null
|
||||
return watch ? { active: watch.active, nested: watch.nested, reserve: watch.reserve, waiting: watch.queue.length } : null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { CollectionConfig, PayloadRequest } from 'payload'
|
||||
|
||||
import { afterCommit, inWatchedTransaction } from '../database/transactions.js'
|
||||
import { expectMailTo, takeExpectedMail } from './relay/kinds.js'
|
||||
import { bareAddresses } from './relay/message.js'
|
||||
|
||||
/**
|
||||
* Payload sends "forgot password" and "verify your e-mail" INSIDE the operation's transaction, so a slow or
|
||||
* hanging mail server holds the transaction — and its database connection — until the send gives up. With
|
||||
* many such requests at once every place for a transaction is taken by requests that only wait for mail
|
||||
* (docs/deployment.md §4.3a).
|
||||
*
|
||||
* This hook on an auth collection says, when such an operation starts inside a watched transaction, that the
|
||||
* next message to that address belongs to it; `mailAdapter()` then sends that message right AFTER the
|
||||
* transaction commits — still inside the same request, so the request ends when the mail is out, as before —
|
||||
* and drops it when the transaction is rolled back (no token was stored, the link would not work).
|
||||
* By address, like the account-mail mark (relay/kinds.ts): Payload passes nothing else to the adapter.
|
||||
* Without a transaction (MongoDB without a replica set, SQLite) nothing changes.
|
||||
* `iapl({ mail: { accountMailAfterCommit: false } })` = inside the transaction, as before.
|
||||
*/
|
||||
|
||||
const MARK = Symbol.for('iapl.accountMailAfterCommit')
|
||||
type Pending = { req: PayloadRequest; until: number }
|
||||
const pending = new Map<string, Pending>()
|
||||
// The mail follows its operation's hook within the same request.
|
||||
const TTL_MS = 30_000
|
||||
|
||||
const keyOf = (address: string) => address.trim().toLowerCase()
|
||||
|
||||
/** The message to `address` belongs to the transaction of `req` (when there is one to wait for). */
|
||||
export function holdAccountMailFor(address: string, req: PayloadRequest): void {
|
||||
const key = keyOf(address)
|
||||
if (!key || !inWatchedTransaction(req)) {return}
|
||||
const now = Date.now()
|
||||
if (pending.size > 1000) {
|
||||
for (const [k, entry] of pending) {
|
||||
if (entry.until <= now) {pending.delete(k)}
|
||||
}
|
||||
}
|
||||
pending.set(key, { req, until: now + TTL_MS })
|
||||
}
|
||||
|
||||
/** The operation ended without a mail to `address`: nothing is held for it any more. */
|
||||
export function releaseAccountMailFor(address: string): void {
|
||||
pending.delete(keyOf(address))
|
||||
}
|
||||
|
||||
/**
|
||||
* For a transport: when this message is the account mail of an operation whose transaction is still open,
|
||||
* schedules `send` for right after its commit and returns true (the caller sends nothing now). The kind the
|
||||
* relay transport was told for the address (`account`, with the visitor) is carried over to that send.
|
||||
*/
|
||||
export function sendAccountMailAfterCommit(message: { to?: unknown }, send: () => Promise<unknown>): boolean {
|
||||
const { addresses } = bareAddresses(message.to)
|
||||
if (addresses.length !== 1) {return false}
|
||||
const key = keyOf(addresses[0])
|
||||
const entry = pending.get(key)
|
||||
if (!entry) {return false}
|
||||
pending.delete(key)
|
||||
if (entry.until <= Date.now()) {return false}
|
||||
const expected = takeExpectedMail(addresses)
|
||||
return afterCommit(entry.req, async () => {
|
||||
if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })}
|
||||
await send()
|
||||
})
|
||||
}
|
||||
|
||||
type OperationArgs = { args?: { data?: { email?: unknown }; req?: PayloadRequest }; operation: string; req?: PayloadRequest; result?: unknown }
|
||||
|
||||
/**
|
||||
* Adds the hook to an auth collection (idempotent): `forgotPassword` always, `create` where the collection
|
||||
* verifies e-mail addresses.
|
||||
*/
|
||||
export function withAccountMailAfterCommit(collection: CollectionConfig): CollectionConfig {
|
||||
const hooks = collection.hooks?.beforeOperation ?? []
|
||||
if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection}
|
||||
const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify)
|
||||
const applies = (operation: string) => operation === 'forgotPassword' || (verifies && operation === 'create')
|
||||
const hold = ((args: OperationArgs) => {
|
||||
const email = args.args?.data?.email
|
||||
const req = args.req ?? args.args?.req
|
||||
if (applies(args.operation) && typeof email === 'string' && req) {holdAccountMailFor(email, req)}
|
||||
return args.args
|
||||
}) as unknown as { [MARK]?: boolean } & NonNullable<NonNullable<CollectionConfig['hooks']>['beforeOperation']>[number]
|
||||
hold[MARK] = true
|
||||
// Ran without a mail (no such account, Payload's interval between two requests): forget the address.
|
||||
const done = ((args: OperationArgs) => {
|
||||
const email = args.args?.data?.email
|
||||
if (applies(args.operation) && typeof email === 'string') {releaseAccountMailFor(email)}
|
||||
return args.result
|
||||
}) as unknown as NonNullable<NonNullable<CollectionConfig['hooks']>['afterOperation']>[number]
|
||||
return { ...collection, hooks: { ...collection.hooks, afterOperation: [...(collection.hooks?.afterOperation ?? []), done], beforeOperation: [...hooks, hold] } }
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js'
|
||||
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
|
||||
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
@@ -153,6 +154,14 @@ export const mailAdapter =
|
||||
defaultFromName: smtp.defaultFromName,
|
||||
|
||||
sendEmail: async (message: SendEmailOptions) => {
|
||||
// Payload's "forgot password" / "verify your e-mail" inside a transaction: sent right after it commits
|
||||
// (accountMailAfterCommit.ts), so a slow mail server holds no database connection.
|
||||
if (sendAccountMailAfterCommit(message, () => send(message))) {return { deferred: true }}
|
||||
return send(message)
|
||||
},
|
||||
}
|
||||
|
||||
async function send(message: SendEmailOptions): Promise<unknown> {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
@@ -241,6 +250,5 @@ export const mailAdapter =
|
||||
: { state: 'ok' },
|
||||
)
|
||||
return result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user