import { Client } from 'pg'; /** Arbitrary keys, one per shared resource a suite needs to own alone. */ export const EXCLUSIVE_KEYS = { /** Open drafts are unique per kind: only one suite may create/clear them. */ authorityNotices: 72707371, } as const; /** * Holds a Postgres session advisory lock for the lifetime of a suite, so * suites that clear or count a table whose rows are global (e.g. the open * draft per notice kind) never run at the same time, even in parallel jest * workers. Blocks until the previous owner released it; the lock disappears * with the connection if a worker dies. Call release() in afterAll. */ export async function acquireExclusive( key: number, ): Promise<() => Promise> { const url = process.env.DATABASE_URL; if (!url) { throw new Error('DATABASE_URL is not set'); } const connection = new URL(url); connection.searchParams.delete('schema'); const client = new Client({ connectionString: connection.toString() }); await client.connect(); await client.query('SELECT pg_advisory_lock($1)', [key]); return async () => { await client.end(); }; }