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
+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 }
}