#!/usr/bin/env bun /** * Creates the pipeline that counts file download bandwidth from the zone's * HTTP request logs (see plugin_runtime/utils/filesBandwidthReplay.ts and * docs/files-bandwidth-logpush.md): * * file read (any host of the zone, Workers cache hit or not) * -> zone Logpush (http_requests, /files/read/attachments/ 200/206) -> R2 * -> R2 object-create notification (.log.gz) -> capgo-files-bandwidth-files * -> plugin worker (prod_eu) sums bytes per (app_id, device_id) * -> capgo-files-bandwidth-replay -> BANDWIDTH_USAGE (Analytics Engine) * * Separate from the snippet edge stats job (setup-snippet-edge-stats.ts): its * bucket, queues and Logpush job are left untouched. * * Two phases, because the plugin worker config binds the bucket and queue * (its deploy fails without them) and the consumers must not be attached to * a deployed worker that does not know these queues yet: * 1. `--resources-only` before the plugin EU deploy: bucket, lifecycle, * queues, notification * 2. without the flag after that deploy: the same (skipped) plus the queue * consumers and the Logpush job * Every step is skipped when it already exists; an existing Logpush job is * updated when its settings differ. Nothing is counted from the logs until * FILES_BANDWIDTH_LOGPUSH_FROM is set on both workers: see the doc's cutover. * * Env (unset values come from internal/cloudflare/.env.prod, or ENV_FILE): * CLOUDFLARE_API_TOKEN Logs Edit + Zone Read + Account API Tokens Edit (Logpush R2 key), * else CF_ANALYTICS_TOKEN. When exported, wrangler uses it too * and then also needs Workers R2 Storage Write + Queues Write. * CLOUDFLARE_ACCOUNT_ID else CF_ACCOUNT_ANALYTICS_ID * R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY optional R2 key for the Logpush destination; by * default the setup creates LOGPUSH_R2_TOKEN_NAME, scoped to the bucket. * ZONE_NAME default capgo.app (run again with usecapgo.com for api.usecapgo.com) * * bun run files-bandwidth:setup [--resources-only] [--dry-run] */ import { spawnSync } from 'node:child_process' import { readFileSync } from 'node:fs' import process from 'node:process' import { FILES_BANDWIDTH_READ_PREFIXES } from '../supabase/functions/_backend/plugin_runtime/utils/filesBandwidthCutover.ts' import { parseJsonc, WRANGLER_PATH } from './generate-plugin-route-hosts.ts' import { r2CredentialsOfToken, readEnvFile, resolveSetupEnv } from './setup-snippet-edge-stats.ts' export const BUCKET = 'capgo-files-bandwidth-logs' export const FILES_QUEUE = 'capgo-files-bandwidth-files' export const REPLAY_QUEUE = 'capgo-files-bandwidth-replay' export const DLQ = 'capgo-files-bandwidth-dlq' export const LOGPUSH_JOB_NAME = 'capgo-files-bandwidth' export const LOGPUSH_R2_TOKEN_NAME = 'capgo-files-bandwidth-logpush (R2 write, used by Logpush, do not delete)' const R2_BUCKET_ITEM_WRITE = '2efd5506f9c8494dacb1fa10a3e7d5b6' /** * The replay deletes each file once queued; the lifecycle clears files it * never read, and the idempotency claims (kept longer than any queue retry * or Logpush re-push). */ const RETENTION_DAYS = 7 /** * The shared list (filesBandwidthCutover.ts): the job filter, the replay and * the files handler's cutover gate cannot drift apart. */ export const READ_PATH_PREFIXES = FILES_BANDWIDTH_READ_PREFIXES export const FIELD_NAMES = [ 'ClientRequestHost', 'ClientRequestPath', 'ClientRequestURI', 'EdgeResponseStatus', 'EdgeResponseBodyBytes', 'EdgeStartTimestamp', 'RayID', 'CacheCacheStatus', 'WorkerSubrequest', ] export function logpushJobBody(destination: string) { return { name: LOGPUSH_JOB_NAME, dataset: 'http_requests', enabled: true, destination_conf: destination, max_upload_interval_seconds: 60, // The consumer streams a file and keeps only per-device sums and RayIDs: // bigger files sum more downloads of one update into one data point. max_upload_bytes: 25_000_000, max_upload_records: 50_000, output_options: { output_type: 'ndjson', timestamp_format: 'unixnano', field_names: FIELD_NAMES, // Every request: a sampled job would undercount the bytes the replay sums. sample_rate: 1, }, // Successful eyeball reads of file bytes; the consumer checks it all again. filter: JSON.stringify({ where: { and: [ { or: READ_PATH_PREFIXES.map(value => ({ key: 'ClientRequestPath', operator: 'startsWith', value })) }, { or: [200, 206].map(value => ({ key: 'EdgeResponseStatus', operator: 'eq', value })) }, { key: 'WorkerSubrequest', operator: 'eq', value: false }, ], }, }), } } interface LogpushJob { id: number name: string enabled?: boolean filter?: string | null max_upload_interval_seconds?: number max_upload_bytes?: number max_upload_records?: number output_options?: { output_type?: string, timestamp_format?: string, field_names?: string[], sample_rate?: number } | null } /** True when the job lacks a setting of logpushJobBody (destination aside: the API hides its secrets). */ export function logpushJobNeedsUpdate(job: LogpushJob) { const wanted = logpushJobBody('') const fields = job.output_options?.field_names ?? [] return job.enabled !== wanted.enabled || job.filter !== wanted.filter || job.max_upload_interval_seconds !== wanted.max_upload_interval_seconds || job.max_upload_bytes !== wanted.max_upload_bytes || job.max_upload_records !== wanted.max_upload_records || job.output_options?.output_type !== wanted.output_options.output_type || job.output_options?.timestamp_format !== wanted.output_options.timestamp_format || wanted.output_options.field_names.some(field => !fields.includes(field)) // The API may omit the rate of an unsampled job. || (job.output_options?.sample_rate ?? 1) !== wanted.output_options.sample_rate } const CONSUMER_ENV = 'prod_eu' interface QueueConsumer { queue: string max_batch_size?: number max_batch_timeout?: number max_retries?: number dead_letter_queue?: string } /** `wrangler queues consumer add` for each files bandwidth consumer of the plugin worker config. */ export function consumerAddArgs(config: unknown, envName = CONSUMER_ENV) { const env = (config as { env?: Record }).env?.[envName] if (!env?.name) throw new Error(`No ${envName} env in ${WRANGLER_PATH}`) return (env.queues?.consumers ?? []) .filter(consumer => consumer.queue === FILES_QUEUE || consumer.queue === REPLAY_QUEUE) .map(consumer => [ 'queues', 'consumer', 'add', consumer.queue, env.name!, ...(consumer.max_batch_size === undefined ? [] : ['--batch-size', String(consumer.max_batch_size)]), ...(consumer.max_batch_timeout === undefined ? [] : ['--batch-timeout', String(consumer.max_batch_timeout)]), ...(consumer.max_retries === undefined ? [] : ['--message-retries', String(consumer.max_retries)]), ...(consumer.dead_letter_queue ? ['--dead-letter-queue', consumer.dead_letter_queue] : []), ]) } /** Wrangler steps that create the bucket, its lifecycle, the queues and the notification. */ export function wranglerSetupSteps() { return [ ['r2', 'bucket', 'create', BUCKET], ['r2', 'bucket', 'lifecycle', 'add', BUCKET, 'expire-logpush', '--expire-days', String(RETENTION_DAYS), '--force'], ...[DLQ, FILES_QUEUE, REPLAY_QUEUE].map(queue => ['queues', 'create', queue]), // Only Logpush files: the replay's own claims and progress objects never end in .log.gz. ['r2', 'bucket', 'notification', 'create', BUCKET, '--event-type', 'object-create', '--queue', FILES_QUEUE, '--suffix', '.log.gz', '--description', 'Logpush files to count'], ] } function required(value: string, names: string) { if (!value) throw new Error(`Missing ${names}`) return value } let apiToken = '' let wranglerEnv: NodeJS.ProcessEnv = process.env function wrangler(args: string[], dryRun: boolean, alreadyExists: RegExp) { console.log(`$ wrangler ${args.join(' ')}`) if (dryRun) return const child = spawnSync('bunx', ['wrangler', ...args], { encoding: 'utf8', env: wranglerEnv }) const output = `${child.stdout}${child.stderr}` if (child.status !== 0 && !alreadyExists.test(output)) { console.error(output) throw new Error(`wrangler ${args.join(' ')} failed`) } } async function cloudflare(path: string, init: RequestInit = {}): Promise { const response = await fetch(`https://api.cloudflare.com/client/v4${path}`, { ...init, headers: { 'Authorization': `Bearer ${required(apiToken, 'CLOUDFLARE_API_TOKEN (or CF_ANALYTICS_TOKEN in the env file)')}`, 'Content-Type': 'application/json', ...init.headers }, }) const json = await response.json().catch(() => null) as { success: boolean, result: T, errors?: unknown } | null if (!json?.success) { const hint = response.status === 403 ? ' (export a CLOUDFLARE_API_TOKEN with Zone Read + Logs Edit on the zone, and Account API Tokens Edit)' : '' throw new Error(`${init.method ?? 'GET'} ${path}: ${response.status} ${JSON.stringify(json?.errors ?? null)}${hint}`) } return json.result } /** An account API token that can only write the bucket: the Logpush destination key. */ async function createLogpushR2Key(accountId: string) { const resource = `com.cloudflare.edge.r2.bucket.${accountId}_default_${BUCKET}` const token = await cloudflare<{ id: string, value: string }>(`/accounts/${accountId}/tokens`, { method: 'POST', body: JSON.stringify({ name: LOGPUSH_R2_TOKEN_NAME, policies: [{ effect: 'allow', permission_groups: [{ id: R2_BUCKET_ITEM_WRITE }], resources: { [resource]: '*' } }], }), }) console.log(`Created R2 key ${token.id} (${LOGPUSH_R2_TOKEN_NAME})`) return r2CredentialsOfToken(token) } /** A new key can take a few seconds to reach R2: Logpush checks the destination by writing to it. */ async function createLogpushJob(zoneId: string, destination: string) { for (let attempt = 1; ; attempt++) { try { return await cloudflare<{ id: number }>(`/zones/${zoneId}/logpush/jobs`, { method: 'POST', body: JSON.stringify(logpushJobBody(destination)), }) } catch (error) { if (attempt >= 6 || !(error instanceof Error && error.message.includes('error validating destination'))) throw error await new Promise(resolve => setTimeout(resolve, 10_000)) } } } async function main() { const dryRun = process.argv.includes('--dry-run') const setup = resolveSetupEnv(process.env, readEnvFile()) const accountId = required(setup.accountId, 'CLOUDFLARE_ACCOUNT_ID (or CF_ACCOUNT_ANALYTICS_ID in the env file)') const zoneName = setup.zoneName apiToken = setup.apiToken // wrangler picks the account from its login, which may see several. wranglerEnv = { ...process.env, CLOUDFLARE_ACCOUNT_ID: accountId } // A previous run left these: 10061 lifecycle rule, 11020 bucket notification (overlap), 11004 queue consumer. const exists = /already exists|already been taken|10004|11009|10061|11020|11004/i for (const args of wranglerSetupSteps()) wrangler(args, dryRun, exists) if (process.argv.includes('--resources-only')) { console.log('Resources ready. Deploy the plugin worker (prod_eu), then run this again without --resources-only.') return } for (const args of consumerAddArgs(parseJsonc(readFileSync(WRANGLER_PATH, 'utf8')))) wrangler(args, dryRun, exists) if (dryRun) { console.log(`Would create Logpush job on ${zoneName} ${JSON.stringify({ ...logpushJobBody('r2://'), destination_conf: undefined })}`) return } const [zone] = await cloudflare<{ id: string }[]>(`/zones?name=${encodeURIComponent(zoneName)}`) if (!zone) throw new Error(`Zone ${zoneName} not found`) const jobs = await cloudflare(`/zones/${zone.id}/logpush/jobs`) const existing = jobs.find(job => job.name === LOGPUSH_JOB_NAME) if (existing) { if (!logpushJobNeedsUpdate(existing)) { console.log(`Logpush job ${LOGPUSH_JOB_NAME} already exists on ${zoneName}`) return } // No destination_conf: the job keeps its R2 key. const { name: _name, destination_conf: _destination, ...settings } = logpushJobBody('') await cloudflare(`/zones/${zone.id}/logpush/jobs/${existing.id}`, { method: 'PUT', body: JSON.stringify(settings) }) console.log(`Updated Logpush job ${LOGPUSH_JOB_NAME} (${existing.id}) on ${zoneName}`) return } const key = setup.r2AccessKeyId && setup.r2SecretAccessKey ? { accessKeyId: setup.r2AccessKeyId, secretAccessKey: setup.r2SecretAccessKey } : await createLogpushR2Key(accountId) const destination = `r2://${BUCKET}/{DATE}?account-id=${accountId}&access-key-id=${key.accessKeyId}&secret-access-key=${key.secretAccessKey}` const job = await createLogpushJob(zone.id, destination) console.log(`Created Logpush job ${LOGPUSH_JOB_NAME} (${job.id}) on ${zoneName}`) } if (import.meta.main) { main().catch((error) => { console.error(error instanceof Error ? error.message : error) process.exit(1) }) }