/** * 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 = (promise: Promise, ms: number, fallback: F) => Promise.race([promise, new Promise((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: 'office@client-pool.example.com' } as never }) const emails = [{ emailTo: 'office@client-pool.example.com', 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() } }) })