Postgres pool, review round 1: nested transactions, account mail after commit
P-1: a transaction begun inside another one (a hook calling the Local API without req) no longer queues behind its caller. An AsyncLocalStorage mark set when a transaction begins lets the inner one through at once, without a place, but never into the last connection (a second level may take that one). If the mark is lost, a queue that has not moved for a second admits its newest waiter. connectionReserve: false now admits everything, as before. Measured on Postgres 17: 9, 12 and 30 such submissions finish (before: stuck from 9). P-2: Payload's "forgot password" and "verify your e-mail" through mailAdapter() go out right after their transaction commits (mail.accountMailAfterCommit, default on). With the relay hanging, 30 resets + 30 submissions finish in about 11 s instead of 43.5 s. P-3: Postgres tests for the "not confirmed" file result after commit, a caller's outer transaction rolled back or committed, the relay hanging, and the nested rows; deployment.md has the measured table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
32bb542e8e
commit
4efadb21d5
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
import type { BasePayload, Payload } from 'payload'
|
||||
|
||||
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.js'
|
||||
@@ -48,26 +49,27 @@ function fakePayload({ max = 5, pool = true, transactions = true }: { max?: numb
|
||||
}
|
||||
|
||||
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
/** Runs a function in the context this file started in (before any transaction mark). */
|
||||
const root = AsyncLocalStorage.snapshot()
|
||||
|
||||
describe('the watch (fake adapter)', () => {
|
||||
test('the default reserve: a fifth of the pool, at least 2; 1 in a pool of fewer than 4', () => {
|
||||
expect([1, 2, 3, 4, 5, 10, 11, 20, 50].map(defaultConnectionReserve)).toEqual([1, 1, 1, 2, 2, 2, 3, 4, 10])
|
||||
})
|
||||
|
||||
// Each call runs in a context of its own that starts from the file's (no transaction mark), as two unrelated
|
||||
// requests do: Node 22 keeps an AsyncLocalStorage mark per callback, which siblings started together share.
|
||||
const apart = <T>(fn: () => T): T => root(() => new AsyncResource('iapl-test-operation').runInAsyncScope(fn))
|
||||
|
||||
test('at most pool size − reserve transactions are open; the next waits for a commit', async () => {
|
||||
const { db, payload } = fakePayload({ max: 5 })
|
||||
watchTransactions(payload)
|
||||
// each from its own operation, as Payload calls it (initTransaction inside the operation)
|
||||
const open = async () => {
|
||||
await tick()
|
||||
return db.beginTransaction()
|
||||
}
|
||||
const ids = await Promise.all([open(), open(), open()])
|
||||
const ids = await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())])
|
||||
let fourth: null | string = null
|
||||
void open().then((id) => (fourth = id))
|
||||
void apart(() => db.beginTransaction()).then((id) => (fourth = id))
|
||||
await tick()
|
||||
expect(fourth).toBeNull()
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 2, waiting: 1 })
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 2, waiting: 1 })
|
||||
await db.commitTransaction(ids[0]!)
|
||||
await tick()
|
||||
expect(fourth).toBe('t4')
|
||||
@@ -75,42 +77,64 @@ describe('the watch (fake adapter)', () => {
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 2, waiting: 0 })
|
||||
})
|
||||
|
||||
test('a transaction begun inside another one gets a place in the reserve after a second, so it never waits for ever on its caller', async () => {
|
||||
const { db, payload } = fakePayload({ max: 5 }) // limit 3; after a second in the queue, up to 4
|
||||
/** An operation whose hook calls the Local API without `req`: `levels` transactions, each inside the last. */
|
||||
const nestedOperation = (db: FakeDb, levels = 2, lost = false) =>
|
||||
apart(async () => {
|
||||
const ids: string[] = []
|
||||
for (let level = 0; level < levels; level++) {
|
||||
await tick()
|
||||
// `lost`: the inner one begins where the mark does not reach (the backstop must still move the queue)
|
||||
ids.push((await (lost && level > 0 ? apart(() => db.beginTransaction()) : db.beginTransaction()))!)
|
||||
}
|
||||
for (const id of ids.reverse()) {await db.commitTransaction(id)}
|
||||
})
|
||||
const finishes = (all: Promise<unknown>, ms = 8000) => Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), ms))])
|
||||
|
||||
for (const [max, count] of [[10, 9], [10, 10], [10, 12], [10, 30], [5, 8], [3, 6]] as const) {
|
||||
test(`pool ${max}: ${count} transactions at once, each with one begun inside it, finish at once (no place for the inner one)`, async () => {
|
||||
const { db, payload } = fakePayload({ max })
|
||||
watchTransactions(payload)
|
||||
const start = Date.now()
|
||||
expect(await finishes(Promise.all(Array.from({ length: count }, () => nestedOperation(db))))).toBe('done')
|
||||
expect(Date.now() - start).toBeLessThan(500)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
})
|
||||
}
|
||||
|
||||
test('two levels inside one another: 12 operations at once in a pool of 10 finish', async () => {
|
||||
const { db, payload } = fakePayload({ max: 10 })
|
||||
watchTransactions(payload)
|
||||
// Each operation opens a transaction and, inside it, a second one (a hook calling the Local API without
|
||||
// `req`). Three outers fill the limit; without the escape every inner would wait for ever.
|
||||
const operation = async () => {
|
||||
await tick()
|
||||
const outer = (await db.beginTransaction())!
|
||||
await tick()
|
||||
const inner = (await db.beginTransaction())!
|
||||
await db.commitTransaction(inner)
|
||||
await db.commitTransaction(outer)
|
||||
}
|
||||
const start = Date.now()
|
||||
const all = Promise.all([operation(), operation(), operation()])
|
||||
const done = await Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), 4000))])
|
||||
expect(done).toBe('done')
|
||||
expect(Date.now() - start).toBeGreaterThanOrEqual(900)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, waiting: 0 })
|
||||
expect(await finishes(Promise.all(Array.from({ length: 12 }, () => nestedOperation(db, 3))))).toBe('done')
|
||||
})
|
||||
|
||||
test('the escape leaves one connection that no transaction holds', async () => {
|
||||
const { db, payload } = fakePayload({ max: 4 }) // reserve 2, limit 2, escape up to 3
|
||||
test('the inner ones never take the last connection: one stays free for the queries outside transactions', async () => {
|
||||
const { db, payload } = fakePayload({ max: 10 })
|
||||
watchTransactions(payload)
|
||||
const open = async () => {
|
||||
await tick()
|
||||
return db.beginTransaction()
|
||||
}
|
||||
await Promise.all([open(), open()])
|
||||
let most = 0
|
||||
const watchOpen = setInterval(() => {
|
||||
const state = transactionWatchState(payload)!
|
||||
most = Math.max(most, state.active + state.nested)
|
||||
}, 0)
|
||||
await Promise.all(Array.from({ length: 30 }, () => nestedOperation(db)))
|
||||
clearInterval(watchOpen)
|
||||
expect(most).toBeLessThanOrEqual(9)
|
||||
})
|
||||
|
||||
test('the mark is lost on the way: the queue still moves (its newest waiter after a second), and one connection stays free', async () => {
|
||||
const { db, payload } = fakePayload({ max: 5 }) // limit 3; the newest waiter may take the 4th place, never the 5th
|
||||
watchTransactions(payload)
|
||||
const start = Date.now()
|
||||
expect(await finishes(Promise.all(Array.from({ length: 4 }, () => nestedOperation(db, 2, true))), 10_000)).toBe('done')
|
||||
expect(Date.now() - start).toBeGreaterThanOrEqual(900)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
|
||||
await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())])
|
||||
const later: (null | string)[] = []
|
||||
void open().then((id) => later.push(id))
|
||||
void open().then((id) => later.push(id))
|
||||
for (let i = 0; i < 3; i++) {void apart(() => db.beginTransaction()).then((id) => later.push(id))}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1300))
|
||||
expect(later).toHaveLength(1)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 3, waiting: 1 })
|
||||
})
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 4, waiting: 2 })
|
||||
}, 15_000)
|
||||
|
||||
test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => {
|
||||
const { db, events, logger, payload } = fakePayload()
|
||||
@@ -156,7 +180,7 @@ describe('the watch (fake adapter)', () => {
|
||||
watchTransactions(payload, reserve)
|
||||
const db = payload.db as unknown as FakeDb
|
||||
const ids = await Promise.all(Array.from({ length: 12 }, () => db.beginTransaction()))
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 12, reserve: null, waiting: 0 })
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 12, nested: 0, reserve: null, waiting: 0 })
|
||||
expect(afterCommit({ payload, transactionID: ids[0]! }, () => {})).toBe(true)
|
||||
}
|
||||
})
|
||||
@@ -174,7 +198,7 @@ describe('the watch (fake adapter)', () => {
|
||||
watchTransactions(payload, 7)
|
||||
expect(db.beginTransaction).toBe(begin)
|
||||
await Promise.all([db.beginTransaction(), db.beginTransaction(), db.beginTransaction()])
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 7, waiting: 0 })
|
||||
expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 7, waiting: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -266,6 +290,20 @@ describe.runIf(POSTGRES)('Postgres, default pool of 10', () => {
|
||||
expect(Date.now() - start).toBeLessThan(30_000)
|
||||
}, 90_000)
|
||||
|
||||
for (const count of [9, 12, 30]) {
|
||||
test(`${count} submissions at once whose hook writes WITHOUT req (a transaction inside the submission's) finish; an ordinary request answers after`, async () => {
|
||||
await useSmtpPort(9)
|
||||
const before = (await payload.count({ collection: 'log' as never })).totalDocs
|
||||
const all = Promise.all(Array.from({ length: count }, (_, i) => submit(300 + count * 10 + i, `nested-${count}-${i}`)))
|
||||
const results = await within(all, 20_000, 'stuck' as const)
|
||||
expect(results).not.toBe('stuck')
|
||||
expect((results as { success: boolean }[]).every((r) => r.success)).toBe(true)
|
||||
expect((await payload.count({ collection: 'log' as never })).totalDocs - before).toBe(count)
|
||||
expect(await ordinaryRequest()).toBeLessThan(2000)
|
||||
expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 })
|
||||
}, 40_000)
|
||||
}
|
||||
|
||||
test('form e-mails go out after the commit: the stored submission is visible to the send; a rolled-back one sends nothing', async () => {
|
||||
await useSmtpPort(9)
|
||||
const send = vi.spyOn(payload, 'sendEmail')
|
||||
|
||||
Reference in New Issue
Block a user