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:
+6
-2
@@ -206,7 +206,10 @@ export {
|
||||
} from './modules/content/index.js'
|
||||
export type { ArchiveEntries } from './modules/content/index.js'
|
||||
export type { SearchResult } from './modules/content/index.js'
|
||||
// Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool").
|
||||
export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js'
|
||||
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
|
||||
export { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js'
|
||||
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
|
||||
export { graphAdapter } from './modules/email/graphAdapter.js'
|
||||
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
|
||||
@@ -215,8 +218,8 @@ export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter
|
||||
// Imported straight from the file, NOT from ./modules/email/index.js — that
|
||||
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
|
||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
|
||||
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
||||
export { panelSmtpAdapter, SMTP_TIMEOUT_DEFAULTS } from './modules/email/panelSmtpAdapter.js'
|
||||
export type { PanelSmtpAdapterArgs, SmtpTimeouts } from './modules/email/panelSmtpAdapter.js'
|
||||
// The Intecion Notifications Webservice (docs/email.md): the transport of a site with no SMTP server.
|
||||
// Every piece is exported, so a project can use the transport alone, enrol from a script, mark its own
|
||||
// mail, build its own panel, or test against the fake service.
|
||||
@@ -281,6 +284,7 @@ export type { MailPanelState } from './modules/email/relay/panel.js'
|
||||
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules, legacyEnvName, readEnv } from './modules/env/index.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from './modules/env/index.js'
|
||||
export { sendAfterCommit, sendFormEmails } from './modules/forms/afterCommit.js'
|
||||
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
|
||||
export { buildFormMailKindHook } from './modules/forms/attachments/delivery.js'
|
||||
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
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> | 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[]
|
||||
/** 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')
|
||||
/** 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<void> | undefined {
|
||||
let resolve = () => {}
|
||||
const done = new Promise<void>((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<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; 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
|
||||
}
|
||||
@@ -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 } : {}) } }
|
||||
}
|
||||
@@ -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
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
|
||||
import type { PayloadRequest } from 'payload'
|
||||
|
||||
import { isolateObjectProperty } from 'payload'
|
||||
|
||||
import { afterCommit } from '../database/transactions.js'
|
||||
|
||||
type Emails = Parameters<BeforeEmail>[0]
|
||||
type HookArgs = Parameters<BeforeEmail>[1]
|
||||
|
||||
/** The same request outside its (committed) transaction: reads in the hooks take a connection of their own. */
|
||||
function outsideTransaction(req: PayloadRequest): PayloadRequest {
|
||||
const own = isolateObjectProperty(req, 'transactionID')
|
||||
own.transactionID = undefined
|
||||
return own
|
||||
}
|
||||
|
||||
/** form-builder's own loop: every e-mail through the project's adapter, a failure logged, never thrown. */
|
||||
export async function sendFormEmails(req: PayloadRequest, emails: Emails): Promise<void> {
|
||||
const { payload } = req
|
||||
await Promise.all(
|
||||
emails.map(async (email) => {
|
||||
try {
|
||||
await payload.sendEmail(email as never)
|
||||
} catch (err) {
|
||||
payload.logger.error({ err, msg: `Error while sending email to address: ${String(email.to)}. Email not sent.` })
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A form-builder `beforeEmail` that composes the e-mails at once (`prepare`: inside the submission's
|
||||
* transaction, with its `req`) and hands them to the mail server right after that transaction commits
|
||||
* (`deliver` — the file delivery — then the send). form-builder gets an empty list back and sends
|
||||
* nothing itself. Inside a caller's outer transaction they go out when that one commits; with no
|
||||
* transaction to wait for (MongoDB without a replica set, SQLite) everything happens at once, as before.
|
||||
*/
|
||||
export function sendAfterCommit(prepare: BeforeEmail, deliver: BeforeEmail): BeforeEmail {
|
||||
return async (emails, args: HookArgs) => {
|
||||
const prepared = await prepare(emails, args)
|
||||
const later = afterCommit(args.req, async () => {
|
||||
const req = outsideTransaction(args.req)
|
||||
await sendFormEmails(req, await deliver(prepared, { ...args, req }))
|
||||
})
|
||||
return later ? [] : deliver(prepared, args)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type { AdminText } from '../admin-i18n/define.js'
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../access/predicates.js'
|
||||
import { sendAfterCommit } from './afterCommit.js'
|
||||
import { resolveFormAttachments } from './attachments/config.js'
|
||||
import { buildFileDeliveryHook, buildFileNoticeHook, buildFormMailKindHook } from './attachments/delivery.js'
|
||||
import { buildFormSubmitEndpoint } from './attachments/endpoint.js'
|
||||
@@ -221,13 +222,16 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
// Every e-mail of a form says what it is (notification to the addresses written in the panel, or
|
||||
// confirmation to an address the visitor typed): the Intecion mail service limits the two differently.
|
||||
const markKinds = buildFormMailKindHook({ formsSlug })
|
||||
const beforeEmail: BeforeEmail = async (emails, args) => {
|
||||
const prepare: BeforeEmail = async (emails, args) => {
|
||||
const noticed = fileNotice ? await fileNotice(emails, args) : emails
|
||||
const laidOut = layout ? await layout(noticed, args) : noticed
|
||||
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
|
||||
const marked = await markKinds(changed, args)
|
||||
return fileDelivery ? fileDelivery(marked, args) : marked
|
||||
return markKinds(changed, args)
|
||||
}
|
||||
const deliver: BeforeEmail = (emails, args) => (fileDelivery ? fileDelivery(emails, args) : emails)
|
||||
// Composed inside the transaction (the hooks read the form with its `req`); sent after it commits
|
||||
// (forms.emailsInTransaction), so a slow mail server holds no database connection.
|
||||
const beforeEmail: BeforeEmail = forms.emailsInTransaction ? async (emails, args) => deliver(await prepare(emails, args), args) : sendAfterCommit(prepare, deliver)
|
||||
const fileBlockOption = forms.fields?.file
|
||||
const formHooks = forms.formOverrides?.hooks
|
||||
const builder = formBuilderPlugin({
|
||||
|
||||
@@ -53,6 +53,16 @@ export type FormsOption = {
|
||||
* with the logo, accent colour and footer from Site Settings → Emails. Default false.
|
||||
*/
|
||||
emailLayout?: boolean
|
||||
/**
|
||||
* When a form's e-mails go out. Default (`false`): right AFTER the submission is saved — its database
|
||||
* transaction has committed and given its connection back — still within the same request, so the
|
||||
* visitor's answer (and a file that could not be sent) is reported as before. A mail server that is
|
||||
* slow or hangs then holds no database connection, and nothing is sent for a submission that was not
|
||||
* saved. A submission saved without its e-mail (the mail server refused it) stays stored, as it always
|
||||
* did. `true` = inside the transaction, as before 1.17.0. Databases without transactions (MongoDB
|
||||
* without a replica set, SQLite by default) send at once either way. docs/forms.md "When e-mails go out".
|
||||
*/
|
||||
emailsInTransaction?: boolean
|
||||
/** Field types available in the form builder. Sensible defaults applied. */
|
||||
fields?: {
|
||||
checkbox?: boolean
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { BasePayload, Field } from 'payload'
|
||||
import type { AdminTextKey } from '../admin-i18n/texts/index.js'
|
||||
import type { IntegrationLabel } from './texts.js'
|
||||
|
||||
import { transactionsBusy } from '../database/transactions.js'
|
||||
|
||||
/**
|
||||
* Health of a third-party integration (Turnstile today, SMTP/Graph later),
|
||||
* stored on the SiteIntegrations global so the panel can show it:
|
||||
@@ -88,7 +90,8 @@ export function buildIntegrationStatusBanner(
|
||||
|
||||
/**
|
||||
* Persist a status change. Never throws — a status write must not break the
|
||||
* request that triggered it.
|
||||
* request that triggered it. The same change already being written is not
|
||||
* written twice; under database load the write is not waited for.
|
||||
*/
|
||||
export async function recordIntegrationStatus(
|
||||
payload: BasePayload,
|
||||
@@ -106,6 +109,15 @@ export async function recordIntegrationStatus(
|
||||
if (!changed && !stale) {return}
|
||||
if (next.state === 'ok' && !previous?.state) {return}
|
||||
|
||||
// The same change already on its way (many sends failing at once): wait for that write, do not repeat it.
|
||||
const key = `${field}|${next.state}|${next.code ?? ''}`
|
||||
const pending = inFlight(payload)
|
||||
// Under load (every transaction place taken, src/modules/database/transactions.ts) the caller may be
|
||||
// inside a transaction itself: the write — a transaction of its own — is not waited for then.
|
||||
const busy = transactionsBusy(payload)
|
||||
const running = pending.get(key)
|
||||
if (running) {return busy ? undefined : running}
|
||||
|
||||
const status: IntegrationStatus = {
|
||||
checkedAt: now.toISOString(),
|
||||
code: next.code ?? null,
|
||||
@@ -113,14 +125,30 @@ export async function recordIntegrationStatus(
|
||||
since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),
|
||||
state: next.state,
|
||||
}
|
||||
try {
|
||||
await payload.updateGlobal({
|
||||
slug: SITE_INTEGRATIONS as never,
|
||||
context: { ipalIntegrationStatus: true },
|
||||
data: { [field]: status } as never,
|
||||
depth: 0,
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
|
||||
const write = (async () => {
|
||||
try {
|
||||
await payload.updateGlobal({
|
||||
slug: SITE_INTEGRATIONS as never,
|
||||
context: { ipalIntegrationStatus: true },
|
||||
data: { [field]: status } as never,
|
||||
depth: 0,
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
|
||||
} finally {
|
||||
pending.delete(key)
|
||||
}
|
||||
})()
|
||||
pending.set(key, write)
|
||||
return busy ? undefined : write
|
||||
}
|
||||
|
||||
const writes = new WeakMap<object, Map<string, Promise<void>>>()
|
||||
function inFlight(payload: BasePayload): Map<string, Promise<void>> {
|
||||
let map = writes.get(payload)
|
||||
if (!map) {
|
||||
map = new Map()
|
||||
writes.set(payload, map)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
@@ -30,7 +30,9 @@ import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
|
||||
import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
|
||||
import { buildConstructionFields } from './modules/construction/fields.js'
|
||||
import { buildArchiveFields } from './modules/content/index.js'
|
||||
import { defaultConnectionReserve, poolSize, watchTransactions } from './modules/database/transactions.js'
|
||||
import { buildDoctorEndpoint } from './modules/doctor/status.js'
|
||||
import { withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js'
|
||||
import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js'
|
||||
import { withAccountMailMark } from './modules/email/relay/accountMail.js'
|
||||
import { relayConfirmEndpoint } from './modules/email/relay/confirm.js'
|
||||
@@ -756,6 +758,11 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
...config.custom,
|
||||
iapl: { ...iaplCustom, mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } },
|
||||
}
|
||||
// "Forgot password" and "verify your e-mail" through mailAdapter(): sent right after their transaction
|
||||
// commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a).
|
||||
if (options.mail?.accountMailAfterCommit !== false) {
|
||||
config.collections = (config.collections ?? []).map((c) => (c.auth ? withAccountMailAfterCommit(c) : c))
|
||||
}
|
||||
if (relay !== false) {
|
||||
// The public route the service calls a site back at (404 unless this site just started an
|
||||
// enrolment), and the admin-only routes of the state block on the e-mail tab.
|
||||
@@ -939,6 +946,9 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
)
|
||||
}
|
||||
adoptConfig(payload)
|
||||
// Postgres: keep a few pool connections free of transactions (connectionReserve), and watch commits so
|
||||
// that form e-mails go out after the submission's transaction (forms.emailsInTransaction).
|
||||
watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)))
|
||||
// Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set.
|
||||
if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)}
|
||||
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
|
||||
|
||||
@@ -75,6 +75,18 @@ export type IaplOptions = {
|
||||
*/
|
||||
agency?: AgencyOption | false
|
||||
|
||||
/**
|
||||
* Postgres: pool connections kept free of transactions. Payload holds a connection for the whole of a
|
||||
* transaction, and code inside it that runs without the transaction's `req` (Payload's own "forgot
|
||||
* password", an e-mail adapter reading its settings, a hook that forgot `req`) needs a second one: with
|
||||
* the default pool of 10, ten such requests at once used to stop the whole site. With the reserve, at
|
||||
* most `pool size − reserve` transactions are open at once and the next one waits for a place.
|
||||
* Default: a fifth of the pool, at least 2 (1 in a pool of fewer than 4). A number sets it; `false`
|
||||
* switches it off (as before 1.17.0). Other adapters: no effect. Building block: `reserveConnections`.
|
||||
* docs/deployment.md "Postgres: the connection pool".
|
||||
*/
|
||||
connectionReserve?: false | number
|
||||
|
||||
/** Internationalization — locales, default locale, fallback behavior */
|
||||
/**
|
||||
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`
|
||||
@@ -456,6 +468,14 @@ export type ThemeOptions = {
|
||||
export type IpalOptions = IaplOptions
|
||||
|
||||
export type MailOptions = {
|
||||
/**
|
||||
* Payload's "forgot password" and "verify your e-mail", sent through `mailAdapter()`: right AFTER the
|
||||
* operation's transaction commits (still in the same request), so a slow mail server holds no database
|
||||
* connection; nothing is sent when the transaction is rolled back. Default true; `false` = inside the
|
||||
* transaction, as before 1.17.0. No transactions (MongoDB without a replica set, SQLite): no change.
|
||||
* docs/deployment.md §4.3a.
|
||||
*/
|
||||
accountMailAfterCommit?: boolean
|
||||
/** `false` silences the one warning per process start of a site on Microsoft Graph (deprecated, removed in 2.0). */
|
||||
graphDeprecationWarning?: boolean
|
||||
/** The Intecion Notifications Webservice. Default on; `false` switches it off. */
|
||||
|
||||
Reference in New Issue
Block a user