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

main
ts 142 lines 5.3 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { notificationPath } from "@alchemy.run/cloudflare/Alerting/NotificationEventSource";
3 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
4 import * as GitHub from "@alchemy.run/github";
5 import { expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as alerting from "@distilled.cloud/cloudflare/alerting";
8 import * as Issues from "@distilled.cloud/github/issues";
9 import * as Effect from "effect/Effect";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Layer from "effect/Layer";
13 import { MinimumLogLevel } from "effect/References";
14 import * as Schedule from "effect/Schedule";
15 import NotificationWorker, {
16 IssuePolicy,
17 owner,
18 Repo,
19 repository,
20 } from "./fixtures/notification-worker.ts";
21
22 const { test } = Test.make({
23 providers: Layer.mergeAll(Cloudflare.providers(), GitHub.providers()),
24 });
25 const { executeWhenReady, getWhenReady } = Test;
26
27 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
28
29 const Stack = Effect.gen(function* () {
30 yield* Repo;
31 const policy = yield* IssuePolicy;
32 const worker = yield* NotificationWorker;
33 yield* Cloudflare.Workers.IssueAutomation("BoomIssues", {
34 policyId: policy.policyId,
35 service: worker.workerName,
36 afterOccurrences: 1,
37 });
38 return {
39 policyId: policy.policyId,
40 workerName: worker.workerName,
41 url: worker.url.as<string>(),
42 };
43 });
44
45 // Open issues the Worker opened about itself since `since`. The Worker's name
46 // is stable across runs, so the creation time singles out this run's issues.
47 const issuesFor = (workerName: string, since: string) =>
48 Effect.gen(function* () {
49 const issues = yield* Issues.listForRepo({ owner, repo: repository, state: "open", since });
50 return issues.filter(
51 (issue) =>
52 !issue.pull_request && issue.created_at >= since && issue.title.includes(workerName),
53 );
54 });
55
56 test.provider(
57 "consumeNotifications opens a GitHub issue for a Workers issue",
58 (stack) =>
59 Effect.gen(function* () {
60 const { accountId } = yield* yield* CloudflareEnvironment;
61 yield* stack.destroy();
62
63 const since = new Date().toISOString();
64 const { policyId, workerName, url } = yield* stack.deploy(Stack);
65 const base = url.replace(/\/+$/, "");
66 const deliveryUrl = `${base}${notificationPath({ LogicalId: "IssuePolicy" })}`;
67
68 // The event source bound a webhook destination at the Worker onto a
69 // policy declared without mechanisms. Cloudflare only creates a
70 // destination whose test message the Worker acknowledged.
71 const policy = yield* alerting.getPolicy({ accountId, policyId });
72 const webhookIds = (policy.mechanisms?.webhooks ?? []).map((w) => w.id);
73 expect(webhookIds).toHaveLength(1);
74 const webhook = yield* alerting.getDestinationWebhook({
75 accountId,
76 webhookId: webhookIds[0]!,
77 });
78 expect(webhook.url).toEqual(deliveryUrl);
79
80 // A delivery without the secret is rejected.
81 yield* getWhenReady(base);
82 const forged = yield* executeWhenReady(
83 HttpClientRequest.post(deliveryUrl).pipe(
84 HttpClientRequest.setHeader("cf-webhook-auth", "not-the-secret"),
85 HttpClientRequest.bodyJsonUnsafe({ alert_type: "workers_observability_real_time_issue" }),
86 ),
87 );
88 expect(forged.status).toBe(401);
89
90 // A 5xx response is a Workers issue occurrence. The automation notifies
91 // the policy, Cloudflare delivers to the Worker, and the Worker opens a
92 // GitHub issue through the `GitHub.CreateIssue` binding.
93 const client = yield* HttpClient.HttpClient;
94 yield* Effect.forEach([1, 2, 3], () => client.get(`${base}/boom`), { discard: true });
95
96 const issues = yield* issuesFor(workerName, since).pipe(
97 Effect.repeat({
98 schedule: Schedule.spaced("5 seconds"),
99 until: (issues) => issues.length > 0,
100 times: 18,
101 }),
102 );
103 expect(issues.length).toBeGreaterThan(0);
104 // Titled with the summary line, with Cloudflare's report as the body.
105 expect(issues[0]!.title).toMatch(/^Real-Time Issue '.*' detected in /);
106 expect(issues[0]!.body).toContain(`/workers/services/view/${workerName}/production/issues/`);
107
108 // The fixture repository is retained across runs: close this run's issues.
109 yield* Effect.forEach(
110 issues,
111 (issue) =>
112 Issues.update({
113 owner,
114 repo: repository,
115 issue_number: issue.number,
116 state: "closed",
117 }),
118 { discard: true },
119 );
120
121 yield* stack.destroy();
122 yield* alerting.getDestinationWebhook({ accountId, webhookId: webhookIds[0]! }).pipe(
123 Effect.flatMap(() => Effect.fail({ _tag: "StillExists" as const })),
124 Effect.catchTag("WebhookNotFound", () => Effect.void),
125 Effect.retry({
126 while: (e) => e._tag === "StillExists",
127 schedule: Schedule.spaced("2 seconds"),
128 times: 10,
129 }),
130 );
131 }).pipe(logLevel),
132 {
133 timeout: 180_000,
134 tags: [
135 "provider:cloudflare",
136 "provider:cloudflare:alerting",
137 "provider:cloudflare:worker",
138 "provider:github",
139 "live",
140 ],
141 },
142 );