@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 312 lines 12.7 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as queues from "@distilled.cloud/cloudflare/queues";
7 import * as Provider from "alchemy/Provider";
8 import * as Effect from "effect/Effect";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import { emailRoutingScoped } from "../Email/scope.ts";
12 const { test } = Test.make({ providers: Cloudflare.providers() });
13
14 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
15
16 // The scoped API token the test harness mints propagates eventually-
17 // consistently across Cloudflare's edge — ride out 403 blips
18 // (`Forbidden`, declared in the distilled error union) on the test's
19 // own out-of-band verification calls.
20 const getSubscription = (accountId: string, subscriptionId: string) =>
21 queues.getSubscription({ accountId, subscriptionId }).pipe(
22 Effect.retry({
23 while: (e) => e._tag === "Forbidden",
24 schedule: Schedule.fixed("500 millis"),
25 times: 20,
26 }),
27 );
28
29 const expectGone = (accountId: string, subscriptionId: string) =>
30 getSubscription(accountId, subscriptionId).pipe(
31 Effect.flatMap(() => Effect.fail({ _tag: "SubscriptionNotDeleted" } as const)),
32 // A missing subscription surfaces as `SubscriptionNotFound`
33 // (HTTP 404 "No subscription with this ID") — that's the success
34 // condition here.
35 Effect.catchTag("SubscriptionNotFound", () => Effect.void),
36 Effect.retry({
37 while: (e) => e._tag === "SubscriptionNotDeleted",
38 schedule: Schedule.max([Schedule.fixed("500 millis"), Schedule.recurs(20)]),
39 }),
40 );
41
42 // Sequential: Cloudflare allows only ONE subscription per source per
43 // account, and every test here uses the same `{ type: "r2" }` (or kv)
44 // source. Run concurrently they adopt/patch/delete each other's
45 // subscription via the AlreadyExists fallback and fail with queueId
46 // mismatches and SubscriptionNotFound. The kv and r2 tests also take the
47 // `cloudflare:event-subscriptions` label that SubscriptionSources.test.ts
48 // holds for the same sources.
49 describe.sequential(
50 "Subscription",
51 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
52 () => {
53 test.provider(
54 "create r2 event subscription into a queue and destroy it",
55 (stack) =>
56 Effect.gen(function* () {
57 const { accountId } = yield* yield* CloudflareEnvironment;
58
59 yield* stack.destroy();
60
61 const deployed = yield* stack.deploy(
62 Effect.gen(function* () {
63 const queue = yield* Cloudflare.Queues.Queue("SubQueue");
64 // Compose with an R2 bucket — the subscription delivers
65 // account-level R2 events (e.g. this bucket's lifecycle)
66 // into the queue.
67 const bucket = yield* Cloudflare.R2.Bucket("SubBucket", {
68 forceDestroy: true,
69 });
70 const subscription = yield* Cloudflare.Queues.Subscription("R2Events", {
71 source: { type: "r2" },
72 events: ["bucket.created", "bucket.deleted"],
73 queueId: queue.queueId,
74 });
75 return { queue, bucket, subscription };
76 }),
77 );
78
79 const sub = deployed.subscription;
80 expect(sub.subscriptionId).toBeDefined();
81 expect(sub.accountId).toEqual(accountId);
82 expect(sub.source).toEqual({ type: "r2" });
83 expect([...sub.events].sort()).toEqual(["bucket.created", "bucket.deleted"]);
84 expect(sub.enabled).toBe(true);
85 expect(sub.queueId).toEqual(deployed.queue.queueId);
86
87 // Out-of-band verification straight against the API.
88 const live = yield* getSubscription(accountId, sub.subscriptionId);
89 expect(live.id).toEqual(sub.subscriptionId);
90 expect(live.destination.queueId).toEqual(deployed.queue.queueId);
91 expect([...live.events].sort()).toEqual(["bucket.created", "bucket.deleted"]);
92 expect(live.enabled).toBe(true);
93
94 yield* stack.destroy();
95
96 yield* expectGone(accountId, sub.subscriptionId);
97 }).pipe(logLevel),
98 { tags: ["provider:cloudflare:r2"], exclusive: "cloudflare:event-subscriptions" },
99 );
100
101 test.provider(
102 "update mutable props in place (same subscriptionId)",
103 (stack) =>
104 Effect.gen(function* () {
105 const { accountId } = yield* yield* CloudflareEnvironment;
106
107 yield* stack.destroy();
108
109 const initial = yield* stack.deploy(
110 Effect.gen(function* () {
111 const queueA = yield* Cloudflare.Queues.Queue("SubQueueA");
112 const queueB = yield* Cloudflare.Queues.Queue("SubQueueB");
113 const subscription = yield* Cloudflare.Queues.Subscription("UpdateSub", {
114 name: `alchemy-sub-update-${stack.stage}`,
115 source: { type: "r2" },
116 events: ["bucket.created"],
117 queueId: queueA.queueId,
118 });
119 return { queueA, queueB, subscription };
120 }),
121 );
122
123 expect(initial.subscription.name).toEqual(`alchemy-sub-update-${stack.stage}`);
124 expect(initial.subscription.enabled).toBe(true);
125 expect(initial.subscription.queueId).toEqual(initial.queueA.queueId);
126
127 // Mutate everything mutable: name, events, enabled, and the
128 // destination queue.
129 const updated = yield* stack.deploy(
130 Effect.gen(function* () {
131 const queueA = yield* Cloudflare.Queues.Queue("SubQueueA");
132 const queueB = yield* Cloudflare.Queues.Queue("SubQueueB");
133 const subscription = yield* Cloudflare.Queues.Subscription("UpdateSub", {
134 name: `alchemy-sub-update-v2-${stack.stage}`,
135 source: { type: "r2" },
136 events: ["bucket.created", "bucket.deleted"],
137 queueId: queueB.queueId,
138 enabled: false,
139 });
140 return { queueA, queueB, subscription };
141 }),
142 );
143
144 // Same subscription mutated in place — not a replacement.
145 expect(updated.subscription.subscriptionId).toEqual(initial.subscription.subscriptionId);
146 expect(updated.subscription.name).toEqual(`alchemy-sub-update-v2-${stack.stage}`);
147 expect(updated.subscription.enabled).toBe(false);
148 expect(updated.subscription.queueId).toEqual(updated.queueB.queueId);
149 expect([...updated.subscription.events].sort()).toEqual([
150 "bucket.created",
151 "bucket.deleted",
152 ]);
153
154 const live = yield* getSubscription(accountId, updated.subscription.subscriptionId);
155 expect(live.name).toEqual(`alchemy-sub-update-v2-${stack.stage}`);
156 expect(live.enabled).toBe(false);
157 expect(live.destination.queueId).toEqual(updated.queueB.queueId);
158 expect([...live.events].sort()).toEqual(["bucket.created", "bucket.deleted"]);
159
160 yield* stack.destroy();
161
162 yield* expectGone(accountId, updated.subscription.subscriptionId);
163 }).pipe(logLevel),
164 { exclusive: "cloudflare:event-subscriptions" },
165 );
166
167 test.provider(
168 "replaces the subscription when the source changes",
169 (stack) =>
170 Effect.gen(function* () {
171 const { accountId } = yield* yield* CloudflareEnvironment;
172
173 yield* stack.destroy();
174
175 const initial = yield* stack.deploy(
176 Effect.gen(function* () {
177 const queue = yield* Cloudflare.Queues.Queue("SubQueueR");
178 const subscription = yield* Cloudflare.Queues.Subscription("ReplaceSub", {
179 source: { type: "kv" },
180 events: ["namespace.created"],
181 queueId: queue.queueId,
182 });
183 return { queue, subscription };
184 }),
185 );
186
187 expect(initial.subscription.source).toEqual({ type: "kv" });
188
189 const replaced = yield* stack.deploy(
190 Effect.gen(function* () {
191 const queue = yield* Cloudflare.Queues.Queue("SubQueueR");
192 const subscription = yield* Cloudflare.Queues.Subscription("ReplaceSub", {
193 source: { type: "r2" },
194 events: ["bucket.created"],
195 queueId: queue.queueId,
196 });
197 return { queue, subscription };
198 }),
199 );
200
201 // The source is fixed at creation — changing it produces a new
202 // subscription identity.
203 expect(replaced.subscription.subscriptionId).not.toEqual(
204 initial.subscription.subscriptionId,
205 );
206 expect(replaced.subscription.source).toEqual({ type: "r2" });
207
208 // The old subscription is gone after the replacement settles.
209 yield* expectGone(accountId, initial.subscription.subscriptionId);
210
211 const live = yield* getSubscription(accountId, replaced.subscription.subscriptionId);
212 expect(live.events).toEqual(["bucket.created"]);
213
214 yield* stack.destroy();
215
216 yield* expectGone(accountId, replaced.subscription.subscriptionId);
217 }).pipe(logLevel),
218 { exclusive: "cloudflare:event-subscriptions" },
219 );
220
221 // Canonical `list()` test (account collection): deploy a subscription,
222 // then enumerate every subscription in the account via the typed provider
223 // and assert the deployed one is present in the exhaustively-paginated
224 // result.
225 test.provider(
226 "list enumerates the deployed subscription",
227 (stack) =>
228 Effect.gen(function* () {
229 yield* stack.destroy();
230
231 const deployed = yield* stack.deploy(
232 Effect.gen(function* () {
233 const queue = yield* Cloudflare.Queues.Queue("ListSubQueue");
234 const subscription = yield* Cloudflare.Queues.Subscription("ListR2Events", {
235 source: { type: "r2" },
236 events: ["bucket.created"],
237 queueId: queue.queueId,
238 });
239 return { queue, subscription };
240 }),
241 );
242
243 const provider = yield* Provider.findProvider(Cloudflare.Queues.Subscription);
244 const all = yield* provider.list();
245
246 expect(all.some((s) => s.subscriptionId === deployed.subscription.subscriptionId)).toBe(
247 true,
248 );
249
250 yield* stack.destroy();
251 }).pipe(logLevel),
252 { exclusive: "cloudflare:event-subscriptions" },
253 );
254
255 // Creates a SendingSubdomain, which needs the Email Routing scope the
256 // rest of this file doesn't (see test/Cloudflare/Email/scope.ts).
257 test.provider.skipIf(!emailRoutingScoped)(
258 "create an email.sending subscription that keeps its zone and domain",
259 (stack) =>
260 Effect.gen(function* () {
261 const { accountId } = yield* yield* CloudflareEnvironment;
262 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
263 const zone = yield* findZoneByName({ accountId, name: zoneName });
264 if (!zone) {
265 return yield* Effect.die(new Error(`zone "${zoneName}" not found`));
266 }
267 const domain = `alchemy-sub-mail-${stack.stage.toLowerCase().replace(/[^a-z0-9-]/g, "-")}.${zoneName}`;
268
269 yield* stack.destroy();
270
271 const deployed = yield* stack.deploy(
272 Effect.gen(function* () {
273 const queue = yield* Cloudflare.Queues.Queue("MailQueue");
274 const sending = yield* Cloudflare.Email.SendingSubdomain("MailSending", {
275 zoneId: zone.id,
276 name: domain,
277 });
278 const subscription = yield* Cloudflare.Queues.Subscription("MailEvents", {
279 source: {
280 type: "email.sending",
281 zoneId: sending.zoneId,
282 domain: sending.name,
283 },
284 events: ["message.bounced", "message.complained"],
285 queueId: queue.queueId,
286 });
287 return { queue, subscription };
288 }),
289 );
290
291 const sub = deployed.subscription;
292 expect(sub.source).toEqual({
293 type: "email.sending",
294 zoneId: zone.id,
295 domain,
296 });
297
298 const live = yield* getSubscription(accountId, sub.subscriptionId);
299 expect(live.source).toMatchObject({
300 type: "email.sending",
301 zoneId: zone.id,
302 domain,
303 });
304
305 yield* stack.destroy();
306
307 yield* expectGone(accountId, sub.subscriptionId);
308 }).pipe(logLevel),
309 { tags: ["provider:cloudflare:email"] },
310 );
311 },
312 );