Files
ipal-kit/test/transactionPool.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 32bb542e8e Postgres: many requests at once no longer stop the site
Each Payload transaction holds a pool connection; code inside it that runs
without its req needs a second one (Payload's own forgotPassword, the mail
adapter's settings read and status write, payload.kv). With the default pool
of 10, ten form submissions or ten "forgot password" requests at once held
every connection and waited for good.

- connectionReserve (default on): at most pool size − reserve transactions
  open at once; a waiter older than a second may use all but the last
  connection. Building blocks in modules/database/transactions.ts.
- Form e-mails go out right after the submission's transaction commits, in
  the same request (forms.emailsInTransaction: true = the old way).
- recordIntegrationStatus merges identical writes and does not hold its
  caller while the pool is busy.
- SMTP time-outs: 10 s connect, 30 s greeting, 60 s silence (smtp.timeouts).

Tests on Postgres 17: 30 submissions, 30 forgot-password, and both against
an SMTP server that never answers, finish while a page answers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 00:33:07 +01:00

292 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.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))
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])
})
test('at most pool size − reserve transactions are open; the next waits for a commit', async () => {
const { db, payload } = fakePayload({ max: 5 })
watchTransactions(payload)
// each from its own operation, as Payload calls it (initTransaction inside the operation)
const open = async () => {
await tick()
return db.beginTransaction()
}
const ids = await Promise.all([open(), open(), open()])
let fourth: null | string = null
void open().then((id) => (fourth = id))
await tick()
expect(fourth).toBeNull()
expect(transactionWatchState(payload)).toEqual({ active: 3, 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 })
})
test('a transaction begun inside another one gets a place in the reserve after a second, so it never waits for ever on its caller', async () => {
const { db, payload } = fakePayload({ max: 5 }) // limit 3; after a second in the queue, up to 4
watchTransactions(payload)
// Each operation opens a transaction and, inside it, a second one (a hook calling the Local API without
// `req`). Three outers fill the limit; without the escape every inner would wait for ever.
const operation = async () => {
await tick()
const outer = (await db.beginTransaction())!
await tick()
const inner = (await db.beginTransaction())!
await db.commitTransaction(inner)
await db.commitTransaction(outer)
}
const start = Date.now()
const all = Promise.all([operation(), operation(), operation()])
const done = await Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), 4000))])
expect(done).toBe('done')
expect(Date.now() - start).toBeGreaterThanOrEqual(900)
expect(transactionWatchState(payload)).toMatchObject({ active: 0, waiting: 0 })
})
test('the escape leaves one connection that no transaction holds', async () => {
const { db, payload } = fakePayload({ max: 4 }) // reserve 2, limit 2, escape up to 3
watchTransactions(payload)
const open = async () => {
await tick()
return db.beginTransaction()
}
await Promise.all([open(), open()])
const later: (null | string)[] = []
void open().then((id) => later.push(id))
void open().then((id) => later.push(id))
await new Promise((resolve) => setTimeout(resolve, 1300))
expect(later).toHaveLength(1)
expect(transactionWatchState(payload)).toMatchObject({ active: 3, waiting: 1 })
})
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, 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, 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)
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()
}
})
})