|
| 1 | +import { describe, expect, it, vi } from 'vitest' |
| 2 | +import { type ActivityCell, aggregateHour } from '@/lib/billing/activity-rollup/cells' |
| 3 | +import type { InstantRange } from '@/lib/billing/activity-rollup/source' |
| 4 | + |
| 5 | +const HOUR = 60 * 60 * 1000 |
| 6 | +const hour = new Date('2026-05-01T10:00:00.000Z') |
| 7 | + |
| 8 | +function cell(workflowId: string, runs: number, durationSumMs: number): ActivityCell { |
| 9 | + return { |
| 10 | + workspaceId: 'ws', |
| 11 | + workflowId, |
| 12 | + trigger: 'api', |
| 13 | + runs, |
| 14 | + completed: runs, |
| 15 | + failed: 0, |
| 16 | + cancelled: 0, |
| 17 | + inFlight: 0, |
| 18 | + durationSumMs, |
| 19 | + durationCount: runs, |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +function cancellation(message: string, code: string) { |
| 24 | + return Object.assign(new Error(message), { code }) |
| 25 | +} |
| 26 | + |
| 27 | +describe('aggregateHour', () => { |
| 28 | + it.each([ |
| 29 | + ['times out', cancellation('canceling statement due to statement timeout', '57014')], |
| 30 | + [ |
| 31 | + 'is cancelled by replica recovery', |
| 32 | + cancellation('canceling statement due to conflict with recovery', '40001'), |
| 33 | + ], |
| 34 | + ])( |
| 35 | + 'reads an hour whose whole read %s in quarter-hour slices summed by cell', |
| 36 | + async (_, error) => { |
| 37 | + const read = vi.fn(async (range: InstantRange) => { |
| 38 | + if (range.to.getTime() - range.from.getTime() === HOUR) throw error |
| 39 | + const quarter = (range.from.getTime() - hour.getTime()) / (HOUR / 4) |
| 40 | + return quarter === 2 ? [cell('a', 1, 10), cell('b', 2, 30)] : [cell('a', 1, 5)] |
| 41 | + }) |
| 42 | + |
| 43 | + const cells = await aggregateHour(hour, read) |
| 44 | + |
| 45 | + expect(read.mock.calls.map(([range]) => range.from.toISOString())).toEqual([ |
| 46 | + '2026-05-01T10:00:00.000Z', |
| 47 | + '2026-05-01T10:00:00.000Z', |
| 48 | + '2026-05-01T10:15:00.000Z', |
| 49 | + '2026-05-01T10:30:00.000Z', |
| 50 | + '2026-05-01T10:45:00.000Z', |
| 51 | + ]) |
| 52 | + expect(read.mock.calls.at(-1)?.[0].to.toISOString()).toBe('2026-05-01T11:00:00.000Z') |
| 53 | + expect(cells).toEqual([cell('a', 4, 25), cell('b', 2, 30)]) |
| 54 | + } |
| 55 | + ) |
| 56 | + |
| 57 | + it('fails without slicing when the read fails for any other reason', async () => { |
| 58 | + const read = vi.fn(async () => { |
| 59 | + throw cancellation('relation "workflow_execution_logs" does not exist', '42P01') |
| 60 | + }) |
| 61 | + |
| 62 | + await expect(aggregateHour(hour, read)).rejects.toThrow('does not exist') |
| 63 | + expect(read).toHaveBeenCalledTimes(1) |
| 64 | + }) |
| 65 | +}) |
0 commit comments