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 | createPolicyName, |
| 12 | findPolicyByName, |
| 13 | narrowPolicy, |
| 14 | type ObservedPolicy, |
| 15 | boundMechanisms, |
| 16 | type NotificationPolicyBinding, |
| 17 | observePolicy, |
| 18 | type PolicyBody, |
| 19 | policyEqualsObserved, |
| 20 | } from "./internal.ts"; |
| 21 | |
| 22 | export class NotificationPolicyUnexpectedResponse extends Data.TaggedError( |
| 23 | "NotificationPolicyUnexpectedResponse", |
| 24 | )<{ |
| 25 | readonly message: string; |
| 26 | readonly cause?: unknown; |
| 27 | }> {} |
| 28 | |
| 29 | export type { NotificationPolicyBinding } from "./internal.ts"; |
| 30 | |
| 31 | const TypeId = "Cloudflare.Alerting.NotificationPolicy" as const; |
| 32 | type TypeId = typeof TypeId; |
| 33 | |
| 34 | /** |
| 35 | * The event that triggers a notification dispatch. The full catalog (and |
| 36 | * which types your plan can use) is returned by the available-alerts |
| 37 | * endpoint. The union is kept open so new Cloudflare alert types aren't |
| 38 | * blocked by stale types. |
| 39 | */ |
| 40 | export type AlertType = alerting.CreatePolicyRequest["alertType"]; |
| 41 | |
| 42 | /** |
| 43 | * Optional filters restricting which events trigger the policy. Which keys |
| 44 | * are valid (or required — Cloudflare returns `FiltersRequired`) depends on |
| 45 | * the alert type. |
| 46 | */ |
| 47 | export type NotificationPolicyFilters = alerting.CreatePolicyRequest["filters"]; |
| 48 | |
| 49 | /** |
| 50 | * Destinations notified when the policy fires. At least one mechanism is |
| 51 | * required (Cloudflare returns `MechanismRequired` otherwise). Email ids |
| 52 | * are email addresses; webhook/pagerduty ids reference destination UUIDs. |
| 53 | */ |
| 54 | export interface NotificationPolicyMechanisms { |
| 55 | /** Email destinations — `id` is the recipient email address. */ |
| 56 | email?: ReadonlyArray<{ id: string }>; |
| 57 | /** Webhook destinations — `id` references a {@link NotificationWebhook}. */ |
| 58 | webhooks?: ReadonlyArray<{ id: string }>; |
| 59 | /** PagerDuty destinations — `id` references a connected PagerDuty service. */ |
| 60 | pagerduty?: ReadonlyArray<{ id: string }>; |
| 61 | } |
| 62 | |
| 63 | export interface NotificationPolicyProps { |
| 64 | /** |
| 65 | * Name of the policy. If omitted, a unique name is generated. |
| 66 | * Mutable — renames are applied in place. |
| 67 | * @default ${app}-${id}-${stage}-${suffix} |
| 68 | */ |
| 69 | name?: string; |
| 70 | /** |
| 71 | * The event that triggers a notification dispatch (e.g. |
| 72 | * `universal_ssl_event_type`, `billing_usage_alert`). Changing the alert |
| 73 | * type triggers a replacement: the valid filter set depends on the alert |
| 74 | * type, so a policy alerting on a different event is a different policy. |
| 75 | */ |
| 76 | alertType: AlertType; |
| 77 | /** |
| 78 | * Whether the policy is enabled. |
| 79 | * @default true |
| 80 | */ |
| 81 | enabled?: boolean; |
| 82 | /** |
| 83 | * Optional human-readable description of the policy. |
| 84 | */ |
| 85 | description?: string; |
| 86 | /** |
| 87 | * How often to re-alert from the same incident (e.g. `"30m"`). Not |
| 88 | * supported by all alert types. |
| 89 | */ |
| 90 | alertInterval?: string; |
| 91 | /** |
| 92 | * Destinations notified when the policy fires. At least one destination is |
| 93 | * required, either declared here or bound by a runtime that consumes the |
| 94 | * policy's notifications (`Cloudflare.Alerting.consumeNotifications`). |
| 95 | */ |
| 96 | mechanisms?: NotificationPolicyMechanisms; |
| 97 | /** |
| 98 | * Optional filters restricting which events trigger the policy. Some |
| 99 | * alert types require specific filters (`FiltersRequired`). |
| 100 | */ |
| 101 | filters?: NotificationPolicyFilters; |
| 102 | } |
| 103 | |
| 104 | export interface NotificationPolicyAttributes { |
| 105 | /** Cloudflare-assigned notification policy UUID. */ |
| 106 | policyId: string; |
| 107 | /** Account that owns this policy. */ |
| 108 | accountId: string; |
| 109 | /** Name of the policy. */ |
| 110 | name: string; |
| 111 | /** The alert type the policy fires on. */ |
| 112 | alertType: AlertType; |
| 113 | /** Whether the policy is enabled. */ |
| 114 | enabled: boolean; |
| 115 | /** ISO8601 creation timestamp. */ |
| 116 | created: string | undefined; |
| 117 | /** ISO8601 last-modified timestamp. */ |
| 118 | modified: string | undefined; |
| 119 | } |
| 120 | |
| 121 | export type NotificationPolicy = Resource< |
| 122 | TypeId, |
| 123 | NotificationPolicyProps, |
| 124 | NotificationPolicyAttributes, |
| 125 | NotificationPolicyBinding, |
| 126 | Providers |
| 127 | >; |
| 128 | |
| 129 | /** |
| 130 | * A Cloudflare Notifications policy. |
| 131 | * |
| 132 | * A notification policy connects an alert type (the event Cloudflare |
| 133 | * watches for) to one or more destinations — email addresses, webhook |
| 134 | * destinations, or PagerDuty services — optionally narrowed by filters. |
| 135 | * ### Creating a policy |
| 136 | * **Example:** Email notifications for Universal SSL events |
| 137 | * ```typescript |
| 138 | * yield* Cloudflare.Alerting.NotificationPolicy("SslAlerts", { |
| 139 | * alertType: "universal_ssl_event_type", |
| 140 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 141 | * }); |
| 142 | * ``` |
| 143 | * |
| 144 | * **Example:** Disabled policy with a description |
| 145 | * ```typescript |
| 146 | * yield* Cloudflare.Alerting.NotificationPolicy("SslAlerts", { |
| 147 | * alertType: "universal_ssl_event_type", |
| 148 | * enabled: false, |
| 149 | * description: "Paused during migration", |
| 150 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 151 | * }); |
| 152 | * ``` |
| 153 | * |
| 154 | * ### Webhook destinations |
| 155 | * **Example:** Dispatch to a webhook destination |
| 156 | * ```typescript |
| 157 | * const webhook = yield* Cloudflare.Alerting.NotificationWebhook("AlertsHook", { |
| 158 | * url: "https://alerts.example.com/cf", |
| 159 | * }); |
| 160 | * |
| 161 | * yield* Cloudflare.Alerting.NotificationPolicy("SslAlerts", { |
| 162 | * alertType: "universal_ssl_event_type", |
| 163 | * mechanisms: { webhooks: [{ id: webhook.webhookId }] }, |
| 164 | * }); |
| 165 | * ``` |
| 166 | * |
| 167 | * ### Filters |
| 168 | * **Example:** Health check alerts for specific zones |
| 169 | * ```typescript |
| 170 | * yield* Cloudflare.Alerting.NotificationPolicy("HealthAlerts", { |
| 171 | * alertType: "health_check_status_notification", |
| 172 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 173 | * filters: { |
| 174 | * healthCheckId: [healthCheckId], |
| 175 | * newHealth: ["Unhealthy"], |
| 176 | * }, |
| 177 | * }); |
| 178 | * ``` |
| 179 | * |
| 180 | * ### Handling notifications in code |
| 181 | * **Example:** Run an Effect for each notification |
| 182 | * `consumeNotifications` adds a webhook destination at the consuming |
| 183 | * runtime, so the policy needs no `mechanisms`. |
| 184 | * ```typescript |
| 185 | * const policy = yield* Cloudflare.Alerting.NotificationPolicy("SslAlerts", { |
| 186 | * alertType: "universal_ssl_event_type", |
| 187 | * }); |
| 188 | * |
| 189 | * // in a Worker's Construction phase, with NotificationEventSourceLive provided |
| 190 | * yield* Cloudflare.Alerting.consumeNotifications(policy, (notification) => |
| 191 | * Effect.log(notification.text), |
| 192 | * ); |
| 193 | * ``` |
| 194 | * |
| 195 | * ### SQL custom alerts <!-- api-prose --> |
| 196 | * Alerts on a SQL query (Cloudflare's `custom_analytics` alert type) have |
| 197 | * their own resource with typed triggers: `Cloudflare.Alerting.CustomAlert`. |
| 198 | * |
| 199 | * ### Workers Issues notifications |
| 200 | * **Example:** Notify on new Worker issues |
| 201 | * ```typescript |
| 202 | * const policy = yield* Cloudflare.Alerting.NotificationPolicy("IssuePolicy", { |
| 203 | * alertType: "workers_observability_real_time_issue", |
| 204 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 205 | * }); |
| 206 | * |
| 207 | * yield* Cloudflare.Workers.IssueAutomation("IssueAlerts", { |
| 208 | * policyId: policy.policyId, |
| 209 | * afterOccurrences: 5, |
| 210 | * }); |
| 211 | * ``` |
| 212 | * |
| 213 | * @see https://developers.cloudflare.com/notifications/ |
| 214 | * |
| 215 | * @resource |
| 216 | * @product Alerting |
| 217 | * @category Observability & Analytics |
| 218 | */ |
| 219 | export const NotificationPolicy = Resource<NotificationPolicy>(TypeId); |
| 220 | |
| 221 | /** |
| 222 | * Returns true if the given value is a NotificationPolicy resource. |
| 223 | */ |
| 224 | export const isNotificationPolicy = (value: unknown): value is NotificationPolicy => |
| 225 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 226 | |
| 227 | export const NotificationPolicyProvider = () => |
| 228 | Provider.succeed(NotificationPolicy, { |
| 229 | stables: ["policyId", "accountId", "alertType"], |
| 230 | |
| 231 | // Account-scoped collection: exhaustively paginate the account's |
| 232 | // notification policies and hydrate each into the `read` attribute shape. |
| 233 | list: Effect.fn(function* () { |
| 234 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 235 | return yield* alerting.listPolicies.pages({ accountId }).pipe( |
| 236 | Stream.runCollect, |
| 237 | Effect.map((chunk) => |
| 238 | Array.from(chunk).flatMap((page) => |
| 239 | (page.result ?? []) |
| 240 | .map(narrowPolicy) |
| 241 | .filter((p): p is ObservedPolicy => p !== undefined) |
| 242 | .map((p) => toPolicyAttributes(p, accountId)), |
| 243 | ), |
| 244 | ), |
| 245 | ); |
| 246 | }), |
| 247 | |
| 248 | diff: Effect.fn(function* ({ olds = {}, news, output }) { |
| 249 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 250 | if ((output?.accountId ?? accountId) !== accountId) { |
| 251 | return { action: "replace" } as const; |
| 252 | } |
| 253 | // The valid filter/mechanism shape depends on the alert type — a |
| 254 | // policy alerting on a different event is a different policy. |
| 255 | // `alertType` is a plain string prop, statically knowable here. |
| 256 | const o = olds as NotificationPolicyProps; |
| 257 | const n = news as NotificationPolicyProps; |
| 258 | const oldAlertType = output?.alertType ?? o.alertType; |
| 259 | if (oldAlertType !== undefined && oldAlertType !== n.alertType) { |
| 260 | return { action: "replace" } as const; |
| 261 | } |
| 262 | }), |
| 263 | |
| 264 | read: Effect.fn(function* ({ id, output, olds }) { |
| 265 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 266 | const acct = output?.accountId ?? accountId; |
| 267 | |
| 268 | // Owned path: refresh by the persisted policy id. |
| 269 | if (output?.policyId) { |
| 270 | const observed = yield* observePolicy(acct, output.policyId); |
| 271 | if (observed) return toPolicyAttributes(observed, acct); |
| 272 | return undefined; |
| 273 | } |
| 274 | |
| 275 | // Cold read: no persisted id (state-persistence failure) — find the |
| 276 | // deterministic physical name in the account's policy list. |
| 277 | const name = yield* createPolicyName(id, olds?.name); |
| 278 | const match = yield* findPolicyByName(acct, name); |
| 279 | if (match) return toPolicyAttributes(match, acct); |
| 280 | return undefined; |
| 281 | }), |
| 282 | |
| 283 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 284 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 285 | const name = yield* createPolicyName(id, news.name); |
| 286 | const desired = buildPolicyBody(name, news, bindings); |
| 287 | |
| 288 | // 1. Observe — by cached id first, then by deterministic name. |
| 289 | let observed: ObservedPolicy | undefined; |
| 290 | if (output?.policyId) { |
| 291 | observed = yield* observePolicy(accountId, output.policyId); |
| 292 | } |
| 293 | if (!observed) { |
| 294 | observed = yield* findPolicyByName(accountId, name); |
| 295 | } |
| 296 | |
| 297 | // 2. Ensure — create when missing. `createPolicy` only returns the |
| 298 | // new id; re-read for the full attribute set. |
| 299 | if (!observed) { |
| 300 | const created = yield* alerting.createPolicy({ |
| 301 | accountId, |
| 302 | ...desired, |
| 303 | }); |
| 304 | if (!created.id) { |
| 305 | return yield* new NotificationPolicyUnexpectedResponse({ |
| 306 | message: "Cloudflare did not return an id for the created notification policy", |
| 307 | }); |
| 308 | } |
| 309 | const fresh = yield* observePolicy(accountId, created.id); |
| 310 | return toPolicyAttributes(fresh ?? { id: created.id }, accountId); |
| 311 | } |
| 312 | |
| 313 | // 3. Sync — PUT the full desired body when any mutable aspect |
| 314 | // drifts from the observed cloud state. |
| 315 | if (!policyEqualsObserved(desired, observed)) { |
| 316 | yield* alerting.updatePolicy({ |
| 317 | accountId, |
| 318 | policyId: observed.id, |
| 319 | ...desired, |
| 320 | }); |
| 321 | const fresh = yield* observePolicy(accountId, observed.id); |
| 322 | return toPolicyAttributes(fresh ?? observed, accountId); |
| 323 | } |
| 324 | |
| 325 | // 4. Return. |
| 326 | return toPolicyAttributes(observed, accountId); |
| 327 | }), |
| 328 | |
| 329 | delete: Effect.fn(function* ({ output }) { |
| 330 | yield* alerting |
| 331 | .deletePolicy({ |
| 332 | accountId: output.accountId, |
| 333 | policyId: output.policyId, |
| 334 | }) |
| 335 | .pipe(Effect.catchTag("PolicyNotFound", () => Effect.void)); |
| 336 | }), |
| 337 | }); |
| 338 | |
| 339 | const toPolicyAttributes = ( |
| 340 | observed: ObservedPolicy, |
| 341 | accountId: string, |
| 342 | ): NotificationPolicyAttributes => ({ |
| 343 | policyId: observed.id, |
| 344 | accountId, |
| 345 | name: observed.name ?? "", |
| 346 | alertType: (observed.alertType ?? "universal_ssl_event_type") as AlertType, |
| 347 | enabled: observed.enabled ?? true, |
| 348 | created: observed.created, |
| 349 | modified: observed.modified, |
| 350 | }); |
| 351 | |
| 352 | const buildPolicyBody = ( |
| 353 | name: string, |
| 354 | news: NotificationPolicyProps, |
| 355 | bindings: ReadonlyArray<{ data: NotificationPolicyBinding }>, |
| 356 | ): PolicyBody => ({ |
| 357 | name, |
| 358 | alertType: news.alertType, |
| 359 | enabled: news.enabled ?? true, |
| 360 | description: news.description, |
| 361 | alertInterval: news.alertInterval, |
| 362 | // `Input<string>` ids are resolved to concrete strings by the engine |
| 363 | // before reconcile runs; bound webhooks extend the declared ones. |
| 364 | mechanisms: boundMechanisms(news.mechanisms, bindings), |
| 365 | filters: news.filters, |
| 366 | }); |
| 367 | |
| 368 | /** |
| 369 | * Compare the desired policy body against observed cloud state. |
| 370 | * `mechanisms`/`filters` are compared structurally with `null`/`undefined` |
| 371 | * dropped and object keys sorted, since Cloudflare echoes optional fields |
| 372 | * as `null`. |
| 373 | */ |