import type { PoolClient } from 'pg' import { randomUUID } from 'node:crypto' import { readFileSync } from 'node:fs' import { afterAll, describe, expect, it } from 'vitest' import { getPostgresClient } from './test-utils.ts' afterAll(async () => (await getPostgresClient()).end()) // Only the seeded user is reused (read only). Every test creates its own // organizations and apps inside a transaction it rolls back. const USER_ID = '6aa76066-55ef-4238-ade6-0b32334a4097' interface QueuedJob { date: string, apps: { app_id: string, owner_org: string }[], visibleNow: boolean } async function withTransaction(run: (client: PoolClient) => Promise) { const client = await (await getPostgresClient()).connect() try { await client.query('BEGIN') // Rolled back: the test sees only its own jobs. await client.query('DELETE FROM pgmq.q_cron_bandwidth_zone') await run(client) } finally { await client.query('ROLLBACK') client.release() } } async function createOrg(client: PoolClient) { const orgId = randomUUID() await client.query('INSERT INTO public.orgs (id, created_by, name, management_email) VALUES ($1, $2, $3, $4)', [orgId, USER_ID, `Zone bandwidth test ${orgId}`, 'test@capgo.app']) return orgId } async function createApp(client: PoolClient, orgId: string, appId: string) { await client.query(`INSERT INTO public.apps (owner_org, app_id, icon_url, name, user_id) VALUES ($1, $2, '', 'Zone bandwidth', $3)`, [orgId, appId, USER_ID]) } async function queuedJobs(client: PoolClient): Promise { const { rows } = await client.query<{ payload: { date: string, apps: QueuedJob['apps'] }, function_name: string, visible_now: boolean }>( `SELECT message->'payload' AS payload, message->>'function_name' AS function_name, vt <= pg_catalog.clock_timestamp() + interval '30 seconds' AS visible_now FROM pgmq.q_cron_bandwidth_zone ORDER BY msg_id`, ) for (const row of rows) expect(row.function_name).toBe('cron_bandwidth_zone') return rows.map(row => ({ date: row.payload.date, apps: row.payload.apps, visibleNow: row.visible_now })) } async function utcToday(client: PoolClient) { const { rows } = await client.query<{ today: string, hour: number }>(`SELECT (pg_catalog.timezone('UTC', now()))::date::text AS today, EXTRACT(HOUR FROM pg_catalog.timezone('UTC', now()))::int AS hour`) return rows[0]! } function addDays(date: string, days: number) { return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10) } describe('enqueue_zone_bandwidth_jobs', () => { it('queues one message per day and 40 apps, for the usage day and the next, 10 visible per minute', async () => { await withTransaction(async (client) => { const { today } = await utcToday(client) const day = addDays(today, -10) const orgId = await createOrg(client) const otherOrg = await createOrg(client) const prefix = `com.test.zonebw.${randomUUID().slice(0, 8)}` // 441 apps: 12 messages a day, so the 10-per-minute spreading shows. const appIds = Array.from({ length: 441 }, (_, index) => `${prefix}.app${String(index).padStart(3, '0')}`) const last = appIds.at(-1)! await client.query(`INSERT INTO public.apps (owner_org, app_id, icon_url, name, user_id) SELECT $1, pg_catalog.unnest($2::varchar[]), '', 'Zone bandwidth', $3`, [orgId, appIds, USER_ID]) await client.query(`INSERT INTO public.daily_mau (app_id, date, mau) SELECT pg_catalog.unnest($1::varchar[]), $2::date, 1`, [appIds.slice(0, -1), day]) // The last app only has bandwidth, and a former owner (deleted_apps). await client.query('INSERT INTO public.daily_bandwidth (app_id, date, bandwidth) VALUES ($1, $2, 5)', [last, day]) await client.query('INSERT INTO public.deleted_apps (app_id, owner_org) VALUES ($1, $2)', [last, otherOrg]) // The 40th app also has a former owner: its two pairs sit on the 40-app boundary. const boundary = appIds[39]! await client.query('INSERT INTO public.deleted_apps (app_id, owner_org) VALUES ($1, $2)', [boundary, otherOrg]) const { rows } = await client.query<{ sent: number }>('SELECT public.enqueue_zone_bandwidth_jobs($1::date, $2::date) AS sent', [day, addDays(day, 2)]) const jobs = await queuedJobs(client) expect(rows[0]!.sent).toBe(jobs.length) for (const date of [day, addDays(day, 1)]) { const ofDay = jobs.filter(job => job.date === date) const apps = ofDay.flatMap(job => job.apps) const distinctApps = (job: typeof ofDay[number]) => new Set(job.apps.map(app => app.app_id)).size // Chunks hold 40 apps (not pairs); every message but the last of a day is full. expect(ofDay.length).toBe(Math.ceil(new Set(apps.map(app => app.app_id)).size / 40)) expect(ofDay.slice(0, -1).every(job => distinctApps(job) === 40)).toBe(true) expect(ofDay.every(job => distinctApps(job) <= 40)).toBe(true) // All owner pairs of an app are in one message: its job sums them before overwriting the day. for (const appId of [boundary, last]) expect(ofDay.filter(job => job.apps.some(app => app.app_id === appId))).toHaveLength(1) // Every pair of ours once: the live apps plus the former owners of two of them. const ours = apps.filter(app => app.app_id.startsWith(prefix)) expect(ours).toHaveLength(appIds.length + 2) expect(new Set(ours.map(app => `${app.owner_org}/${app.app_id}`)).size).toBe(appIds.length + 2) expect(ours.filter(app => app.app_id === last).map(app => app.owner_org).sort()).toEqual([orgId, otherOrg].sort()) expect(ours.filter(app => app.app_id === boundary).map(app => app.owner_org).sort()).toEqual([orgId, otherOrg].sort()) } // Only the usage day and the day after are candidates. expect(jobs.some(job => job.date !== day && job.date !== addDays(day, 1) && job.apps.some(app => app.app_id.startsWith(prefix)))).toBe(false) // 10 messages become visible per minute. expect(jobs.length).toBeGreaterThan(20) expect(jobs.filter(job => job.visibleNow)).toHaveLength(10) }) }) it('queues the former owners of a transferred app with its current owner, in one message', async () => { await withTransaction(async (client) => { const { today } = await utcToday(client) const day = addDays(today, -5) const orgId = await createOrg(client) const formerOrg = await createOrg(client) const appId = `com.test.zonebw.transfer.${randomUUID().slice(0, 8)}` const history = [{ transferred_from: formerOrg, transferred_to: orgId, transferred_at: new Date().toISOString(), initiated_by: USER_ID }, { transferred_from: 'not-a-uuid' }] await client.query(`INSERT INTO public.apps (owner_org, app_id, icon_url, name, user_id, transfer_history) VALUES ($1, $2, '', 'Zone bandwidth', $3, $4::jsonb[])`, [orgId, appId, USER_ID, history.map(entry => JSON.stringify(entry))]) await client.query('INSERT INTO public.daily_mau (app_id, date, mau) VALUES ($1, $2, 1)', [appId, day]) await client.query('SELECT public.enqueue_zone_bandwidth_jobs($1::date, $2::date)', [day, addDays(day, 1)]) const withApp = (await queuedJobs(client)).filter(job => job.date === day && job.apps.some(app => app.app_id === appId)) expect(withApp).toHaveLength(1) expect(withApp[0]!.apps.filter(app => app.app_id === appId).map(app => app.owner_org).sort()).toEqual([orgId, formerOrg].sort()) }) }) it('queues the former owners of a deleted app from deleted_apps.transfer_history', async () => { await withTransaction(async (client) => { const { today } = await utcToday(client) const day = addDays(today, -5) const lastOrg = await createOrg(client) const formerOrg = await createOrg(client) const appId = `com.test.zonebw.deleted.${randomUUID().slice(0, 8)}` const history = [JSON.stringify({ transferred_from: formerOrg, transferred_to: lastOrg })] await client.query('INSERT INTO public.deleted_apps (app_id, owner_org, transfer_history) VALUES ($1, $2, $3::jsonb[])', [appId, lastOrg, history]) await client.query('INSERT INTO public.daily_bandwidth (app_id, date, bandwidth) VALUES ($1, $2, 5)', [appId, day]) await client.query('SELECT public.enqueue_zone_bandwidth_jobs($1::date, $2::date)', [day, addDays(day, 1)]) const withApp = (await queuedJobs(client)).filter(job => job.date === day && job.apps.some(app => app.app_id === appId)) expect(withApp).toHaveLength(1) expect(withApp[0]!.apps.filter(app => app.app_id === appId).map(app => app.owner_org).sort()).toEqual([lastOrg, formerOrg].sort()) }) }) it('backfills only the last 90 days and nothing past today', async () => { await withTransaction(async (client) => { const { today } = await utcToday(client) const orgId = await createOrg(client) const appId = `com.test.zonebw.${randomUUID().slice(0, 8)}` await createApp(client, orgId, appId) await client.query(`INSERT INTO public.daily_mau (app_id, date, mau) VALUES ($1, $2, 1), ($1, $3, 1), ($1, $4, 1)`, [appId, addDays(today, -120), addDays(today, -90), today]) await client.query('SELECT public.enqueue_zone_bandwidth_jobs($1::date, $2::date)', [addDays(today, -200), addDays(today, 30)]) const dates = (await queuedJobs(client)).filter(job => job.apps.some(app => app.app_id === appId)).map(job => job.date).sort() expect(dates).toEqual([addDays(today, -90), addDays(today, -89), today]) const { rows } = await client.query<{ sent: number }>('SELECT public.enqueue_zone_bandwidth_jobs($1::date, $1::date) AS sent', [today]) expect(rows[0]!.sent).toBe(0) await expect(client.query('SELECT public.enqueue_zone_bandwidth_jobs($1::date)', [today])).rejects.toThrow(/both p_from and p_to/) }) }) it('hourly: queues today, yesterday too during hours 0-2 UTC, and skips days still queued', async () => { await withTransaction(async (client) => { const { today, hour } = await utcToday(client) const orgId = await createOrg(client) const appId = `com.test.zonebw.${randomUUID().slice(0, 8)}` await createApp(client, orgId, appId) await client.query(`INSERT INTO public.daily_mau (app_id, date, mau) VALUES ($1, $2, 1), ($1, $3, 1)`, [appId, addDays(today, -1), today]) await client.query('SELECT public.enqueue_zone_bandwidth_jobs()') const dates = [...new Set((await queuedJobs(client)).map(job => job.date))].sort() expect(dates).toEqual(hour < 3 ? [addDays(today, -1), today] : [today]) const { rows } = await client.query<{ sent: number }>('SELECT public.enqueue_zone_bandwidth_jobs() AS sent') expect(rows[0]!.sent).toBe(0) }) }) it('is callable by service_role only', async () => { const client = await (await getPostgresClient()).connect() try { const { rows } = await client.query<{ anon: boolean, authenticated: boolean, service_role: boolean }>(`SELECT has_function_privilege('anon', 'public.enqueue_zone_bandwidth_jobs(date, date)', 'EXECUTE') AS anon, has_function_privilege('authenticated', 'public.enqueue_zone_bandwidth_jobs(date, date)', 'EXECUTE') AS authenticated, has_function_privilege('service_role', 'public.enqueue_zone_bandwidth_jobs(date, date)', 'EXECUTE') AS service_role`) expect(rows[0]).toEqual({ anon: false, authenticated: false, service_role: true }) } finally { client.release() } }) it('registers the hourly producer and the queue processor', async () => { const client = await (await getPostgresClient()).connect() try { const { rows } = await client.query<{ name: string, task_type: string, target: string, hour_interval: number | null, run_at_minute: number | null, minute_interval: number | null, batch_size: number | null }>( `SELECT name, task_type::text, target, hour_interval, run_at_minute, minute_interval, batch_size FROM public.cron_tasks WHERE name IN ('zone_bandwidth', 'zone_bandwidth_queue') ORDER BY name`, ) expect(rows).toEqual([ { name: 'zone_bandwidth', task_type: 'function', target: 'public.enqueue_zone_bandwidth_jobs()', hour_interval: 1, run_at_minute: 7, minute_interval: null, batch_size: null }, { name: 'zone_bandwidth_queue', task_type: 'function', target: 'public.wake_cron_bandwidth_zone_queue()', hour_interval: null, run_at_minute: null, minute_interval: 1, batch_size: 2 }, ]) } finally { client.release() } }) const jobMessage = { function_name: 'cron_bandwidth_zone', function_type: 'cloudflare', payload: { date: '2026-11-28', apps: [{ app_id: 'com.a.app', owner_org: '046a36ac-e03c-4590-9257-bd6c9dba9ee8' }] }, } it('wake_cron_bandwidth_zone_queue dispatches once with batch_size from cron_tasks', async () => { await withTransaction(async (client) => { await client.query( `SELECT pgmq.send_batch('cron_bandwidth_zone', ARRAY(SELECT $1::jsonb FROM generate_series(1, 12)), 0)`, [JSON.stringify(jobMessage)], ) await client.query(`DELETE FROM public.http_dispatch_outbox`) await client.query(`INSERT INTO public.http_dispatch_targets (target) VALUES ('cron_bandwidth_zone') ON CONFLICT DO NOTHING`) await client.query(`SELECT public.wake_cron_bandwidth_zone_queue()`) const { rows } = await client.query<{ calls: number, body: { batch_size: number, queue_name: string } }>( `SELECT calls, body FROM public.http_dispatch_outbox WHERE target = 'cron_bandwidth_zone'`, ) expect(rows).toHaveLength(1) expect(rows[0]!.calls).toBe(1) expect(rows[0]!.body.queue_name).toBe('cron_bandwidth_zone') expect(rows[0]!.body.batch_size).toBe(2) }) }) it('delays budget-depleted retries at least 300 seconds', async () => { await withTransaction(async (client) => { const { rows } = await client.query<{ msg_id: string }>( `SELECT pgmq.send('cron_bandwidth_zone', $1::jsonb, 0)::text AS msg_id`, [JSON.stringify(jobMessage)], ) const msgId = Number(rows[0]!.msg_id) await client.query(`SELECT public.delay_cron_bandwidth_zone_queue_messages($1::bigint[], 300)`, [[msgId]]) const { rows: vtRows } = await client.query<{ delay_seconds: number }>( `SELECT EXTRACT(EPOCH FROM (vt - pg_catalog.clock_timestamp()))::int AS delay_seconds FROM pgmq.q_cron_bandwidth_zone WHERE msg_id = $1`, [msgId], ) expect(vtRows[0]!.delay_seconds).toBeGreaterThanOrEqual(299) }) }) }) describe('unlimited bandwidth migration: stale is_good_plan', () => { // The exact statement of the migration, so the test cannot drift from it. const refreshStatement = /UPDATE public\.org_stats_refresh_state AS state[\s\S]*?;/.exec( readFileSync(new URL('../supabase/migrations/20261201120300_unlimited_bandwidth.sql', import.meta.url), 'utf8'), )![0] async function createPayingOrg(client: PoolClient, isGoodPlan: boolean, isAbovePlan = false) { const orgId = randomUUID() const customerId = `cus_zonebw_${orgId.slice(0, 8)}` await client.query( `INSERT INTO public.stripe_info (customer_id, status, product_id, is_good_plan, is_above_plan) SELECT $1, 'succeeded', stripe_id, $2, $3 FROM public.plans ORDER BY price_m LIMIT 1`, [customerId, isGoodPlan, isAbovePlan], ) await client.query('INSERT INTO public.orgs (id, created_by, name, management_email, customer_id) VALUES ($1, $2, $3, $4, $5)', [orgId, USER_ID, `Zone bandwidth plan ${orgId}`, 'test@capgo.app', customerId]) // Plan state already calculated and nothing requested: idle until the migration asks. await client.query( `INSERT INTO public.org_stats_refresh_state (org_id, stats_updated_at, stats_refresh_requested_at) VALUES ($1, pg_catalog.timezone('UTC', now()) - interval '1 hour', NULL) ON CONFLICT (org_id) DO UPDATE SET stats_updated_at = EXCLUDED.stats_updated_at, stats_refresh_requested_at = NULL`, [orgId], ) return orgId } it('requests a stats refresh for orgs with is_good_plan false or is_above_plan true only, and the scheduler queues them', async () => { await withTransaction(async (client) => { const staleOrg = await createPayingOrg(client, false) // Good plan, but still marked above plan (a bandwidth overage covered by credits). const aboveOrg = await createPayingOrg(client, true, true) const goodOrg = await createPayingOrg(client, true) const orgs = [staleOrg, aboveOrg, goodOrg] await client.query(refreshStatement) const { rows } = await client.query<{ org_id: string, requested: boolean }>( 'SELECT org_id::text, stats_refresh_requested_at IS NOT NULL AS requested FROM public.org_stats_refresh_state WHERE org_id = ANY($1::uuid[])', [orgs], ) expect(Object.fromEntries(rows.map(row => [row.org_id, row.requested]))).toEqual({ [staleOrg]: true, [aboveOrg]: true, [goodOrg]: false }) // The org stats scheduler picks the requested orgs up (cron_stat_org then recomputes the plan state). for (const orgId of orgs) await client.query('SELECT public.process_cron_stat_org_jobs(500, $1::uuid)', [orgId]) const queued = await client.query<{ org_id: string }>( `SELECT message->'payload'->>'orgId' AS org_id FROM pgmq.q_cron_stat_org WHERE message->'payload'->>'orgId' = ANY($1::text[])`, [orgs], ) expect(queued.rows.map(row => row.org_id).sort()).toEqual([staleOrg, aboveOrg].sort()) }) }) }) describe('daily_bandwidth_adjustment removal', () => { it('drops the table; dashboards read daily_bandwidth again', async () => { await withTransaction(async (client) => { const { rows: [table] } = await client.query<{ exists: boolean }>(`SELECT to_regclass('public.daily_bandwidth_adjustment') IS NOT NULL AS exists`) expect(table!.exists).toBe(false) const orgId = await createOrg(client) const appId = `com.test.zonebw.${randomUUID().slice(0, 8)}` await createApp(client, orgId, appId) await client.query(`INSERT INTO public.daily_bandwidth (app_id, date, bandwidth) VALUES ($1, '2001-01-01', 1234)`, [appId]) const { rows } = await client.query<{ response: { app_id: string, bandwidth: number }[] }>(`SELECT (public.seed_get_app_metrics_caches($1::uuid, '2001-01-01', '2001-01-01')).response AS response`, [orgId]) expect(rows[0]!.response.find(row => row.app_id === appId)?.bandwidth).toBe(1234) // The purge no longer references the dropped table. await client.query(`INSERT INTO public.deleted_apps (app_id, owner_org, deleted_at) VALUES ($1, $2, now() - interval '40 days')`, [`${appId}.gone`, orgId]) await client.query(`INSERT INTO public.daily_bandwidth (app_id, date, bandwidth) VALUES ($1, '2001-01-01', 1)`, [`${appId}.gone`]) await client.query('SELECT public.delete_old_deleted_apps()') const { rows: left } = await client.query('SELECT 1 FROM public.daily_bandwidth WHERE app_id = $1', [`${appId}.gone`]) expect(left).toHaveLength(0) }) }) })