import { Hono } from 'hono' import { afterAll, describe, expect, it, vi } from 'vitest' import { DoRequestScope } from '../supabase/functions/_backend/utils/do_request_scope.ts' import { closeClient, getPgClient } from '../supabase/functions/_backend/utils/pg.ts' import { backgroundTask } from '../supabase/functions/_backend/utils/utils.ts' import { getPostgresClient, POSTGRES_URL } from './test-utils.ts' // Run pg.ts and backgroundTask as they run on Cloudflare: Hyperdrive Clients, waitUntil. vi.mock('hono/adapter', async importOriginal => ({ ...(await importOriginal()), getRuntimeKey: () => 'workerd', })) afterAll(async () => (await getPostgresClient()).end()) async function openBackends(pids: number[]): Promise { const admin = await getPostgresClient() const { rows } = await admin.query<{ pid: number }>('SELECT pid FROM pg_catalog.pg_stat_activity WHERE pid = ANY($1::int[])', [pids]) return rows.map(row => row.pid) } async function backendPid(c: Parameters[0]): Promise<{ pid: number, close: () => void }> { const db = await getPgClient(c) const { rows } = await db.query<{ pid: number }>('SELECT pg_backend_pid() AS pid') return { pid: rows[0].pid, close: () => closeClient(c, db) } } describe('DoRequestScope with pg.ts on a Hyperdrive binding', () => { it('closes every connection the request opened once settle() has drained its background work', async () => { const pids: number[] = [] let backgroundPid: number | undefined const app = new Hono() app.post('/run', async (c) => { // Two holders at once, so two connections. const first = await backendPid(c) const second = await backendPid(c) pids.push(first.pid, second.pid) first.close() second.close() // Work after the response, like a trigger's backgroundTask: it reuses an idle Client. await backgroundTask(c, (async () => { await new Promise(resolve => setTimeout(resolve, 50)) const late = await backendPid(c) backgroundPid = late.pid late.close() })()) return c.json({ ok: true }) }) const scope = new DoRequestScope() const env = { HYPERDRIVE_CAPGO_DIRECT_EU: { connectionString: POSTGRES_URL } } const response = await app.fetch(new Request('https://do.capgo.internal/run', { method: 'POST' }), env, scope) expect(response.status).toBe(200) expect(new Set(pids).size).toBe(2) expect(backgroundPid).toBeUndefined() expect(await openBackends(pids)).toHaveLength(2) await scope.settle() expect(pids).toContain(backgroundPid) await vi.waitFor(async () => expect(await openBackends(pids)).toEqual([]), { timeout: 5000 }) }) })