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
+13
-6
@@ -139,10 +139,17 @@ once there are more than 20.
|
||||
second one; the default pool has 10. Measured on Postgres 17: 12 submissions or 12 resets at once never finished;
|
||||
now 30 of each, also against an SMTP server that never answers, finish while an ordinary request answers at once.
|
||||
- **`connectionReserve`** (new plugin option, default on): a fifth of the pool, at least 2, stays free of
|
||||
transactions; at most `pool size − reserve` transactions are open at once and the next one waits; one that has
|
||||
waited a second may use all but the last connection. `false` = as before. Building blocks `reserveConnections`,
|
||||
`watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`,
|
||||
`poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a).
|
||||
transactions; at most `pool size − reserve` transactions are open at once and the next one waits. A transaction
|
||||
begun inside another one (a project hook that calls the Local API without `req`) takes no place and goes at once,
|
||||
but never takes the last connection — 9, 12 and 30 such submissions at once finish (before: 12 stopped the site).
|
||||
`false` = as before. Building blocks `reserveConnections`, `watchTransactions`, `afterCommit`,
|
||||
`inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`,
|
||||
`RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a, with the measured table).
|
||||
- **Payload's "forgot password" and "verify your e-mail" go out after their transaction commits** when sent through
|
||||
`mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). With the mail
|
||||
service hanging, 30 resets and 30 submissions at once finish in about one send budget (11 s) instead of 43.5 s.
|
||||
Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMailFor`,
|
||||
`releaseAccountMailFor`.
|
||||
- **Form e-mails go out after the submission's transaction commits** — same request, same answer to the visitor
|
||||
(a file that could not be sent is still reported). A submission rolled back by a later hook now sends nothing; a
|
||||
send that fails after the commit leaves the submission stored (as a failed e-mail always did). Sites without
|
||||
@@ -153,8 +160,8 @@ once there are more than 20.
|
||||
is busy the write is not waited for.
|
||||
- **SMTP time-outs**: 10 s to connect (was nodemailer's 2 min), 30 s for the greeting, 60 s of silence (was 10 min);
|
||||
`mailAdapter({ smtp: { timeouts } })` / `panelSmtpAdapter({ timeouts })`, `SMTP_TIMEOUT_DEFAULTS`, `SmtpTimeouts`.
|
||||
- Not fixed here: Payload's own "forgot password" and "verify your e-mail" still send inside their transaction, so a
|
||||
hanging mail server makes them hold a place until the SMTP time-out (others wait; nothing stops).
|
||||
- Not covered: an e-mail adapter of your own (not `mailAdapter()`) still gets Payload's account mail inside the
|
||||
transaction unless it calls `sendAccountMailAfterCommit` first.
|
||||
|
||||
### Deprecated
|
||||
- **Microsoft Graph as an e-mail transport** — `graphAdapter`, `GraphAdapterArgs`, `mailAdapter({ graph })`,
|
||||
|
||||
+2
-1
@@ -1246,7 +1246,8 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| Account e-mails through the mail service: at most 5 to one address and 10 asked for by one visitor an hour | `mail: { relay: { accountMail: false } }` | `accountMail: { perAddress, perVisitor, windowMinutes }` |
|
||||
| Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` |
|
||||
| Microsoft Graph as transport: deprecated, one warning per start, removed in 2.0 | `mail: { graphDeprecationWarning: false }` (the warning only) | move off it: email.md "Moving off Microsoft Graph" |
|
||||
| Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; one waiting a second may use all but the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: <number>`; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) |
|
||||
| Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; a transaction begun inside another one (a hook without `req`) takes no place and goes at once, but never the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: <number>`; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) |
|
||||
| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMailFor`, `releaseAccountMailFor` (email.md "Payload system mail") |
|
||||
| Form e-mails go out right after the submission's transaction commits (same request, same answer); a rolled-back submission sends nothing; a send that fails after the commit leaves the submission stored. No transactions (MongoDB without a replica set, SQLite): at once, as before | `forms: { emailsInTransaction: true }` | `sendAfterCommit(prepare, deliver)`, `sendFormEmails(req, emails)`, `afterCommit(req, fn)` (forms.md "When e-mails go out") |
|
||||
| SMTP time-outs: 10 s to connect, 30 s greeting, 60 s silence | — | `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })`, `panelSmtpAdapter({ timeouts })`; `SMTP_TIMEOUT_DEFAULTS`, type `SmtpTimeouts` (email.md "SMTP") |
|
||||
|
||||
|
||||
@@ -121,7 +121,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP |
|
||||
| start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` |
|
||||
| Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) |
|
||||
| Postgres: requests are slow while a mail server hangs (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) |
|
||||
| Postgres: requests are slow while a mail server hangs (logins and saves wait behind "forgot password") | the account mail is sent inside its transaction: `mail: { accountMailAfterCommit: false }`, `forms.emailsInTransaction: true`, or an e-mail adapter of your own that does not call `sendAccountMailAfterCommit` | remove the option / call it in your adapter; fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })` |
|
||||
| Postgres: a project hook writes without `req` and the log row stays when its submission is rolled back | a Local API call without `req` is a transaction of its own (it no longer blocks the pool, but it is not rolled back with its caller) | pass `req` to every Local API call in a hook |
|
||||
| a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" |
|
||||
| old email sender | mail client cache | check the raw headers |
|
||||
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts |
|
||||
|
||||
@@ -581,7 +581,9 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
|
||||
5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's
|
||||
"forgot password" are marked by the plugin.
|
||||
6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of
|
||||
10; `connectionReserve`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`),
|
||||
10; `connectionReserve`; a transaction begun inside another one takes no place), form e-mails and Payload's
|
||||
"forgot password" / "verify your e-mail" go out right after their transaction commits (`forms.emailsInTransaction`,
|
||||
`mail.accountMailAfterCommit`),
|
||||
SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the
|
||||
reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out".
|
||||
**Check:** `pnpm exec iapl-doctor --deep --url <site>` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` /
|
||||
|
||||
+26
-9
@@ -366,29 +366,46 @@ Since 1.17.0 the plugin keeps a few connections free of transactions (`connectio
|
||||
- at most `pool size − reserve` transactions are open at once; the next one waits for a place — its request is
|
||||
slower, nothing stops. Default reserve: a fifth of the pool, at least 2 (1 in a pool of fewer than 4): with the
|
||||
default pool of 10, eight transactions at once and two connections for everything else;
|
||||
- a transaction that has waited a second (`RESERVE_ESCAPE_MS`) may use the reserve too, all but one connection — so a
|
||||
transaction begun inside another one (a hook without `req`) does not wait for ever on its caller, and one connection
|
||||
is never held by a transaction;
|
||||
- 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 is open — does not queue: it takes no place, because its caller cannot
|
||||
finish without it. It may use the reserve but the last connection (a second level inside it that one too), so one
|
||||
connection stays free for the queries outside transactions. "Inside" is told by a mark the plugin sets when a
|
||||
transaction begins (`AsyncLocalStorage`); in case the mark is lost on the way, a queue that has not moved for a
|
||||
second (`RESERVE_ESCAPE_MS`) lets its newest waiter use the reserve, all but the last connection;
|
||||
- form e-mails go out **after** the submission's transaction commits ([forms.md](./forms.md) "When e-mails go out"),
|
||||
so a slow mail server holds no connection; Payload's own account mail ("forgot password", "verify your e-mail") is
|
||||
still sent inside its transaction — with a mail server that hangs, those requests hold a place until the SMTP
|
||||
time-out ([email.md](./email.md) "SMTP": 10 s to connect, 30 s for the greeting by default).
|
||||
and so do Payload's own "forgot password" and "verify your e-mail" sent through `mailAdapter()`
|
||||
(`mail.accountMailAfterCommit`, default on): a slow or hanging mail server holds no connection and no place; the
|
||||
request still ends when the mail is out. A rolled-back operation sends nothing.
|
||||
|
||||
Measured on Postgres 17, default pool of 10 (`test/transactionPool*.test.ts`):
|
||||
|
||||
| At the same moment | 1.16.8 / `connectionReserve: false` | 1.17.0 |
|
||||
|---|---|---|
|
||||
| 12 or 30 form submissions, or 12 or 30 "forgot password" | site stops for good, pages too | all finish, a page answers in milliseconds |
|
||||
| 9 / 12 / 30 submissions whose hook writes without `req` | 9 finish (363 ms); 12 and 30 stop the site | all finish (under 2 s) |
|
||||
| 30 "forgot password" + 30 submissions, the mail service hanging (10 s budget a send) | site stops for good | all finish in about 11 s (one budget); with the reset mail inside its transaction (`accountMailAfterCommit: false`) the last waited 43.5 s |
|
||||
| the same with an SMTP server that never answers (2 s time-outs in the test) | site stops for good | all finish in a few seconds |
|
||||
|
||||
```ts
|
||||
iapl({ connectionReserve: 3 }) // keep three connections free
|
||||
iapl({ connectionReserve: false }) // no limit, as before 1.17.0 (not recommended)
|
||||
iapl({ mail: { accountMailAfterCommit: false } }) // "forgot password" mail inside its transaction, as before
|
||||
```
|
||||
|
||||
MongoDB, SQLite and other adapters without a pool: no effect. A larger pool (`postgresAdapter({ pool: { max: 20 } })`)
|
||||
moves the reserve with it; the Postgres server's own `max_connections` must allow every instance's pool.
|
||||
Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnections(payload) }`.
|
||||
Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction
|
||||
commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route),
|
||||
`poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`.
|
||||
commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route:
|
||||
`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail
|
||||
`withAccountMailAfterCommit(collection)` (the hook the plugin puts on every auth collection),
|
||||
`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMailFor`,
|
||||
`releaseAccountMailFor`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled
|
||||
back with its caller's. Pass `req`.
|
||||
|
||||
**Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different
|
||||
accounts) while loading a page — the page answers at once, every request finishes. `transactionWatchState(payload)`
|
||||
shows `{ active, waiting, reserve }`.
|
||||
shows `{ active, nested, waiting, reserve }`.
|
||||
|
||||
### 4.4 Health check and rolling updates
|
||||
|
||||
|
||||
+7
-2
@@ -425,7 +425,8 @@ and password switches the site to the client's server.
|
||||
- The adapter reads the config on every send, so changing the mailbox in the panel works without a restart.
|
||||
- **Time-outs** (since 1.17.0): 10 s to connect, 30 s for the server's greeting, 60 s of silence during the
|
||||
dialogue (`SMTP_TIMEOUT_DEFAULTS`; nodemailer's own were 2 min and 10 min). A send inside a database transaction —
|
||||
Payload's "forgot password" — holds a connection that long ([deployment.md](./deployment.md) §4.3a). Change them:
|
||||
Payload's "forgot password" with `mail: { accountMailAfterCommit: false }` — holds a connection that long
|
||||
([deployment.md](./deployment.md) §4.3a; by default that mail goes out after its transaction commits). Change them:
|
||||
`mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })` or `panelSmtpAdapter({ timeouts })`
|
||||
(type `SmtpTimeouts`).
|
||||
|
||||
@@ -494,7 +495,11 @@ if (result.sent) {
|
||||
|
||||
Password reset and e-mail verification go through Payload's built-in mechanism (`config.email`). With
|
||||
`mailAdapter()` wired they take the same transport as everything else; with the mail service they are sent as
|
||||
account mail ("What a message is").
|
||||
account mail ("What a message is"). Payload sends them inside the operation's database transaction; `mailAdapter()`
|
||||
sends them right **after** it commits instead (still in the same request; nothing when it is rolled back), so a slow
|
||||
mail server holds no database connection — `mail: { accountMailAfterCommit: false }` keeps them inside
|
||||
([deployment.md](./deployment.md) §4.3a). An e-mail adapter of your own does the same by calling
|
||||
`sendAccountMailAfterCommit(message, () => send(message))` first.
|
||||
|
||||
## Masking secrets in the panel (MaskedField)
|
||||
|
||||
|
||||
@@ -121,7 +121,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP |
|
||||
| start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` |
|
||||
| Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) |
|
||||
| Postgres: requests are slow while a mail server hangs (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) |
|
||||
| Postgres: requests are slow while a mail server hangs (logins and saves wait behind "forgot password") | the account mail is sent inside its transaction: `mail: { accountMailAfterCommit: false }`, `forms.emailsInTransaction: true`, or an e-mail adapter of your own that does not call `sendAccountMailAfterCommit` | remove the option / call it in your adapter; fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })` |
|
||||
| Postgres: a project hook writes without `req` and the log row stays when its submission is rolled back | a Local API call without `req` is a transaction of its own (it no longer blocks the pool, but it is not rolled back with its caller) | pass `req` to every Local API call in a hook |
|
||||
| a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" |
|
||||
| old email sender | mail client cache | check the raw headers |
|
||||
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts |
|
||||
|
||||
@@ -581,7 +581,9 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
|
||||
5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's
|
||||
"forgot password" are marked by the plugin.
|
||||
6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of
|
||||
10; `connectionReserve`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`),
|
||||
10; `connectionReserve`; a transaction begun inside another one takes no place), form e-mails and Payload's
|
||||
"forgot password" / "verify your e-mail" go out right after their transaction commits (`forms.emailsInTransaction`,
|
||||
`mail.accountMailAfterCommit`),
|
||||
SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the
|
||||
reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out".
|
||||
**Check:** `pnpm exec iapl-doctor --deep --url <site>` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` /
|
||||
|
||||
@@ -209,6 +209,7 @@ 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 { holdAccountMailFor, releaseAccountMailFor, 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'
|
||||
|
||||
@@ -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
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ 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'
|
||||
@@ -757,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.
|
||||
|
||||
@@ -468,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. */
|
||||
|
||||
@@ -33,7 +33,8 @@ import { totp } from './http/totp.js'
|
||||
* A `beforeOperation` hook of the account rules. Every auth collection also carries the mark that tells the mail
|
||||
* service what Payload's own account mail is (modules/email/relay/accountMail.ts): that one is not counted here.
|
||||
*/
|
||||
const ruleHook = (hook: unknown) => !(hook as Record<symbol, unknown>)[Symbol.for('iapl.accountMailMark')]
|
||||
// the account-mail hooks (the relay's kind mark, the after-commit hold) are not account rules
|
||||
const ruleHook = (hook: unknown) => !(hook as Record<symbol, unknown>)[Symbol.for('iapl.accountMailMark')] && !(hook as Record<symbol, unknown>)[Symbol.for('iapl.accountMailAfterCommit')]
|
||||
|
||||
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
import type { BasePayload, Payload } from 'payload'
|
||||
|
||||
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.js'
|
||||
@@ -48,26 +49,27 @@ function fakePayload({ max = 5, pool = true, transactions = true }: { max?: numb
|
||||
}
|
||||
|
||||
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
/** Runs a function in the context this file started in (before any transaction mark). */
|
||||
const root = AsyncLocalStorage.snapshot()
|
||||
|
||||
describe('the watch (fake adapter)', () => {
|
||||
test('the default reserve: a fifth of the pool, at least 2; 1 in a pool of fewer than 4', () => {
|
||||
expect([1, 2, 3, 4, 5, 10, 11, 20, 50].map(defaultConnectionReserve)).toEqual([1, 1, 1, 2, 2, 2, 3, 4, 10])
|
||||
})
|
||||
|
||||
// Each call runs in a context of its own that starts from the file's (no transaction mark), as two unrelated
|
||||
// requests do: Node 22 keeps an AsyncLocalStorage mark per callback, which siblings started together share.
|
||||
const apart = <T>(fn: () => T): T => root(() => new AsyncResource('iapl-test-operation').runInAsyncScope(fn))
|
||||
|
||||
test('at most pool size − reserve transactions are open; the next waits for a commit', async () => {
|
||||
const { db, payload } = fakePayload({ max: 5 })
|
||||
watchTransactions(payload)
|
||||
// each from its own operation, as Payload calls it (initTransaction inside the operation)
|
||||
const open = async () => {
|
||||
await tick()
|
||||
return db.beginTransaction()
|
||||
}
|
||||
const ids = await Promise.all([open(), open(), open()])
|
||||
const ids = await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())])
|
||||
let fourth: null | string = null
|
||||
void open().then((id) => (fourth = id))
|
||||
void apart(() => db.beginTransaction()).then((id) => (fourth = id))
|
||||
await tick()
|
||||
expect(fourth).toBeNull()
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 2, waiting: 1 })
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 2, waiting: 1 })
|
||||
await db.commitTransaction(ids[0]!)
|
||||
await tick()
|
||||
expect(fourth).toBe('t4')
|
||||
@@ -75,42 +77,64 @@ describe('the watch (fake adapter)', () => {
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 2, waiting: 0 })
|
||||
})
|
||||
|
||||
test('a transaction begun inside another one gets a place in the reserve after a second, so it never waits for ever on its caller', async () => {
|
||||
const { db, payload } = fakePayload({ max: 5 }) // limit 3; after a second in the queue, up to 4
|
||||
/** An operation whose hook calls the Local API without `req`: `levels` transactions, each inside the last. */
|
||||
const nestedOperation = (db: FakeDb, levels = 2, lost = false) =>
|
||||
apart(async () => {
|
||||
const ids: string[] = []
|
||||
for (let level = 0; level < levels; level++) {
|
||||
await tick()
|
||||
// `lost`: the inner one begins where the mark does not reach (the backstop must still move the queue)
|
||||
ids.push((await (lost && level > 0 ? apart(() => db.beginTransaction()) : db.beginTransaction()))!)
|
||||
}
|
||||
for (const id of ids.reverse()) {await db.commitTransaction(id)}
|
||||
})
|
||||
const finishes = (all: Promise<unknown>, ms = 8000) => Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), ms))])
|
||||
|
||||
for (const [max, count] of [[10, 9], [10, 10], [10, 12], [10, 30], [5, 8], [3, 6]] as const) {
|
||||
test(`pool ${max}: ${count} transactions at once, each with one begun inside it, finish at once (no place for the inner one)`, async () => {
|
||||
const { db, payload } = fakePayload({ max })
|
||||
watchTransactions(payload)
|
||||
const start = Date.now()
|
||||
expect(await finishes(Promise.all(Array.from({ length: count }, () => nestedOperation(db))))).toBe('done')
|
||||
expect(Date.now() - start).toBeLessThan(500)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
})
|
||||
}
|
||||
|
||||
test('two levels inside one another: 12 operations at once in a pool of 10 finish', async () => {
|
||||
const { db, payload } = fakePayload({ max: 10 })
|
||||
watchTransactions(payload)
|
||||
// Each operation opens a transaction and, inside it, a second one (a hook calling the Local API without
|
||||
// `req`). Three outers fill the limit; without the escape every inner would wait for ever.
|
||||
const operation = async () => {
|
||||
await tick()
|
||||
const outer = (await db.beginTransaction())!
|
||||
await tick()
|
||||
const inner = (await db.beginTransaction())!
|
||||
await db.commitTransaction(inner)
|
||||
await db.commitTransaction(outer)
|
||||
}
|
||||
const start = Date.now()
|
||||
const all = Promise.all([operation(), operation(), operation()])
|
||||
const done = await Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), 4000))])
|
||||
expect(done).toBe('done')
|
||||
expect(Date.now() - start).toBeGreaterThanOrEqual(900)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, waiting: 0 })
|
||||
expect(await finishes(Promise.all(Array.from({ length: 12 }, () => nestedOperation(db, 3))))).toBe('done')
|
||||
})
|
||||
|
||||
test('the escape leaves one connection that no transaction holds', async () => {
|
||||
const { db, payload } = fakePayload({ max: 4 }) // reserve 2, limit 2, escape up to 3
|
||||
test('the inner ones never take the last connection: one stays free for the queries outside transactions', async () => {
|
||||
const { db, payload } = fakePayload({ max: 10 })
|
||||
watchTransactions(payload)
|
||||
const open = async () => {
|
||||
await tick()
|
||||
return db.beginTransaction()
|
||||
}
|
||||
await Promise.all([open(), open()])
|
||||
let most = 0
|
||||
const watchOpen = setInterval(() => {
|
||||
const state = transactionWatchState(payload)!
|
||||
most = Math.max(most, state.active + state.nested)
|
||||
}, 0)
|
||||
await Promise.all(Array.from({ length: 30 }, () => nestedOperation(db)))
|
||||
clearInterval(watchOpen)
|
||||
expect(most).toBeLessThanOrEqual(9)
|
||||
})
|
||||
|
||||
test('the mark is lost on the way: the queue still moves (its newest waiter after a second), and one connection stays free', async () => {
|
||||
const { db, payload } = fakePayload({ max: 5 }) // limit 3; the newest waiter may take the 4th place, never the 5th
|
||||
watchTransactions(payload)
|
||||
const start = Date.now()
|
||||
expect(await finishes(Promise.all(Array.from({ length: 4 }, () => nestedOperation(db, 2, true))), 10_000)).toBe('done')
|
||||
expect(Date.now() - start).toBeGreaterThanOrEqual(900)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
|
||||
await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())])
|
||||
const later: (null | string)[] = []
|
||||
void open().then((id) => later.push(id))
|
||||
void open().then((id) => later.push(id))
|
||||
for (let i = 0; i < 3; i++) {void apart(() => db.beginTransaction()).then((id) => later.push(id))}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1300))
|
||||
expect(later).toHaveLength(1)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 3, waiting: 1 })
|
||||
})
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 4, waiting: 2 })
|
||||
}, 15_000)
|
||||
|
||||
test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => {
|
||||
const { db, events, logger, payload } = fakePayload()
|
||||
@@ -156,7 +180,7 @@ describe('the watch (fake adapter)', () => {
|
||||
watchTransactions(payload, reserve)
|
||||
const db = payload.db as unknown as FakeDb
|
||||
const ids = await Promise.all(Array.from({ length: 12 }, () => db.beginTransaction()))
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 12, reserve: null, waiting: 0 })
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 12, nested: 0, reserve: null, waiting: 0 })
|
||||
expect(afterCommit({ payload, transactionID: ids[0]! }, () => {})).toBe(true)
|
||||
}
|
||||
})
|
||||
@@ -174,7 +198,7 @@ describe('the watch (fake adapter)', () => {
|
||||
watchTransactions(payload, 7)
|
||||
expect(db.beginTransaction).toBe(begin)
|
||||
await Promise.all([db.beginTransaction(), db.beginTransaction(), db.beginTransaction()])
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 7, waiting: 0 })
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 7, waiting: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -266,6 +290,20 @@ describe.runIf(POSTGRES)('Postgres, default pool of 10', () => {
|
||||
expect(Date.now() - start).toBeLessThan(30_000)
|
||||
}, 90_000)
|
||||
|
||||
for (const count of [9, 12, 30]) {
|
||||
test(`${count} submissions at once whose hook writes WITHOUT req (a transaction inside the submission's) finish; an ordinary request answers after`, async () => {
|
||||
await useSmtpPort(9)
|
||||
const before = (await payload.count({ collection: 'log' as never })).totalDocs
|
||||
const all = Promise.all(Array.from({ length: count }, (_, i) => submit(300 + count * 10 + i, `nested-${count}-${i}`)))
|
||||
const results = await within(all, 20_000, 'stuck' as const)
|
||||
expect(results).not.toBe('stuck')
|
||||
expect((results as { success: boolean }[]).every((r) => r.success)).toBe(true)
|
||||
expect((await payload.count({ collection: 'log' as never })).totalDocs - before).toBe(count)
|
||||
expect(await ordinaryRequest()).toBeLessThan(2000)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
}, 40_000)
|
||||
}
|
||||
|
||||
test('form e-mails go out after the commit: the stored submission is visible to the send; a rolled-back one sends nothing', async () => {
|
||||
await useSmtpPort(9)
|
||||
const send = vi.spyOn(payload, 'sendEmail')
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Transactions and the Postgres pool with the Intecion mail service as the transport, the service hanging:
|
||||
* it takes every request and never answers (each send gives up after its budget). Postgres only
|
||||
* (IPAL_TEST_POSTGRES_URI); its own file because one test process pushes the schema of one Payload.
|
||||
* - 30 "forgot password" + 30 submissions at once finish within about one send budget: the reset mail goes out
|
||||
* after its transaction commits (mail.accountMailAfterCommit), so no request waits for a place behind it;
|
||||
* - a file on a form whose e-mail is "not confirmed" after the commit: the visitor gets `unconfirmed`, the
|
||||
* submission is stored;
|
||||
* - a submission created inside the caller's own transaction that is rolled back sends nothing.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { createLocalReq, getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { transactionWatchState } from '../src/modules/database/transactions.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const text = (value: string) => ({
|
||||
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', text: value, version: 1 }], direction: null, format: '', indent: 0, version: 1 }], direction: null, format: '', indent: 0, version: 1 },
|
||||
})
|
||||
const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), Buffer.alloc(4000, 0x20)])
|
||||
const within = <T, F>(promise: Promise<T>, ms: number, fallback: F) => Promise.race([promise, new Promise<F>((resolve) => setTimeout(() => resolve(fallback), ms))])
|
||||
|
||||
/** The service: takes the request and never answers (the client aborts it at its time-out). */
|
||||
let calls = 0
|
||||
const hanging: typeof fetch = (_url, init) => {
|
||||
calls += 1
|
||||
return new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))
|
||||
}
|
||||
|
||||
const N = 30
|
||||
const ACCOUNTS = Array.from({ length: N }, (_, i) => `relay-account${i}@example.com`)
|
||||
const BUDGET_MS = 3000
|
||||
|
||||
describe.runIf(Boolean(process.env.IPAL_TEST_POSTGRES_URI))('Postgres, the mail service hanging', () => {
|
||||
let payload: Payload
|
||||
let server: TestServer
|
||||
let formId: string
|
||||
let fileFormId: string
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({
|
||||
config: buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-test-pool-relay-media') } },
|
||||
{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] },
|
||||
],
|
||||
db: testDatabase('txrelay'),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
forms: { attachments: { maxConcurrent: 0 } },
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
// a token from the deployment: no enrolment, every send goes to /v1/send and hangs there
|
||||
mail: { relay: { fetchImpl: hanging, timeoutMs: BUDGET_MS, token: `ims_${'a'.repeat(43)}`, totalTimeoutMs: BUDGET_MS, url: 'http://relay.test' } },
|
||||
twoFactor: false,
|
||||
}),
|
||||
],
|
||||
secret: 'transaction-pool-relay-secret-0123456789',
|
||||
serverURL: 'https://client-pool.example.com',
|
||||
telemetry: false,
|
||||
}),
|
||||
})
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]' } as never })
|
||||
const emails = [{ emailTo: '[email protected]', message: text('{{message}}'), subject: 'New message' }]
|
||||
formId = String(
|
||||
(await payload.create({ collection: 'forms' as never, data: { confirmationMessage: text('ok'), confirmationType: 'message', emails, fields: [{ name: 'message', blockType: 'text', label: 'Message', required: true }], title: 'Contact' } as never })).id,
|
||||
)
|
||||
fileFormId = String(
|
||||
(
|
||||
await payload.create({
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationMessage: text('ok'),
|
||||
confirmationType: 'message',
|
||||
emails,
|
||||
fields: [
|
||||
{ name: 'message', blockType: 'text', label: 'Message', required: true },
|
||||
{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV', maxFiles: 1, maxSizeMB: 1 },
|
||||
],
|
||||
title: 'Careers',
|
||||
} as never,
|
||||
})
|
||||
).id,
|
||||
)
|
||||
for (const email of ACCOUNTS) {
|
||||
await payload.create({ collection: 'users' as never, data: { email, password: 'Correct-horse-battery-9' } as never, disableVerificationEmail: true })
|
||||
}
|
||||
server = await startPayloadServer(Promise.resolve(payload.config))
|
||||
}, 180_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
test(`${N} "forgot password" + ${N} submissions at once finish within about one send budget; an ordinary request answers`, async () => {
|
||||
const start = Date.now()
|
||||
const resets = Promise.all(
|
||||
ACCOUNTS.map((email) =>
|
||||
fetch(`${server.url}/api/users/forgot-password`, { body: JSON.stringify({ email }), headers: { 'Content-Type': 'application/json' }, method: 'POST' }).then((r) => [r.status, Date.now() - start] as const),
|
||||
),
|
||||
)
|
||||
const submissions = Promise.all(
|
||||
Array.from({ length: N }, (_, i) => submitForm({ data: { message: `m${i}` }, formId, ip: `10.7.0.${i}`, maxPerMinute: 0, payload }).then((r) => [r.success, Date.now() - start] as const)),
|
||||
)
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
const ordinary = Date.now()
|
||||
expect(await within(fetch(`${server.url}/api/pages`).then((r) => r.status), 8000, 'no answer')).toBe(200)
|
||||
expect(Date.now() - ordinary).toBeLessThan(2000)
|
||||
// the reset transactions commit at once and give their places back; the mail waits outside them
|
||||
const both = await within(Promise.all([resets, submissions]), 60_000, 'stuck' as const)
|
||||
expect(both).not.toBe('stuck')
|
||||
const [r, s] = both as [(readonly [number, number])[], (readonly [boolean, number])[]]
|
||||
expect(r.every(([status]) => status === 200)).toBe(true)
|
||||
expect(s.every(([ok]) => ok)).toBe(true)
|
||||
// Before (inside the transaction, eight at a time): about four budgets. Now about one.
|
||||
expect(Math.max(...r.map(([, ms]) => ms), ...s.map(([, ms]) => ms))).toBeLessThan(BUDGET_MS * 2.5)
|
||||
expect(calls).toBeGreaterThan(0)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
}, 90_000)
|
||||
|
||||
test('a file whose e-mail is not confirmed after the commit: the visitor gets `unconfirmed`, the submission is stored', async () => {
|
||||
const result = await submitForm({ data: { message: 'with a file' }, files: { cv: [{ name: 'cv.pdf', data: PDF }] }, formId: fileFormId, ip: '10.7.1.1', maxPerMinute: 0, payload })
|
||||
expect(result).toMatchObject({ field: 'cv', file: 'cv.pdf', reason: 'delivery', success: false, unconfirmed: true })
|
||||
const stored = (await payload.findByID({ id: (result as { submissionId: number | string }).submissionId, collection: 'form-submissions' as never, depth: 0 })) as { filesDelivery?: string; filesDeliveryNote?: string }
|
||||
expect(stored.filesDelivery).toBe('failed')
|
||||
expect(stored.filesDeliveryNote).toMatch(/not confirmed/i)
|
||||
}, 30_000)
|
||||
|
||||
test('a submission created inside the caller\'s own transaction that is rolled back sends nothing', async () => {
|
||||
const send = vi.spyOn(payload, 'sendEmail').mockResolvedValue({ sent: true })
|
||||
try {
|
||||
const req = (await createLocalReq({}, payload))
|
||||
req.transactionID = (await payload.db.beginTransaction())!
|
||||
await payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [{ field: 'message', value: 'outer-rolled-back' }] } as never, req })
|
||||
expect(send).not.toHaveBeenCalled() // composed, waiting for the caller's commit
|
||||
await payload.db.rollbackTransaction(req.transactionID)
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
|
||||
const committed = (await createLocalReq({}, payload))
|
||||
committed.transactionID = (await payload.db.beginTransaction())!
|
||||
await payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [{ field: 'message', value: 'outer-committed' }] } as never, req: committed })
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
await payload.db.commitTransaction(committed.transactionID)
|
||||
expect(send).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
send.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,7 @@ export async function site(name: string, { emailsInTransaction = false } = {}) {
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-test-pool-media') } },
|
||||
{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] },
|
||||
{ slug: 'log', fields: [{ name: 'note', type: 'text' }] },
|
||||
],
|
||||
db: testDatabase(name),
|
||||
editor: lexicalEditor(),
|
||||
@@ -52,9 +53,19 @@ export async function site(name: string, { emailsInTransaction = false } = {}) {
|
||||
formSubmissionOverrides: {
|
||||
hooks: {
|
||||
// a later hook that fails: the submission is rolled back
|
||||
afterChange: [({ doc }) => {
|
||||
if ((doc as { submissionData?: { value?: string }[] }).submissionData?.some((row) => row.value === 'roll-me-back')) {throw new Error('rolled back on purpose')}
|
||||
}],
|
||||
afterChange: [
|
||||
({ doc }) => {
|
||||
if ((doc as { submissionData?: { value?: string }[] }).submissionData?.some((row) => row.value === 'roll-me-back')) {throw new Error('rolled back on purpose')}
|
||||
},
|
||||
// a project's hook that writes through the Local API WITHOUT `req`: a transaction of its own,
|
||||
// begun while the submission's is still open
|
||||
async ({ doc, req }) => {
|
||||
const rows = (doc as { id: number | string; submissionData?: { value?: string }[] }).submissionData ?? []
|
||||
if (!rows.some((row) => row.value?.startsWith('nested-'))) {return}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
await req.payload.create({ collection: 'log' as never, data: { note: `submission ${doc.id}` } as never })
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user