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 { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Predicate from "effect/Predicate"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | const TypeId = "Cloudflare.Alerting.Silence" as const; |
| 15 | type TypeId = typeof TypeId; |
| 16 | |
| 17 | export interface SilenceProps { |
| 18 | /** |
| 19 | * The notification policy to silence. References a |
| 20 | * {@link NotificationPolicy} id. Changing the policy triggers a |
| 21 | * replacement — the silence update API cannot move a silence to a |
| 22 | * different policy. |
| 23 | */ |
| 24 | policyId: string; |
| 25 | /** |
| 26 | * When the silence window starts, as an RFC3339/ISO8601 timestamp (e.g. |
| 27 | * `2026-07-01T00:00:00Z`). Must be within 90 days of now — Cloudflare |
| 28 | * rejects windows further out with `InvalidSilence`. Pass an explicit, |
| 29 | * deterministic value; the provider never derives times from the clock. |
| 30 | * Mutable — updated in place. |
| 31 | */ |
| 32 | startTime: string; |
| 33 | /** |
| 34 | * When the silence window ends, as an RFC3339/ISO8601 timestamp. Must be |
| 35 | * after `startTime` (`InvalidSilence` otherwise). |
| 36 | * Mutable — updated in place. |
| 37 | */ |
| 38 | endTime: string; |
| 39 | } |
| 40 | |
| 41 | export interface SilenceAttributes { |
| 42 | /** Cloudflare-assigned silence id. */ |
| 43 | silenceId: string; |
| 44 | /** Account that owns this silence. */ |
| 45 | accountId: string; |
| 46 | /** The notification policy this silence applies to. */ |
| 47 | policyId: string; |
| 48 | /** When the silence window starts (ISO8601). */ |
| 49 | startTime: string; |
| 50 | /** When the silence window ends (ISO8601). */ |
| 51 | endTime: string; |
| 52 | /** ISO8601 creation timestamp. */ |
| 53 | createdAt: string | undefined; |
| 54 | /** ISO8601 last-modified timestamp. */ |
| 55 | updatedAt: string | undefined; |
| 56 | } |
| 57 | |
| 58 | export type Silence = Resource<TypeId, SilenceProps, SilenceAttributes, never, Providers>; |
| 59 | |
| 60 | /** |
| 61 | * A Cloudflare Notifications silence window. |
| 62 | * |
| 63 | * A silence suppresses notification dispatches for a |
| 64 | * {@link NotificationPolicy} between `startTime` and `endTime` — e.g. |
| 65 | * during a planned maintenance window. The window times are explicit |
| 66 | * ISO8601 props supplied by you; Cloudflare requires the start time to be |
| 67 | * within 90 days of now. |
| 68 | * |
| 69 | * Note: the create API returns no id, so the provider resolves the created |
| 70 | * silence by listing and matching on `(policyId, startTime, endTime)`. Two |
| 71 | * silences sharing the exact same policy and window are indistinguishable. |
| 72 | * ### Creating a silence |
| 73 | * **Example:** Silence a policy during a maintenance window |
| 74 | * ```typescript |
| 75 | * const policy = yield* Cloudflare.Alerting.NotificationPolicy("SslAlerts", { |
| 76 | * alertType: "universal_ssl_event_type", |
| 77 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 78 | * }); |
| 79 | * |
| 80 | * yield* Cloudflare.Alerting.Silence("MaintenanceWindow", { |
| 81 | * policyId: policy.policyId, |
| 82 | * startTime: "2026-07-01T00:00:00Z", |
| 83 | * endTime: "2026-07-01T04:00:00Z", |
| 84 | * }); |
| 85 | * ``` |
| 86 | * |
| 87 | * ### Updating the window |
| 88 | * **Example:** Extend the silence end time in place |
| 89 | * Window times are mutable — changing them updates the existing silence. |
| 90 | * ```typescript |
| 91 | * yield* Cloudflare.Alerting.Silence("MaintenanceWindow", { |
| 92 | * policyId: policy.policyId, |
| 93 | * startTime: "2026-07-01T00:00:00Z", |
| 94 | * endTime: "2026-07-01T08:00:00Z", |
| 95 | * }); |
| 96 | * ``` |
| 97 | * |
| 98 | * @see https://developers.cloudflare.com/notifications/ |
| 99 | * |
| 100 | * @resource |
| 101 | * @product Alerting |
| 102 | * @category Observability & Analytics |
| 103 | */ |
| 104 | export const Silence = Resource<Silence>(TypeId); |
| 105 | |
| 106 | /** |
| 107 | * Returns true if the given value is a Silence resource. |
| 108 | */ |
| 109 | export const isSilence = (value: unknown): value is Silence => |
| 110 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 111 | |
| 112 | export const SilenceProvider = () => |
| 113 | Provider.succeed(Silence, { |
| 114 | stables: ["silenceId", "accountId", "policyId", "createdAt"], |
| 115 | |
| 116 | // Silences are account-scoped; listSilences enumerates every silence in |
| 117 | // the account and the response carries the full attribute shape, so no |
| 118 | // per-item hydration is needed. |
| 119 | list: Effect.fn(function* () { |
| 120 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 121 | return yield* alerting.listSilences.pages({ accountId }).pipe( |
| 122 | Stream.runCollect, |
| 123 | Effect.map((chunk) => |
| 124 | Array.from(chunk).flatMap((page) => |
| 125 | (page.result ?? []) |
| 126 | .map(narrowSilence) |
| 127 | .filter((s): s is ObservedSilence => s !== undefined) |
| 128 | .map((s) => toSilenceAttributes(s, accountId)), |
| 129 | ), |
| 130 | ), |
| 131 | ); |
| 132 | }), |
| 133 | |
| 134 | diff: Effect.fn(function* ({ olds = {}, news, output }) { |
| 135 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 136 | if ((output?.accountId ?? accountId) !== accountId) { |
| 137 | return { action: "replace" } as const; |
| 138 | } |
| 139 | // The silence update body carries no policyId — a silence cannot be |
| 140 | // moved to a different policy, so a policy change is a replacement. |
| 141 | // policyId is Input<string>; compare only once both are concrete. |
| 142 | const o = olds as SilenceProps; |
| 143 | const n = news as SilenceProps; |
| 144 | const oldPolicyId = |
| 145 | output?.policyId ?? (typeof o.policyId === "string" ? o.policyId : undefined); |
| 146 | if ( |
| 147 | oldPolicyId !== undefined && |
| 148 | typeof n.policyId === "string" && |
| 149 | oldPolicyId !== n.policyId |
| 150 | ) { |
| 151 | return { action: "replace" } as const; |
| 152 | } |
| 153 | }), |
| 154 | |
| 155 | read: Effect.fn(function* ({ output, olds }) { |
| 156 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 157 | const acct = output?.accountId ?? accountId; |
| 158 | |
| 159 | // Owned path: refresh by the persisted silence id. |
| 160 | if (output?.silenceId) { |
| 161 | const observed = yield* observeSilence(acct, output.silenceId); |
| 162 | if (observed) return toSilenceAttributes(observed, acct); |
| 163 | return undefined; |
| 164 | } |
| 165 | |
| 166 | // Cold read: no persisted id (state-persistence failure) — match on |
| 167 | // the silence identity `(policyId, startTime, endTime)`. Silences |
| 168 | // carry no ownership markers, so we cannot prove we created a match: |
| 169 | // brand it `Unowned` so the engine gates takeover behind adoption. |
| 170 | const o = olds as SilenceProps | undefined; |
| 171 | const policyId = typeof o?.policyId === "string" ? o.policyId : undefined; |
| 172 | if (policyId && o?.startTime && o?.endTime) { |
| 173 | const match = yield* findSilence(acct, policyId, o.startTime, o.endTime); |
| 174 | if (match) return Unowned(toSilenceAttributes(match, acct)); |
| 175 | } |
| 176 | return undefined; |
| 177 | }), |
| 178 | |
| 179 | reconcile: Effect.fn(function* ({ news, output }) { |
| 180 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 181 | // Inputs are resolved to concrete values by the engine before |
| 182 | // reconcile runs. |
| 183 | const policyId = news.policyId as string; |
| 184 | |
| 185 | // 1. Observe — by cached id first, then by silence identity. |
| 186 | let observed: ObservedSilence | undefined; |
| 187 | if (output?.silenceId) { |
| 188 | observed = yield* observeSilence(accountId, output.silenceId); |
| 189 | } |
| 190 | if (!observed) { |
| 191 | observed = yield* findSilence(accountId, policyId, news.startTime, news.endTime); |
| 192 | } |
| 193 | |
| 194 | // 2. Ensure — create when missing. The create response carries no |
| 195 | // id, so resolve the created silence by listing and matching on |
| 196 | // `(policyId, startTime, endTime)` with a short bounded retry for |
| 197 | // read-after-write consistency. A concurrent create of the same |
| 198 | // window surfaces as `SilenceAlreadyExists`: converge by reusing |
| 199 | // the silence that won the race. |
| 200 | if (!observed) { |
| 201 | yield* alerting |
| 202 | .createSilence({ |
| 203 | accountId, |
| 204 | body: [ |
| 205 | { |
| 206 | policyId, |
| 207 | startTime: news.startTime, |
| 208 | endTime: news.endTime, |
| 209 | }, |
| 210 | ], |
| 211 | }) |
| 212 | .pipe( |
| 213 | Effect.catchTag("SilenceAlreadyExists", (error) => |
| 214 | findSilence(accountId, policyId, news.startTime, news.endTime).pipe( |
| 215 | Effect.flatMap((existing) => (existing ? Effect.void : Effect.fail(error))), |
| 216 | ), |
| 217 | ), |
| 218 | ); |
| 219 | observed = yield* findSilence(accountId, policyId, news.startTime, news.endTime).pipe( |
| 220 | Effect.flatMap((found) => |
| 221 | found ? Effect.succeed(found) : Effect.fail(new SilencePending()), |
| 222 | ), |
| 223 | Effect.retry({ |
| 224 | while: (e) => e._tag === "SilencePending", |
| 225 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]), |
| 226 | }), |
| 227 | ); |
| 228 | return toSilenceAttributes(observed, accountId); |
| 229 | } |
| 230 | |
| 231 | // 3. Sync — diff the observed window against the desired one |
| 232 | // (instant-equal, so `00:00:00Z` matches `00:00:00+00:00`) and |
| 233 | // PUT only on drift. |
| 234 | if ( |
| 235 | !sameInstant(observed.startTime, news.startTime) || |
| 236 | !sameInstant(observed.endTime, news.endTime) |
| 237 | ) { |
| 238 | yield* alerting.updateSilence({ |
| 239 | accountId, |
| 240 | body: [ |
| 241 | { |
| 242 | id: observed.id, |
| 243 | startTime: news.startTime, |
| 244 | endTime: news.endTime, |
| 245 | }, |
| 246 | ], |
| 247 | }); |
| 248 | const fresh = yield* observeSilence(accountId, observed.id); |
| 249 | return toSilenceAttributes(fresh ?? observed, accountId); |
| 250 | } |
| 251 | |
| 252 | // 4. Return. |
| 253 | return toSilenceAttributes(observed, accountId); |
| 254 | }), |
| 255 | |
| 256 | delete: Effect.fn(function* ({ output }) { |
| 257 | yield* alerting |
| 258 | .deleteSilence({ |
| 259 | accountId: output.accountId, |
| 260 | silenceId: output.silenceId, |
| 261 | }) |
| 262 | .pipe(Effect.catchTag("SilenceNotFound", () => Effect.void)); |
| 263 | }), |
| 264 | }); |
| 265 | |
| 266 | /** Created silence not yet visible in the list — retried internally. */ |
| 267 | class SilencePending extends Data.TaggedError("SilencePending") {} |
| 268 | |
| 269 | interface ObservedSilence { |
| 270 | readonly id: string; |
| 271 | readonly policyId?: string; |
| 272 | readonly startTime?: string; |
| 273 | readonly endTime?: string; |
| 274 | readonly createdAt?: string; |
| 275 | readonly updatedAt?: string; |
| 276 | } |
| 277 | |
| 278 | const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v); |
| 279 | |
| 280 | const narrowSilence = (raw: { |
| 281 | id?: string | null; |
| 282 | policyId?: string | null; |
| 283 | startTime?: string | null; |
| 284 | endTime?: string | null; |
| 285 | createdAt?: string | null; |
| 286 | updatedAt?: string | null; |
| 287 | }): ObservedSilence | undefined => |
| 288 | raw.id == null |
| 289 | ? undefined |
| 290 | : { |
| 291 | id: raw.id, |
| 292 | policyId: undef(raw.policyId), |
| 293 | startTime: undef(raw.startTime), |
| 294 | endTime: undef(raw.endTime), |
| 295 | createdAt: undef(raw.createdAt), |
| 296 | updatedAt: undef(raw.updatedAt), |
| 297 | }; |
| 298 | |
| 299 | const observeSilence = (accountId: string, silenceId: string) => |
| 300 | alerting.getSilence({ accountId, silenceId }).pipe( |
| 301 | Effect.map((s) => narrowSilence({ ...s, id: s.id ?? silenceId })), |
| 302 | Effect.catchTag("SilenceNotFound", () => Effect.undefined), |
| 303 | ); |
| 304 | |
| 305 | /** |
| 306 | * Locate a silence by its identity `(policyId, startTime, endTime)`. |
| 307 | * Timestamps are compared as instants so formatting differences (trailing |
| 308 | * `Z` vs `+00:00`, fractional seconds) don't defeat the match. |
| 309 | */ |
| 310 | const findSilence = (accountId: string, policyId: string, startTime: string, endTime: string) => |
| 311 | alerting.listSilences.items({ accountId }).pipe( |
| 312 | Stream.filter( |
| 313 | (s) => |
| 314 | s.id != null && |
| 315 | s.policyId === policyId && |
| 316 | sameInstant(undef(s.startTime), startTime) && |
| 317 | sameInstant(undef(s.endTime), endTime), |
| 318 | ), |
| 319 | Stream.runHead, |
| 320 | Effect.map(Option.getOrUndefined), |
| 321 | Effect.map((s) => (s === undefined ? undefined : narrowSilence(s))), |
| 322 | ); |
| 323 | |
| 324 | /** Compare two ISO8601 timestamps by the instant they denote. */ |
| 325 | const sameInstant = (a: string | undefined, b: string | undefined): boolean => { |
| 326 | if (a === undefined || b === undefined) return a === b; |
| 327 | const ta = Date.parse(a); |
| 328 | const tb = Date.parse(b); |
| 329 | if (Number.isNaN(ta) || Number.isNaN(tb)) return a === b; |
| 330 | return ta === tb; |
| 331 | }; |
| 332 | |
| 333 | const toSilenceAttributes = (observed: ObservedSilence, accountId: string): SilenceAttributes => ({ |
| 334 | silenceId: observed.id, |
| 335 | accountId, |
| 336 | policyId: observed.policyId ?? "", |
| 337 | startTime: observed.startTime ?? "", |
| 338 | endTime: observed.endTime ?? "", |
| 339 | createdAt: observed.createdAt, |
| 340 | updatedAt: observed.updatedAt, |
| 341 | }); |