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

main
ts 381 lines 13.4 KB
Raw
1 import * as Railway from "@alchemy.run/railway";
2 import { activeReplicaRegions, serviceRegionPlacement } from "@alchemy.run/railway/ServiceRegion";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import { Query } from "@distilled.cloud/core/query";
6 import { Railway as RailwayApi } from "@distilled.cloud/railway";
7 import * as Provider from "alchemy/Provider";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import { AsyncPing } from "./fixtures/async-ping-fn.ts";
13 import Ping from "./fixtures/ping.ts";
14 import { suitePartition } from "./suiteProject.ts";
15
16 const { test } = Test.make({ providers: Railway.providers() });
17
18 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
19
20 const HTTP_SOURCE = `
21 Bun.serve({
22 hostname: "0.0.0.0",
23 port: Number(process.env.PORT ?? 3000),
24 fetch() {
25 return new Response("ok");
26 },
27 });
28 `;
29
30 const readServiceDeletedAt = Query.fn((id: string) => ({
31 deletedAt: RailwayApi.service({ id }).deletedAt,
32 }));
33
34 const readService = Query.fn((id: string) => {
35 const service = RailwayApi.service({ id });
36 return {
37 id: service.id,
38 name: service.name,
39 projectId: service.projectId,
40 deletedAt: service.deletedAt,
41 };
42 });
43
44 const readServiceInstance = Query.fn((environmentId: string, serviceId: string) => {
45 const instance = RailwayApi.serviceInstance({ environmentId, serviceId });
46 return {
47 serviceId: instance.serviceId,
48 environmentId: instance.environmentId,
49 source: instance.source.pipe(Query.map((source) => ({ image: source.image }))),
50 startCommand: instance.startCommand,
51 cronSchedule: instance.cronSchedule,
52 };
53 });
54
55 const readBunRuntime = Query.fn(() => {
56 const runtime = RailwayApi.functionRuntime({ name: "bun" });
57 return { name: runtime.name, latestVersion: { image: runtime.latestVersion.image } };
58 });
59
60 const readEnvironmentConfig = Query.fn((id: string, projectId: string) => ({
61 config: RailwayApi.environment({ id, projectId }).config,
62 }));
63
64 const waitUntilGone = (serviceId: string) =>
65 readServiceDeletedAt(serviceId).pipe(
66 Effect.map((service) => (service.deletedAt != null ? ("gone" as const) : ("found" as const))),
67 Effect.catchTag("RailwayNotFound", () => Effect.succeed("gone" as const)),
68 Effect.repeat({
69 schedule: Schedule.spaced("1 second"),
70 until: (status) => status === "gone",
71 times: 10,
72 }),
73 );
74
75 test.provider(
76 "create, list, and delete a canvas Function",
77 (stack) =>
78 Effect.gen(function* () {
79 yield* stack.destroy();
80
81 const created = yield* stack.deploy(
82 Effect.gen(function* () {
83 const { project, environment } = yield* suitePartition;
84 const ping = yield* Railway.Function("Ping", {
85 project,
86 environment,
87 source: HTTP_SOURCE,
88 });
89 const job = yield* Railway.Function("Cleanup", {
90 project,
91 environment,
92 source: `console.log("tick");`,
93 cronSchedule: "0 * * * *",
94 });
95 return { project, environment, ping, job };
96 }),
97 );
98
99 expect(created.ping.serviceId).toEqual(expect.any(String));
100 expect(created.ping.serviceId.length).toBeGreaterThan(0);
101 expect(created.ping.projectId).toEqual(created.project.projectId);
102 expect(created.ping.environmentId).toEqual(created.environment.environmentId);
103 expect(created.ping.name).toEqual(expect.any(String));
104 expect(created.ping.name.length).toBeGreaterThan(0);
105 expect(created.ping.name.length).toBeLessThanOrEqual(32);
106 expect(created.ping.name).toMatch(/^[a-z][a-z0-9-]*$/);
107 expect(created.ping.runtime).toEqual("bun");
108 expect(created.ping.image).toEqual(expect.any(String));
109 expect(Railway.isFunctionImage(created.ping.image)).toEqual(true);
110 expect(created.ping.code.hash).toEqual(expect.any(String));
111 expect(created.ping.code.hash.length).toBeGreaterThan(0);
112 expect(created.ping.domain).toEqual(expect.any(String));
113 expect(created.ping.domain).toContain("up.railway.app");
114 expect(created.ping.url).toEqual(`https://${created.ping.domain}`);
115 expect(created.ping.dnsName).toEqual(`${created.ping.name}.railway.internal`);
116 expect(created.ping.rpcToken.length).toBeGreaterThanOrEqual(32);
117 expect(created.ping.domainId).toEqual(expect.any(String));
118 expect(created.ping.domainId!.length).toBeGreaterThan(0);
119
120 const fetched = yield* readService(created.ping.serviceId);
121 expect(fetched.id).toEqual(created.ping.serviceId);
122 expect(fetched.name).toEqual(created.ping.name);
123 expect(fetched.projectId).toEqual(created.ping.projectId);
124 expect(fetched.deletedAt).toBeNull();
125
126 const instance = yield* readServiceInstance(
127 created.ping.environmentId,
128 created.ping.serviceId,
129 );
130 expect(instance.serviceId).toEqual(created.ping.serviceId);
131 expect(instance.environmentId).toEqual(created.ping.environmentId);
132 expect(Railway.isFunctionImage(instance.source?.image)).toEqual(true);
133 expect(instance.startCommand).toEqual(expect.stringMatching(/^\.\/run\.sh /));
134
135 const runtime = yield* readBunRuntime();
136 expect(runtime.name).toEqual("bun");
137 expect(runtime.latestVersion.image.length).toBeGreaterThan(0);
138 expect(instance.source?.image).toEqual(runtime.latestVersion.image);
139
140 const provider = yield* Provider.findProvider(Railway.Function);
141 const listed = yield* provider.list();
142 const found = listed.find((fn) => fn.serviceId === created.ping.serviceId);
143 expect(found).toBeDefined();
144 expect(found?.name).toEqual(created.ping.name);
145 expect(found?.projectId).toEqual(created.ping.projectId);
146 expect(Railway.isFunctionImage(found?.image)).toEqual(true);
147
148 const client = yield* HttpClient.HttpClient;
149 const body = yield* client.get(created.ping.url!).pipe(
150 Effect.flatMap((res) =>
151 res.status === 200 ? res.text : Effect.fail(new Error(`function returned ${res.status}`)),
152 ),
153 Effect.retry({ schedule: Schedule.spaced("4 seconds"), times: 10 }),
154 );
155 expect(body).toEqual("ok");
156
157 expect(created.job.serviceId).toEqual(expect.any(String));
158 expect(created.job.cronSchedule).toEqual("0 * * * *");
159 expect(created.job.url).toBeUndefined();
160 expect(created.job.domain).toBeUndefined();
161 const jobInstance = yield* readServiceInstance(
162 created.job.environmentId,
163 created.job.serviceId,
164 );
165 expect(jobInstance.cronSchedule).toEqual("0 * * * *");
166 expect(Railway.isFunctionImage(jobInstance.source?.image)).toEqual(true);
167
168 yield* stack.destroy();
169
170 const gone = yield* waitUntilGone(created.ping.serviceId);
171 expect(gone).toEqual("gone");
172 }).pipe(logLevel),
173 {
174 tags: [
175 "provider:railway",
176 "provider:railway:function",
177 "provider:railway:project",
178 "provider:railway:projectenvironment",
179 "provider:railway:service",
180 "live",
181 ],
182 timeout: 120_000,
183 },
184 );
185
186 test.provider(
187 "create, serve, and delete an async Function (main + fetch, no Effect)",
188 (stack) =>
189 Effect.gen(function* () {
190 yield* stack.destroy();
191
192 const created = yield* stack.deploy(
193 Effect.gen(function* () {
194 const ping = yield* AsyncPing;
195 return { ping };
196 }),
197 );
198
199 expect(created.ping.serviceId).toEqual(expect.any(String));
200 expect(created.ping.runtime).toEqual("bun");
201 expect(Railway.isFunctionImage(created.ping.image)).toEqual(true);
202 expect(created.ping.code.hash).toEqual(expect.any(String));
203 expect(created.ping.domain).toContain("up.railway.app");
204 expect(created.ping.url).toEqual(`https://${created.ping.domain}`);
205 expect(created.ping.dnsName).toEqual(`${created.ping.name}.railway.internal`);
206
207 const instance = yield* readServiceInstance(
208 created.ping.environmentId,
209 created.ping.serviceId,
210 );
211 expect(Railway.isFunctionImage(instance.source?.image)).toEqual(true);
212 expect(instance.startCommand).toEqual(expect.stringMatching(/^\.\/run\.sh /));
213 expect(instance.startCommand!.length).toBeLessThanOrEqual(Railway.FUNCTION_MAX_BYTES);
214
215 const client = yield* HttpClient.HttpClient;
216 const body = yield* client.get(created.ping.url!).pipe(
217 Effect.flatMap((res) =>
218 res.status === 200
219 ? res.text
220 : res.text.pipe(
221 Effect.flatMap((text) =>
222 Effect.fail(new Error(`function returned ${res.status}: ${text}`)),
223 ),
224 ),
225 ),
226 Effect.retry({ schedule: Schedule.spaced("4 seconds"), times: 10 }),
227 );
228 expect(body).toEqual("ok");
229
230 yield* stack.destroy();
231
232 const gone = yield* waitUntilGone(created.ping.serviceId);
233 expect(gone).toEqual("gone");
234 }).pipe(logLevel),
235 {
236 tags: [
237 "provider:railway",
238 "provider:railway:function",
239 "provider:railway:project",
240 "provider:railway:projectenvironment",
241 "provider:railway:service",
242 "live",
243 ],
244 timeout: 120_000,
245 },
246 );
247
248 test.provider.skip(
249 "create, serve, and delete an Effect-native Function (canvas start command max 96KB)",
250 (stack) =>
251 Effect.gen(function* () {
252 yield* stack.destroy();
253
254 const created = yield* stack.deploy(
255 Effect.gen(function* () {
256 const ping = yield* Ping;
257 return { ping };
258 }),
259 );
260
261 expect(created.ping.serviceId).toEqual(expect.any(String));
262 expect(created.ping.runtime).toEqual("bun");
263 expect(Railway.isFunctionImage(created.ping.image)).toEqual(true);
264 expect(created.ping.code.hash).toEqual(expect.any(String));
265 expect(created.ping.domain).toContain("up.railway.app");
266 expect(created.ping.url).toEqual(`https://${created.ping.domain}`);
267 expect(created.ping.dnsName).toEqual(`${created.ping.name}.railway.internal`);
268 expect(created.ping.rpcToken.length).toBeGreaterThanOrEqual(32);
269
270 const instance = yield* readServiceInstance(
271 created.ping.environmentId,
272 created.ping.serviceId,
273 );
274 expect(Railway.isFunctionImage(instance.source?.image)).toEqual(true);
275 expect(instance.startCommand).toEqual(expect.stringMatching(/^\.\/run\.sh /));
276
277 const client = yield* HttpClient.HttpClient;
278 const body = yield* client.get(created.ping.url!).pipe(
279 Effect.timeout("10 seconds"),
280 Effect.flatMap((res) =>
281 res.status === 200
282 ? res.text
283 : res.text.pipe(
284 Effect.flatMap((text) =>
285 Effect.fail(new Error(`function returned ${res.status}: ${text}`)),
286 ),
287 ),
288 ),
289 Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 5 }),
290 );
291 expect(body).toEqual("ok");
292
293 yield* stack.destroy();
294
295 const gone = yield* waitUntilGone(created.ping.serviceId);
296 expect(gone).toEqual("gone");
297 }).pipe(logLevel),
298 {
299 tags: [
300 "provider:railway",
301 "provider:railway:function",
302 "provider:railway:project",
303 "provider:railway:projectenvironment",
304 "provider:railway:service",
305 "live",
306 ],
307 timeout: 120_000,
308 },
309 );
310
311 const placedRegions = (config: unknown, serviceId: string) =>
312 activeReplicaRegions(serviceRegionPlacement(config, serviceId)).map((row) => row.region);
313
314 test.provider(
315 "pin a function to a region and move it",
316 (stack) =>
317 Effect.gen(function* () {
318 yield* stack.destroy();
319
320 const region = "europe-west4-drams3a";
321 const created = yield* stack.deploy(
322 Effect.gen(function* () {
323 const { project, environment } = yield* suitePartition;
324 const ping = yield* Railway.Function("FnRegion", {
325 project,
326 environment,
327 source: `console.log("tick");`,
328 http: false,
329 region,
330 });
331 return { ping };
332 }),
333 );
334
335 expect(created.ping.region).toEqual(region);
336 const createdConfig = yield* readEnvironmentConfig(
337 created.ping.environmentId,
338 created.ping.projectId,
339 );
340 expect(placedRegions(createdConfig.config, created.ping.serviceId)).toEqual([region]);
341
342 const moved = "us-west2";
343 const updated = yield* stack.deploy(
344 Effect.gen(function* () {
345 const { project, environment } = yield* suitePartition;
346 const ping = yield* Railway.Function("FnRegion", {
347 project,
348 environment,
349 source: `console.log("tick");`,
350 http: false,
351 region: moved,
352 });
353 return { ping };
354 }),
355 );
356
357 expect(updated.ping.serviceId).toEqual(created.ping.serviceId);
358 expect(updated.ping.region).toEqual(moved);
359 const updatedConfig = yield* readEnvironmentConfig(
360 updated.ping.environmentId,
361 updated.ping.projectId,
362 );
363 expect(placedRegions(updatedConfig.config, updated.ping.serviceId)).toEqual([moved]);
364
365 yield* stack.destroy();
366
367 const gone = yield* waitUntilGone(created.ping.serviceId);
368 expect(gone).toEqual("gone");
369 }).pipe(logLevel),
370 {
371 tags: [
372 "provider:railway",
373 "provider:railway:function",
374 "provider:railway:project",
375 "provider:railway:projectenvironment",
376 "provider:railway:service",
377 "live",
378 ],
379 timeout: 180_000,
380 },
381 );