@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 263 lines 10.7 KB
Raw
1 import { createHash } from "node:crypto";
2 import * as Fly from "@alchemy.run/fly";
3 import { sameStopConfig } from "@alchemy.run/fly/replicas";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as machines from "@distilled.cloud/fly-io/machines";
7 import * as Deferred from "effect/Deferred";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 import * as FileSystem from "effect/FileSystem";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as Path from "effect/Path";
13 import { MinimumLogLevel } from "effect/References";
14 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
15 import {
16 assertAppGone,
17 assertMachineGone,
18 assertOnlyMachine,
19 getText,
20 initialText,
21 startTraffic,
22 websiteChecks,
23 websiteServices,
24 } from "./fixtures/deployment.ts";
25
26 const { test } = Test.make({ providers: Fly.providers() });
27 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
28
29 type ResponseRecord = {
30 event: string;
31 version: string;
32 machine: string;
33 managedTimeout: null;
34 payload?: string;
35 startedAt: number;
36 signaledAt: number;
37 completedAt: number;
38 signal: string;
39 activeAtSignal: number;
40 shutdownMs: number;
41 };
42
43 for (const policy of [
44 {
45 old: "60 seconds",
46 next: "10 seconds",
47 oldMs: 60_000,
48 nextMs: 10_000,
49 delay: 12_000,
50 signal: "SIGTERM",
51 nextSignal: "SIGINT",
52 },
53 {
54 old: "10 seconds",
55 next: "60 seconds",
56 oldMs: 10_000,
57 nextMs: 60_000,
58 delay: 3_000,
59 signal: "SIGINT",
60 nextSignal: "SIGTERM",
61 },
62 ] as const) {
63 test.provider(
64 `R08/R02 SvelteKit external SSR: v1 to v2, old ${policy.old}/${policy.signal}, new ${policy.next}/${policy.nextSignal}, application-owned response drain`,
65 (stack) =>
66 Effect.gen(function* () {
67 yield* stack.destroy();
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const rootDir = yield* cloneFixture(
71 path.resolve(import.meta.dirname, "../../AWS/Website/fixtures/sveltekit-app"),
72 {
73 prefix: "alchemy-sveltekit-fly-",
74 tempRoot: path.resolve(import.meta.dirname, "../../../.tmp"),
75 entries: [".gitignore", "package.json", "src", "static"],
76 },
77 );
78 const route = path.join(rootDir, "src/routes/api/deployment/[operation]");
79 yield* fs.makeDirectory(route, { recursive: true });
80 for (const file of ["+server.ts", "state.ts", "version.ts"]) {
81 yield* fs.writeFileString(
82 path.join(route, file),
83 yield* fs.readFileString(
84 path.join(
85 import.meta.dirname,
86 "fixtures/sveltekit/src/routes/api/deployment/[operation]",
87 file,
88 ),
89 ),
90 );
91 }
92 yield* fs.writeFileString(
93 path.join(rootDir, "src/hooks.server.ts"),
94 yield* fs.readFileString(
95 path.join(import.meta.dirname, "fixtures/sveltekit/src/hooks.server.ts"),
96 ),
97 );
98 const pagePath = path.join(rootDir, "src/routes/+page.server.ts");
99 const page = yield* fs.readFileString(pagePath);
100 const writeVersion = (version: string) =>
101 Effect.gen(function* () {
102 yield* fs.writeFileString(
103 path.join(route, "version.ts"),
104 `export const version: string = ${JSON.stringify(version)};\n`,
105 );
106 yield* fs.writeFileString(
107 pagePath,
108 page.replace("SVELTEKIT_AWS_PAGE_MARKER", `SVELTEKIT_AWS_PAGE_MARKER ${version}`),
109 );
110 });
111 const deploy = (next: boolean) =>
112 stack.deploy(
113 Effect.gen(function* () {
114 const site = yield* Fly.Website.SvelteKit("Web", {
115 rootDir,
116 deploy: { strategy: "bluegreen", healthTimeout: "90 seconds" },
117 shutdown: {
118 signal: next ? policy.nextSignal : policy.signal,
119 timeout: next ? policy.next : policy.old,
120 },
121 checks: websiteChecks("/api/deployment/ready"),
122 services: websiteServices("/api/deployment/ready"),
123 env: {
124 WEBSITE_SHUTDOWN_MS: String(next ? policy.nextMs : policy.oldMs),
125 WEBSITE_AFTER_SIGNAL_MS: String(next ? 1000 : policy.delay),
126 },
127 memo: { include: ["src/**", "static/**", "package.json"] },
128 });
129 return { site };
130 }),
131 );
132 let appName: string | undefined;
133 yield* Effect.gen(function* () {
134 yield* writeVersion("v1");
135 const first = yield* deploy(false);
136 appName = first.site.app!.appName;
137 const oldId = first.site.service!.machineId;
138 const url = first.site.url!;
139 expect(url).toBe(`https://${appName}.fly.dev`);
140 expect(yield* initialText(`${url}/`)).toContain("SVELTEKIT_AWS_PAGE_MARKER v1");
141 expect(yield* getText(`${url}/api/hello?echo=roundtrip`)).toContain(
142 "SVELTEKIT_AWS_API_MARKER",
143 );
144 expect(JSON.parse(yield* getText(`${url}/api/deployment/version`))).toEqual({
145 version: "v1",
146 machine: oldId,
147 managedTimeout: null,
148 });
149 const oldMachine = yield* machines.getMachine({
150 app_name: appName,
151 machine_id: oldId,
152 });
153 expect(oldMachine.config?.checks?.website?.path).toBe("/api/deployment/ready");
154 expect(oldMachine.config?.services?.[0]?.checks?.[0]?.path).toBe("/api/deployment/ready");
155 expect(oldMachine.config?.stop_config?.signal).toBe(policy.signal);
156 expect(
157 sameStopConfig(oldMachine.config?.stop_config, {
158 signal: policy.signal,
159 timeout: `${policy.oldMs}ms`,
160 }),
161 ).toBe(true);
162 expect(oldMachine.config?.env?.ALCHEMY_FLY_SHUTDOWN_TIMEOUT_MS).toBeUndefined();
163
164 const slowStarted = yield* Deferred.make<void>();
165 const streamStarted = yield* Deferred.make<void>();
166 const slowRequest = (operation: string, started: Deferred.Deferred<void>) =>
167 HttpClient.get(`${url}/api/deployment/${operation}`, {
168 headers: { connection: "close" },
169 }).pipe(
170 Effect.tap((response) =>
171 Effect.gen(function* () {
172 expect(response.status).toBe(200);
173 expect(response.headers["x-website-machine"]).toBe(oldId);
174 expect(response.headers["x-website-version"]).toBe("v1");
175 yield* Deferred.succeed(started, undefined);
176 }),
177 ),
178 Effect.flatMap((response) => response.text),
179 Effect.timeout("10 minutes"),
180 );
181 const slow = yield* slowRequest("slow", slowStarted).pipe(Effect.forkScoped);
182 const streamed = yield* slowRequest("stream", streamStarted).pipe(Effect.forkScoped);
183 yield* Effect.all([Deferred.await(slowStarted), Deferred.await(streamStarted)], {
184 concurrency: "unbounded",
185 }).pipe(Effect.timeout("20 seconds"));
186 const traffic = yield* startTraffic(`${url}/api/deployment/version`);
187 yield* traffic.waitFor((body) => JSON.parse(body).version === "v1");
188 yield* writeVersion("v2");
189 const second = yield* deploy(true);
190 const newId = second.site.service!.machineId;
191 expect(second.site.url).toBe(url);
192 expect(newId).not.toBe(oldId);
193 const slowResult = JSON.parse(yield* Fiber.join(slow)) as ResponseRecord;
194 const streamBody = yield* Fiber.join(streamed);
195 const records = streamBody
196 .trim()
197 .split("\n")
198 .map((line) => JSON.parse(line) as ResponseRecord);
199 expect(records[0].event).toBe("started");
200 expect(records.filter((record) => record.event === "finished")).toHaveLength(1);
201 expect(records[records.length - 1].event).toBe("finished");
202 const completed = records[records.length - 1];
203 const payload = records.map((record) => record.payload ?? "").join("");
204 const expected = "website-v1\n".repeat(8192);
205 const hashes = yield* Effect.sync(() =>
206 [payload, expected].map((value) => createHash("sha256").update(value).digest("hex")),
207 );
208 expect(payload.length).toBe(expected.length);
209 expect(hashes[0]).toBe(hashes[1]);
210 for (const result of [slowResult, completed]) {
211 expect(result.version).toBe("v1");
212 expect(result.machine).toBe(oldId);
213 expect(result.managedTimeout).toBeNull();
214 expect(result.signal).toBe(policy.signal);
215 expect(result.shutdownMs).toBe(policy.oldMs);
216 expect(result.activeAtSignal).toBe(2);
217 expect(result.signaledAt).toBeGreaterThan(result.startedAt);
218 expect(result.completedAt - result.signaledAt).toBeGreaterThanOrEqual(policy.delay);
219 expect(result.completedAt - result.signaledAt).toBeLessThan(policy.oldMs);
220 }
221 expect(yield* getText(`${url}/`)).toContain("SVELTEKIT_AWS_PAGE_MARKER v2");
222 yield* traffic.waitFor((body) => JSON.parse(body).version === "v2");
223 const samples = yield* traffic.finish;
224 for (const body of samples) {
225 const sample = JSON.parse(body);
226 expect(sample).toEqual({
227 version: sample.version,
228 machine: sample.version === "v1" ? oldId : newId,
229 managedTimeout: null,
230 });
231 expect(["v1", "v2"]).toContain(sample.version);
232 }
233 const newMachine = yield* machines.getMachine({
234 app_name: appName,
235 machine_id: newId,
236 });
237 expect(newMachine.config?.stop_config?.signal).toBe(policy.nextSignal);
238 expect(
239 sameStopConfig(newMachine.config?.stop_config, {
240 signal: policy.nextSignal,
241 timeout: `${policy.nextMs}ms`,
242 }),
243 ).toBe(true);
244 expect(newMachine.config?.env?.ALCHEMY_FLY_SHUTDOWN_TIMEOUT_MS).toBeUndefined();
245 yield* assertMachineGone(appName, oldId);
246 yield* assertOnlyMachine(appName, newId);
247 }).pipe(
248 Effect.scoped,
249 Effect.ensuring(
250 Effect.gen(function* () {
251 yield* stack.destroy();
252 if (appName) yield* assertAppGone(appName);
253 }).pipe(Effect.orDie),
254 ),
255 );
256 }).pipe(logLevel),
257 // Includes two SSR/image builds, real registry pushes, old-policy drain and cleanup.
258 {
259 tags: ["provider:fly", "provider:fly:machine", "provider:fly:website", "live"],
260 timeout: 900_000,
261 },
262 );
263 }