|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Cost killswitch: queries Cloudflare GraphQL Analytics for today's usage |
| 4 | + * and exits non-zero when any threshold is exceeded. |
| 5 | + * |
| 6 | + * Env: |
| 7 | + * CF_ACCOUNT_ID — required |
| 8 | + * CF_API_TOKEN — required, needs Analytics: Read |
| 9 | + * DAILY_WORKER_REQUESTS — optional, default 1_000_000 |
| 10 | + * DAILY_D1_ROWS_READ — optional, default 10_000_000 |
| 11 | + * DAILY_DO_REQUESTS — optional, default 500_000 |
| 12 | + * DAILY_DO_DURATION_SEC — optional, default 100_000 (active seconds, not GB-sec) |
| 13 | + * |
| 14 | + * Exit codes: |
| 15 | + * 0 — all thresholds ok |
| 16 | + * 1 — one or more thresholds tripped |
| 17 | + * 2 — query failed (treat as unknown, do NOT auto-disable) |
| 18 | + * |
| 19 | + * Stdout: a single JSON line with { tripped, usage, thresholds, reasons } |
| 20 | + * Stderr: human-readable diagnostics |
| 21 | + */ |
| 22 | + |
| 23 | +const ACCOUNT_ID = process.env.CF_ACCOUNT_ID; |
| 24 | +const API_TOKEN = process.env.CF_API_TOKEN; |
| 25 | + |
| 26 | +if (!ACCOUNT_ID || !API_TOKEN) { |
| 27 | + console.error("CF_ACCOUNT_ID and CF_API_TOKEN are required"); |
| 28 | + process.exit(2); |
| 29 | +} |
| 30 | + |
| 31 | +const thresholds = { |
| 32 | + workerRequests: Number(process.env.DAILY_WORKER_REQUESTS ?? 1_000_000), |
| 33 | + d1RowsRead: Number(process.env.DAILY_D1_ROWS_READ ?? 10_000_000), |
| 34 | + doRequests: Number(process.env.DAILY_DO_REQUESTS ?? 500_000), |
| 35 | + doDurationSec: Number(process.env.DAILY_DO_DURATION_SEC ?? 100_000), |
| 36 | +}; |
| 37 | + |
| 38 | +// UTC day window — CF billing resets at 00:00 UTC |
| 39 | +const now = new Date(); |
| 40 | +const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())); |
| 41 | +const startIso = start.toISOString(); |
| 42 | +const nowIso = now.toISOString(); |
| 43 | + |
| 44 | +const query = ` |
| 45 | + query Usage($accountTag: String!, $start: Time!, $end: Time!) { |
| 46 | + viewer { |
| 47 | + accounts(filter: { accountTag: $accountTag }) { |
| 48 | + workersInvocationsAdaptive( |
| 49 | + filter: { datetime_geq: $start, datetime_lt: $end } |
| 50 | + limit: 10000 |
| 51 | + ) { |
| 52 | + sum { requests errors } |
| 53 | + } |
| 54 | + durableObjectsInvocationsAdaptiveGroups( |
| 55 | + filter: { datetime_geq: $start, datetime_lt: $end } |
| 56 | + limit: 10000 |
| 57 | + ) { |
| 58 | + sum { requests } |
| 59 | + } |
| 60 | + durableObjectsPeriodicGroups( |
| 61 | + filter: { datetime_geq: $start, datetime_lt: $end } |
| 62 | + limit: 10000 |
| 63 | + ) { |
| 64 | + sum { activeTime } |
| 65 | + } |
| 66 | + d1AnalyticsAdaptiveGroups( |
| 67 | + filter: { datetime_geq: $start, datetime_lt: $end } |
| 68 | + limit: 10000 |
| 69 | + ) { |
| 70 | + sum { readQueries writeQueries rowsRead rowsWritten } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +`; |
| 76 | + |
| 77 | +async function callGraphQL() { |
| 78 | + const res = await fetch("https://api.cloudflare.com/client/v4/graphql", { |
| 79 | + method: "POST", |
| 80 | + headers: { |
| 81 | + "Authorization": `Bearer ${API_TOKEN}`, |
| 82 | + "Content-Type": "application/json", |
| 83 | + }, |
| 84 | + body: JSON.stringify({ |
| 85 | + query, |
| 86 | + variables: { accountTag: ACCOUNT_ID, start: startIso, end: nowIso }, |
| 87 | + }), |
| 88 | + }); |
| 89 | + if (!res.ok) { |
| 90 | + throw new Error(`GraphQL HTTP ${res.status}: ${await res.text()}`); |
| 91 | + } |
| 92 | + const data = await res.json(); |
| 93 | + if (data.errors?.length) { |
| 94 | + throw new Error(`GraphQL errors: ${JSON.stringify(data.errors)}`); |
| 95 | + } |
| 96 | + return data.data.viewer.accounts[0] ?? {}; |
| 97 | +} |
| 98 | + |
| 99 | +function sumBy(rows, key) { |
| 100 | + if (!Array.isArray(rows)) return 0; |
| 101 | + return rows.reduce((acc, r) => acc + (r?.sum?.[key] ?? 0), 0); |
| 102 | +} |
| 103 | + |
| 104 | +function main() { |
| 105 | + return callGraphQL().then((acct) => { |
| 106 | + const usage = { |
| 107 | + workerRequests: sumBy(acct.workersInvocationsAdaptive, "requests"), |
| 108 | + workerErrors: sumBy(acct.workersInvocationsAdaptive, "errors"), |
| 109 | + doRequests: sumBy(acct.durableObjectsInvocationsAdaptiveGroups, "requests"), |
| 110 | + // activeTime is returned in microseconds; convert to seconds for human-friendly threshold |
| 111 | + doDurationSec: Math.round(sumBy(acct.durableObjectsPeriodicGroups, "activeTime") / 1_000_000), |
| 112 | + d1RowsRead: sumBy(acct.d1AnalyticsAdaptiveGroups, "rowsRead"), |
| 113 | + d1RowsWritten: sumBy(acct.d1AnalyticsAdaptiveGroups, "rowsWritten"), |
| 114 | + }; |
| 115 | + |
| 116 | + const reasons = []; |
| 117 | + if (usage.workerRequests > thresholds.workerRequests) { |
| 118 | + reasons.push(`workerRequests ${usage.workerRequests} > ${thresholds.workerRequests}`); |
| 119 | + } |
| 120 | + if (usage.d1RowsRead > thresholds.d1RowsRead) { |
| 121 | + reasons.push(`d1RowsRead ${usage.d1RowsRead} > ${thresholds.d1RowsRead}`); |
| 122 | + } |
| 123 | + if (usage.doRequests > thresholds.doRequests) { |
| 124 | + reasons.push(`doRequests ${usage.doRequests} > ${thresholds.doRequests}`); |
| 125 | + } |
| 126 | + if (usage.doDurationSec > thresholds.doDurationSec) { |
| 127 | + reasons.push(`doDurationSec ${usage.doDurationSec} > ${thresholds.doDurationSec}`); |
| 128 | + } |
| 129 | + |
| 130 | + const tripped = reasons.length > 0; |
| 131 | + const result = { tripped, windowStart: startIso, windowEnd: nowIso, usage, thresholds, reasons }; |
| 132 | + |
| 133 | + console.log(JSON.stringify(result)); |
| 134 | + console.error( |
| 135 | + `[killswitch] window=${startIso}..${nowIso}\n` + |
| 136 | + ` workerRequests: ${usage.workerRequests} / ${thresholds.workerRequests}\n` + |
| 137 | + ` d1RowsRead: ${usage.d1RowsRead} / ${thresholds.d1RowsRead}\n` + |
| 138 | + ` doRequests: ${usage.doRequests} / ${thresholds.doRequests}\n` + |
| 139 | + ` doDurationSec: ${usage.doDurationSec} / ${thresholds.doDurationSec}\n` + |
| 140 | + ` tripped: ${tripped}${tripped ? ` (${reasons.join("; ")})` : ""}` |
| 141 | + ); |
| 142 | + |
| 143 | + process.exit(tripped ? 1 : 0); |
| 144 | + }).catch((err) => { |
| 145 | + console.error(`[killswitch] query failed: ${err.message}`); |
| 146 | + console.log(JSON.stringify({ tripped: false, error: err.message })); |
| 147 | + process.exit(2); |
| 148 | + }); |
| 149 | +} |
| 150 | + |
| 151 | +main(); |
0 commit comments