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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 01:38:31 +01:00
co-authored by Claude Opus 5.5
30 changed files with 1431 additions and 27 deletions
+33
View File
@@ -132,6 +132,39 @@ once there are more than 20.
Not a switch for a live site: it would start visitors' histories and the running 2FA counts again.
- `EnvRule.aliases` for `assertEnv`: older names of a variable, read when the main one is missing.
### Fixed — Postgres: many requests at once no longer stop the site (draft; release decided by the owner)
- **Ten or more form submissions at the same moment, or ten "forgot password" requests, stopped the whole site on
Postgres** — every request, also pages that only read, waited for good (older than 1.17.0; MongoDB sites were not
affected). Each transaction holds a pool connection, and code inside it that runs without its `req` (Payload's own
"forgot password", the e-mail adapter reading Site integrations and writing the send status, `payload.kv`) needs a
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. 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). The message is
matched to its request by its token (Payload's `generateEmailSubject` is wrapped; a project's own one is kept). 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`, `holdAccountMail`,
`releaseAccountMail`.
- **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
transactions (MongoDB without a replica set, SQLite) send at once, as before. The old way:
`forms: { emailsInTransaction: true }`. Building blocks `sendAfterCommit`, `sendFormEmails`
([forms.md](./forms.md) "When e-mails go out").
- **The panel's send status** (`recordIntegrationStatus`): many sends failing at once write it once; while the pool
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 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 })`,
`iaplEnvRules({ emailGraph })` and the four `GRAPH_*` variables. Nothing new is built on it; it gets fixes only and
+4
View File
@@ -1246,6 +1246,10 @@ 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; 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)`, `holdAccountMail`, `releaseAccountMail` (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") |
### 7.2 E-mail — the mail service (default), SMTP (on request), Graph (deprecated)
+4
View File
@@ -121,6 +121,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
| 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 (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 |
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
+6
View File
@@ -120,6 +120,12 @@ Tell the client plainly: **there is no antivirus scan** (the e-mail says so), th
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
### E-mails go out after the save (1.17.0)
A form's e-mails are composed inside the submission's transaction and sent right after it commits, in the same
request (`submitForm` answers as before). A submission rolled back by a hook of yours sends nothing. Keep the old way
only on the owner's word: `forms: { emailsInTransaction: true }` (forms.md "When e-mails go out"). Check on Postgres:
a submission arrives; your own `afterChange` hooks on form-submissions pass `req` to every Local API call.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
+6
View File
@@ -584,6 +584,12 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent".
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`; 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` /
`mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending →
**Send test e-mail** names the transport you expect; a form submission arrives. **The service has to be live for a site
+57
View File
@@ -356,6 +356,63 @@ with `NODE_ENV=production` — also during `next build` when the build reaches t
schema: add columns/tables first, drop or rename in a later release (`iapl-migrate-fields` skill). Take a
**Backup now** (§4.6) before a large migration.
### 4.3a Postgres: the connection pool
Payload holds one pool connection for the whole of a transaction (a form submission, "forgot password", a save in
the panel). Code inside it that runs **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,
`payload.kv`, a project hook that calls the Local API without `req`. With the default pool of 10, **ten such requests
at the same moment held all ten connections and each waited for an eleventh — the whole site stopped, for good**
(measured on 1.16.8 and the 1.17.0 branch: 12 form submissions or 12 "forgot password" requests at once, an ordinary
page got no answer).
Since 1.17.0 the plugin keeps a few connections free of transactions (`connectionReserve`):
- 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 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"),
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:
`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail
`withAccountMailAfterCommit(collection)` (what the plugin does to every auth collection: wraps its
`generateEmailSubject`, which Payload calls with the request and the token right before the send),
`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMail`,
`releaseAccountMail`. 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, nested, waiting, reserve }`.
### 4.4 Health check and rolling updates
Coolify → the application → **Health Checks**: HTTP, path `/api/health`, port 3000, a start period long enough
+20 -4
View File
@@ -455,6 +455,12 @@ and password switches the site to the client's server.
- Missing SMTP config or a send error → the adapter **does not throw**, it returns `{ sent: false, error }` and logs.
- Port 465 → implicit TLS, others → STARTTLS.
- 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" 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`).
SMTP only, without the dispatcher:
@@ -470,7 +476,8 @@ export default buildConfig({
})
```
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`).
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`), `timeouts`
(`{ connectionMs: 10000, greetingMs: 30000, socketMs: 60000 }`).
## Dependency
@@ -520,7 +527,14 @@ 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). The message is matched to its request by the token it carries (and the
account's address), never by the address alone: a form's mail to the same address goes out as usual. A project's own
`forgotPassword.generateEmailSubject` / `verify.generateEmailSubject` is kept; an own `generateEmailHTML` must put the
token in the body (any working reset link does), or that mail is sent inside the transaction as before. An e-mail adapter of your own does the same by calling
`sendAccountMailAfterCommit(message, () => send(message))` first.
## Masking secrets in the panel (MaskedField)
@@ -717,7 +731,8 @@ Save your changes before the test — the endpoint reads from the database, not
## Send status in the panel
`mailAdapter()` stores the send result in Site integrations (at most once per 10 min
while an error persists, immediately when the state changes). When sending fails:
while an error persists, immediately when the state changes; many sends failing at once write it once, and while a
Postgres pool is busy the write goes on in the background — [integrations.md](./integrations.md)). When sending fails:
- **Dashboard** — a red alert with the cause and a link to Site integrations,
- **Site integrations → E-mail sending** — a banner with the error (e.g. `SMTP: connect ECONNREFUSED …`,
`SMTP: Invalid login: 535 …`, `Microsoft Graph: Graph sendMail failed (403).`, or the text of a mail service
@@ -756,7 +771,8 @@ SDK); you then skip the panel's SMTP fields, the mail service and the send statu
integrations and the endpoint `POST /api/ipal/test-email` are always added.
- **Choosing the transport:** `mailAdapter()` (decided per send) or a fixed `relayAdapter()` /
`panelSmtpAdapter()` / `graphAdapter()`; any other Payload adapter also works.
- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` and `graph`
- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` (with
`smtp.timeouts`) and `graph`
(`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments"); every option of the
mail service ("Options"); panel texts through `i18n.translations` (keys `mailRelay…`, `statusEmailRelay…`);
the tab's fields through `integrationsFields`.
+27 -2
View File
@@ -453,7 +453,8 @@ Limits are kept in memory by default, separately for each instance. Several inst
`turnstile`, rejected **before** storing. Keys not set → the widget does not
show, and the check is skipped. Details: [turnstile.md](./turnstile.md).
3. **Validation** against the form definition from the panel (+ enforced GDPR consent).
4. **Storing** the submission (form-submissions) → the form-builder sends the emails from the Emails tab.
4. **Storing** the submission (form-submissions) → the form-builder composes the emails from the Emails tab;
they go out right after the submission is saved ("When e-mails go out").
**A stored submission = success, even when the email fails** — Payload logs the sending error,
the submission data is not lost (it is in Form Submissions).
@@ -474,6 +475,29 @@ body (placeholders: `{{field}}`, `{{*}}`, `{{*:table}}`) without touching the co
`submitForm` is responsible only for Turnstile verification and storing. It stores the submission in the page's language
(`locale` from `createSubmitAction`), so the form-builder takes the email texts and labels in that language.
### When e-mails go out (`emailsInTransaction`)
By default (since 1.17.0) a form's e-mails go out **right after the submission is saved**: they are composed inside
the submission's database transaction (layout, `forms.beforeEmail`, the kind marks, all with the transaction's
`req`), and handed to the mail server once that transaction has committed and given its connection back — still
within the same request, so `submitForm` answers as before (a file that could not be sent is still reported to the
visitor). What this changes:
- a slow or hanging mail server holds **no database connection** — on Postgres, many submissions at once used to stop
the site ([deployment.md](./deployment.md) §4.3a);
- a submission whose transaction is **rolled back** (a later hook of yours throws) sends **nothing**; before, its
e-mails had already gone out;
- **a failure after the commit leaves a stored submission without its e-mail** (the mail server refused it, or the
process ended in between) — as an e-mail failure always did: the submission is in Form Submissions, the error in
the log and the panel status, a file marked **File delivery: Not sent**;
- `payload.create` of a submission inside **your own transaction** (`req` passed from a hook or a script): the e-mails
go out when that transaction commits, and not at all when it is rolled back;
- **MongoDB without a replica set, SQLite** (no transactions): sent at once, exactly as before.
`forms: { emailsInTransaction: true }` sends them inside the transaction, as before 1.17.0 (not recommended on
Postgres). Building blocks: `sendAfterCommit(prepare, deliver)` (the `beforeEmail` that does this),
`sendFormEmails(req, emails)` (form-builder's own send loop), `afterCommit(req, fn)` (deployment.md §4.3a).
### Nice emails (`emailLayout`)
```ts
@@ -848,6 +872,7 @@ filter it out on the client.
site-wide consent field name: `forms.consentFieldName`; shared limit store: `setRateLimitStore`; missing IP: `setUnknownIpFactor`.
- **Check:** `POST /api/form-submissions` without a session = 403; a `user` account → `PATCH /api/forms/<id>` = 403;
submits without an IP header → past `maxPerMinute × 20` per minute (100 by default) you get `rate_limited`.
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template.
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template,
`emailsInTransaction: true` sends them inside the submission's transaction ("When e-mails go out").
- **Your own front end:** `BuilderForm` (`renderField`), `useBuilderForm`, pure logic (`splitSteps`,
`visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, validators, `buildFormsPlugin` (root).
+3 -1
View File
@@ -34,7 +34,9 @@ The state block above it reads `GET /api/iapl/mail-relay/status` and acts throug
- **Write:** `mailAdapter()` on every send (`emailStatus`) and Turnstile verification on a
form (`turnstileStatus`) call `recordIntegrationStatus`. It writes only when the state changes,
or at most every 10 min while an error lasts; it never throws.
or at most every 10 min while an error lasts; it never throws. The same change already being written (many sends
failing at once) is written once; while every transaction place of a Postgres pool is taken
([deployment.md](./deployment.md) §4.3a) the write goes on in the background instead of holding the caller.
- **Changing keys in the admin panel** (Turnstile, `emailTransport` / `smtp*`) clears that integration's old status.
- **`emailStatus.code`** of a send through the Intecion mail service is one of the `relay-…` codes (`relay-pending`,
`relay-quota`, `relay-unreachable`, …), each with a text in the editor's language — the list and what to do:
@@ -121,6 +121,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
| 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 (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 |
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
@@ -120,6 +120,12 @@ Tell the client plainly: **there is no antivirus scan** (the e-mail says so), th
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
### E-mails go out after the save (1.17.0)
A form's e-mails are composed inside the submission's transaction and sent right after it commits, in the same
request (`submitForm` answers as before). A submission rolled back by a hook of yours sends nothing. Keep the old way
only on the owner's word: `forms: { emailsInTransaction: true }` (forms.md "When e-mails go out"). Check on Postgres:
a submission arrives; your own `afterChange` hooks on form-submissions pass `req` to every Local API call.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
@@ -584,6 +584,12 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent".
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`; 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` /
`mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending →
**Send test e-mail** names the transport you expect; a form submission arrives. **The service has to be live for a site
+6 -2
View File
@@ -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'
+286
View File
@@ -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
}
+106
View File
@@ -0,0 +1,106 @@
import type { CollectionConfig, PayloadRequest } from 'payload'
import { afterCommit, inWatchedTransaction } from '../database/transactions.js'
import { expectMailTo, takeExpectedMail } from './relay/kinds.js'
import { bareAddresses } from './relay/message.js'
/**
* Payload sends "forgot password" and "verify your e-mail" INSIDE the operation's transaction, so a slow or
* hanging mail server holds the transaction — and its database connection — until the send gives up. With
* many such requests at once every place for a transaction is taken by requests that only wait for mail
* (docs/deployment.md §4.3a).
*
* Payload calls the collection's `generateEmailSubject({ req, token, user })` right before it sends that mail,
* and the mail carries the same token (in its link). The wrapper below holds the token for the transaction of
* that `req`; `mailAdapter()` sends the message whose body contains a held token right AFTER that transaction
* commits — still inside the same request, so the request ends when the mail is out, as before — and drops it
* when the transaction is rolled back (the token was not stored, the link would not work).
* Matched by the token (and the account's address as a second check), never by the address alone: two
* requests for one account at once, or a form's mail to the same address, are each their own message.
* A project's own `generateEmailSubject` is kept and called; without one the subject is Payload's own.
* Without a transaction (MongoDB without a replica set, SQLite) nothing changes; a message without a held
* token (a project's own e-mail template that leaves the token out) is sent at once, as before.
* `iapl({ mail: { accountMailAfterCommit: false } })` = inside the transaction, as before.
*/
const MARK = Symbol.for('iapl.accountMailAfterCommit')
type Held = { address: string; req: PayloadRequest; until: number }
const held = new Map<string, Held>()
// Payload sends the mail right after it composed the subject, within the same request.
const TTL_MS = 30_000
// Payload's tokens are 40 hexadecimal characters; a shorter one could be found in an unrelated message.
const MIN_TOKEN = 16
const keyOf = (address: string) => address.trim().toLowerCase()
/** The message that carries `token` (to `address`) belongs to the transaction of `req`, when there is one to wait for. */
export function holdAccountMail(token: string, address: string, req: PayloadRequest): void {
if (typeof token !== 'string' || token.length < MIN_TOKEN || !inWatchedTransaction(req)) {return}
const now = Date.now()
for (const [k, entry] of held) {
if (entry.until <= now) {held.delete(k)}
}
held.set(token, { address: keyOf(address), req, until: now + TTL_MS })
}
/** Nothing is held for `token` any more. */
export function releaseAccountMail(token: string): void {
held.delete(token)
}
const bodyOf = (message: { html?: unknown; text?: unknown }) => `${typeof message.html === 'string' ? message.html : ''}\n${typeof message.text === 'string' ? message.text : ''}`
/**
* For a transport: when this message carries the token of an account operation whose transaction is still
* open, and goes to that account's address alone, schedules `send` for right after the commit and returns
* true (the caller sends nothing now). The kind the relay transport was told for the address (`account`, with
* the visitor) is carried over to that send.
*/
export function sendAccountMailAfterCommit(message: { html?: unknown; text?: unknown; to?: unknown }, send: () => Promise<unknown>): boolean {
if (!held.size) {return false}
const { addresses } = bareAddresses(message.to)
if (addresses.length !== 1) {return false}
const body = bodyOf(message)
const now = Date.now()
for (const [token, entry] of held) {
if (entry.until <= now || entry.address !== keyOf(addresses[0]) || !body.includes(token)) {continue}
held.delete(token)
const expected = takeExpectedMail(addresses)
return afterCommit(entry.req, async () => {
if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })}
await send()
})
}
return false
}
type SubjectArgs = { req: PayloadRequest; token: string; user: { email?: unknown } }
type SubjectFn = ((args: SubjectArgs) => Promise<string> | string) & { [MARK]?: boolean }
function holdingSubject(own: SubjectFn | undefined, fallback: string): SubjectFn {
if (own?.[MARK]) {return own}
const fn: SubjectFn = async (args) => {
const subject = own ? await own(args) : args.req.t(fallback as never)
if (typeof args.user?.email === 'string') {holdAccountMail(args.token, args.user.email, args.req)}
return subject
}
fn[MARK] = true
return fn
}
/**
* Wraps an auth collection's `forgotPassword.generateEmailSubject`, and `verify.generateEmailSubject` where it
* verifies e-mail addresses (idempotent). Payload's own subjects stay when the collection has none.
*/
export function withAccountMailAfterCommit(collection: CollectionConfig): CollectionConfig {
const auth = collection.auth
if (!auth) {return collection}
const own = typeof auth === 'object' ? auth : {}
if (own.disableLocalStrategy === true) {return collection}
const forgotPassword = { ...own.forgotPassword, generateEmailSubject: holdingSubject(own.forgotPassword?.generateEmailSubject as SubjectFn | undefined, 'authentication:resetYourPassword') }
const verify =
own.verify === true || (own.verify && typeof own.verify === 'object')
? { ...(typeof own.verify === 'object' ? own.verify : {}), generateEmailSubject: holdingSubject((typeof own.verify === 'object' ? own.verify.generateEmailSubject : undefined) as SubjectFn | undefined, 'authentication:verifyYourEmail') }
: own.verify
return { ...collection, auth: { ...own, forgotPassword: forgotPassword as never, ...(verify !== undefined ? { verify: verify as never } : {}) } }
}
+9 -1
View File
@@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js'
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
@@ -153,6 +154,14 @@ export const mailAdapter =
defaultFromName: smtp.defaultFromName,
sendEmail: async (message: SendEmailOptions) => {
// Payload's "forgot password" / "verify your e-mail" inside a transaction: sent right after it commits
// (accountMailAfterCommit.ts), so a slow mail server holds no database connection.
if (sendAccountMailAfterCommit(message, () => send(message))) {return { deferred: true }}
return send(message)
},
}
async function send(message: SendEmailOptions): Promise<unknown> {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
const choice = settings.emailTransport ?? 'smtp'
const previous = settings[STATUS_FIELD]
@@ -241,6 +250,5 @@ export const mailAdapter =
: { state: 'ok' },
)
return result
},
}
}
+16 -1
View File
@@ -20,8 +20,19 @@ export type PanelSmtpAdapterArgs = {
*/
fallbackFromAddress?: string
fallbackFromName?: string
/**
* How long a send waits for the SMTP server, in milliseconds: `connectionMs` to connect (default 10 000),
* `greetingMs` for its greeting (default 30 000), `socketMs` of silence during the dialogue (default 60 000).
* A send that runs inside a database transaction (Payload's "forgot password") holds a connection that long.
*/
timeouts?: SmtpTimeouts
}
export type SmtpTimeouts = { connectionMs?: number; greetingMs?: number; socketMs?: number }
/** nodemailer's own defaults are 2 minutes to connect and 10 minutes of silence. */
export const SMTP_TIMEOUT_DEFAULTS: Required<SmtpTimeouts> = { connectionMs: 10_000, greetingMs: 30_000, socketMs: 60_000 }
/**
* Payload email adapter backed by the SMTP settings in the SiteIntegrations
* global.
@@ -83,11 +94,15 @@ export const panelSmtpAdapter =
const { default: nodemailer } = await import('nodemailer')
const timeouts = { ...SMTP_TIMEOUT_DEFAULTS, ...args.timeouts }
const transporter = nodemailer.createTransport({
auth: { pass, user },
connectionTimeout: timeouts.connectionMs,
greetingTimeout: timeouts.greetingMs,
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
socketTimeout: timeouts.socketMs,
})
try {
+48
View File
@@ -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 -3
View File
@@ -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({
+10
View File
@@ -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
+38 -10
View File
@@ -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
}
+10
View File
@@ -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.
+20
View File
@@ -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. */
+2 -1
View File
@@ -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'
+4 -1
View File
@@ -24,6 +24,7 @@ import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachme
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'
vi.mock('server-only', () => ({}))
@@ -127,7 +128,9 @@ beforeAll(async () => {
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: mediaDir } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
// SQLite in memory by default; IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI run the same tests there (on
// Postgres the e-mails go out after the submission's transaction commits: forms.emailsInTransaction).
db: testDatabase('formfiles'),
editor: lexicalEditor(),
email: recordingMail,
plugins: [
+2 -1
View File
@@ -72,7 +72,8 @@ describe('iapl — auth collection', () => {
secret: 'x',
} as unknown as Config)
const users = config.collections?.find((c) => c.slug === 'users')
expect(users?.auth).toBe(true)
// an auth collection with Payload's defaults; the plugin only wraps the reset mail's subject (mail.accountMailAfterCommit)
expect(users?.auth).toEqual({ forgotPassword: { generateEmailSubject: expect.any(Function) } })
expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true)
})
+394
View File
@@ -0,0 +1,394 @@
/**
* Transactions and the Postgres pool (modules/database/transactions.ts, forms.emailsInTransaction;
* `true` is checked in transactionPoolInTx.test.ts).
*
* Payload holds a pool connection for the whole of a transaction; code inside it that runs without the
* transaction's `req` needs a second one. Ten such requests at once (form submissions sending e-mail,
* Payload's own "forgot password") used to hold the default pool of 10 and wait for an eleventh — the
* whole site stopped. Part 1 checks the watch against a fake adapter; part 2 runs a real Payload on
* Postgres when IPAL_TEST_POSTGRES_URI is set (test/http/db.ts), with the default pool:
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17
* IPAL_TEST_POSTGRES_URI=postgres://postgres:[email protected]:55432/postgres pnpm vitest run test/transactionPool.test.ts
*/
import type { BasePayload, Payload, PayloadRequest } 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'
import { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAccountMailAfterCommit } from '../src/modules/email/accountMailAfterCommit.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { startPayloadServer, type TestServer } from './http/server.js'
import { silentServer, site } from './transactionPoolSite.js'
vi.mock('server-only', () => ({}))
// ---- part 1: the watch, against a fake adapter ---------------------------------------------------
type FakeDb = {
beginTransaction: () => Promise<null | string>
commitTransaction: (id: Promise<string> | string) => Promise<void>
pool?: { options: { max?: number } }
rollbackTransaction: (id: Promise<string> | string) => Promise<void>
}
function fakePayload({ max = 5, pool = true, transactions = true }: { max?: number; pool?: boolean; transactions?: boolean } = {}) {
let n = 0
const events: string[] = []
const db: FakeDb = {
beginTransaction: () => Promise.resolve(transactions ? `t${++n}` : null),
commitTransaction: async (id) => {
events.push(`commit ${await id}`)
},
rollbackTransaction: async (id) => {
events.push(`rollback ${await id}`)
},
...(pool ? { pool: { options: { max } } } : {}),
}
const logger = { error: vi.fn(), info: vi.fn(), warn: vi.fn() }
return { db, events, logger, payload: { db, logger } as unknown as BasePayload }
}
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)
const ids = await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())])
let fourth: null | string = null
void apart(() => db.beginTransaction()).then((id) => (fourth = id))
await tick()
expect(fourth).toBeNull()
expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 2, waiting: 1 })
await db.commitTransaction(ids[0]!)
await tick()
expect(fourth).toBe('t4')
await db.rollbackTransaction(ids[1]!)
expect(transactionWatchState(payload)).toMatchObject({ active: 2, waiting: 0 })
})
/** 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)
expect(await finishes(Promise.all(Array.from({ length: 12 }, () => nestedOperation(db, 3))))).toBe('done')
})
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)
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)[] = []
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: 4, waiting: 2 })
}, 15_000)
describe('account mail after commit (matched by its token, never by the address alone)', () => {
const TOKEN_A = 'a'.repeat(40)
const TOKEN_B = 'b'.repeat(40)
const reqOf = async (payload: BasePayload, db: FakeDb) => ({ payload, transactionID: (await db.beginTransaction())! }) as unknown as PayloadRequest
const resetMail = (token: string, to = '[email protected]') => ({ html: `<a href="https://site.example/admin/reset/${token}">reset</a>`, to })
test('two "forgot password" for one address at once, the second rolled back: the first one\'s mail goes out at its commit', async () => {
const { db, payload } = fakePayload({ max: 10 })
watchTransactions(payload)
const sent: string[] = []
const a = await reqOf(payload, db)
const b = await reqOf(payload, db)
holdAccountMail(TOKEN_A, '[email protected]', a)
holdAccountMail(TOKEN_B, '[email protected]', b)
expect(sendAccountMailAfterCommit(resetMail(TOKEN_A), async () => void sent.push('A'))).toBe(true)
expect(sendAccountMailAfterCommit(resetMail(TOKEN_B), async () => void sent.push('B'))).toBe(true)
await db.commitTransaction(a.transactionID as string)
expect(sent).toEqual(['A'])
await db.rollbackTransaction(b.transactionID as string)
expect(sent).toEqual(['A'])
})
test('a form\'s mail to an address whose "forgot password" is in flight is sent at once; the reset mail waits for its commit', async () => {
const { db, payload } = fakePayload({ max: 10 })
watchTransactions(payload)
const sent: string[] = []
const reset = await reqOf(payload, db)
holdAccountMail(TOKEN_A, '[email protected]', reset)
expect(sendAccountMailAfterCommit({ html: '<p>New message from the contact form</p>', to: '[email protected]' }, async () => void sent.push('form'))).toBe(false)
// the same token to another address, or to several, is not the account's mail either
expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, '[email protected]'), async () => {})).toBe(false)
expect(sendAccountMailAfterCommit({ ...resetMail(TOKEN_A), to: ['[email protected]', '[email protected]'] }, async () => {})).toBe(false)
expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, '[email protected]'), async () => void sent.push('reset'))).toBe(true)
await db.rollbackTransaction(reset.transactionID as string)
expect(sent).toEqual([]) // the form mail was the caller's to send; the reset of a rolled-back request is dropped
releaseAccountMail(TOKEN_A)
})
test('nothing held without a watched transaction, or for a short token', async () => {
const { db, payload } = fakePayload({ max: 10 })
watchTransactions(payload)
holdAccountMail(TOKEN_A, '[email protected]', { payload, transactionID: undefined } as unknown as PayloadRequest)
holdAccountMail('short', '[email protected]', await reqOf(payload, db))
expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, '[email protected]'), async () => {})).toBe(false)
expect(sendAccountMailAfterCommit({ html: 'short', to: '[email protected]' }, async () => {})).toBe(false)
})
test('the collection: Payload\'s own subjects, a project\'s own one kept; collections without a password left alone', async () => {
const t = (key: string) => `t:${key}`
const plain = withAccountMailAfterCommit({ slug: 'users', auth: true, fields: [] })
const auth = plain.auth as { forgotPassword: { generateEmailSubject: (a: unknown) => Promise<string> }; verify?: unknown }
expect(await auth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: '[email protected]' } })).toBe('t:authentication:resetYourPassword')
expect(auth.verify).toBeUndefined()
const own = withAccountMailAfterCommit({ slug: 'members', auth: { forgotPassword: { generateEmailSubject: () => 'Reset' }, verify: true }, fields: [] })
const ownAuth = own.auth as { forgotPassword: { generateEmailSubject: (a: unknown) => Promise<string> }; verify: { generateEmailSubject: (a: unknown) => Promise<string> } }
expect(await ownAuth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: '[email protected]' } })).toBe('Reset')
expect(await ownAuth.verify.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: '[email protected]' } })).toBe('t:authentication:verifyYourEmail')
expect(withAccountMailAfterCommit(own)).toEqual(own) // idempotent
const keyOnly = { slug: 'keys', auth: { disableLocalStrategy: true as const }, fields: [] }
expect(withAccountMailAfterCommit(keyOnly)).toBe(keyOnly)
expect(withAccountMailAfterCommit({ slug: 'pages', fields: [] })).toEqual({ slug: 'pages', fields: [] })
})
})
test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => {
const { db, events, logger, payload } = fakePayload()
watchTransactions(payload)
const a = (await db.beginTransaction())!
expect(inWatchedTransaction({ payload, transactionID: a })).toBe(true)
expect(afterCommit({ payload, transactionID: a }, () => void events.push('after a'))).toBe(true)
expect(afterCommit({ payload, transactionID: a }, () => Promise.reject(new Error('mail down')))).toBe(true)
expect(afterCommit({ payload, transactionID: a }, () => void events.push('after a, 3rd'))).toBe(true)
await db.commitTransaction(a)
expect(events).toEqual(['commit t1', 'after a', 'after a, 3rd'])
expect(logger.error).toHaveBeenCalledTimes(1)
const b = (await db.beginTransaction())!
afterCommit({ payload, transactionID: b }, () => void events.push('after b'))
await db.rollbackTransaction(b)
expect(events).toContain('rollback t2')
expect(events).not.toContain('after b')
})
test('nothing to wait for → afterCommit returns false and schedules nothing', async () => {
const { db, payload } = fakePayload()
watchTransactions(payload)
expect(afterCommit({ payload, transactionID: undefined }, () => {})).toBe(false)
expect(afterCommit({ payload, transactionID: 'not-seen' }, () => {})).toBe(false)
expect(afterCommit({ payload, transactionID: Promise.resolve('t1') as never }, () => {})).toBe(false)
const id = (await db.beginTransaction())!
await db.commitTransaction(id)
expect(afterCommit({ payload, transactionID: id }, () => {})).toBe(false) // already committed
// An adapter without transactions (MongoDB without a replica set, SQLite by default) begins none.
const none = fakePayload({ transactions: false })
watchTransactions(none.payload)
expect(await none.db.beginTransaction()).toBeNull()
expect(transactionWatchState(none.payload)).toMatchObject({ active: 0 })
})
test('`false`, or an adapter without a pool: no limit (the watch for afterCommit stays)', async () => {
for (const { payload, reserve } of [
{ payload: fakePayload({ max: 3 }).payload, reserve: false as const },
{ payload: fakePayload({ pool: false }).payload, reserve: 2 },
]) {
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, nested: 0, reserve: null, waiting: 0 })
expect(afterCommit({ payload, transactionID: ids[0]! }, () => {})).toBe(true)
}
})
test('an adapter with no transaction functions is not watched', () => {
const payload = { db: {}, logger: console } as unknown as BasePayload
expect(watchTransactions(payload)).toBeNull()
expect(transactionWatchState(payload)).toBeNull()
})
test('installed once: a second call changes the reserve, it does not wrap again', async () => {
const { db, payload } = fakePayload({ max: 10 })
watchTransactions(payload)
const begin = db.beginTransaction
watchTransactions(payload, 7)
expect(db.beginTransaction).toBe(begin)
await Promise.all([db.beginTransaction(), db.beginTransaction(), db.beginTransaction()])
expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 7, waiting: 0 })
})
})
// ---- part 2: a real Payload on Postgres, the default pool of 10 -----------------------------------
const POSTGRES = Boolean(process.env.IPAL_TEST_POSTGRES_URI)
const N = 30
const ACCOUNTS = Array.from({ length: N }, (_, i) => `account${i}@example.com`)
/** Resolves with `fallback` when `promise` takes longer than `ms`. */
const within = <T, F>(promise: Promise<T>, ms: number, fallback: F) => Promise.race([promise, new Promise<F>((resolve) => setTimeout(() => resolve(fallback), ms))])
describe.runIf(POSTGRES)('Postgres, default pool of 10', () => {
let payload: Payload
let formId: string
let server: TestServer
let silent: Awaited<ReturnType<typeof silentServer>>
const useSmtpPort = (port: number) =>
payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'p', smtpPort: port, smtpUser: 'u' } as never })
const submit = (i: number, message = `message ${i}`) =>
submitForm({ data: { email: `visitor${i}@example.org`, message }, formId, ip: `10.9.0.${i}`, maxPerMinute: 0, payload })
const forgot = (email: string) =>
fetch(`${server.url}/api/users/forgot-password`, { body: JSON.stringify({ email }), headers: { 'Content-Type': 'application/json' }, method: 'POST' }).then((r) => r.status)
/** An ordinary request while the others wait: its time in ms, or 'no answer'. */
const ordinaryRequest = async () => {
const start = Date.now()
const status = await within(fetch(`${server.url}/api/pages`).then((r) => r.status), 8000, 'no answer' as const)
return status === 200 ? Date.now() - start : status
}
beforeAll(async () => {
;({ formId, payload } = await site('txpool'))
const config = Promise.resolve(payload.config)
server = await startPayloadServer(config)
silent = await silentServer()
for (const email of ACCOUNTS) {
await payload.create({ collection: 'users' as never, data: { email, password: 'Correct-horse-battery-9' } as never, disableVerificationEmail: true })
}
}, 120_000)
afterAll(async () => {
await silent?.close()
await server?.close()
await payload?.destroy()
})
test('the reserve is in force: 2 of the 10 connections stay free of transactions', () => {
expect(transactionWatchState(payload)).toMatchObject({ reserve: 2 })
})
test(`${N} form submissions at once finish, and an ordinary request answers meanwhile (SMTP refuses at once)`, async () => {
await useSmtpPort(9)
const pending = Promise.all(Array.from({ length: N }, (_, i) => submit(i)))
await new Promise((resolve) => setTimeout(resolve, 300))
expect(await ordinaryRequest()).toBeLessThan(2000)
const results = await within(pending, 30_000, 'stuck' as const)
expect(results).not.toBe('stuck')
expect((results as { success: boolean }[]).every((r) => r.success)).toBe(true)
// the panel status says so
const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never })) as { emailStatus?: { code?: string; state?: string } }
expect(integrations.emailStatus).toMatchObject({ code: 'smtp-error', state: 'degraded' })
}, 60_000)
test(`${N} "forgot password" requests for different accounts at once finish, and an ordinary request answers`, async () => {
await useSmtpPort(9)
const pending = Promise.all(ACCOUNTS.map(forgot))
await new Promise((resolve) => setTimeout(resolve, 300))
expect(await ordinaryRequest()).toBeLessThan(2000)
expect(await within(pending, 30_000, 'stuck')).toEqual(ACCOUNTS.map(() => 200))
}, 60_000)
test(`a hanging SMTP server: ${N} submissions and ${N} "forgot password" at once all finish; an ordinary request answers`, async () => {
await useSmtpPort(silent.port)
// Payload allows one reset request per account every 15 s: wait it out, so every request really sends.
await new Promise((resolve) => setTimeout(resolve, 15_500))
const start = Date.now()
const submissions = Promise.all(Array.from({ length: N }, (_, i) => submit(100 + i)))
const resets = Promise.all(ACCOUNTS.map(forgot))
await new Promise((resolve) => setTimeout(resolve, 500))
expect(await ordinaryRequest()).toBeLessThan(2000)
const both = await within(Promise.all([submissions, resets]), 45_000, 'stuck' as const)
expect(both).not.toBe('stuck')
const [subs, codes] = both as [{ success: boolean }[], number[]]
expect(subs.every((r) => r.success)).toBe(true)
expect(codes).toEqual(ACCOUNTS.map(() => 200))
// Submissions send in parallel after their commit (≈ one time-out); the resets send inside their
// transactions, eight at a time (30 × 2 s / 8 ≈ 8 s).
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')
const seen: number[] = []
send.mockImplementation(async () => {
// outside the transaction: only a committed submission can be found
seen.push((await payload.count({ collection: 'form-submissions' as never, where: { 'submissionData.value': { equals: 'after-commit-check' } } })).totalDocs)
return { sent: true }
})
try {
expect(await submit(201, 'after-commit-check')).toMatchObject({ success: true })
expect(seen).toEqual([1, 1]) // both e-mails of the form, each after the commit
send.mockClear()
expect(await submit(202, 'roll-me-back')).toEqual({ reason: 'error', success: false })
expect(send).not.toHaveBeenCalled()
expect((await payload.count({ collection: 'form-submissions' as never, where: { 'submissionData.value': { equals: 'roll-me-back' } } })).totalDocs).toBe(0)
} finally {
send.mockRestore()
}
})
})
+31
View File
@@ -0,0 +1,31 @@
/**
* forms.emailsInTransaction: true — the e-mails of a form go out inside the submission's transaction, as
* before 1.17.0. Postgres only (IPAL_TEST_POSTGRES_URI); its own file, because one test process pushes the
* schema of one Payload (test/transactionPool.test.ts has the default).
*/
import { describe, expect, test, vi } from 'vitest'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { site } from './transactionPoolSite.js'
vi.mock('server-only', () => ({}))
describe.runIf(Boolean(process.env.IPAL_TEST_POSTGRES_URI))('Postgres, forms.emailsInTransaction: true', () => {
test('forms.emailsInTransaction: true sends inside the transaction, as before 1.17.0', async () => {
const other = await site('txpoolin', { emailsInTransaction: true })
const send = vi.spyOn(other.payload, 'sendEmail')
const seen: number[] = []
send.mockImplementation(async () => {
seen.push((await other.payload.count({ collection: 'form-submissions' as never })).totalDocs)
return { sent: true }
})
try {
const result = await submitForm({ data: { email: '[email protected]', message: 'm' }, formId: other.formId, maxPerMinute: 0, payload: other.payload })
expect(result).toMatchObject({ success: true })
expect(seen).toEqual([0, 0]) // not committed yet when the e-mails went out
} finally {
send.mockRestore()
await other.payload.destroy()
}
}, 60_000)
})
+166
View File
@@ -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()
}
})
})
+100
View File
@@ -0,0 +1,100 @@
/** The site of test/transactionPool*.test.ts: a contact form, accounts, mailAdapter with short SMTP time-outs. */
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import net from 'node:net'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
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 },
})
/** An SMTP server that accepts the connection and never says a word. */
export async function silentServer(): Promise<{ close: () => Promise<void>; port: number }> {
const sockets = new Set<net.Socket>()
const server = net.createServer((socket) => {
sockets.add(socket)
socket.on('close', () => sockets.delete(socket))
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
return {
close: () => {
for (const s of sockets) {s.destroy()}
return new Promise((resolve) => server.close(() => resolve()))
},
port: (server.address() as net.AddressInfo).port,
}
}
export async function site(name: string, { emailsInTransaction = false } = {}) {
const 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-media') } },
{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] },
{ slug: 'log', fields: [{ name: 'note', type: 'text' }] },
],
db: testDatabase(name),
editor: lexicalEditor(),
// Short SMTP time-outs: a server that hangs costs two seconds a send.
email: mailAdapter({ smtp: { timeouts: { connectionMs: 2000, greetingMs: 2000, socketMs: 2000 } } }),
plugins: [
iapl({
access: { authCollection: 'users' },
forms: {
emailsInTransaction,
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')}
},
// 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 })
},
],
},
},
},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
mail: { relay: false },
twoFactor: false,
}),
],
secret: 'transaction-pool-test-secret-0123456789',
serverURL: 'https://example.com',
telemetry: false,
}),
})
const form = await payload.create({
collection: 'forms' as never,
data: {
confirmationMessage: text('ok'),
confirmationType: 'message',
emails: [
{ emailTo: '[email protected]', message: text('{{message}}'), subject: 'New message' },
{ emailTo: '{{email}}', message: text('Thank you'), subject: 'Thank you' },
],
fields: [
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
{ name: 'message', blockType: 'text', label: 'Message', required: true },
],
title: 'Contact',
} as never,
})
return { formId: String(form.id), payload }
}