Open History to see the last commit
1import type { Pool, PoolClient } from 'pg'
2
3export interface TransactionOptions {
4 readonly readOnly?: boolean
5 /** Snapshot replay can write its pins while preserving one MVCC snapshot. */
6 readonly repeatableRead?: boolean
7 readonly timeoutMs?: number
8 readonly lockTimeoutMs?: number
9}
10
11/** Never retry here: a lost COMMIT response has an ambiguous outcome. */
12export async function transaction<T>(
13 pool: Pool,
14 options: TransactionOptions,
15 work: (client: PoolClient) => Promise<T>,
16): Promise<T> {
17 const timeout = options.timeoutMs ?? 10_000
18 const lockTimeout = options.lockTimeoutMs ?? 5_000
19 if (![timeout, lockTimeout].every((n) => Number.isSafeInteger(n) && n > 0 && n <= 300_000)) throw new RangeError('Invalid transaction timeout')
20 const client = await pool.connect()
21 let releaseError: Error | undefined
22 let phase: 'begin' | 'work' | 'commit' = 'begin'
23 try {
24 const begin = options.readOnly ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY'
25 : options.repeatableRead ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ WRITE'
26 : 'BEGIN ISOLATION LEVEL READ COMMITTED READ WRITE'
27 // Both interpolated values were validated as bounded positive integers.
28 // One simple-protocol round trip preserves explicit BEGIN/SET LOCAL while
29 // avoiding a network round trip before any application SQL can execute.
30 await client.query(`${begin}; SELECT set_config('synchronous_commit', 'on', true),
31 set_config('statement_timeout', '${timeout}', true), set_config('lock_timeout', '${lockTimeout}', true),
32 set_config('idle_in_transaction_session_timeout', '${timeout}', true), set_config('transaction_timeout', '${timeout}', true)`)
33 phase = 'work'
34 const result = await work(client)
35 phase = 'commit'
36 await client.query('COMMIT')
37 return result
38 } catch (error) {
39 const original = error instanceof Error ? error : new Error('Transaction failed')
40 // A fully rolled-back application conflict can reuse its connection.
41 // A failed COMMIT/begin or rollback discards uncertain session state.
42 if (phase !== 'work') releaseError = original
43 try { await client.query('ROLLBACK') } catch { releaseError = original }
44 throw error
45 } finally {
46 client.release(releaseError)
47 }
48}