Merge claude/postgres-mail-deadlock: Postgres keeps connections free of transactions; form and account mail go out after the commit

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 01:38:31 +01:00
co-authored by Claude Opus 5.5
30 changed files with 1431 additions and 27 deletions
+106
View File
@@ -0,0 +1,106 @@
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).
*
* Payload calls the collection's `generateEmailSubject({ req, token, user })` right before it sends that mail,
* and the mail carries the same token (in its link). The wrapper below holds the token for the transaction of
* that `req`; `mailAdapter()` sends the message whose body contains a held token right AFTER that 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 (the token was not stored, the link would not work).
* Matched by the token (and the account's address as a second check), never by the address alone: two
* requests for one account at once, or a form's mail to the same address, are each their own message.
* A project's own `generateEmailSubject` is kept and called; without one the subject is Payload's own.
* Without a transaction (MongoDB without a replica set, SQLite) nothing changes; a message without a held
* token (a project's own e-mail template that leaves the token out) is sent at once, as before.
* `iapl({ mail: { accountMailAfterCommit: false } })` = inside the transaction, as before.
*/
const MARK = Symbol.for('iapl.accountMailAfterCommit')
type Held = { address: string; req: PayloadRequest; until: number }
const held = new Map<string, Held>()
// Payload sends the mail right after it composed the subject, within the same request.
const TTL_MS = 30_000
// Payload's tokens are 40 hexadecimal characters; a shorter one could be found in an unrelated message.
const MIN_TOKEN = 16
const keyOf = (address: string) => address.trim().toLowerCase()
/** The message that carries `token` (to `address`) belongs to the transaction of `req`, when there is one to wait for. */
export function holdAccountMail(token: string, address: string, req: PayloadRequest): void {
if (typeof token !== 'string' || token.length < MIN_TOKEN || !inWatchedTransaction(req)) {return}
const now = Date.now()
for (const [k, entry] of held) {
if (entry.until <= now) {held.delete(k)}
}
held.set(token, { address: keyOf(address), req, until: now + TTL_MS })
}
/** Nothing is held for `token` any more. */
export function releaseAccountMail(token: string): void {
held.delete(token)
}
const bodyOf = (message: { html?: unknown; text?: unknown }) => `${typeof message.html === 'string' ? message.html : ''}\n${typeof message.text === 'string' ? message.text : ''}`
/**
* For a transport: when this message carries the token of an account operation whose transaction is still
* open, and goes to that account's address alone, schedules `send` for right after the 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: { html?: unknown; text?: unknown; to?: unknown }, send: () => Promise<unknown>): boolean {
if (!held.size) {return false}
const { addresses } = bareAddresses(message.to)
if (addresses.length !== 1) {return false}
const body = bodyOf(message)
const now = Date.now()
for (const [token, entry] of held) {
if (entry.until <= now || entry.address !== keyOf(addresses[0]) || !body.includes(token)) {continue}
held.delete(token)
const expected = takeExpectedMail(addresses)
return afterCommit(entry.req, async () => {
if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })}
await send()
})
}
return false
}
type SubjectArgs = { req: PayloadRequest; token: string; user: { email?: unknown } }
type SubjectFn = ((args: SubjectArgs) => Promise<string> | string) & { [MARK]?: boolean }
function holdingSubject(own: SubjectFn | undefined, fallback: string): SubjectFn {
if (own?.[MARK]) {return own}
const fn: SubjectFn = async (args) => {
const subject = own ? await own(args) : args.req.t(fallback as never)
if (typeof args.user?.email === 'string') {holdAccountMail(args.token, args.user.email, args.req)}
return subject
}
fn[MARK] = true
return fn
}
/**
* Wraps an auth collection's `forgotPassword.generateEmailSubject`, and `verify.generateEmailSubject` where it
* verifies e-mail addresses (idempotent). Payload's own subjects stay when the collection has none.
*/
export function withAccountMailAfterCommit(collection: CollectionConfig): CollectionConfig {
const auth = collection.auth
if (!auth) {return collection}
const own = typeof auth === 'object' ? auth : {}
if (own.disableLocalStrategy === true) {return collection}
const forgotPassword = { ...own.forgotPassword, generateEmailSubject: holdingSubject(own.forgotPassword?.generateEmailSubject as SubjectFn | undefined, 'authentication:resetYourPassword') }
const verify =
own.verify === true || (own.verify && typeof own.verify === 'object')
? { ...(typeof own.verify === 'object' ? own.verify : {}), generateEmailSubject: holdingSubject((typeof own.verify === 'object' ? own.verify.generateEmailSubject : undefined) as SubjectFn | undefined, 'authentication:verifyYourEmail') }
: own.verify
return { ...collection, auth: { ...own, forgotPassword: forgotPassword as never, ...(verify !== undefined ? { verify: verify as never } : {}) } }
}
+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
},
}
}
+16 -1
View File
@@ -20,8 +20,19 @@ export type PanelSmtpAdapterArgs = {
*/
fallbackFromAddress?: string
fallbackFromName?: string
/**
* How long a send waits for the SMTP server, in milliseconds: `connectionMs` to connect (default 10 000),
* `greetingMs` for its greeting (default 30 000), `socketMs` of silence during the dialogue (default 60 000).
* A send that runs inside a database transaction (Payload's "forgot password") holds a connection that long.
*/
timeouts?: SmtpTimeouts
}
export type SmtpTimeouts = { connectionMs?: number; greetingMs?: number; socketMs?: number }
/** nodemailer's own defaults are 2 minutes to connect and 10 minutes of silence. */
export const SMTP_TIMEOUT_DEFAULTS: Required<SmtpTimeouts> = { connectionMs: 10_000, greetingMs: 30_000, socketMs: 60_000 }
/**
* Payload email adapter backed by the SMTP settings in the SiteIntegrations
* global.
@@ -83,11 +94,15 @@ export const panelSmtpAdapter =
const { default: nodemailer } = await import('nodemailer')
const timeouts = { ...SMTP_TIMEOUT_DEFAULTS, ...args.timeouts }
const transporter = nodemailer.createTransport({
auth: { pass, user },
connectionTimeout: timeouts.connectionMs,
greetingTimeout: timeouts.greetingMs,
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
socketTimeout: timeouts.socketMs,
})
try {