@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 335 lines 11.8 KB
Raw
1 import * as Railway from "@alchemy.run/railway";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import { Query } from "@distilled.cloud/core/query";
5 import { Railway as RailwayApi } from "@distilled.cloud/railway";
6 import * as Provider from "alchemy/Provider";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Result from "effect/Result";
11 import * as Schedule from "effect/Schedule";
12 import { suitePartition } from "./suiteProject.ts";
13
14 const { test } = Test.make({ providers: Railway.providers() });
15
16 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
17
18 const isGoneStatus = (status: string | undefined) => status === "DESTROYED";
19
20 // Railway answers a missing sandbox with `null`, not an error.
21 const readSandboxStatus = Query.fn((environmentId: string, id: string) =>
22 RailwayApi.sandbox({ environmentId, id }).pipe(
23 Query.map((sandbox) => ({ status: sandbox.status })),
24 ),
25 );
26
27 const readSandbox = Query.fn((environmentId: string, id: string) =>
28 RailwayApi.sandbox({ environmentId, id }).pipe(
29 Query.map((sandbox) => ({
30 id: sandbox.id,
31 environmentId: sandbox.environmentId,
32 status: sandbox.status,
33 idleTimeoutMinutes: sandbox.idleTimeoutMinutes,
34 })),
35 ),
36 );
37
38 const readSandboxDomains = Query.fn((environmentId: string, id: string) =>
39 RailwayApi.sandbox({ environmentId, id }).pipe(
40 Query.map((sandbox) => ({
41 domains: sandbox.domains.pipe(
42 Query.map((domain) => ({
43 domain: domain.domain,
44 port: domain.port,
45 prefix: domain.prefix,
46 })),
47 ),
48 networkIsolation: sandbox.networkIsolation,
49 })),
50 ),
51 );
52
53 const createSandbox = Query.fn((input: { environmentId: string; idleTimeoutMinutes: number }) => {
54 const sandbox = RailwayApi.sandboxCreate({ input });
55 return { environmentId: sandbox.environmentId, id: sandbox.id };
56 });
57
58 const destroySandbox = Query.fn((environmentId: string, id: string) =>
59 RailwayApi.sandboxDestroy({ environmentId, id }).pipe(
60 Query.map((sandbox) => ({ id: sandbox.id })),
61 ),
62 );
63
64 const waitUntilGone = (environmentId: string, sandboxId: string) =>
65 readSandboxStatus(environmentId, sandboxId).pipe(
66 Effect.map((sandbox) =>
67 sandbox === null || isGoneStatus(sandbox.status) ? ("gone" as const) : ("found" as const),
68 ),
69 Effect.repeat({
70 schedule: Schedule.spaced("1 second"),
71 until: (status) => status === "gone",
72 times: 10,
73 }),
74 );
75
76 const destroyLive = (environmentId: string, sandboxId: string) =>
77 destroySandbox(environmentId, sandboxId).pipe(
78 Effect.flatMap(() => waitUntilGone(environmentId, sandboxId)),
79 );
80
81 test.provider(
82 "sandbox create succeeds or surfaces a typed authorization error",
83 (stack) =>
84 Effect.gen(function* () {
85 yield* stack.destroy();
86
87 const created = yield* stack.deploy(
88 Effect.gen(function* () {
89 const { project, environment } = yield* suitePartition;
90 return { project, environment };
91 }),
92 );
93
94 const result = yield* Effect.result(
95 createSandbox({ environmentId: created.environment.environmentId, idleTimeoutMinutes: 5 }),
96 );
97
98 if (Result.isSuccess(result)) {
99 yield* Effect.logInfo("sandboxes are entitled on this token; probe is a no-op");
100 yield* destroyLive(result.success.environmentId, result.success.id);
101 yield* stack.destroy();
102 return;
103 }
104
105 expect(result.failure._tag === "RailwayForbidden").toBe(true);
106
107 yield* stack.destroy();
108 }).pipe(logLevel),
109 {
110 tags: [
111 "provider:railway",
112 "provider:railway:project",
113 "provider:railway:projectenvironment",
114 "provider:railway:sandbox",
115 "live",
116 ],
117 timeout: 120_000,
118 },
119 );
120
121 test.provider(
122 "create, exec, and destroy a sandbox",
123 (stack) =>
124 Effect.gen(function* () {
125 yield* stack.destroy();
126
127 const created = yield* stack.deploy(
128 Effect.gen(function* () {
129 const { project, environment } = yield* suitePartition;
130 const box = yield* Railway.Sandbox("Box", { environment, idleTimeoutMinutes: 5 });
131 return { project, environment, box };
132 }),
133 );
134
135 expect(created.box.sandboxId).toEqual(expect.any(String));
136 expect(created.box.sandboxId.length).toBeGreaterThan(0);
137 expect(created.box.environmentId).toEqual(created.environment.environmentId);
138 expect(created.box.projectId).toEqual(created.project.projectId);
139 expect(created.box.status).toEqual("RUNNING");
140 expect(created.box.region).toEqual(expect.any(String));
141 expect(created.box.region.length).toBeGreaterThan(0);
142 expect(created.box.createdAt).toEqual(expect.any(String));
143 expect(created.box.idleTimeoutMinutes).toEqual(5);
144 expect(created.box.domains).toEqual([]);
145
146 const fetched = yield* readSandbox(created.box.environmentId, created.box.sandboxId);
147 if (fetched === null) {
148 return yield* Effect.fail(new Error("Deployed Railway sandbox was not found"));
149 }
150 expect(fetched.id).toEqual(created.box.sandboxId);
151 expect(fetched.environmentId).toEqual(created.box.environmentId);
152 expect(fetched.status).toEqual("RUNNING");
153 expect(fetched.idleTimeoutMinutes).toEqual(5);
154
155 const executed = yield* Railway.execSandbox({
156 sandboxId: created.box.sandboxId,
157 environmentId: created.box.environmentId,
158 command: "echo hello",
159 timeoutSec: 30,
160 });
161 expect(executed.exitCode).toEqual(0);
162 expect(executed.timedOut).toEqual(false);
163 expect(executed.stdout).toContain("hello");
164
165 const provider = yield* Provider.findProvider(Railway.Sandbox);
166 const listed = yield* provider.list();
167 const found = listed.find((sandbox) => sandbox.sandboxId === created.box.sandboxId);
168 expect(found).toBeDefined();
169 expect(found?.environmentId).toEqual(created.box.environmentId);
170 expect(found?.status).toEqual("RUNNING");
171
172 yield* stack.destroy();
173
174 const gone = yield* waitUntilGone(created.box.environmentId, created.box.sandboxId);
175 expect(gone).toEqual("gone");
176 }).pipe(logLevel),
177 {
178 tags: [
179 "provider:railway",
180 "provider:railway:project",
181 "provider:railway:projectenvironment",
182 "provider:railway:sandbox",
183 "live",
184 ],
185 timeout: 120_000,
186 },
187 );
188
189 test.provider(
190 "publishes a domain with custom resources and replaces removed options",
191 (stack) =>
192 Effect.gen(function* () {
193 yield* stack.destroy();
194 const deploy = (configured: boolean) =>
195 stack.deploy(
196 Effect.gen(function* () {
197 const { environment } = yield* suitePartition;
198 const box = yield* Railway.Sandbox("Preview", {
199 environment,
200 idleTimeoutMinutes: 5,
201 ...(configured
202 ? {
203 networkIsolation: "PRIVATE" as const,
204 publicDomains: [{ port: 8080 }],
205 resources: { cpu: 0.5, memoryGB: 1 },
206 variables: { ALCHEMY_SANDBOX_TEST: "configured" },
207 }
208 : {}),
209 });
210 return { box };
211 }),
212 );
213 const { box } = yield* deploy(true);
214 expect(box.status).toBe("RUNNING");
215 expect(box.networkIsolation).toBe("PRIVATE");
216 expect(box.domains).toHaveLength(1);
217 expect(box.domains[0]?.port).toBe(8080);
218 const observed = yield* readSandboxDomains(box.environmentId, box.sandboxId);
219 expect(observed?.domains).toEqual(box.domains);
220 const started = yield* Railway.execSandbox({
221 ...box,
222 command: `python3 -c 'import os, pathlib, subprocess; root = pathlib.Path("/tmp/alchemy-http"); root.mkdir(exist_ok=True); (root / "index.html").write_text(os.environ["ALCHEMY_SANDBOX_TEST"]); subprocess.Popen(["python3", "-m", "http.server", "8080", "--bind", "0.0.0.0", "--directory", str(root)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)'`,
223 timeoutSec: 10,
224 });
225 expect(started.exitCode).toBe(0);
226 const client = yield* HttpClient.HttpClient;
227 const body = yield* client.get(`https://${box.domains[0]!.domain}`).pipe(
228 Effect.flatMap((response) =>
229 response.status === 200
230 ? response.text
231 : Effect.fail(new Error(`HTTP ${response.status}`)),
232 ),
233 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 8 }),
234 );
235 expect(body).toBe("configured");
236 const unchanged = yield* deploy(true);
237 expect(unchanged.box.sandboxId).toBe(box.sandboxId);
238 const cleared = yield* deploy(false);
239 expect(cleared.box.sandboxId).not.toBe(box.sandboxId);
240 expect(cleared.box.domains).toEqual([]);
241 expect(cleared.box.networkIsolation).toBe("ISOLATED");
242 const env = yield* Railway.execSandbox({
243 ...cleared.box,
244 command: "printf '%s' \"${ALCHEMY_SANDBOX_TEST-unset}\"",
245 timeoutSec: 10,
246 });
247 expect(env.stdout).toBe("unset");
248 expect(yield* waitUntilGone(box.environmentId, box.sandboxId)).toBe("gone");
249 yield* stack.destroy();
250 expect(yield* waitUntilGone(cleared.box.environmentId, cleared.box.sandboxId)).toBe("gone");
251 }).pipe(logLevel),
252 {
253 tags: [
254 "provider:railway",
255 "provider:railway:project",
256 "provider:railway:projectenvironment",
257 "provider:railway:sandbox",
258 "live",
259 ],
260 timeout: 120_000,
261 },
262 );
263
264 test.provider(
265 "forks a running sandbox disk without inheriting variables",
266 (stack) =>
267 Effect.gen(function* () {
268 yield* stack.destroy();
269 const program = (fork: boolean) =>
270 Effect.gen(function* () {
271 const { environment } = yield* suitePartition;
272 const source = yield* Railway.Sandbox("Source", {
273 environment,
274 idleTimeoutMinutes: 5,
275 variables: { SOURCE_ONLY: "source" },
276 });
277 const copy = fork
278 ? yield* Railway.Sandbox("Fork", {
279 environment,
280 sourceSandboxId: source.sandboxId,
281 idleTimeoutMinutes: 5,
282 resources: { cpu: 1 },
283 variables: { FORK_ONLY: "fork" },
284 })
285 : undefined;
286 return { source, copy };
287 });
288 const { source } = yield* stack.deploy(program(false));
289 expect(
290 (yield* Railway.execSandbox({
291 ...source,
292 command: "printf disk-content > /tmp/alchemy-fork",
293 timeoutSec: 10,
294 })).exitCode,
295 ).toBe(0);
296 const { copy } = yield* stack.deploy(program(true));
297 expect(copy).toBeDefined();
298 expect(copy!.sandboxId).not.toBe(source.sandboxId);
299 const read = yield* Railway.execSandbox({
300 ...copy!,
301 command: 'cat /tmp/alchemy-fork; printf \'\\n%s:%s\' "${SOURCE_ONLY-unset}" "$FORK_ONLY"',
302 timeoutSec: 10,
303 });
304 expect(read.exitCode).toBe(0);
305 expect(read.stdout).toContain("disk-content");
306 expect(read.stdout).toContain("unset:fork");
307 expect(
308 (yield* Railway.execSandbox({
309 ...copy!,
310 command: "printf fork-content > /tmp/alchemy-fork",
311 timeoutSec: 10,
312 })).exitCode,
313 ).toBe(0);
314 expect(
315 (yield* Railway.execSandbox({
316 ...source,
317 command: "cat /tmp/alchemy-fork",
318 timeoutSec: 10,
319 })).stdout,
320 ).toBe("disk-content");
321 yield* stack.destroy();
322 expect(yield* waitUntilGone(source.environmentId, source.sandboxId)).toBe("gone");
323 expect(yield* waitUntilGone(copy!.environmentId, copy!.sandboxId)).toBe("gone");
324 }).pipe(logLevel),
325 {
326 tags: [
327 "provider:railway",
328 "provider:railway:project",
329 "provider:railway:projectenvironment",
330 "provider:railway:sandbox",
331 "live",
332 ],
333 timeout: 120_000,
334 },
335 );