Files
CatoandClaude 19ffeaff74 fix(auth): a session read that hangs cannot take the site down (#298)
On 2026-10-30 every Substrata page answered 502 after 23 seconds for hours
while /api/health still answered 200: session reads hung (get-session took
251 s) and every page waits for one. A restart cleared it; the cause was not
visible from outside the box.

- currentSession() gives up after 4 s and answers "signed out", logged, so a
  public page always renders.
- Accounts read from their own small pool, so a session read never queues
  behind long research queries for one of the five shared connections, and
  the server cancels any account query after 5 s instead of letting it hold
  its connection forever.


Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-30 10:00:49 +01:00

30 lines
1.0 KiB
TypeScript

import { Pool } from 'pg';
const globalDb = globalThis as typeof globalThis & { substrataPool?: Pool; accountsPool?: Pool };
/**
* Accounts get their own small pool, so a page's session read never queues
* behind long research queries for one of the five shared connections, and a
* query that stops answering is cancelled by the server instead of holding its
* connection forever.
*/
export function accountsDatabase() {
if (!process.env.DATABASE_URL) throw new Error('Substrata database not configured');
return (globalDb.accountsPool ??= new Pool({
connectionString: process.env.DATABASE_URL,
max: 3,
connectionTimeoutMillis: 3000,
idleTimeoutMillis: 30000,
statement_timeout: 5000,
query_timeout: 6000,
}));
}
export function database() {
if (!process.env.DATABASE_URL) throw new Error('Substrata database not configured');
return (globalDb.substrataPool ??= new Pool({
connectionString: process.env.DATABASE_URL,
max: 5,
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 30000,
}));
}