@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 201 lines 8.79 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Effect from "effect/Effect";
5 import * as HttpClientRequest from "effect/http/HttpClientRequest";
6 import { MinimumLogLevel } from "effect/References";
7 import * as Schedule from "effect/Schedule";
8 import { expectUrlContains } from "../Utils/Http.ts";
9 import { requestWorker } from "../Utils/WorkerRequest.ts";
10 import Stack from "./fixtures/wait-until/stack.ts";
11
12 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
13 providers: Cloudflare.providers(),
14 state: Cloudflare.state(),
15 });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 const stack = beforeAll(deploy(Stack));
20 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
21
22 // Cache-busting query param on every request: after destroy+recreate of the
23 // same workers.dev subdomain the edge can serve a cached "nothing here yet"
24 // placeholder (with a 200) for the bare URL even though busted requests
25 // already reach the worker. Route matching uses `url.pathname`, so the
26 // param is invisible to the fixture.
27 let bust = 0;
28 const getText = Effect.fn(function* (url: string) {
29 const request = yield* Effect.sync(() =>
30 HttpClientRequest.get(`${url}?cb=${Date.now()}-${bust++}`).pipe(
31 HttpClientRequest.setHeader("cache-control", "no-cache"),
32 ),
33 );
34 const response = yield* requestWorker(request);
35 const body = yield* response.text;
36 if (response.status !== 200) {
37 return yield* Effect.fail(new Error(`GET ${url}: ${response.status}: ${body}`));
38 }
39 return body;
40 });
41
42 describe.skipIf(!!process.env.FAST)(
43 "waitUntil runs background Effects past the response (worker ctx + DO state)",
44 { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"] },
45 () => {
46 test(
47 "concurrent background journal writes retain every entry",
48 Effect.gen(function* () {
49 const { url } = yield* stack;
50 yield* expectUrlContains(`${url}/bg-many`, "bg-many-scheduled");
51 const entries = yield* Effect.gen(function* () {
52 const text = yield* getText(`${url}/entries-many`);
53 return yield* Effect.try({
54 try: () => (JSON.parse(text) as { entries: string[] }).entries,
55 catch: (cause) => new Error(`Invalid journal response: ${text}`, { cause }),
56 });
57 }).pipe(
58 Effect.repeat({
59 schedule: Schedule.spaced("500 millis"),
60 times: 8,
61 until: (entries) => entries.length === 40,
62 }),
63 );
64 expect(entries.toSorted()).toEqual(
65 Array.from({ length: 40 }, (_, i) => `parallel-${i}`).sort(),
66 );
67 }).pipe(logLevel),
68 { timeout: 60_000 },
69 );
70
71 test(
72 "waitUntil runs background Effects past the response (worker ctx + DO state)",
73 Effect.gen(function* () {
74 const { url } = yield* stack;
75
76 // Content-based readiness through workers.dev propagation (the
77 // placeholder page serves 200s); also asserts the raw escape hatch is
78 // the genuine workerd ExecutionContext.
79 yield* expectUrlContains(`${url}/raw`, "ok", {
80 label: "wait-until worker propagation",
81 });
82
83 // Fire both background writes: one from the Worker's ExecutionContext,
84 // one from inside the DO via DurableObjectState.waitUntil. Both routes
85 // respond before the journal entry is persisted. Probed via
86 // expectUrlContains so transient placeholders/5xx during propagation
87 // are retried (a duplicate journal entry from a retry is harmless —
88 // the assertions below use `toContain`).
89 yield* expectUrlContains(`${url}/bg`, "bg-scheduled", {
90 label: "waitUntil /bg",
91 });
92 yield* expectUrlContains(`${url}/bg-do`, "bg-do-scheduled", {
93 label: "waitUntil /bg-do",
94 });
95 // Regression for #2173: an HttpApi handler built in init sees the
96 // live per-event context, not init's deferred stand-in.
97 yield* expectUrlContains(`${url}/api/bg`, "bg-api-scheduled", {
98 label: "waitUntil /api/bg",
99 });
100
101 // The entries only appear if waitUntil kept the invocations alive until
102 // the delayed writes completed.
103 const entries = yield* Effect.gen(function* () {
104 const text = yield* getText(`${url}/entries`);
105 // The workers.dev placeholder serves HTML with a 200 during subdomain
106 // propagation; a bare JSON.parse throw would be a *defect* that the
107 // `Effect.catch` below can't see, so parse as a typed failure.
108 const body = yield* Effect.try(() => JSON.parse(text) as { entries?: string[] });
109 return body.entries ?? [];
110 }).pipe(
111 Effect.catch(() => Effect.succeed([] as string[])),
112 Effect.repeat({
113 schedule: Schedule.spaced("1 second"),
114 until: (entries) =>
115 entries.includes("from-worker-wait-until") &&
116 entries.includes("from-do-wait-until") &&
117 entries.includes("from-http-api-wait-until"),
118 times: 30,
119 }),
120 );
121
122 expect(entries).toContain("from-worker-wait-until");
123 expect(entries).toContain("from-do-wait-until");
124 expect(entries).toContain("from-http-api-wait-until");
125 }).pipe(logLevel),
126 { timeout: 180_000 },
127 );
128
129 // Scope finalizers piggyback on the same mechanism: the bridge closes the
130 // per-event scope after the handler completes and registers the close
131 // promise with waitUntil, so `Effect.addFinalizer` work lands after the
132 // response without blocking it.
133 test(
134 "Effect.addFinalizer runs after the response (request scope + DO call scope)",
135 Effect.gen(function* () {
136 const { url } = yield* stack;
137
138 // Content-based readiness: a fresh workers.dev URL serves Cloudflare's
139 // placeholder page (with a 200) while the subdomain propagates.
140 yield* expectUrlContains(`${url}/raw`, "ok", {
141 label: "wait-until worker propagation",
142 });
143
144 // Both routes respond before their finalizers persist the entries.
145 // Probed via expectUrlContains so transient placeholders/5xx during
146 // propagation are retried (duplicate journal entries are harmless —
147 // the assertions below use `toContain`).
148 yield* expectUrlContains(`${url}/finalizer`, "finalizer-scheduled", {
149 label: "finalizer /finalizer",
150 });
151 yield* expectUrlContains(`${url}/finalizer-do`, "do-finalizer-scheduled", {
152 label: "finalizer /finalizer-do",
153 });
154
155 const entries = yield* Effect.gen(function* () {
156 const text = yield* getText(`${url}/entries`);
157 // The workers.dev placeholder serves HTML with a 200 during subdomain
158 // propagation; a bare JSON.parse throw would be a *defect* that the
159 // `Effect.catch` below can't see, so parse as a typed failure.
160 const body = yield* Effect.try(() => JSON.parse(text) as { entries?: string[] });
161 return body.entries ?? [];
162 }).pipe(
163 Effect.catch(() => Effect.succeed([] as string[])),
164 Effect.repeat({
165 schedule: Schedule.spaced("1 second"),
166 until: (entries) =>
167 entries.includes("from-request-finalizer") && entries.includes("from-do-finalizer"),
168 times: 30,
169 }),
170 );
171
172 expect(entries).toContain("from-request-finalizer");
173 expect(entries).toContain("from-do-finalizer");
174
175 // Init-phase semantics (documented on the Worker resource): the init
176 // closure runs exactly once per isolate — the bridge builds the layer
177 // stack on the first event and every later event reuses the built
178 // context. The build scope is never closed (workerd has no isolate
179 // teardown), so a finalizer added in the init closure NEVER fires;
180 // request-coupled cleanup belongs in handlers, where `addFinalizer`
181 // attaches to the per-event scope (asserted above). Each observation
182 // may come from a different isolate, but every isolate must report
183 // exactly one init run and zero init-finalizer runs no matter how many
184 // events it has served.
185 const observation = yield* Effect.gen(function* () {
186 const init = Number(yield* getText(`${url}/init-runs`));
187 const finalized = Number(yield* getText(`${url}/init-finalizer-runs`));
188 return { init, finalized };
189 }).pipe(
190 Effect.repeat({
191 schedule: Schedule.spaced("500 millis"),
192 until: (o) => o.init === 1 && o.finalized === 0,
193 times: 10,
194 }),
195 );
196 expect(observation).toEqual({ init: 1, finalized: 0 });
197 }).pipe(logLevel),
198 { timeout: 180_000 },
199 );
200 },
201 );