import { Hono } from 'hono' import { describe, expect, it, vi } from 'vitest' import { DoRequestScope, getDoRequestScope } from '../supabase/functions/_backend/utils/do_request_scope.ts' vi.mock('../supabase/functions/_backend/utils/logging.ts', async importOriginal => ({ ...(await importOriginal()), cloudlogErr: vi.fn(), })) function deferred() { let resolve!: () => void const promise = new Promise((r) => { resolve = r }) return { promise, resolve } } describe('DoRequestScope', () => { it('drains tasks added while draining, then runs cleanups', async () => { const scope = new DoRequestScope() const order: string[] = [] const first = deferred() const nested = deferred() scope.onEnd(() => { order.push('cleanup') }) scope.waitUntil(first.promise.then(() => { order.push('first') // Like closeClient → backgroundTask: a task that starts another task. scope.waitUntil(nested.promise.then(() => order.push('nested'))) })) const settled = scope.settle() await Promise.resolve() expect(order).toEqual([]) first.resolve() await new Promise(resolve => setTimeout(resolve, 0)) // The first batch is done; the nested task still holds settle() open. expect(order).toEqual(['first']) nested.resolve() await settled expect(order).toEqual(['first', 'nested', 'cleanup']) }) it('logs failed tasks and cleanups without throwing, and still runs every cleanup', async () => { const { cloudlogErr } = await import('../supabase/functions/_backend/utils/logging.ts') vi.mocked(cloudlogErr).mockClear() const scope = new DoRequestScope() const cleanup = vi.fn() scope.waitUntil(Promise.reject(new Error('task failed'))) scope.onEnd(() => { throw new Error('cleanup failed') }) scope.onEnd(() => Promise.reject(new Error('async cleanup failed'))) scope.onEnd(cleanup) await expect(scope.settle()).resolves.toBeUndefined() expect(cleanup).toHaveBeenCalledTimes(1) expect(vi.mocked(cloudlogErr).mock.calls.map(([log]) => log.message)).toEqual([ 'DoRequestScope background task failed', 'DoRequestScope cleanup failed', 'DoRequestScope cleanup failed', ]) }) it('handles a task that fails before settle or while draining, with no unhandled rejection', async () => { const { cloudlogErr } = await import('../supabase/functions/_backend/utils/logging.ts') vi.mocked(cloudlogErr).mockClear() const unhandled = vi.fn() process.on('unhandledRejection', unhandled) const nextTurn = () => new Promise(resolve => setTimeout(resolve, 0)) try { const scope = new DoRequestScope() scope.waitUntil(Promise.reject(new Error('failed early'))) await nextTurn() scope.waitUntil(nextTurn().then(() => { scope.waitUntil(Promise.reject(new Error('failed while draining'))) return nextTurn() })) await scope.settle() await nextTurn() expect(unhandled).not.toHaveBeenCalled() expect(vi.mocked(cloudlogErr)).toHaveBeenCalledTimes(2) } finally { process.off('unhandledRejection', unhandled) } }) it('runs each cleanup once even when settle is called twice', async () => { const scope = new DoRequestScope() const cleanup = vi.fn() scope.onEnd(cleanup) await scope.settle() await scope.settle() expect(cleanup).toHaveBeenCalledTimes(1) }) it('is the execution context Hono hands to handlers through app.fetch', async () => { const scope = new DoRequestScope() const app = new Hono() let seen: DoRequestScope | undefined app.get('/', (c) => { seen = getDoRequestScope(c) c.executionCtx.waitUntil(Promise.resolve()) return c.text('ok') }) const response = await app.fetch(new Request('https://do.capgo.internal/'), {}, scope) await scope.settle() expect(response.status).toBe(200) expect(seen).toBe(scope) }) it('returns undefined for a normal Worker execution context or none at all', async () => { const app = new Hono() const seen: unknown[] = [] app.get('/', (c) => { seen.push(getDoRequestScope(c)) return c.text('ok') }) const workerCtx = { waitUntil: vi.fn(), passThroughOnException: vi.fn(), props: {} } await app.fetch(new Request('https://api.capgo.app/'), {}, workerCtx) await app.fetch(new Request('https://api.capgo.app/'), {}) expect(seen).toEqual([undefined, undefined]) }) })