import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { Hono } from 'hono' import { afterEach, describe, expect, it, vi } from 'vitest' import { QueueConsumer, QueueMessage } from '../cloudflare_workers/api/index.ts' import { createQueueMessage, MESSAGE_BACKGROUND_TIMEOUT_MS, MESSAGE_RESET_REASON, messageDurableObjectDispatcher } from '../cloudflare_workers/api/queue_do.ts' import { cloudlogErr } from '../supabase/functions/_backend/utils/logging.ts' import { backgroundTask } from '../supabase/functions/_backend/utils/utils.ts' import { parseJsonc } from '../scripts/generate-plugin-route-hosts.ts' // Run backgroundTask as on Cloudflare: work goes to executionCtx.waitUntil. vi.mock('hono/adapter', async importOriginal => ({ ...(await importOriginal()), getRuntimeKey: () => 'workerd', })) vi.mock('../supabase/functions/_backend/utils/logging.ts', async importOriginal => ({ ...(await importOriginal()), cloudlogErr: vi.fn(), })) const API_CONFIG = fileURLToPath(new URL('../cloudflare_workers/api/wrangler.jsonc', import.meta.url)) afterEach(() => { vi.useRealTimers() vi.mocked(cloudlogErr).mockClear() }) function fakeState() { return { abort: vi.fn((reason?: string) => { throw new Error(reason) }) } } function runRequest(run: Record) { return new Request('https://queue-message.capgo.internal/run', { method: 'POST', body: JSON.stringify(run) }) } function messageObject(app: Hono, env: Record = {}) { const Message = createQueueMessage(app as never) const state = fakeState() return { message: new Message(state as never, env as never), state } } describe('QueueMessage', () => { it('runs the trigger in-process and answers once its background work is done', async () => { let backgroundDone = false const app = new Hono() app.post('/triggers/sample', async (c) => { await backgroundTask(c, new Promise(resolve => setTimeout(() => { backgroundDone = true resolve() }, 20))) return c.json({ msgId: c.req.header('x-capgo-queue-msg-id'), body: await c.req.json() }, 202) }) const { message } = messageObject(app) const response = await message.fetch(runRequest({ functionName: 'sample', body: { a: 1 }, headers: { 'x-capgo-queue-msg-id': '7' } })) expect(response.status).toBe(202) expect(await response.json()).toEqual({ msgId: '7', body: { a: 1 } }) expect(backgroundDone).toBe(true) }) it('stops waiting for background work after the Worker waitUntil cap', async () => { vi.useFakeTimers() const app = new Hono() app.post('/triggers/stuck', async (c) => { await backgroundTask(c, new Promise(() => {})) return c.json({ ok: true }) }) const { message } = messageObject(app) const pending = message.fetch(runRequest({ functionName: 'stuck', body: {}, headers: {} })) await vi.advanceTimersByTimeAsync(MESSAGE_BACKGROUND_TIMEOUT_MS) const response = await pending expect(response.status).toBe(200) expect(cloudlogErr).toHaveBeenCalledWith(expect.objectContaining({ message: 'queue_message_background_timeout', functionName: 'stuck' })) }) it('resets itself on /reset', async () => { const { message, state } = messageObject(new Hono()) await expect(message.fetch(new Request('https://queue-message.capgo.internal/reset', { method: 'POST' }))).rejects.toThrow(MESSAGE_RESET_REASON) expect(state.abort).toHaveBeenCalledWith(MESSAGE_RESET_REASON) }) it('refuses function names that are not a trigger name', async () => { const app = new Hono() const handler = vi.fn() app.all('*', handler) const { message } = messageObject(app) const response = await message.fetch(runRequest({ functionName: '../private/log_as', body: {}, headers: {} })) expect(response.status).toBe(400) expect(handler).not.toHaveBeenCalled() }) it('is wired to the API worker triggers', async () => { const message = new QueueMessage(fakeState() as never, {} as never) const response = await message.fetch(runRequest({ functionName: 'ok', body: {}, headers: { 'content-type': 'application/json' } })) expect(response.status).toBe(200) }) }) function fakeNamespace(fetchImpl: (url: string, init?: RequestInit) => Promise) { const names: string[] = [] const calls: string[] = [] const stubs = { count: 0 } const namespace = { idFromName: (name: string) => { names.push(name) return name }, get: () => (stubs.count++, { fetch: async (url: string, init?: RequestInit) => { calls.push(new URL(url).pathname) return fetchImpl(url, init) }, }), } return { namespace: namespace as never, names, calls, stubs } } const triggerRequest = { functionName: 'on_app_create', body: { record: { id: 1 } }, headers: { apisecret: 'secret' }, metadata: { queueName: 'on_app_create', msgId: 12, readCount: 3 }, timeoutMs: 15_000, } describe('messageDurableObjectDispatcher', () => { it('runs one message on its own object, then resets that object', async () => { let runBody: unknown const { namespace, names, calls, stubs } = fakeNamespace(async (url, init) => { if (url.endsWith('/reset')) throw new Error(MESSAGE_RESET_REASON) runBody = JSON.parse(String(init?.body)) return Response.json({ status: 'ok' }, { status: 202 }) }) const response = await messageDurableObjectDispatcher(namespace)(triggerRequest) expect(names).toEqual(['on_app_create:12:3']) expect(runBody).toEqual({ functionName: 'on_app_create', body: { record: { id: 1 } }, headers: { apisecret: 'secret' } }) expect(calls).toEqual(['/run', '/reset']) // The reset goes through a fresh stub: a stub whose call threw cannot be reused. expect(stubs.count).toBe(2) expect(response.status).toBe(202) expect(await response.json()).toEqual({ status: 'ok' }) expect(cloudlogErr).not.toHaveBeenCalled() }) it('logs a reset that failed for another reason', async () => { const { namespace } = fakeNamespace(async (url) => { if (url.endsWith('/reset')) throw new Error('object unreachable') return Response.json({ status: 'ok' }) }) const response = await messageDurableObjectDispatcher(namespace)(triggerRequest) expect(response.status).toBe(200) expect(cloudlogErr).toHaveBeenCalledWith(expect.objectContaining({ message: 'queue_message_reset_failed', key: 'on_app_create:12:3' })) }) it('fails the message after its timeout plus the background cap, and still resets the object', async () => { vi.useFakeTimers() const { namespace, calls } = fakeNamespace(async (url) => { if (url.endsWith('/reset')) throw new Error(MESSAGE_RESET_REASON) return new Promise(() => {}) }) const pending = messageDurableObjectDispatcher(namespace)(triggerRequest) const outcome = pending.catch((error: unknown) => error) await vi.advanceTimersByTimeAsync(triggerRequest.timeoutMs + MESSAGE_BACKGROUND_TIMEOUT_MS) const error = await outcome as { cause?: { error?: string } } expect(error.cause?.error).toBe('queue_message_do_failed') expect(calls).toEqual(['/run', '/reset']) }) }) describe('QueueConsumer', () => { it('needs the QUEUE_MESSAGE binding', async () => { const consumer = new QueueConsumer({} as never, { API_SECRET: 'secret' } as never) const response = await consumer.fetch(new Request('https://queue-consumer.capgo.internal/run', { method: 'POST', body: JSON.stringify({ queueName: 'on_app_create' }) })) expect(response.status).toBe(400) expect(await response.json()).toMatchObject({ error: 'queue_message_binding_missing' }) }) it('only serves POST /run', async () => { const consumer = new QueueConsumer({} as never, {} as never) const response = await consumer.fetch(new Request('https://queue-consumer.capgo.internal/other')) expect(response.status).toBe(404) }) }) interface ApiConfig { migrations: { tag: string, new_sqlite_classes?: string[] }[] env: Record }> } describe('queue Durable Object wrangler config', () => { const config = parseJsonc(readFileSync(API_CONFIG, 'utf8')) as ApiConfig it('adds both classes in their own migration', () => { expect(config.migrations.at(-1)).toEqual({ tag: 'queue-do-v1', new_sqlite_classes: ['QueueConsumer', 'QueueMessage'] }) }) it('binds them in every env that runs the queue dispatcher', () => { const envs = Object.entries(config.env).filter(([, env]) => env.durable_objects?.bindings.some(binding => binding.name === 'QUEUE_DISPATCHER')) expect(envs.map(([name]) => name).sort()).toEqual(['alpha', 'local', 'preprod', 'prod']) for (const [, env] of envs) { expect(env.durable_objects?.bindings).toContainEqual({ name: 'QUEUE_CONSUMER', class_name: 'QueueConsumer' }) expect(env.durable_objects?.bindings).toContainEqual({ name: 'QUEUE_MESSAGE', class_name: 'QueueMessage' }) } }) it('lets only prod and local route to them: alpha shares the prod database, so it claims prod wakeups', () => { const routing = Object.entries(config.env).filter(([, env]) => env.vars?.QUEUE_DO_ROUTING !== undefined) expect(routing.map(([name, env]) => [name, env.vars?.QUEUE_DO_ROUTING]).sort()).toEqual([['local', 'on'], ['prod', 'on']]) }) })