The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as alerting from "@distilled.cloud/cloudflare/alerting"; |
| 2 | import * as Provider from "alchemy/Provider"; |
| 3 | import { Resource } from "alchemy/Resource"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Predicate from "effect/Predicate"; |
| 7 | import * as Stream from "effect/Stream"; |
| 8 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { |
| 11 | boundMechanisms, |
| 12 | createPolicyName, |
| 13 | findPolicyByName, |
| 14 | narrowPolicy, |
| 15 | type NotificationPolicyBinding, |
| 16 | type ObservedPolicy, |
| 17 | observePolicy, |
| 18 | type PolicyBody, |
| 19 | policyEqualsObserved, |
| 20 | } from "./internal.ts"; |
| 21 | import type { NotificationPolicyMechanisms } from "./NotificationPolicy.ts"; |
| 22 | |
| 23 | export class CustomAlertUnexpectedResponse extends Data.TaggedError( |
| 24 | "CustomAlertUnexpectedResponse", |
| 25 | )<{ |
| 26 | readonly message: string; |
| 27 | readonly cause?: unknown; |
| 28 | }> {} |
| 29 | |
| 30 | const TypeId = "Cloudflare.Alerting.CustomAlert" as const; |
| 31 | type TypeId = typeof TypeId; |
| 32 | |
| 33 | /** |
| 34 | * A time window in minutes or hours, at least one minute (e.g. `"5m"`, |
| 35 | * `"1h"`). |
| 36 | */ |
| 37 | export type CustomAlertWindow = `${number}m` | `${number}h`; |
| 38 | |
| 39 | /** |
| 40 | * Fire when the query result crosses a fixed value. |
| 41 | */ |
| 42 | export interface CustomAlertThresholdTrigger { |
| 43 | type: "threshold"; |
| 44 | /** How the query result is compared to `value`. */ |
| 45 | operator: "<" | ">" | "<=" | ">=" | "==" | "!="; |
| 46 | /** The value the query result is compared to. */ |
| 47 | value: number; |
| 48 | /** The time range the query covers on each evaluation. */ |
| 49 | window: CustomAlertWindow; |
| 50 | /** Don't fire while the query result is below this value. */ |
| 51 | minimumThreshold?: number; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Fire when the query result moves away from its recent baseline. |
| 56 | */ |
| 57 | export interface CustomAlertAnomalyTrigger { |
| 58 | type: "anomaly"; |
| 59 | /** Fire on spikes, drops, or both. */ |
| 60 | direction: "spike" | "drop" | "both"; |
| 61 | /** How many standard deviations from the baseline count as an anomaly. */ |
| 62 | zScore: number; |
| 63 | /** The time range the query covers on each evaluation. */ |
| 64 | window: CustomAlertWindow; |
| 65 | /** The longer time range the baseline is computed over. */ |
| 66 | baselineWindow: CustomAlertWindow; |
| 67 | /** Don't fire while the query result is below this value. */ |
| 68 | minimumThreshold?: number; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Fire when the query result falls below a service level objective, |
| 73 | * checked over a short and a long window. |
| 74 | */ |
| 75 | export interface CustomAlertSloTrigger { |
| 76 | type: "slo"; |
| 77 | /** The objective the query result is held to (e.g. `99.9`). */ |
| 78 | target: number; |
| 79 | /** The short window the objective is checked over. */ |
| 80 | shortWindow: CustomAlertWindow; |
| 81 | /** The long window the objective is checked over. */ |
| 82 | longWindow: CustomAlertWindow; |
| 83 | /** Don't fire while the query result is below this value. */ |
| 84 | minimumThreshold?: number; |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * When a custom alert fires. |
| 89 | */ |
| 90 | export type CustomAlertTrigger = |
| 91 | | CustomAlertThresholdTrigger |
| 92 | | CustomAlertAnomalyTrigger |
| 93 | | CustomAlertSloTrigger; |
| 94 | |
| 95 | export interface CustomAlertProps { |
| 96 | /** |
| 97 | * Name of the alert. If omitted, a unique name is generated. |
| 98 | * Mutable — renames are applied in place. |
| 99 | * @default ${app}-${id}-${stage}-${suffix} |
| 100 | */ |
| 101 | name?: string; |
| 102 | /** |
| 103 | * Optional human-readable description of the alert. |
| 104 | */ |
| 105 | description?: string; |
| 106 | /** |
| 107 | * A [SQL API](https://developers.cloudflare.com/analytics/sql-api/) query |
| 108 | * returning the number the trigger evaluates, e.g. |
| 109 | * `SELECT count() AS value FROM logs.workersLogs WHERE …`. The query must |
| 110 | * scope itself to the account (`accountTag = '…'`). Cloudflare checks |
| 111 | * it when the alert is saved and rejects it with `InvalidAlertQuery`. |
| 112 | */ |
| 113 | query: string; |
| 114 | /** When the alert fires. */ |
| 115 | trigger: CustomAlertTrigger; |
| 116 | /** |
| 117 | * How often Cloudflare runs the query. |
| 118 | * @default "1m" |
| 119 | */ |
| 120 | every?: CustomAlertWindow; |
| 121 | /** |
| 122 | * Destinations notified when the alert fires. At least one destination is |
| 123 | * required, either declared here or bound by a runtime that consumes the |
| 124 | * alert's notifications (`Cloudflare.Alerting.consumeNotifications`). |
| 125 | */ |
| 126 | mechanisms?: NotificationPolicyMechanisms; |
| 127 | /** |
| 128 | * How often to re-alert while the alert keeps firing (e.g. `"30m"`). |
| 129 | */ |
| 130 | alertInterval?: string; |
| 131 | /** |
| 132 | * Whether the alert is enabled. |
| 133 | * @default true |
| 134 | */ |
| 135 | enabled?: boolean; |
| 136 | } |
| 137 | |
| 138 | export interface CustomAlertAttributes { |
| 139 | /** Cloudflare-assigned notification policy UUID. */ |
| 140 | policyId: string; |
| 141 | /** Account that owns this alert. */ |
| 142 | accountId: string; |
| 143 | /** Name of the alert. */ |
| 144 | name: string; |
| 145 | /** Whether the alert is enabled. */ |
| 146 | enabled: boolean; |
| 147 | /** ISO8601 creation timestamp. */ |
| 148 | created: string | undefined; |
| 149 | /** ISO8601 last-modified timestamp. */ |
| 150 | modified: string | undefined; |
| 151 | } |
| 152 | |
| 153 | export type CustomAlert = Resource< |
| 154 | TypeId, |
| 155 | CustomAlertProps, |
| 156 | CustomAlertAttributes, |
| 157 | NotificationPolicyBinding, |
| 158 | Providers |
| 159 | >; |
| 160 | |
| 161 | /** |
| 162 | * A Cloudflare custom alert: a SQL query Cloudflare runs on a schedule, |
| 163 | * with a trigger that decides when to notify. |
| 164 | * |
| 165 | * The query runs against the |
| 166 | * [SQL API](https://developers.cloudflare.com/analytics/sql-api/), so it |
| 167 | * can read Workers logs and traces, HTTP requests, Analytics Engine |
| 168 | * datasets and the other analytics datasets. Notifications go to the same |
| 169 | * destinations as a `NotificationPolicy` (email, webhooks, PagerDuty). |
| 170 | * ### Alerting on a threshold |
| 171 | * **Example:** Alert when a Worker logs more than 100 errors in 5 minutes |
| 172 | * ```typescript |
| 173 | * yield* Cloudflare.Alerting.CustomAlert("ErrorSpike", { |
| 174 | * query: `SELECT count() AS value FROM logs.workersLogs |
| 175 | * WHERE accountTag = '${accountId}' AND level = 'error'`, |
| 176 | * trigger: { type: "threshold", operator: ">", value: 100, window: "5m" }, |
| 177 | * every: "5m", |
| 178 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 179 | * }); |
| 180 | * ``` |
| 181 | * |
| 182 | * ### Alerting on anomalies |
| 183 | * **Example:** Alert when request volume spikes or drops |
| 184 | * ```typescript |
| 185 | * yield* Cloudflare.Alerting.CustomAlert("TrafficAnomaly", { |
| 186 | * query: `SELECT count() AS value FROM events.httpRequests |
| 187 | * WHERE accountTag = '${accountId}'`, |
| 188 | * trigger: { |
| 189 | * type: "anomaly", |
| 190 | * direction: "both", |
| 191 | * zScore: 3, |
| 192 | * window: "5m", |
| 193 | * baselineWindow: "1h", |
| 194 | * }, |
| 195 | * mechanisms: { webhooks: [{ id: webhook.webhookId }] }, |
| 196 | * }); |
| 197 | * ``` |
| 198 | * |
| 199 | * ### Alerting on an SLO |
| 200 | * **Example:** Alert when the success rate drops below 99.9% |
| 201 | * ```typescript |
| 202 | * yield* Cloudflare.Alerting.CustomAlert("Availability", { |
| 203 | * query: `SELECT 100 * countIf(httpStatus < 500) / count() AS value |
| 204 | * FROM logs.workersLogs WHERE accountTag = '${accountId}'`, |
| 205 | * trigger: { type: "slo", target: 99.9, shortWindow: "5m", longWindow: "1h" }, |
| 206 | * mechanisms: { pagerduty: [{ id: pagerDutyId }] }, |
| 207 | * }); |
| 208 | * ``` |
| 209 | * |
| 210 | * @see https://developers.cloudflare.com/notifications/ |
| 211 | * |
| 212 | * @resource |
| 213 | * @product Alerting |
| 214 | * @category Observability & Analytics |
| 215 | */ |
| 216 | export const CustomAlert = Resource<CustomAlert>(TypeId); |
| 217 | |
| 218 | /** |
| 219 | * Returns true if the given value is a CustomAlert resource. |
| 220 | */ |
| 221 | export const isCustomAlert = (value: unknown): value is CustomAlert => |
| 222 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 223 | |
| 224 | export const CustomAlertProvider = () => |
| 225 | Provider.succeed(CustomAlert, { |
| 226 | stables: ["policyId", "accountId"], |
| 227 | |
| 228 | // Account-scoped collection: the account's `custom_analytics` policies. |
| 229 | list: Effect.fn(function* () { |
| 230 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 231 | return yield* alerting.listPolicies.items({ accountId }).pipe( |
| 232 | Stream.filter((p) => p.alertType === "custom_analytics"), |
| 233 | Stream.runCollect, |
| 234 | Effect.map((chunk) => |
| 235 | Array.from(chunk) |
| 236 | .map(narrowPolicy) |
| 237 | .filter((p): p is ObservedPolicy => p !== undefined) |
| 238 | .map((p) => toAttributes(p, accountId)), |
| 239 | ), |
| 240 | ); |
| 241 | }), |
| 242 | |
| 243 | diff: Effect.fn(function* ({ output }) { |
| 244 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 245 | if ((output?.accountId ?? accountId) !== accountId) { |
| 246 | return { action: "replace" } as const; |
| 247 | } |
| 248 | }), |
| 249 | |
| 250 | read: Effect.fn(function* ({ id, output, olds }) { |
| 251 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 252 | const acct = output?.accountId ?? accountId; |
| 253 | |
| 254 | // Owned path: refresh by the persisted policy id. |
| 255 | if (output?.policyId) { |
| 256 | const observed = yield* observePolicy(acct, output.policyId); |
| 257 | return observed ? toAttributes(observed, acct) : undefined; |
| 258 | } |
| 259 | |
| 260 | // Cold read: no persisted id (state-persistence failure) — find the |
| 261 | // deterministic physical name in the account's policy list. |
| 262 | const name = yield* createPolicyName(id, olds?.name); |
| 263 | const match = yield* findPolicyByName(acct, name); |
| 264 | return match ? toAttributes(match, acct) : undefined; |
| 265 | }), |
| 266 | |
| 267 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 268 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 269 | const name = yield* createPolicyName(id, news.name ?? output?.name); |
| 270 | const desired = buildBody(name, news, bindings); |
| 271 | |
| 272 | // 1. Observe — by cached id first, then by deterministic name. |
| 273 | let observed: ObservedPolicy | undefined; |
| 274 | if (output?.policyId) { |
| 275 | observed = yield* observePolicy(accountId, output.policyId); |
| 276 | } |
| 277 | if (!observed) { |
| 278 | observed = yield* findPolicyByName(accountId, name); |
| 279 | } |
| 280 | |
| 281 | // 2. Ensure — create when missing. `createPolicy` only returns the |
| 282 | // new id; re-read for the full attribute set. |
| 283 | if (!observed) { |
| 284 | const created = yield* alerting.createPolicy({ accountId, ...desired }); |
| 285 | if (!created.id) { |
| 286 | return yield* new CustomAlertUnexpectedResponse({ |
| 287 | message: "Cloudflare did not return an id for the created custom alert", |
| 288 | }); |
| 289 | } |
| 290 | const fresh = yield* observePolicy(accountId, created.id); |
| 291 | return toAttributes(fresh ?? { id: created.id, name }, accountId); |
| 292 | } |
| 293 | |
| 294 | // 3. Sync — PUT the full desired body when anything drifts from the |
| 295 | // observed policy, filters included. |
| 296 | if (!policyEqualsObserved(desired, observed)) { |
| 297 | yield* alerting.updatePolicy({ accountId, policyId: observed.id, ...desired }); |
| 298 | const fresh = yield* observePolicy(accountId, observed.id); |
| 299 | return toAttributes(fresh ?? observed, accountId); |
| 300 | } |
| 301 | |
| 302 | // 4. Return. |
| 303 | return toAttributes(observed, accountId); |
| 304 | }), |
| 305 | |
| 306 | delete: Effect.fn(function* ({ output }) { |
| 307 | yield* alerting |
| 308 | .deletePolicy({ accountId: output.accountId, policyId: output.policyId }) |
| 309 | .pipe(Effect.catchTag("PolicyNotFound", () => Effect.void)); |
| 310 | }), |
| 311 | }); |
| 312 | |
| 313 | const buildBody = ( |
| 314 | name: string, |
| 315 | news: CustomAlertProps, |
| 316 | bindings: ReadonlyArray<{ data: NotificationPolicyBinding }>, |
| 317 | ): PolicyBody => ({ |
| 318 | name, |
| 319 | alertType: "custom_analytics", |
| 320 | enabled: news.enabled ?? true, |
| 321 | description: news.description, |
| 322 | alertInterval: news.alertInterval, |
| 323 | // `Input<string>` ids are resolved to concrete strings by the engine |
| 324 | // before reconcile runs; bound webhooks extend the declared ones. |
| 325 | mechanisms: boundMechanisms(news.mechanisms, bindings), |
| 326 | filters: { |
| 327 | source: ["sql_api"], |
| 328 | selectors: [news.query], |
| 329 | // Cloudflare stores 1m when omitted; send it so observed state matches. |
| 330 | executionInterval: [news.every ?? "1m"], |
| 331 | ...triggerFilters(news.trigger), |
| 332 | }, |
| 333 | }); |
| 334 | |
| 335 | const ZSCORE_ALGORITHMS = { |
| 336 | spike: "zscore_spike", |
| 337 | drop: "zscore_drop", |
| 338 | both: "zscore_spike_and_drop", |
| 339 | } as const; |
| 340 | |
| 341 | /** |
| 342 | * Encode a trigger as the `alert_trigger_preferences*` filters. Anomaly |
| 343 | * and SLO triggers only accept the `<` operator, so it is fixed here. |
| 344 | */ |
| 345 | const triggerFilters = (trigger: CustomAlertTrigger): NonNullable<PolicyBody["filters"]> => { |
| 346 | const minimum = |
| 347 | trigger.minimumThreshold === undefined |
| 348 | ? {} |
| 349 | : { alertTriggerPreferencesMinimumThreshold: [String(trigger.minimumThreshold)] }; |
| 350 | switch (trigger.type) { |
| 351 | case "threshold": |
| 352 | return { |
| 353 | alertTriggerPreferences: ["threshold"], |
| 354 | alertTriggerPreferencesOperator: [trigger.operator], |
| 355 | alertTriggerPreferencesValue: [String(trigger.value)], |
| 356 | alertTriggerPreferencesShortWindow: [trigger.window], |
| 357 | ...minimum, |
| 358 | }; |
| 359 | case "anomaly": |
| 360 | return { |
| 361 | alertTriggerPreferences: [ZSCORE_ALGORITHMS[trigger.direction]], |
| 362 | alertTriggerPreferencesOperator: ["<"], |
| 363 | alertTriggerPreferencesValue: [String(trigger.zScore)], |
| 364 | alertTriggerPreferencesShortWindow: [trigger.window], |
| 365 | alertTriggerPreferencesLongWindow: [trigger.baselineWindow], |
| 366 | ...minimum, |
| 367 | }; |
| 368 | case "slo": |
| 369 | return { |
| 370 | alertTriggerPreferences: ["slo"], |
| 371 | alertTriggerPreferencesOperator: ["<"], |
| 372 | alertTriggerPreferencesValue: [String(trigger.target)], |
| 373 | alertTriggerPreferencesShortWindow: [trigger.shortWindow], |
| 374 | alertTriggerPreferencesLongWindow: [trigger.longWindow], |
| 375 | ...minimum, |
| 376 | }; |
| 377 | } |
| 378 | }; |
| 379 | |
| 380 | const toAttributes = (observed: ObservedPolicy, accountId: string): CustomAlertAttributes => ({ |
| 381 | policyId: observed.id, |
| 382 | accountId, |
| 383 | name: observed.name ?? "", |
| 384 | enabled: observed.enabled ?? true, |
| 385 | created: observed.created, |
| 386 | modified: observed.modified, |
| 387 | }); |