The best way to control Claude Code, Codex and more from any computer or phone

main
ts 343 lines 12.3 KB
Raw
1 import * as alerting from "@distilled.cloud/cloudflare/alerting";
2 import { createPhysicalName } from "alchemy/PhysicalName";
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 Redacted from "effect/Redacted";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 export class WebhookUnexpectedResponse extends Data.TaggedError("WebhookUnexpectedResponse")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 const TypeId = "Cloudflare.Alerting.Webhook" as const;
21 type TypeId = typeof TypeId;
22
23 /**
24 * Webhook destination endpoint type, inferred by Cloudflare from the URL.
25 */
26 export type NotificationWebhookType =
27 | "datadog"
28 | "discord"
29 | "feishu"
30 | "gchat"
31 | "generic"
32 | "opsgenie"
33 | "slack"
34 | "splunk"
35 // Keep the union open so new Cloudflare destination types aren't blocked
36 // by stale types.
37 | (string & {});
38
39 export interface NotificationWebhookProps {
40 /**
41 * Name of the webhook destination. Included in the request body when a
42 * notification is dispatched. If omitted, a unique name is generated.
43 * Mutable — renames are applied in place.
44 * @default ${app}-${id}-${stage}-${suffix}
45 */
46 name?: string;
47 /**
48 * The POST endpoint Cloudflare calls when dispatching a notification.
49 * Cloudflare sends a test request on create/update; the endpoint must
50 * respond with a 2xx or the operation fails with `WebhookTestFailed`.
51 * Mutable — updated in place.
52 */
53 url: string;
54 /**
55 * Optional secret sent in the `cf-webhook-auth` header on every
56 * notification dispatch (for generic webhooks). Write-only: Cloudflare
57 * never returns it, so drift cannot be observed — the secret is re-sent
58 * whenever the prop value changes.
59 */
60 secret?: Redacted.Redacted<string>;
61 }
62
63 export interface NotificationWebhookAttributes {
64 /** Cloudflare-assigned webhook destination UUID. */
65 webhookId: string;
66 /** Account that owns this webhook destination. */
67 accountId: string;
68 /** Name of the webhook destination. */
69 name: string;
70 /** The POST endpoint called when dispatching a notification. */
71 url: string;
72 /** Endpoint type inferred by Cloudflare from the URL (e.g. `generic`, `slack`). */
73 type: NotificationWebhookType | undefined;
74 /** ISO8601 creation timestamp. */
75 createdAt: string | undefined;
76 }
77
78 export type NotificationWebhook = Resource<
79 TypeId,
80 NotificationWebhookProps,
81 NotificationWebhookAttributes,
82 never,
83 Providers
84 >;
85
86 /**
87 * A Cloudflare Notifications webhook destination.
88 *
89 * Webhook destinations receive alert notifications dispatched by
90 * {@link NotificationPolicy | notification policies}. Cloudflare sends a
91 * test POST to the URL when the webhook is created or updated, so the
92 * endpoint must be live and respond with a 2xx.
93 * ### Creating a Webhook destination
94 * **Example:** Generic webhook with a generated name
95 * ```typescript
96 * const webhook = yield* Cloudflare.Alerting.NotificationWebhook("AlertsHook", {
97 * url: "https://alerts.example.com/cf",
98 * });
99 * ```
100 *
101 * **Example:** Webhook with an auth secret
102 * The secret is sent in the `cf-webhook-auth` header on every dispatch.
103 * ```typescript
104 * const webhook = yield* Cloudflare.Alerting.NotificationWebhook("AlertsHook", {
105 * name: "production-alerts",
106 * url: "https://alerts.example.com/cf",
107 * secret: yield* Config.Redacted("WEBHOOK_SECRET"),
108 * });
109 * ```
110 *
111 * ### Using with a Notification policy
112 * **Example:** Dispatch policy notifications to the webhook
113 * ```typescript
114 * yield* Cloudflare.Alerting.NotificationPolicy("SslAlerts", {
115 * alertType: "universal_ssl_event_type",
116 * mechanisms: { webhooks: [{ id: webhook.webhookId }] },
117 * });
118 * ```
119 *
120 * @see https://developers.cloudflare.com/notifications/get-started/configure-webhooks/
121 *
122 * @resource
123 * @product Alerting
124 * @category Observability & Analytics
125 */
126 export const NotificationWebhook = Resource<NotificationWebhook>(TypeId);
127
128 /**
129 * Returns true if the given value is a NotificationWebhook resource.
130 */
131 export const isNotificationWebhook = (value: unknown): value is NotificationWebhook =>
132 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
133
134 export const NotificationWebhookProvider = () =>
135 Provider.succeed(NotificationWebhook, {
136 stables: ["webhookId", "accountId"],
137
138 // Account collection (pattern b): enumerate every webhook destination in
139 // the account and hydrate each into the same Attributes shape `read`
140 // returns. The secret is write-only (never returned by Cloudflare), so it
141 // is absent from Attributes and there is nothing extra to fetch per item.
142 list: Effect.fn(function* () {
143 const { accountId } = yield* yield* CloudflareEnvironment;
144 return yield* alerting.listDestinationWebhooks.pages({ accountId }).pipe(
145 Stream.runCollect,
146 Effect.map((chunk) =>
147 Array.from(chunk).flatMap((page) =>
148 (page.result ?? [])
149 .map(narrowWebhook)
150 .filter((w): w is ObservedWebhook => w !== undefined)
151 .map((w) => toWebhookAttributes(w, accountId)),
152 ),
153 ),
154 );
155 }),
156
157 diff: Effect.fn(function* ({ output }) {
158 const { accountId } = yield* yield* CloudflareEnvironment;
159 if ((output?.accountId ?? accountId) !== accountId) {
160 return { action: "replace" } as const;
161 }
162 }),
163
164 read: Effect.fn(function* ({ id, output, olds }) {
165 const { accountId } = yield* yield* CloudflareEnvironment;
166 const acct = output?.accountId ?? accountId;
167
168 // Owned path: refresh by the persisted webhook id.
169 if (output?.webhookId) {
170 const observed = yield* observeWebhook(acct, output.webhookId);
171 if (observed) return toWebhookAttributes(observed, acct);
172 }
173
174 // Cold read: no persisted id (state-persistence failure) — find the
175 // deterministic physical name in the account's webhook list.
176 const name = yield* createWebhookName(id, olds?.name);
177 const match = yield* findWebhookByName(acct, name);
178 if (match) return toWebhookAttributes(match, acct);
179 return undefined;
180 }),
181
182 reconcile: Effect.fn(function* ({ id, news, output, olds }) {
183 const { accountId } = yield* yield* CloudflareEnvironment;
184 const name = yield* createWebhookName(id, news.name);
185 // Inputs are resolved to concrete values by the engine before
186 // reconcile runs.
187 const url = news.url as string;
188 const secret = news.secret === undefined ? undefined : Redacted.value(news.secret);
189
190 // 1. Observe — by cached id first, then by deterministic name.
191 let observed: ObservedWebhook | undefined;
192 if (output?.webhookId) {
193 observed = yield* observeWebhook(accountId, output.webhookId);
194 }
195 if (!observed) {
196 observed = yield* findWebhookByName(accountId, name);
197 }
198
199 // 2. Ensure — create when missing. Cloudflare fires a test POST at
200 // the URL from an arbitrary PoP; when the destination is a
201 // just-deployed Worker that PoP may not have the fresh
202 // workers.dev subdomain yet and the test POST 404s even though
203 // the URL serves elsewhere. A bounded retry (~2 min, capped
204 // backoff) rides out edge propagation — fresh workers.dev URLs
205 // have been observed to 404 for well over a minute under heavy
206 // account-wide deploy load; a genuinely broken endpoint still
207 // fails after the budget is exhausted.
208 if (!observed) {
209 const created = yield* alerting
210 .createDestinationWebhook({
211 accountId,
212 name,
213 url,
214 secret,
215 })
216 .pipe(
217 Effect.retry({
218 while: (e) => e._tag === "WebhookTestFailed",
219 schedule: Schedule.max([
220 Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("5 seconds")]),
221 Schedule.recurs(24),
222 ]),
223 }),
224 );
225 if (!created.id) {
226 return yield* new WebhookUnexpectedResponse({
227 message: "Cloudflare did not return an id for the created webhook destination",
228 });
229 }
230 const fresh = yield* observeWebhook(accountId, created.id);
231 return toWebhookAttributes(fresh ?? { id: created.id }, accountId);
232 }
233
234 // 3. Sync — PUT the full desired body when any observable field
235 // drifts, or when the (write-only, unobservable) secret prop
236 // changed between olds and news.
237 const oldSecret = olds?.secret === undefined ? undefined : Redacted.value(olds.secret);
238 const secretChanged = secret !== oldSecret;
239 if (observed.name !== name || observed.url !== url || secretChanged) {
240 // The update PUT fires the same test POST as create — ride out edge
241 // propagation of a just-deployed destination URL the same way.
242 yield* alerting
243 .updateDestinationWebhook({
244 accountId,
245 webhookId: observed.id,
246 name,
247 url,
248 secret,
249 })
250 .pipe(
251 Effect.retry({
252 while: (e) => e._tag === "WebhookTestFailed",
253 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(5)]),
254 }),
255 );
256 const fresh = yield* observeWebhook(accountId, observed.id);
257 return toWebhookAttributes(fresh ?? observed, accountId);
258 }
259
260 // 4. Return.
261 return toWebhookAttributes(observed, accountId);
262 }),
263
264 delete: Effect.fn(function* ({ output }) {
265 // Cloudflare answers `deleteDestinationWebhook` for a webhook that no
266 // longer exists with a generic `InternalServerError` (code 15000)
267 // rather than a not-found error. Since that envelope is
268 // indistinguishable from a genuine server fault, catch the typed tag
269 // and verify the webhook is actually gone: `WebhookNotFound` on the
270 // follow-up read confirms idempotent success; anything still present
271 // re-fails with the original error.
272 yield* alerting
273 .deleteDestinationWebhook({
274 accountId: output.accountId,
275 webhookId: output.webhookId,
276 })
277 .pipe(
278 Effect.catchTag("InternalServerError", (e) =>
279 observeWebhook(output.accountId, output.webhookId).pipe(
280 Effect.flatMap((observed) => (observed === undefined ? Effect.void : Effect.fail(e))),
281 ),
282 ),
283 );
284 }),
285 });
286
287 interface ObservedWebhook {
288 readonly id: string;
289 readonly name?: string;
290 readonly url?: string;
291 readonly type?: NotificationWebhookType;
292 readonly createdAt?: string;
293 }
294
295 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
296
297 const narrowWebhook = (raw: {
298 id?: string | null;
299 name?: string | null;
300 url?: string | null;
301 type?: string | null;
302 createdAt?: string | null;
303 }): ObservedWebhook | undefined =>
304 raw.id == null
305 ? undefined
306 : {
307 id: raw.id,
308 name: undef(raw.name),
309 url: undef(raw.url),
310 type: undef(raw.type) as NotificationWebhookType | undefined,
311 createdAt: undef(raw.createdAt),
312 };
313
314 const observeWebhook = (accountId: string, webhookId: string) =>
315 alerting.getDestinationWebhook({ accountId, webhookId }).pipe(
316 Effect.map((w) => narrowWebhook({ ...w, id: w.id ?? webhookId })),
317 Effect.catchTag("WebhookNotFound", () => Effect.undefined),
318 );
319
320 const findWebhookByName = (accountId: string, name: string) =>
321 alerting.listDestinationWebhooks.items({ accountId }).pipe(
322 Stream.filter((w) => w.name === name && w.id != null),
323 Stream.runHead,
324 Effect.map(Option.getOrUndefined),
325 Effect.map((w) => (w === undefined ? undefined : narrowWebhook(w))),
326 );
327
328 const toWebhookAttributes = (
329 observed: ObservedWebhook,
330 accountId: string,
331 ): NotificationWebhookAttributes => ({
332 webhookId: observed.id,
333 accountId,
334 name: observed.name ?? "",
335 url: observed.url ?? "",
336 type: observed.type,
337 createdAt: observed.createdAt,
338 });
339
340 const createWebhookName = (id: string, name: string | undefined) =>
341 Effect.gen(function* () {
342 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
343 });