The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as workers from "@distilled.cloud/cloudflare/workers"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Predicate from "effect/Predicate"; |
| 8 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | |
| 11 | const TypeId = "Cloudflare.Workers.IssueAutomation" as const; |
| 12 | type TypeId = typeof TypeId; |
| 13 | |
| 14 | /** |
| 15 | * What makes an automation notify: an issue reaching an occurrence count, |
| 16 | * or an issue recurring after a period of inactivity. |
| 17 | */ |
| 18 | export type IssueAutomationTriggerType = workers.ObservabilityIssueAutomationTriggerType; |
| 19 | |
| 20 | export interface IssueAutomationProps { |
| 21 | /** |
| 22 | * Name of the automation. If omitted, a unique name is generated. |
| 23 | * Mutable — renames are applied in place. |
| 24 | * @default ${app}-${id}-${stage}-${suffix} |
| 25 | */ |
| 26 | name?: string; |
| 27 | /** |
| 28 | * Id of the notification policy to notify. Use a |
| 29 | * `Cloudflare.Alerting.NotificationPolicy` with alert type |
| 30 | * `workers_observability_real_time_issue`; its mechanisms decide where |
| 31 | * the notification goes (email, webhook, PagerDuty). Cloudflare does not |
| 32 | * check that the policy exists. |
| 33 | */ |
| 34 | policyId: string; |
| 35 | /** |
| 36 | * Limit the automation to one Worker, by script name. Omit to cover |
| 37 | * every Worker in the account. |
| 38 | */ |
| 39 | service?: string; |
| 40 | /** |
| 41 | * Notify once an issue has occurred this many times. Set exactly one of |
| 42 | * `afterOccurrences` and `afterInactivitySeconds`. |
| 43 | */ |
| 44 | afterOccurrences?: number; |
| 45 | /** |
| 46 | * Notify when an issue occurs again after this many seconds without |
| 47 | * occurrences (3600 to 31536000). Set exactly one of `afterOccurrences` |
| 48 | * and `afterInactivitySeconds`. |
| 49 | */ |
| 50 | afterInactivitySeconds?: number; |
| 51 | /** |
| 52 | * Whether the automation is enabled. |
| 53 | * @default true |
| 54 | */ |
| 55 | enabled?: boolean; |
| 56 | } |
| 57 | |
| 58 | export interface IssueAutomationAttributes { |
| 59 | /** Cloudflare-assigned automation id. */ |
| 60 | automationId: string; |
| 61 | /** Account that owns this automation. */ |
| 62 | accountId: string; |
| 63 | /** Name of the automation. */ |
| 64 | name: string; |
| 65 | /** Id of the notification policy the automation notifies. */ |
| 66 | policyId: string; |
| 67 | /** Worker the automation is limited to, if any. */ |
| 68 | service: string | undefined; |
| 69 | /** `service` when limited to one Worker, otherwise `account`. */ |
| 70 | scope: workers.ObservabilityIssueAutomationScope; |
| 71 | /** What makes the automation notify. */ |
| 72 | triggerType: IssueAutomationTriggerType; |
| 73 | /** Occurrence count for an `occurrence_threshold` trigger. */ |
| 74 | afterOccurrences: number | undefined; |
| 75 | /** Inactivity period for a `recurrence_after_inactivity` trigger. */ |
| 76 | afterInactivitySeconds: number | undefined; |
| 77 | /** Whether the automation is enabled. */ |
| 78 | enabled: boolean; |
| 79 | /** Revision, incremented by Cloudflare on every update. */ |
| 80 | revision: number; |
| 81 | } |
| 82 | |
| 83 | export type IssueAutomation = Resource< |
| 84 | TypeId, |
| 85 | IssueAutomationProps, |
| 86 | IssueAutomationAttributes, |
| 87 | never, |
| 88 | Providers |
| 89 | >; |
| 90 | |
| 91 | /** |
| 92 | * A Workers Issues automation. |
| 93 | * |
| 94 | * [Workers Issues](https://developers.cloudflare.com/workers/observability/issues/) |
| 95 | * groups a Worker's errors into issues. An automation sends a notification |
| 96 | * when an issue reaches an occurrence count, or comes back after a quiet |
| 97 | * period. It notifies a `workers_observability_real_time_issue` |
| 98 | * notification policy, which decides where the notification goes. |
| 99 | * |
| 100 | * Automations carry no ownership markers. When there is no prior state, |
| 101 | * `read` finds an automation by name and reports it as `Unowned`, so the |
| 102 | * engine only takes it over with `--adopt`. |
| 103 | * ### Notifying on issues |
| 104 | * **Example:** Email after five occurrences of any issue |
| 105 | * ```typescript |
| 106 | * const policy = yield* Cloudflare.Alerting.NotificationPolicy("IssuePolicy", { |
| 107 | * alertType: "workers_observability_real_time_issue", |
| 108 | * mechanisms: { email: [{ id: "ops@example.com" }] }, |
| 109 | * }); |
| 110 | * |
| 111 | * yield* Cloudflare.Workers.IssueAutomation("IssueAlerts", { |
| 112 | * policyId: policy.policyId, |
| 113 | * afterOccurrences: 5, |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * **Example:** Notify when an issue comes back after a quiet day |
| 118 | * ```typescript |
| 119 | * yield* Cloudflare.Workers.IssueAutomation("Regressions", { |
| 120 | * policyId: policy.policyId, |
| 121 | * afterInactivitySeconds: 86_400, |
| 122 | * }); |
| 123 | * ``` |
| 124 | * |
| 125 | * ### Sending issues to a webhook or agent |
| 126 | * **Example:** Post one Worker's issues to a webhook |
| 127 | * ```typescript |
| 128 | * const webhook = yield* Cloudflare.Alerting.NotificationWebhook("IssueHook", { |
| 129 | * url: "https://agent.example.com/issues", |
| 130 | * }); |
| 131 | * |
| 132 | * const policy = yield* Cloudflare.Alerting.NotificationPolicy("IssuePolicy", { |
| 133 | * alertType: "workers_observability_real_time_issue", |
| 134 | * mechanisms: { webhooks: [{ id: webhook.webhookId }] }, |
| 135 | * }); |
| 136 | * |
| 137 | * yield* Cloudflare.Workers.IssueAutomation("ApiIssues", { |
| 138 | * policyId: policy.policyId, |
| 139 | * service: worker.workerName, |
| 140 | * afterOccurrences: 1, |
| 141 | * }); |
| 142 | * ``` |
| 143 | * |
| 144 | * ### Handling issues in code |
| 145 | * **Example:** Open a GitHub issue for every new Worker issue |
| 146 | * A Worker only records issues with `observability.issues.enabled`. |
| 147 | * `consumeNotifications` points the policy at the handling Worker, so the |
| 148 | * policy declares no `mechanisms`. |
| 149 | * ```typescript |
| 150 | * const Repo = GitHub.Repository("Repo", { owner: "acme", name: "api" }); |
| 151 | * |
| 152 | * const IssuePolicy = Cloudflare.Alerting.NotificationPolicy("IssuePolicy", { |
| 153 | * alertType: "workers_observability_real_time_issue", |
| 154 | * }); |
| 155 | * |
| 156 | * class Api extends Cloudflare.Worker<Api>()( |
| 157 | * "Api", |
| 158 | * { main: import.meta.url, observability: { enabled: true, issues: { enabled: true } } }, |
| 159 | * Effect.gen(function* () { |
| 160 | * const policy = yield* IssuePolicy; |
| 161 | * const createIssue = yield* GitHub.CreateIssue(yield* Repo); |
| 162 | * yield* Cloudflare.Alerting.consumeNotifications(policy, (notification) => |
| 163 | * createIssue({ title: notification.text.split("\n")[0], body: notification.text }), |
| 164 | * ); |
| 165 | * return { fetch: Effect.succeed(HttpServerResponse.text("ok")) }; |
| 166 | * }).pipe( |
| 167 | * Effect.provide( |
| 168 | * Layer.mergeAll(Cloudflare.Alerting.NotificationEventSourceLive, GitHub.CreateIssueHttp), |
| 169 | * ), |
| 170 | * ), |
| 171 | * ) {} |
| 172 | * |
| 173 | * const Stack = Effect.gen(function* () { |
| 174 | * yield* Repo; |
| 175 | * const policy = yield* IssuePolicy; |
| 176 | * const api = yield* Api; |
| 177 | * yield* Cloudflare.Workers.IssueAutomation("ApiIssues", { |
| 178 | * policyId: policy.policyId, |
| 179 | * service: api.workerName, |
| 180 | * afterOccurrences: 1, |
| 181 | * }); |
| 182 | * }); |
| 183 | * ``` |
| 184 | * |
| 185 | * @see https://developers.cloudflare.com/workers/observability/issues/ |
| 186 | * |
| 187 | * @resource |
| 188 | * @product Workers |
| 189 | * @category Observability & Analytics |
| 190 | */ |
| 191 | export const IssueAutomation = Resource<IssueAutomation>(TypeId); |
| 192 | |
| 193 | /** |
| 194 | * Returns true if the given value is an IssueAutomation resource. |
| 195 | */ |
| 196 | export const isIssueAutomation = (value: unknown): value is IssueAutomation => |
| 197 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 198 | |
| 199 | export const IssueAutomationProvider = () => |
| 200 | Provider.succeed(IssueAutomation, { |
| 201 | stables: ["automationId", "accountId"], |
| 202 | |
| 203 | diff: Effect.fn(function* ({ output }) { |
| 204 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 205 | if ((output?.accountId ?? accountId) !== accountId) { |
| 206 | return { action: "replace" } as const; |
| 207 | } |
| 208 | }), |
| 209 | |
| 210 | read: Effect.fn(function* ({ id, output, olds }) { |
| 211 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 212 | const acct = output?.accountId ?? accountId; |
| 213 | |
| 214 | // Owned path: refresh by the persisted automation id. |
| 215 | if (output?.automationId) { |
| 216 | const observed = yield* observeAutomation(acct, output.automationId); |
| 217 | return observed ? toAttributes(observed, acct) : undefined; |
| 218 | } |
| 219 | |
| 220 | // No state of our own: look the automation up by name. Automations |
| 221 | // carry no ownership markers, so brand a match `Unowned` and let the |
| 222 | // engine gate takeover behind the adopt policy. |
| 223 | const name = olds?.name ?? (yield* createAutomationName(id)); |
| 224 | const observed = yield* findAutomationByName(acct, name); |
| 225 | return observed ? Unowned(toAttributes(observed, acct)) : undefined; |
| 226 | }), |
| 227 | |
| 228 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 229 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 230 | // Prefer the deployed name: regenerating would target a different |
| 231 | // automation if the generator's output for this id ever drifts. |
| 232 | const name = news.name ?? output?.name ?? (yield* createAutomationName(id)); |
| 233 | const desired = buildBody(name, news); |
| 234 | |
| 235 | // 1. Observe — by cached id first, then by name (ownership of a name |
| 236 | // match has already been checked by `read` + the adopt policy). |
| 237 | let observed: workers.ObservabilityIssueAutomation | undefined; |
| 238 | if (output?.automationId) { |
| 239 | observed = yield* observeAutomation(accountId, output.automationId); |
| 240 | } |
| 241 | if (!observed) { |
| 242 | observed = yield* findAutomationByName(accountId, name); |
| 243 | } |
| 244 | |
| 245 | // 2. Ensure — create when missing. |
| 246 | if (!observed) { |
| 247 | const { automation } = yield* workers.createObservabilityIssueAutomation({ |
| 248 | accountId, |
| 249 | ...desired, |
| 250 | }); |
| 251 | return toAttributes(automation, accountId); |
| 252 | } |
| 253 | |
| 254 | // 3. Sync — PUT is a full replace, so send the whole desired body |
| 255 | // when any field drifts from the observed automation. |
| 256 | if (!matchesObserved(desired, observed)) { |
| 257 | const { automation } = yield* workers.updateObservabilityIssueAutomation({ |
| 258 | accountId, |
| 259 | automationId: observed.id, |
| 260 | ...desired, |
| 261 | }); |
| 262 | return toAttributes(automation, accountId); |
| 263 | } |
| 264 | |
| 265 | // 4. Return. |
| 266 | return toAttributes(observed, accountId); |
| 267 | }), |
| 268 | |
| 269 | delete: Effect.fn(function* ({ output }) { |
| 270 | yield* workers |
| 271 | .deleteObservabilityIssueAutomation({ |
| 272 | accountId: output.accountId, |
| 273 | automationId: output.automationId, |
| 274 | }) |
| 275 | .pipe(Effect.catchTag("ObservabilityIssueAutomationNotFound", () => Effect.void)); |
| 276 | }), |
| 277 | |
| 278 | // Account collection. The list endpoint returns every account- and |
| 279 | // service-scoped automation in one response. |
| 280 | list: Effect.fn(function* () { |
| 281 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 282 | const { automations } = yield* workers.listObservabilityIssueAutomations({ accountId }); |
| 283 | return automations.map((automation) => toAttributes(automation, accountId)); |
| 284 | }), |
| 285 | }); |
| 286 | |
| 287 | type AutomationBody = Omit<workers.CreateObservabilityIssueAutomationRequest, "accountId">; |
| 288 | |
| 289 | const createAutomationName = (id: string) => createPhysicalName({ id, lowercase: true }); |
| 290 | |
| 291 | const buildBody = (name: string, news: IssueAutomationProps): AutomationBody => ({ |
| 292 | name, |
| 293 | policyId: news.policyId, |
| 294 | enabled: news.enabled ?? true, |
| 295 | service: news.service, |
| 296 | afterOccurrences: news.afterOccurrences, |
| 297 | afterInactivitySeconds: news.afterInactivitySeconds, |
| 298 | }); |
| 299 | |
| 300 | const matchesObserved = ( |
| 301 | desired: AutomationBody, |
| 302 | observed: workers.ObservabilityIssueAutomation, |
| 303 | ): boolean => |
| 304 | desired.name === observed.name && |
| 305 | desired.policyId === observed.ansPolicyId && |
| 306 | desired.enabled === observed.enabled && |
| 307 | desired.service === (observed.service ?? undefined) && |
| 308 | desired.afterOccurrences === (observed.threshold ?? undefined) && |
| 309 | desired.afterInactivitySeconds === (observed.inactivitySeconds ?? undefined); |
| 310 | |
| 311 | const observeAutomation = (accountId: string, automationId: string) => |
| 312 | workers.getObservabilityIssueAutomation({ accountId, automationId }).pipe( |
| 313 | Effect.map(({ automation }) => automation), |
| 314 | Effect.catchTag("ObservabilityIssueAutomationNotFound", () => Effect.undefined), |
| 315 | ); |
| 316 | |
| 317 | const findAutomationByName = (accountId: string, name: string) => |
| 318 | workers |
| 319 | .listObservabilityIssueAutomations({ accountId }) |
| 320 | .pipe(Effect.map(({ automations }) => automations.find((a) => a.name === name))); |
| 321 | |
| 322 | const toAttributes = ( |
| 323 | observed: workers.ObservabilityIssueAutomation, |
| 324 | accountId: string, |
| 325 | ): IssueAutomationAttributes => ({ |
| 326 | automationId: observed.id, |
| 327 | accountId, |
| 328 | name: observed.name, |
| 329 | policyId: observed.ansPolicyId, |
| 330 | service: observed.service ?? undefined, |
| 331 | scope: observed.scope, |
| 332 | triggerType: observed.triggerType, |
| 333 | afterOccurrences: observed.threshold ?? undefined, |
| 334 | afterInactivitySeconds: observed.inactivitySeconds ?? undefined, |
| 335 | enabled: observed.enabled, |
| 336 | revision: observed.revision, |
| 337 | }); |