import { execSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { PostgreSqlContainer } from '@testcontainers/postgresql'; import { WorkflowWorldError } from '@workflow/errors'; import { type AnyEventRequest, IN_BAND_SEQ_AT_RUN_CREATION, SPEC_VERSION_SINGLE_ORCHESTRATOR, type World, } from '@workflow/world'; import { ulid } from 'ulid'; import { afterAll, beforeAll, describe, expect, test } from 'vitest'; import { handleConnectionErrors } from '../src/connection-errors.js'; import { createWorld } from '../src/index.js'; import { TestPool } from './pool.js'; /** * A connection the server ends in the middle of a write surfaces from the * World as a retryable transport error, not as the raw `pg` error, and the * write it cut off committed nothing, so sending it again with the same fence * count is safe. * * The connection is ended by the server itself: a trigger on the events table * runs `pg_terminate_backend()` on its own session, once, in the middle of the * INSERT. A sequence arms it, since `nextval()` is not rolled back with the * transaction the termination aborts. */ describe('lost connections (world-postgres)', () => { if (process.platform === 'win32') { test.skip('skipped on Windows since it relies on a docker container', () => {}); return; } const SPEC = SPEC_VERSION_SINGLE_ORCHESTRATOR; // Unique, so the test can tell a leaked password from any other text. const password = randomUUID(); let container: Awaited>; let pool: TestPool; let world: World; beforeAll(async () => { container = await new PostgreSqlContainer('postgres:15-alpine') .withPassword(password) .start(); const dbUrl = container.getConnectionUri(); execSync('pnpm db:push', { stdio: 'ignore', cwd: process.cwd(), env: { ...process.env, WORKFLOW_POSTGRES_URL: dbUrl }, }); pool = new TestPool({ connectionString: dbUrl, max: 4 }); // A pool the caller passes in is the caller's to listen on: without this // the terminated client's `'error'` would be an uncaught exception. handleConnectionErrors(pool, () => false); await pool.query(` CREATE SEQUENCE workflow.test_drop_next_insert; SELECT nextval('workflow.test_drop_next_insert'); CREATE FUNCTION workflow.test_drop_on_insert() RETURNS trigger AS $$ BEGIN IF nextval('workflow.test_drop_next_insert') = 1 THEN PERFORM pg_terminate_backend(pg_backend_pid()); END IF; RETURN NEW; END $$ LANGUAGE plpgsql; CREATE TRIGGER test_drop_on_insert BEFORE INSERT ON workflow.workflow_events FOR EACH ROW EXECUTE FUNCTION workflow.test_drop_on_insert(); `); world = createWorld({ pool, skipWorkers: true }); }, 120_000); afterAll(async () => { await world?.close?.(); await pool?.end(); await container?.stop(); }); /** Ends the connection of the next event INSERT, once. */ async function dropNextInsert() { await pool.query( `SELECT setval('workflow.test_drop_next_insert', 1, false)` ); } async function createRun(): Promise { const runId = `wrun_${ulid()}`; await world.events.create(runId, { eventType: 'run_created', specVersion: SPEC, eventData: { deploymentId: 'dpl_transport', workflowName: 'transport', input: new Uint8Array([1]), }, } as AnyEventRequest); return runId; } const runStarted = { eventType: 'run_started', specVersion: SPEC, } as AnyEventRequest; test('answers a write whose connection the server ended with a transport error, and commits nothing', async () => { const runId = await createRun(); await dropNextInsert(); const error = await world.events .create(runId, runStarted, { inBand: true, expectedSeqInBand: IN_BAND_SEQ_AT_RUN_CREATION, }) .catch((caught: unknown) => caught); expect(WorkflowWorldError.is(error)).toBe(true); expect(error).toMatchObject({ code: 'TRANSPORT' }); expect((error as Error).message).toMatch(/^PostgreSQL connection lost/); expect(JSON.stringify(error)).not.toContain(password); // The cut-off write moved nothing: the same write, with the same count, // is the one the run takes next. const page = await world.events.list({ runId }); expect(page.snapshot?.seqInBand).toBe(IN_BAND_SEQ_AT_RUN_CREATION); expect(page.data.map((event) => event.eventType)).toEqual(['run_created']); await expect( world.events.create(runId, runStarted, { inBand: true, expectedSeqInBand: IN_BAND_SEQ_AT_RUN_CREATION, }) ).resolves.toBeDefined(); }); });