|
| 1 | +import { stripLiteralsAndComments } from '@dotaz/shared/sql' |
| 2 | +import type { ReservedSQL } from 'bun' |
| 3 | + |
| 4 | +/** Minimal interface for transaction state tracking. */ |
| 5 | +interface TxTrackable { |
| 6 | + txActive: boolean |
| 7 | + txAborted?: boolean |
| 8 | +} |
| 9 | + |
| 10 | +/** Detect raw transaction-control statements and sync txActive/txAborted flags. */ |
| 11 | +export function syncTxActive(session: TxTrackable, sql: string): void { |
| 12 | + const upper = stripLiteralsAndComments(sql).trim().toUpperCase() |
| 13 | + if (/^(BEGIN|START\s+TRANSACTION)\b/.test(upper)) { |
| 14 | + session.txActive = true |
| 15 | + if ('txAborted' in session) session.txAborted = false |
| 16 | + } else if (/^(COMMIT|END)\b/.test(upper)) { |
| 17 | + session.txActive = false |
| 18 | + if ('txAborted' in session) session.txAborted = false |
| 19 | + } else if (/^ROLLBACK\b/.test(upper) && !/^ROLLBACK\s+TO\b/.test(upper)) { |
| 20 | + session.txActive = false |
| 21 | + if ('txAborted' in session) session.txAborted = false |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +/** Detect connection-level errors (TCP drop, reset, etc.) as opposed to protocol errors. */ |
| 26 | +export function isConnectionLevelError(err: unknown): boolean { |
| 27 | + const code = (err as any)?.code |
| 28 | + if (typeof code === 'string' && /^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(code)) { |
| 29 | + return true |
| 30 | + } |
| 31 | + // fallback for errors without .code (Bun-specific, string messages, etc.) |
| 32 | + const message = err instanceof Error ? err.message : String(err) |
| 33 | + return /ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i |
| 34 | + .test(message) |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Safely release a reserved connection back to the pool. |
| 39 | + * Optionally rolls back, then runs the reset function (e.g. DISCARD ALL or RESET CONNECTION), |
| 40 | + * releases the connection, or closes it if reset/release fails. |
| 41 | + */ |
| 42 | +export async function safeReleaseConnection( |
| 43 | + conn: ReservedSQL, |
| 44 | + resetFn: (conn: ReservedSQL) => Promise<void>, |
| 45 | + options?: { rollback?: boolean }, |
| 46 | +): Promise<void> { |
| 47 | + if (options?.rollback) { |
| 48 | + try { |
| 49 | + await conn.unsafe('ROLLBACK') |
| 50 | + } catch { /* ignore — no tx is fine */ } |
| 51 | + } |
| 52 | + try { |
| 53 | + await resetFn(conn) |
| 54 | + try { |
| 55 | + conn.release() |
| 56 | + } catch { /* broken connection */ } |
| 57 | + } catch { |
| 58 | + try { |
| 59 | + conn.close({ timeout: 0 }) |
| 60 | + } catch { /* already dead */ } |
| 61 | + } |
| 62 | +} |
0 commit comments