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:
Radosław Smoliński
2026-11-26 01:19:27 +01:00
co-authored by Claude Opus 5.5
parent 32bb542e8e
commit 4efadb21d5
18 changed files with 534 additions and 107 deletions
@@ -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] } }
}
+9 -1
View File
@@ -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
},
}
}