import { readFileSync } from 'node:fs' import { describe, expect, it, vi } from 'vitest' import pluginWorker from '../cloudflare_workers/plugin/index.ts' import { parseJsonc, WRANGLER_PATH } from '../scripts/generate-plugin-route-hosts.ts' import { consumerAddArgs, FIELD_NAMES, logpushJobBody, logpushJobNeedsUpdate, READ_PATH_PREFIXES, wranglerSetupSteps } from '../scripts/setup-files-bandwidth-logpush.ts' import { aggregateFilesBandwidth as aggregateAtCutover, buildFilesBandwidthMessages as buildAtCutover, chunkFilesBandwidth, deviceIdOfRequestUri, edgeStartMs, emptyFilesBandwidthReadStats, enqueueFilesBandwidthFile, FILES_BANDWIDTH_DONE_PREFIX, FILES_BANDWIDTH_FILES_QUEUE, FILES_BANDWIDTH_READ_PREFIXES, FILES_BANDWIDTH_REPLAY_QUEUE, handleFilesBandwidthMessage, edgeStartToken, logRowRequestKey, MAX_ENTRIES_PER_CHUNK, parseFilesBandwidthLine as parseAtCutover, replayFilesBandwidthChunk, } from '../supabase/functions/_backend/plugin_runtime/utils/filesBandwidthReplay.ts' const ORG = '046a36ac-e03c-4590-9257-bd6c9dba9ee8' const DEVICE = '6f0a1b2c-3d4e-4f50-8a6b-7c8d9e0f1a2b' /** 2025-11-26T00:00:00Z, the EdgeStartTimestamp of logLine. */ const EVENT_HOUR = 1764115200 /** A cutover before every test line: the replay counts them all. */ const ALL = { cutoverMs: 1 } const CUTOVER_ENV = { FILES_BANDWIDTH_LOGPUSH_FROM: '1' } function parseFilesBandwidthLine(line: string, stats?: Parameters[1]) { return parseAtCutover(line, stats, ALL) } function aggregateFilesBandwidth(lines: string[], stats?: Parameters[1]) { return aggregateAtCutover(lines, stats, ALL) } function buildFilesBandwidthMessages(file: string, lines: string[]) { return buildAtCutover(file, lines, undefined, ALL) } function logLine(overrides: Record = {}) { const path = overrides.ClientRequestPath ?? `/files/read/attachments/orgs/${ORG}/apps/com.demo.app/delta/abc_main.js` return JSON.stringify({ ClientRequestHost: 'plugin.eu.capgo.app', ClientRequestPath: path, ClientRequestURI: `${path}?key=sum&device_id=${DEVICE}`, EdgeResponseStatus: 200, EdgeResponseBodyBytes: 1000, EdgeStartTimestamp: 1764115200000000000, RayID: 'ray-1', CacheCacheStatus: 'dynamic', WorkerSubrequest: false, ...overrides, }) } /** In-memory R2 bucket with create-only puts (If-None-Match: *). */ function memoryBucket(initial: Record = {}) { const objects = new Map(Object.entries(initial)) const body = (text: string) => ({ body: new Response(text).body, text: async () => text }) return { objects, get: vi.fn(async (key: string) => (objects.has(key) ? body(objects.get(key)!) : null)), head: vi.fn(async (key: string) => (objects.has(key) ? { key } : null)), put: vi.fn(async (key: string, value: string, options?: { onlyIf?: Headers }) => { if (options?.onlyIf instanceof Headers && options.onlyIf.get('if-none-match') === '*' && objects.has(key)) return null objects.set(key, value) return { key } }), delete: vi.fn(async (key: string) => { objects.delete(key) }), } } function memoryQueue() { const sent: unknown[] = [] return { sent, sendBatch: vi.fn(async (messages: { body: unknown }[]) => { sent.push(...messages.map(message => message.body)) }), send: vi.fn(async (body: unknown) => { sent.push(body) }), } } function dataset() { return { writeDataPoint: vi.fn() } } describe('files bandwidth Logpush line parser', () => { it('reads app_id from the path and device_id from the query', () => { expect(parseFilesBandwidthLine(logLine())).toEqual({ appId: 'com.demo.app', deviceId: DEVICE, bytes: 1000, rayId: 'ray-1', requestKey: `ray-1|1764115200000000000|plugin.eu.capgo.app|/files/read/attachments/orgs/${ORG}/apps/com.demo.app/delta/abc_main.js`, eventMs: EVENT_HOUR * 1000 }) expect(parseFilesBandwidthLine(logLine({ ClientRequestPath: `/private/files/read/attachments/orgs/${ORG}/apps/com.demo.app/1.0.0.zip`, EdgeResponseStatus: 206 }))) .toMatchObject({ appId: 'com.demo.app', bytes: 1000 }) // Percent-encoded app id segment, as the files handler decodes it. expect(parseFilesBandwidthLine(logLine({ ClientRequestPath: `/files/read/attachments/orgs/${ORG}/apps/com%2Edemo%2Eapp/x.zip` }))) .toMatchObject({ appId: 'com.demo.app' }) }) it('ignores what is not a billed eyeball download', () => { const stats = emptyFilesBandwidthReadStats() const ignored = [ logLine({ EdgeResponseStatus: 304 }), logLine({ EdgeResponseStatus: 404 }), logLine({ EdgeResponseBodyBytes: 0 }), logLine({ WorkerSubrequest: true }), logLine({ ClientRequestHost: 'plugin.preprod.capgo.app' }), logLine({ ClientRequestHost: 'api.dev.capgo.app' }), logLine({ ClientRequestPath: '/updates' }), logLine({ ClientRequestPath: `/files/read/attachments/orgs/${ORG}/apps/../x` }), logLine({ ClientRequestPath: '/files/read/attachments/legacy/file.zip' }), ] for (const line of ignored) expect(parseFilesBandwidthLine(line, stats)).toBeNull() expect(stats.ignored).toBe(ignored.length) expect(parseFilesBandwidthLine(logLine({ ClientRequestURI: '/files/read/attachments/x?key=1' }), stats)).toBeNull() expect(stats.noDevice).toBe(1) expect(parseFilesBandwidthLine('{not json', stats)).toBeNull() expect(parseFilesBandwidthLine(logLine({ RayID: undefined }), stats)).toBeNull() expect(stats.invalid).toBe(2) expect(parseFilesBandwidthLine('', stats)).toBeNull() }) it('takes device_id from the query only, bounded', () => { expect(deviceIdOfRequestUri('/a?device_id=d1&key=k')).toBe('d1') expect(deviceIdOfRequestUri('/a?key=k')).toBeNull() expect(deviceIdOfRequestUri('/a/device_id=d1')).toBeNull() expect(deviceIdOfRequestUri(`/a?device_id=${'x'.repeat(129)}`)).toBeNull() }) it('covers the paths of the files worker cache key', () => { const cacheKey = readFileSync('cloudflare_workers/files/cache_key.ts', 'utf8') for (const prefix of FILES_BANDWIDTH_READ_PREFIXES) expect(cacheKey).toContain(`'${prefix}'`) }) }) describe('files bandwidth aggregation', () => { it('keeps the exact EdgeStartTimestamp digits in the request identity (above 2^53)', async () => { // Two requests 1 ns apart: JSON.parse rounds both to the same number. const line = (ns: string) => logLine({ RayID: 'same' }).replace('"EdgeStartTimestamp":1764115200000000000', `"EdgeStartTimestamp":${ns}`) expect(JSON.parse(line('1764115200000000001')).EdgeStartTimestamp).toBe(JSON.parse(line('1764115200000000002')).EdgeStartTimestamp) expect(edgeStartToken(line('1764115200000000001'), 0)).toBe('1764115200000000001') const stats = emptyFilesBandwidthReadStats() await aggregateFilesBandwidth([line('1764115200000000001'), line('1764115200000000002'), line('1764115200000000002')], stats) expect(stats).toMatchObject({ counted: 2, duplicates: 1 }) // The case from the review: ...000 and ...001, same RayID, host and path, both kept. expect(JSON.parse(line('1764115200000000000')).EdgeStartTimestamp).toBe(JSON.parse(line('1764115200000000001')).EdgeStartTimestamp) const lowDigits = emptyFilesBandwidthReadStats() const aggregates = await aggregateFilesBandwidth([line('1764115200000000000'), line('1764115200000000001')], lowDigits) expect(lowDigits).toMatchObject({ counted: 2, duplicates: 0 }) expect(aggregates.reduce((total, aggregate) => total + aggregate.entry[2], 0)).toBe(2000) }) it('keeps distinct requests that share a RayID, drops a row delivered twice', async () => { const stats = emptyFilesBandwidthReadStats() const aggregates = await aggregateFilesBandwidth([ logLine({ RayID: 'same', EdgeResponseBodyBytes: 100 }), // Same RayID, another request: different edge start and path. logLine({ RayID: 'same', EdgeResponseBodyBytes: 200, EdgeStartTimestamp: (EVENT_HOUR + 1) * 1e9, ClientRequestPath: `/files/read/attachments/orgs/${ORG}/apps/com.demo.app/delta/other.js` }), // The first row again (Logpush delivered it twice). logLine({ RayID: 'same', EdgeResponseBodyBytes: 100 }), ], stats) expect(aggregates.reduce((total, aggregate) => total + aggregate.entry[2], 0)).toBe(300) expect(stats).toMatchObject({ counted: 2, duplicates: 1 }) expect(logRowRequestKey('r', 1, 'Plugin.Capgo.App', '/p')).toBe('r|1|plugin.capgo.app|/p') }) it('sums bytes per (app_id, device_id) and drops repeated RayIDs', async () => { const stats = emptyFilesBandwidthReadStats() const aggregates = await aggregateFilesBandwidth([ logLine({ RayID: 'r1', EdgeResponseBodyBytes: 100 }), logLine({ RayID: 'r2', EdgeResponseBodyBytes: 200 }), logLine({ RayID: 'r2', EdgeResponseBodyBytes: 200 }), logLine({ RayID: 'r3', EdgeResponseBodyBytes: 50, ClientRequestURI: '/f?device_id=other' }), logLine({ RayID: 'r4', EdgeResponseBodyBytes: 7, ClientRequestPath: `/files/read/attachments/orgs/${ORG}/apps/com.another.app/a.js` }), ], stats) expect(aggregates.map(aggregate => aggregate.entry)).toEqual([ ['com.another.app', DEVICE, 7, EVENT_HOUR], ['com.demo.app', DEVICE, 300, EVENT_HOUR], ['com.demo.app', 'other', 50, EVENT_HOUR], ]) expect(stats).toMatchObject({ lines: 5, counted: 4, duplicates: 1, bytes: 357 }) }) it('chunks under the Analytics Engine limit, deterministically', async () => { const lines = Array.from({ length: 450 }, (_, index) => logLine({ RayID: `r${index}`, ClientRequestURI: `/f?device_id=d${index}` })) const chunks = chunkFilesBandwidth(await aggregateFilesBandwidth(lines)) expect(chunks.map(chunk => chunk.length)).toEqual([MAX_ENTRIES_PER_CHUNK, MAX_ENTRIES_PER_CHUNK, 50]) const first = await buildFilesBandwidthMessages('a.log.gz', lines) const reversed = await buildFilesBandwidthMessages('b.log.gz', [...lines].reverse()) expect(reversed.map(message => message.filesBandwidth.claim)).toEqual(first.map(message => message.filesBandwidth.claim)) expect(new Set(first.map(message => message.filesBandwidth.claim)).size).toBe(3) }) }) describe('files bandwidth replay idempotency', () => { it('writes a chunk once, whatever the number of deliveries', async () => { const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: memoryBucket(), BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine({ RayID: 'r1' }), logLine({ RayID: 'r2', EdgeResponseBodyBytes: 24 })]) expect(await replayFilesBandwidthChunk(env as any, message!)).toEqual({ written: 1, rejected: 0, invalid: 0, lostEntries: [], duplicate: false }) expect(await replayFilesBandwidthChunk(env as any, message!)).toEqual({ written: 0, duplicate: true }) expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledOnce() expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledWith({ blobs: [DEVICE, 'logpush'], doubles: [1024, EVENT_HOUR], indexes: ['com.demo.app'] }) expect([...env.FILES_BANDWIDTH_LOGS.objects.keys()]).toEqual([`${FILES_BANDWIDTH_DONE_PREFIX}${message!.filesBandwidth.claim}`]) }) it('writes nothing when a concurrent delivery claimed the chunk first', async () => { const bucket = memoryBucket() const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) // Both deliveries find no claim; only one create-only put succeeds. bucket.get.mockResolvedValueOnce(null).mockResolvedValueOnce(null) await Promise.all([replayFilesBandwidthChunk(env as any, message!, { id: 'a', attempt: 1 }), replayFilesBandwidthChunk(env as any, message!, { id: 'b', attempt: 1 })]) expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledOnce() }) it('retries (throws) without writing when the claim cannot be stored', async () => { const bucket = memoryBucket() bucket.put.mockRejectedValueOnce(new Error('R2 down')) const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) await expect(replayFilesBandwidthChunk(env as any, message!)).rejects.toThrow('R2 down') expect(env.BANDWIDTH_USAGE.writeDataPoint).not.toHaveBeenCalled() expect(await replayFilesBandwidthChunk(env as any, message!)).toEqual({ written: 1, rejected: 0, invalid: 0, lostEntries: [], duplicate: false }) }) it('counts a log object once: repeated notification, retried file, and the same file pushed twice', async () => { const content = Array.from({ length: 300 }, (_, index) => logLine({ RayID: `r${index}`, ClientRequestURI: `/f?device_id=d${index}` })).join('\n') const bucket = memoryBucket({ '20261127/a.log': content, '20261127/a-again.log': content }) const queue = memoryQueue() const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: queue, BANDWIDTH_USAGE: dataset() } const notification = (key: string) => ({ action: 'PutObject', object: { key } }) await handleFilesBandwidthMessage(env as any, 'm1', notification('20261127/a.log')) await handleFilesBandwidthMessage(env as any, 'm2', notification('20261127/a.log')) await handleFilesBandwidthMessage(env as any, 'm3', notification('20261127/a-again.log')) expect(bucket.objects.has('20261127/a.log')).toBe(false) expect(queue.sent).toHaveLength(4) // Each chunk message delivered twice. for (const body of [...queue.sent, ...queue.sent]) await handleFilesBandwidthMessage(env as any, 'replay', body) expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledTimes(300) }) it('resumes a file from the first group it failed to send', async () => { const content = Array.from({ length: 20_500 }, (_, index) => logLine({ RayID: `r${index}`, ClientRequestURI: `/f?device_id=d${index}` })).join('\n') const bucket = memoryBucket({ 'big.log': content }) const queue = memoryQueue() queue.sendBatch.mockImplementationOnce(async (messages: { body: unknown }[]) => { queue.sent.push(...messages.map(message => message.body)) }).mockRejectedValueOnce(new Error('queue down')) const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: queue } const first = await enqueueFilesBandwidthFile(env as any, 'big.log') expect(first).toMatchObject({ chunks: 103, resumeFromGroup: 1 }) expect(bucket.objects.has('big.log')).toBe(true) const resume = queue.sent.at(-1) expect(resume).toEqual({ filesBandwidthFile: 'big.log', fromGroup: 1, attempt: 1 }) const firstGroup = queue.sent.length - 1 expect(firstGroup).toBeGreaterThan(0) expect(firstGroup).toBeLessThan(103) queue.sent.length = 0 await handleFilesBandwidthMessage(env as any, 'resume', resume) // The rest of the chunks, none of the first group again. expect(queue.sent).toHaveLength(103 - firstGroup) expect(bucket.objects.has('big.log')).toBe(false) expect([...bucket.objects.keys()]).toEqual([]) }) it('stops rescheduling after the resume budget and lets the queue retry it', async () => { const content = Array.from({ length: 20_500 }, (_, index) => logLine({ RayID: `r${index}`, ClientRequestURI: `/f?device_id=d${index}` })).join('\n') const bucket = memoryBucket({ 'big.log': content }) const queue = memoryQueue() queue.sendBatch.mockRejectedValue(new Error('queue down')) const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: queue } let message: unknown = { action: 'PutObject', object: { key: 'big.log' } } for (let attempt = 1; attempt < 5; attempt++) { await handleFilesBandwidthMessage(env as any, `m${attempt}`, message) message = queue.sent.at(-1) expect(message).toEqual({ filesBandwidthFile: 'big.log', fromGroup: 0, attempt }) } await expect(handleFilesBandwidthMessage(env as any, 'm5', message)).rejects.toThrow('queue down') expect(queue.send).toHaveBeenCalledTimes(4) }) it('validates Analytics Engine indexes before the claim and isolates rejected points', async () => { const longApp = `com.${'a'.repeat(100)}` expect(parseFilesBandwidthLine(logLine({ ClientRequestPath: `/files/read/attachments/orgs/${ORG}/apps/${longApp}/delta/abc_main.js` }))).toBeNull() const ds = dataset() ds.writeDataPoint.mockImplementationOnce(() => { throw new Error('rejected') }) const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: memoryBucket(), BANDWIDTH_USAGE: ds } const message = { filesBandwidth: { file: 'f', chunk: 0, claim: 'c1', entries: [[longApp, DEVICE, 10, EVENT_HOUR], ['com.a.app', DEVICE, 10, EVENT_HOUR], ['com.b.app', DEVICE, 20, EVENT_HOUR]] } } expect(await replayFilesBandwidthChunk(env as any, message as any)).toEqual({ written: 1, rejected: 1, invalid: 1, lostEntries: [[longApp, DEVICE, 10, EVENT_HOUR], ['com.a.app', DEVICE, 10, EVENT_HOUR]], duplicate: false }) expect(ds.writeDataPoint).toHaveBeenCalledTimes(2) }) it('logs the points it could not write, with the chunk identity, before the ack', async () => { const ds = dataset() ds.writeDataPoint.mockImplementationOnce(() => { throw new Error('rejected') }) const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: memoryBucket(), BANDWIDTH_USAGE: ds } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine({ RayID: 'r1' }), logLine({ RayID: 'r2', ClientRequestURI: '/f?device_id=other' })]) const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) const logs = vi.spyOn(console, 'log').mockImplementation(() => undefined) const messages = [{ id: 'm0', body: message, ack: vi.fn(), retry: vi.fn() }] await pluginWorker.queue({ queue: FILES_BANDWIDTH_REPLAY_QUEUE, messages } as any, env as any, {} as any) const logged = [...errors.mock.calls, ...logs.mock.calls].map(call => JSON.stringify(call)).join('\n') expect(logged).toContain('files bandwidth points not written') expect(logged).toContain(message!.filesBandwidth.claim) expect(messages[0]!.ack).toHaveBeenCalledOnce() expect(messages[0]!.retry).not.toHaveBeenCalled() errors.mockRestore() logs.mockRestore() }) /** A create-only put that commits, then loses its response. */ function lostPutResponse(bucket: ReturnType) { const realPut = bucket.put.getMockImplementation()! bucket.put.mockImplementationOnce(async (key: string, value: string, options?: { onlyIf?: Headers }) => { await realPut(key, value, options) throw new Error('connection reset') }) } it('loses the chunk, never doubles it, when the put response and the re-read both fail', async () => { const bucket = memoryBucket() lostPutResponse(bucket) bucket.get.mockRejectedValueOnce(new Error('R2 down')) const env = { FILES_BANDWIDTH_LOGS: bucket, BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) await expect(replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 1 })).rejects.toThrow('connection reset') // The retry finds the claim the lost put committed: at most once. expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 2 })).toEqual({ written: 0, duplicate: true }) expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 3 })).toEqual({ written: 0, duplicate: true }) expect(env.BANDWIDTH_USAGE.writeDataPoint).not.toHaveBeenCalled() }) it('writes nothing when a message is redelivered after its points were written', async () => { const env = { FILES_BANDWIDTH_LOGS: memoryBucket(), BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 1 })).toMatchObject({ written: 1, duplicate: false }) // Same message id, next attempt (the ack was lost): its own earlier claim is a duplicate too. expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 2 })).toEqual({ written: 0, duplicate: true }) expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledOnce() }) it('owns a claim whose put response was lost when the re-read shows its token, once', async () => { const bucket = memoryBucket() lostPutResponse(bucket) const env = { FILES_BANDWIDTH_LOGS: bucket, BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 1 })).toMatchObject({ written: 1, duplicate: false }) expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 2 })).toEqual({ written: 0, duplicate: true }) expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledOnce() }) it('treats a claim held by another delivery as a duplicate after a lost put response', async () => { const bucket = memoryBucket() const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) const claim = `${FILES_BANDWIDTH_DONE_PREFIX}${message!.filesBandwidth.claim}` // Another delivery creates the claim between our head and our put; our put response is lost. bucket.put.mockImplementationOnce(async () => { bucket.objects.set(claim, 'other|1|token') throw new Error('connection reset') }) const env = { FILES_BANDWIDTH_LOGS: bucket, BANDWIDTH_USAGE: dataset() } expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 1 })).toEqual({ written: 0, duplicate: true }) expect(env.BANDWIDTH_USAGE.writeDataPoint).not.toHaveBeenCalled() }) it('never writes for an existing claim of another message or attempt', async () => { const bucket = memoryBucket() const env = { FILES_BANDWIDTH_LOGS: bucket, BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) for (const value of ['other|1|token', 'm|1|token', 'pending|m|1', '']) { bucket.objects.set(`${FILES_BANDWIDTH_DONE_PREFIX}${message!.filesBandwidth.claim}`, value) expect(await replayFilesBandwidthChunk(env as any, message!, { id: 'm', attempt: 2 }), `claim ${JSON.stringify(value)}`).toEqual({ written: 0, duplicate: true }) } expect(env.BANDWIDTH_USAGE.writeDataPoint).not.toHaveBeenCalled() }) it('reads base64 TUS upload IDs like the files worker', () => { const tusId = btoa(`capgo/orgs/${ORG}/apps/com.demo.app/delta/abc_main.js/upload-id`) const path = `/files/read/attachments/${tusId}` expect(parseFilesBandwidthLine(logLine({ ClientRequestPath: path, ClientRequestURI: `${path}?device_id=${DEVICE}` }))).toMatchObject({ appId: 'com.demo.app', deviceId: DEVICE }) }) it('never reads its own claims and progress objects as logs', async () => { const bucket = memoryBucket({ [`${FILES_BANDWIDTH_DONE_PREFIX}abc`]: '' }) const env = { ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: memoryQueue() } expect(await enqueueFilesBandwidthFile(env as any, `${FILES_BANDWIDTH_DONE_PREFIX}abc`)).toEqual({ skipped: true }) expect(bucket.objects.has(`${FILES_BANDWIDTH_DONE_PREFIX}abc`)).toBe(true) }) }) describe('files bandwidth event time', () => { it('reads EdgeStartTimestamp in unixnano, as a number or a string', () => { expect(edgeStartMs(1764115200123e6)).toBe(1764115200123) expect(edgeStartMs('1764115200123456789')).toBe(1764115200123) expect(edgeStartMs(undefined)).toBeNull() expect(edgeStartMs('soon')).toBeNull() expect(parseFilesBandwidthLine(logLine({ EdgeStartTimestamp: undefined }))).toBeNull() }) it('sums per UTC minute, so a file spanning midnight keeps each day apart', async () => { const beforeMidnight = (EVENT_HOUR - 1) * 1e9 const afterMidnight = (EVENT_HOUR + 1) * 1e9 const aggregates = await aggregateFilesBandwidth([ logLine({ RayID: 'r1', EdgeStartTimestamp: beforeMidnight, EdgeResponseBodyBytes: 10 }), logLine({ RayID: 'r2', EdgeStartTimestamp: afterMidnight, EdgeResponseBodyBytes: 20 }), logLine({ RayID: 'r3', EdgeStartTimestamp: afterMidnight + 30e9, EdgeResponseBodyBytes: 30 }), ]) expect(aggregates.map(aggregate => aggregate.entry)).toEqual([ ['com.demo.app', DEVICE, 10, EVENT_HOUR - 60], ['com.demo.app', DEVICE, 50, EVENT_HOUR], ]) }) it('keeps reads after a mid-hour billing anchor in the new cycle', async () => { const anchor = EVENT_HOUR + 30 * 60 const messages = await buildFilesBandwidthMessages('f.log.gz', [ logLine({ RayID: 'before', EdgeStartTimestamp: (anchor - 61) * 1e9 }), logLine({ RayID: 'after', EdgeStartTimestamp: (anchor + 15 * 60) * 1e9 }), ]) const times = messages.flatMap(message => message.filesBandwidth.entries.map(entry => entry[3])) expect(times.sort()).toEqual([anchor - 120, anchor + 15 * 60]) }) it('writes the event minute, not the replay time, as double2', async () => { const env = { FILES_BANDWIDTH_LOGS: memoryBucket(), BANDWIDTH_USAGE: dataset() } const [message] = await buildFilesBandwidthMessages('f.log.gz', [logLine({ EdgeStartTimestamp: (EVENT_HOUR + 45) * 1e9 })]) await replayFilesBandwidthChunk(env as any, message!) expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledWith({ blobs: [DEVICE, 'logpush'], doubles: [1000, EVENT_HOUR], indexes: ['com.demo.app'] }) // An entry without an event hour (an old message shape) is never written. const legacy = { filesBandwidth: { ...message!.filesBandwidth, claim: 'a'.repeat(64), entries: [['com.demo.app', DEVICE, 1000]] } } expect(await replayFilesBandwidthChunk(env as any, legacy as any)).toMatchObject({ written: 0, invalid: 1 }) }) }) describe('files bandwidth cutover', () => { const cutoverMs = (EVENT_HOUR + 600) * 1000 it('counts only the lines at or after the cutover, and nothing without one', () => { const stats = emptyFilesBandwidthReadStats() expect(parseAtCutover(logLine({ EdgeStartTimestamp: (EVENT_HOUR + 599) * 1e9 }), stats, { cutoverMs })).toBeNull() expect(parseAtCutover(logLine({ EdgeStartTimestamp: (EVENT_HOUR + 600) * 1e9 }), stats, { cutoverMs })).toMatchObject({ bytes: 1000 }) expect(parseAtCutover(logLine(), stats, { cutoverMs: null })).toBeNull() expect(stats.beforeCutover).toBe(2) }) it('leaves the files alone without a cutover on the plugin worker', async () => { const bucket = memoryBucket({ 'a.log': logLine() }) const queue = memoryQueue() expect(await enqueueFilesBandwidthFile({ FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: queue } as any, 'a.log')).toEqual({ disabled: true }) expect(bucket.get).not.toHaveBeenCalled() expect(queue.sent).toHaveLength(0) }) it('puts every download in exactly one source', async () => { const { parseFilesBandwidthCutover, requestCountsFileBandwidth } = await import('../supabase/functions/_backend/plugin_runtime/utils/filesBandwidthCutover.ts') const instant = parseFilesBandwidthCutover(String(cutoverMs / 1000)) expect(instant).toBe(cutoverMs) expect(parseFilesBandwidthCutover(new Date(cutoverMs).toISOString())).toBe(cutoverMs) // The handler's clock is never before the request's edge start. for (const offsetMs of [-60_000, -1, 0, 1, 60_000]) { const edgeStartMs = cutoverMs + offsetMs for (const handlerLagMs of [0, 5]) { const byRequest = requestCountsFileBandwidth(instant, edgeStartMs + handlerLagMs) const byReplay = parseAtCutover(logLine({ EdgeStartTimestamp: edgeStartMs * 1e6 }), undefined, { cutoverMs: instant }) !== null expect(byRequest && byReplay).toBe(false) if (handlerLagMs === 0) expect(byRequest || byReplay).toBe(true) } } }) it('rolls back with UNTIL: never double counts at the end boundary', async () => { const { requestCountsFileBandwidth, FILES_BANDWIDTH_UNTIL_GRACE_MS } = await import('../supabase/functions/_backend/plugin_runtime/utils/filesBandwidthCutover.ts') const untilMs = cutoverMs + 3_600_000 for (const offsetMs of [-60_000, -1, 0, 1, 30_000, 60_000, 120_000]) { const edgeStartMs = untilMs + offsetMs for (const handlerLagMs of [0, 5, 30_000]) { const byRequest = requestCountsFileBandwidth(cutoverMs, edgeStartMs + handlerLagMs, untilMs) const byReplay = parseAtCutover(logLine({ EdgeStartTimestamp: edgeStartMs * 1e6 }), undefined, { cutoverMs, untilMs }) !== null expect(byRequest && byReplay).toBe(false) } } // Well after the grace, the handler counts again and the replay does not. const later = untilMs + FILES_BANDWIDTH_UNTIL_GRACE_MS + 1 expect(requestCountsFileBandwidth(cutoverMs, later, untilMs)).toBe(true) expect(parseAtCutover(logLine({ EdgeStartTimestamp: later * 1e6 }), undefined, { cutoverMs, untilMs })).toBeNull() }) it('still counts a late-delivered pre-rollback line after UNTIL is set', async () => { const bucket = memoryBucket({ 'late.log': logLine({ EdgeStartTimestamp: (cutoverMs + 1000) * 1e6 }) }) const queue = memoryQueue() const env = { FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: queue, FILES_BANDWIDTH_LOGPUSH_FROM: String(cutoverMs / 1000), FILES_BANDWIDTH_LOGPUSH_UNTIL: String((cutoverMs + 3_600_000) / 1000) } expect(await enqueueFilesBandwidthFile(env as any, 'late.log')).toMatchObject({ counted: 1, chunks: 1 }) }) it('parses ISO with a time zone or unix seconds, and nothing else', async () => { const { parseFilesBandwidthCutover, requestCountsFileBandwidth } = await import('../supabase/functions/_backend/plugin_runtime/utils/filesBandwidthCutover.ts') expect(parseFilesBandwidthCutover('2026-12-01T00:00:00Z')).toBe(Date.UTC(2026, 11, 1)) expect(parseFilesBandwidthCutover('2026-12-01T01:00:00+01:00')).toBe(Date.UTC(2026, 11, 1)) expect(parseFilesBandwidthCutover(' 1764547200 ')).toBe(1764547200_000) for (const value of ['', undefined, null, '2026-12-01', '2026-12-01T00:00:00', 'tomorrow', '0', '-5']) expect(parseFilesBandwidthCutover(value as string)).toBeNull() expect(requestCountsFileBandwidth(null, Date.now())).toBe(true) }) }) describe('plugin worker files bandwidth queues', () => { it('handles them in the queue invocation, without the placed relay', async () => { const fetch = vi.fn() const bucket = memoryBucket() const env = { PLACED_SELF: { fetch }, API_SECRET: 's', ...CUTOVER_ENV, FILES_BANDWIDTH_LOGS: bucket, FILES_BANDWIDTH_REPLAY: memoryQueue(), BANDWIDTH_USAGE: dataset() } const [chunk] = await buildFilesBandwidthMessages('f.log.gz', [logLine()]) const messages = [{ id: 'm0', body: chunk, ack: vi.fn(), retry: vi.fn() }] vi.spyOn(console, 'log').mockImplementation(() => undefined) await pluginWorker.queue({ queue: FILES_BANDWIDTH_REPLAY_QUEUE, messages } as any, env as any, {} as any) expect(fetch).not.toHaveBeenCalled() expect(env.BANDWIDTH_USAGE.writeDataPoint).toHaveBeenCalledOnce() expect(messages[0]!.ack).toHaveBeenCalledOnce() const missing = [{ id: 'm1', body: { action: 'PutObject', object: { key: 'gone.log.gz' } }, ack: vi.fn(), retry: vi.fn() }] await pluginWorker.queue({ queue: FILES_BANDWIDTH_FILES_QUEUE, messages: missing } as any, env as any, {} as any) expect(bucket.get).toHaveBeenCalledWith('gone.log.gz') expect(missing[0]!.ack).toHaveBeenCalledOnce() }) it('retries a message when the bindings are missing', async () => { const messages = [{ id: 'm0', body: { action: 'PutObject', object: { key: 'a.log.gz' } }, ack: vi.fn(), retry: vi.fn() }] vi.spyOn(console, 'log').mockImplementation(() => undefined) await pluginWorker.queue({ queue: FILES_BANDWIDTH_FILES_QUEUE, messages } as any, {} as any, {} as any) expect(messages[0]!.retry).toHaveBeenCalledOnce() }) }) describe('files-bandwidth:setup', () => { it('pushes successful eyeball file reads with the fields the replay reads', () => { const job = logpushJobBody('r2://bucket/{DATE}') expect(job.dataset).toBe('http_requests') for (const field of ['ClientRequestHost', 'ClientRequestPath', 'ClientRequestURI', 'EdgeResponseStatus', 'EdgeResponseBodyBytes', 'EdgeStartTimestamp', 'RayID', 'WorkerSubrequest']) expect(job.output_options.field_names).toContain(field) expect(job.output_options.field_names).toEqual(FIELD_NAMES) const [paths, statuses, subrequest] = JSON.parse(job.filter).where.and expect(paths.or.map((condition: { operator: string, value: string }) => [condition.operator, condition.value])).toEqual(FILES_BANDWIDTH_READ_PREFIXES.map(prefix => ['startsWith', prefix])) // One shared list: the job filter cannot drift from the replay and the cutover gate. expect(READ_PATH_PREFIXES).toBe(FILES_BANDWIDTH_READ_PREFIXES) expect(statuses.or.map((condition: { value: number }) => condition.value)).toEqual([200, 206]) expect(subrequest).toEqual({ key: 'WorkerSubrequest', operator: 'eq', value: false }) }) it('updates an existing Logpush job only when a setting differs', () => { const { destination_conf: _destination, ...current } = logpushJobBody('r2://bucket/{DATE}') expect(logpushJobNeedsUpdate({ id: 1, ...current })).toBe(false) expect(logpushJobNeedsUpdate({ id: 1, ...current, filter: null })).toBe(true) expect(logpushJobNeedsUpdate({ id: 1, ...current, output_options: { ...current.output_options, field_names: ['RayID'] } })).toBe(true) // A sampled job would undercount; an omitted rate means unsampled. expect(logpushJobNeedsUpdate({ id: 1, ...current, output_options: { ...current.output_options, sample_rate: 0.1 } })).toBe(true) expect(logpushJobNeedsUpdate({ id: 1, ...current, output_options: { ...current.output_options, sample_rate: undefined } })).toBe(false) }) it('notifies only for Logpush files and keeps claims past queue retries', () => { const steps = wranglerSetupSteps() const notification = steps.find(step => step.includes('notification'))! expect(notification[notification.indexOf('--suffix') + 1]).toBe('.log.gz') const lifecycle = steps.find(step => step.includes('lifecycle'))! expect(Number(lifecycle[lifecycle.indexOf('--expire-days') + 1])).toBeGreaterThanOrEqual(5) }) it('attaches the EU worker consumers, one chunk per replay invocation, within the retry budget', () => { const args = consumerAddArgs(parseJsonc(readFileSync(WRANGLER_PATH, 'utf8'))) expect(args).toEqual([ ['queues', 'consumer', 'add', 'capgo-files-bandwidth-files', 'capgo_plugin-eu-prod', '--batch-size', '5', '--batch-timeout', '5', '--message-retries', '3', '--dead-letter-queue', 'capgo-files-bandwidth-dlq'], ['queues', 'consumer', 'add', 'capgo-files-bandwidth-replay', 'capgo_plugin-eu-prod', '--batch-size', '1', '--batch-timeout', '1', '--message-retries', '3', '--dead-letter-queue', 'capgo-files-bandwidth-dlq'], ]) }) })