// Stampwing: a local PostgreSQL outbox experiment. No email transport exists here. // Node.js 22+, PostgreSQL 17+, npm install pg@8 // Set OUTBOX_LAB_DATABASE_URL to a disposable loopback database ending in _test. // Creates a random schema and removes only that schema on normal completion. import assert from 'node:assert/strict'; import { randomUUID } from 'node:crypto'; import pg from 'pg'; const connectionString = process.env.OUTBOX_LAB_DATABASE_URL; if (!connectionString) throw new Error('Set OUTBOX_LAB_DATABASE_URL to a local, disposable _test database.'); let target; try { target = new URL(connectionString); } catch { throw new Error('Invalid local database URL.'); } if (!['postgres:', 'postgresql:'].includes(target.protocol) || !['127.0.0.1', '[::1]'].includes(target.hostname) || !/^\/[a-zA-Z0-9_]+_test$/.test(target.pathname) || target.search || target.hash) { throw new Error('Use a numeric loopback host, a database ending in _test, and no URL query parameters.'); } const schema = `outbox_lab_${randomUUID().replaceAll('-', '')}`; const config = { connectionString, max: 6, connectionTimeoutMillis: 3000, statement_timeout: 5000 }; const pool = new pg.Pool(config); const table = `${schema}.outbox`; const passed = []; let created = false; const payload = { to: 'reader@example.test', subject: 'Receipt', text: 'Synthetic order 42' }; async function orderAndEmail(client, id, body, commit = true) { await client.query('BEGIN'); try { await client.query(`INSERT INTO ${schema}.orders(id) VALUES ($1) ON CONFLICT DO NOTHING`, [id]); await client.query(`INSERT INTO ${table}(event_key, payload) VALUES ($1, $2::jsonb) ON CONFLICT (event_key) DO NOTHING`, [`receipt:${id}:v1`, JSON.stringify(body)]); // DO NOTHING alone hides changed-payload bugs. Compare the immutable intent. const { rows } = await client.query(`SELECT payload = $2::jsonb AS matches FROM ${table} WHERE event_key = $1`, [`receipt:${id}:v1`, JSON.stringify(body)]); if (!rows[0]?.matches) throw new Error('Payload conflict'); await client.query(commit ? 'COMMIT' : 'ROLLBACK'); } catch (error) { await client.query('ROLLBACK'); throw error; } } const claimSql = `WITH candidate AS ( SELECT event_key FROM ${table} WHERE state = 'pending' ORDER BY event_key FOR UPDATE SKIP LOCKED LIMIT 1 ) UPDATE ${table} AS job SET state = 'claimed', claim_version = claim_version + 1, lease_until = clock_timestamp() + interval '30 seconds' FROM candidate WHERE job.event_key = candidate.event_key RETURNING job.event_key, job.claim_version`; try { await pool.query(`CREATE SCHEMA ${schema}`); created = true; console.log(`Temporary schema: ${schema}`); await pool.query(`CREATE TABLE ${schema}.orders (id integer PRIMARY KEY); CREATE TABLE ${table} ( event_key text PRIMARY KEY, payload jsonb NOT NULL, state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'claimed', 'uncertain', 'submitted')), claim_version integer NOT NULL DEFAULT 0, lease_until timestamptz, provider_message_id text )`); const producer = await pool.connect(); try { await orderAndEmail(producer, 41, payload, false); assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${schema}.orders`)).rows[0].n, 0); assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${table}`)).rows[0].n, 0); passed.push('rollback leaves neither order nor outbox row'); await orderAndEmail(producer, 42, payload); assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${schema}.orders`)).rows[0].n, 1); assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${table}`)).rows[0].n, 1); passed.push('commit persists order and email intent together'); await orderAndEmail(producer, 42, payload); assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${table}`)).rows[0].n, 1); passed.push('repeated business event keeps one outbox row'); await assert.rejects(orderAndEmail(producer, 42, { ...payload, text: 'Changed content' }), /Payload conflict/); assert.deepEqual((await pool.query(`SELECT payload FROM ${table}`)).rows[0].payload, payload); passed.push('changed payload conflicts without replacing the original'); } finally { producer.release(); } // Hold a real lock while other connections try to claim the same row. const worker = await pool.connect(); let claim; try { await worker.query('BEGIN'); claim = (await worker.query(claimSql)).rows[0]; assert.ok(claim); const competing = await Promise.all(Array.from({ length: 5 }, () => pool.query(claimSql))); assert.deepEqual(competing.map(result => result.rowCount), [0, 0, 0, 0, 0]); await worker.query('COMMIT'); passed.push('five competing workers skip the locked claim'); } catch (error) { await worker.query('ROLLBACK'); throw error; } finally { worker.release(); } // Simulated remote acceptance followed by loss of the acknowledgement. // This list is an observation for the experiment, not a recovery API. const simulatedProvider = [{ eventKey: claim.event_key, id: 'simulated-message-1' }]; // Advance the stored lease instead of sleeping; the provider has no SQL lock. await pool.query(`UPDATE ${table} SET lease_until = clock_timestamp() - interval '1 second'`); const recovered = await pool.query(`UPDATE ${table} SET state = 'uncertain', claim_version = claim_version + 1, lease_until = NULL WHERE state = 'claimed' AND lease_until < clock_timestamp() RETURNING event_key`); assert.equal(recovered.rowCount, 1); assert.equal((await pool.query(claimSql)).rowCount, 0); assert.equal(simulatedProvider.length, 1); passed.push('expired unresolved claim is quarantined, not automatically resent'); const stale = await pool.query(`UPDATE ${table} SET state = 'submitted', provider_message_id = $3 WHERE event_key = $1 AND claim_version = $2 AND state = 'claimed'`, [claim.event_key, claim.claim_version, simulatedProvider[0].id]); assert.equal(stale.rowCount, 0); passed.push('stale worker cannot overwrite the new local state'); // A brand-new connection sees the persisted uncertainty. No process-kill or // database-failover claim is made: those require a separate fault-injection test. const observer = new pg.Client(config); try { await observer.connect(); const row = (await observer.query(`SELECT state, provider_message_id FROM ${table}`)).rows[0]; assert.deepEqual(row, { state: 'uncertain', provider_message_id: null }); passed.push('new database connection sees the unresolved operation'); } finally { await observer.end(); } console.log(JSON.stringify({ checks: passed.length, passed, simulatedProviderAcceptances: simulatedProvider.length, finalState: 'uncertain', sendsRealEmail: false }, null, 2)); } finally { try { if (created) await pool.query(`DROP SCHEMA ${schema} CASCADE`); } finally { await pool.end(); } }