alerts.ts
This file
Path
infra/alerts.ts
138 lines · 5.2 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
Merge observability into mainoscabrielbefore adoption1985111
lines 1–138why, one step back1// A stage's alerts, as data: Cloudflare Custom Alerts (beta), each a SQL API2// query run on a schedule and judged by a threshold or an anomaly. A person3// makes them by hand: the Notifications API lists the `custom_analytics`4// alert type but documents none of its fields, and nothing in cf or the API5// takes a custom alert's query, so bootstrap prints each for the dashboard6// (README, Alerts), makes none, and records none in the ledger. Every query7// counts rows by Worker; none reads a log's text, a path or a layer8// (principle 7).9import { Data, Duration } from "effect";1011import { ERRORED, quoted, workersOf } from "./logs.ts";12import { resources } from "./stages.ts";13import type { Stage } from "./stages.ts";1415export type Detection = Data.TaggedEnum<{16 // The query's value over the evaluation window reaches `atLeast`.17 Threshold: { readonly atLeast: number };18 // The value is `sensitivity` standard deviations above the baseline19 // window's, and at least `minimum`: a spike, never a drop.20 Spike: {21 readonly baseline: Duration.Duration;22 readonly sensitivity: number;23 readonly minimum: number;24 };25}>;2627export const Detection = Data.taggedEnum<Detection>();2829export const alertKinds = [30 "errors",31 "issue spike",32 "container failures",33 "refusal spike",34] as const;3536export interface Alert {37 readonly kind: (typeof alertKinds)[number];38 readonly name: string;39 // One numeric column named `value`, and no time filter: the alert's40 // Automatic time range is its evaluation window.41 readonly query: string;42 readonly window: Duration.Duration;43 readonly detection: Detection;44}4546// What the apps log at error level when a sandbox job's container never47// answered: the platform when a job comes back blocked, and the sandbox when48// a Checker can't be reached. `alerts.test.ts` holds each to its source.49export const CONTAINER_FAILURES = [50 "sandbox job blocked",51 "the Checker could not be reached",52] as const;5354// The metrics dataset's layout, as the platform's writer55// (`packages/project/src/metrics/binding.ts`) lays it out: its first blob is56// the point's kind, `Refused` for one refusal. `alerts.test.ts` holds it to57// the writer.58export const REFUSED = "blob1 = 'Refused'";5960const within = (column: string, values: readonly string[]) =>61 `${column} IN (${values.map(quoted).join(", ")})`;6263export const alerts = (stage: Stage, account: string): readonly Alert[] => {64 const { metrics, platform, sandbox } = resources(stage);65 // A custom alert's SQL names its account. Smoke's names none: the SQL API66 // refuses a query that names one beside the request's own scope.67 const scoped = `accountTag = ${quoted(account)}`;6869 const failed = CONTAINER_FAILURES.map(70 (line) => `message LIKE ${quoted(`%${line}%`)}`71 ).join(" OR ");7273 return [74 ...workersOf(stage).map((worker): Alert => ({75 detection: Detection.Threshold({ atLeast: 5 }),76 kind: "errors",77 name: `${worker} errors`,78 query: `SELECT count() AS value FROM logs.workersLogs WHERE ${scoped} AND scriptName = ${quoted(worker)} AND ${ERRORED}`,79 window: Duration.minutes(15),80 })),81 {82 detection: Detection.Spike({83 baseline: Duration.hours(2),84 minimum: 3,85 sensitivity: 3,86 }),87 kind: "issue spike",88 name: `${stage} issue spike`,89 query: `SELECT count() AS value FROM logs.issues WHERE ${scoped} AND ${within("scriptName", workersOf(stage))}`,90 window: Duration.minutes(10),91 },92 {93 detection: Detection.Threshold({ atLeast: 3 }),94 kind: "container failures",95 name: `${stage} container failures`,96 query: `SELECT count() AS value FROM logs.workersLogs WHERE ${scoped} AND ${within("scriptName", [platform, sandbox])} AND level = 'error' AND (${failed})`,97 window: Duration.minutes(30),98 },99 {100 detection: Detection.Spike({101 baseline: Duration.hours(6),102 minimum: 5,103 sensitivity: 3,104 }),105 kind: "refusal spike",106 name: `${stage} refusal spike`,107 query: `SELECT count() AS value FROM events.analyticsEngine."${metrics}" WHERE ${scoped} AND ${REFUSED}`,108 window: Duration.minutes(15),109 },110 ];111};112113const detected = ({ detection, window }: Alert) =>114 Detection.$match(detection, {115 Spike: ({ baseline, minimum, sensitivity }) =>116 `anomaly detection on spikes, evaluation window ${Duration.format(window)}, baseline window ${Duration.format(baseline)}, sensitivity ${sensitivity}, minimum event count ${minimum}`,117 Threshold: ({ atLeast }) =>118 `threshold, value >= ${atLeast}, evaluation window ${Duration.format(window)}`,119 });120121// The destination is named, never shown: `addressed` says whether infra's122// env sets it.123export const alertLines = (124 stage: Stage,125 all: readonly Alert[],126 addressed: boolean127): readonly string[] => [128 `bootstrap ${stage}: make these ${all.length} alerts by hand, as Custom Alerts in the dashboard: no API takes a custom alert's query yet (README, Alerts)`,129 `bootstrap ${stage}: each is custom SQL with an Automatic time range, sent to ${130 addressed131 ? "ALERT_EMAIL's address"132 : "ALERT_EMAIL's address, which infra/.env.local does not set yet"133 }`,134 ...all.flatMap((alert) => [135 ` ${alert.name}: ${detected(alert)}`,136 ` ${alert.query}`,137 ]),138];