@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 147 lines 5.68 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 HttpClient from "effect/http/HttpClient";
6 import * as HttpClientRequest from "effect/http/HttpClientRequest";
7 import { MinimumLogLevel } from "effect/References";
8 import * as Schedule from "effect/Schedule";
9 import RestartStack from "./fixtures/restart/stack.ts";
10
11 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
12 providers: Cloudflare.providers(),
13 state: Cloudflare.state(),
14 });
15
16 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
17
18 // Image build + push + worker/DO deploy comfortably exceeds the default hook
19 // budget, and a restart adds another cold start on top, so be generous.
20 const HOOK_TIMEOUT = 600_000;
21 const TEST_TIMEOUT = 300_000;
22
23 const DEPLOY_PLACEHOLDER = "Alchemy worker is being deployed...";
24
25 // Force `Connection: close` so each attempt opens a fresh connection and can
26 // land on an edge that already has the new deploy / restarted container.
27 const freshConn = HttpClient.mapRequest(HttpClientRequest.setHeader("connection", "close"));
28
29 const readinessSchedule = Schedule.min([
30 Schedule.exponential("500 millis"),
31 Schedule.spaced("3 seconds"),
32 ]);
33
34 // Retry a route until it answers 200 with a body containing `expected`,
35 // rejecting transient non-200s and the pre-create deploy stub. This is how we
36 // assert "the container is up and serving" both initially and after a restart.
37 const fetchReady = (url: string, expected: string) =>
38 Effect.gen(function* () {
39 const client = freshConn(yield* HttpClient.HttpClient);
40 return yield* client.get(url).pipe(
41 Effect.flatMap((r) =>
42 r.status !== 200
43 ? Effect.fail(new Error(`not ready: ${r.status}`))
44 : Effect.flatMap(r.text, (body) =>
45 body.includes(DEPLOY_PLACEHOLDER) || !body.includes(expected)
46 ? Effect.fail(new Error(`not ready: got ${body}`))
47 : Effect.succeed(body),
48 ),
49 ),
50 Effect.timeout("30 seconds"),
51 Effect.retry({ schedule: readinessSchedule, times: 40 }),
52 );
53 });
54
55 // Fire a single GET and return its body (used for /stop, /crash).
56 const hit = (url: string) =>
57 Effect.gen(function* () {
58 const client = freshConn(yield* HttpClient.HttpClient);
59 const res = yield* client.get(url);
60 return yield* res.text;
61 });
62
63 // Poll `/running` until the reported state matches `want`. Used to confirm the
64 // container actually went down before we assert the next request restarts it,
65 // so the test exercises the real restart path (not a still-warm container).
66 const waitRunning = (baseUrl: string, name: string, want: boolean) =>
67 Effect.gen(function* () {
68 const client = freshConn(yield* HttpClient.HttpClient);
69 return yield* client.get(`${baseUrl}/running?name=${encodeURIComponent(name)}`).pipe(
70 Effect.flatMap((r) =>
71 r.status !== 200
72 ? Effect.fail(new Error(`running not ready: ${r.status}`))
73 : Effect.flatMap(r.json, (body) => {
74 const running = (body as { running?: boolean }).running;
75 return running === want
76 ? Effect.succeed(running)
77 : Effect.fail(new Error(`running=${running}, want ${want}`));
78 }),
79 ),
80 Effect.timeout("15 seconds"),
81 Effect.retry({ schedule: readinessSchedule, times: 40 }),
82 );
83 });
84
85 /**
86 * Auto-restart: a Durable Object's container that has stopped or crashed must
87 * be transparently restarted on the next request. Regression coverage for the
88 * `readyPorts` cache going stale — previously a port confirmed ready once was
89 * never re-probed and `ensureRunning` was skipped, so a stopped container was
90 * never restarted.
91 */
92 describe(
93 "container auto-restart",
94 {
95 tags: [
96 "provider:cloudflare",
97 "provider:cloudflare:container",
98 "provider:cloudflare:worker",
99 "live",
100 ],
101 },
102 () => {
103 const stack = beforeAll(deploy(RestartStack), { timeout: HOOK_TIMEOUT });
104 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(RestartStack), { timeout: HOOK_TIMEOUT });
105
106 test(
107 "restarts the container after it is stopped (destroy)",
108 Effect.gen(function* () {
109 const { url } = yield* stack;
110 const name = "stop";
111
112 // Start + confirm up.
113 expect(yield* fetchReady(`${url}/ping?name=${name}`, "pong")).toContain("pong");
114
115 // Hard-stop it, then confirm it is actually down before re-pinging — so
116 // the next ping must go through the restart path.
117 yield* hit(`${url}/stop?name=${name}`);
118 yield* waitRunning(url, name, false);
119
120 // Next request transparently restarts it.
121 expect(yield* fetchReady(`${url}/ping?name=${name}`, "pong")).toContain("pong");
122 expect(yield* waitRunning(url, name, true)).toBe(true);
123 }).pipe(logLevel),
124 { timeout: TEST_TIMEOUT },
125 );
126
127 test(
128 "restarts the container after it crashes (non-zero exit)",
129 Effect.gen(function* () {
130 const { url } = yield* stack;
131 const name = "crash";
132
133 expect(yield* fetchReady(`${url}/ping?name=${name}`, "pong")).toContain("pong");
134
135 // Make the container process exit on its own, then wait for the monitor
136 // to observe the exit (running === false).
137 yield* hit(`${url}/crash?name=${name}`);
138 yield* waitRunning(url, name, false);
139
140 // Next request transparently restarts it.
141 expect(yield* fetchReady(`${url}/ping?name=${name}`, "pong")).toContain("pong");
142 expect(yield* waitRunning(url, name, true)).toBe(true);
143 }).pipe(logLevel),
144 { timeout: TEST_TIMEOUT },
145 );
146 },
147 );