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

main
ts 375 lines 14 KB
Raw
1 import * as Railway from "@alchemy.run/railway";
2 import { RailwayAuth } from "@alchemy.run/railway/AuthProvider";
3 import { fromAuthProvider } from "@alchemy.run/railway/Credentials";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import { Query } from "@distilled.cloud/core/query";
7 import { GraphQLLive, Railway as RailwayApi } from "@distilled.cloud/railway";
8 import * as Alchemy from "alchemy";
9 import * as Provider from "alchemy/Provider";
10 import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as Layer from "effect/Layer";
14 import { MinimumLogLevel } from "effect/References";
15 import * as Schedule from "effect/Schedule";
16 import MongoApi, { Db, Site } from "./fixtures/mongo-api.ts";
17 import { suitePartition } from "./suiteProject.ts";
18 import { waitUntilVolumeGone } from "./waitUntilVolumeGone.ts";
19
20 const { test } = Test.make({ providers: Railway.providers() });
21
22 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
23
24 const distilled = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
25 effect.pipe(
26 Effect.provide(Layer.merge(GraphQLLive, fromAuthProvider().pipe(Layer.provide(RailwayAuth)))),
27 );
28
29 const ping = (url: string) =>
30 Railway.pingMongo(url).pipe(
31 // Allow the new database and TCP proxy to become ready. Ten retries
32 // bound backoff to 50 seconds within the test's overall timeout.
33 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 10 }),
34 );
35
36 const readVariables = Query.fn((projectId: string, environmentId: string, serviceId: string) =>
37 RailwayApi.variables({ projectId, environmentId, serviceId, unrendered: true }),
38 );
39
40 const readServiceDeletedAt = Query.fn((id: string) => ({
41 deletedAt: RailwayApi.service({ id }).deletedAt,
42 }));
43
44 const readService = Query.fn((id: string) => {
45 const service = RailwayApi.service({ id });
46 return {
47 id: service.id,
48 name: service.name,
49 projectId: service.projectId,
50 deletedAt: service.deletedAt,
51 };
52 });
53
54 const readServiceInstance = Query.fn((environmentId: string, serviceId: string) => {
55 const instance = RailwayApi.serviceInstance({ environmentId, serviceId });
56 return {
57 serviceId: instance.serviceId,
58 image: instance.source.image,
59 startCommand: instance.startCommand,
60 };
61 });
62
63 const readVolumeInstance = Query.fn((id: string) => {
64 const volume = RailwayApi.volumeInstance({ id });
65 return {
66 id: volume.id,
67 volumeId: volume.volumeId,
68 mountPath: volume.mountPath,
69 serviceId: volume.serviceId,
70 };
71 });
72
73 const readTcpProxies = Query.fn((environmentId: string, serviceId: string) =>
74 RailwayApi.tcpProxies({ environmentId, serviceId }).pipe(
75 Query.map((proxy) => ({
76 id: proxy.id,
77 domain: proxy.domain,
78 proxyPort: proxy.proxyPort,
79 applicationPort: proxy.applicationPort,
80 deletedAt: proxy.deletedAt,
81 syncStatus: proxy.syncStatus,
82 })),
83 ),
84 );
85
86 const asVariableMap = (value: unknown): Record<string, string> => {
87 if (value === null || typeof value !== "object" || Array.isArray(value)) {
88 return {};
89 }
90 const out: Record<string, string> = {};
91 for (const [key, item] of Object.entries(value)) {
92 if (typeof item === "string") {
93 out[key] = item;
94 }
95 }
96 return out;
97 };
98
99 const readServiceVariables = (projectId: string, environmentId: string, serviceId: string) =>
100 readVariables(projectId, environmentId, serviceId).pipe(
101 Effect.map(asVariableMap),
102 Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as Record<string, string>)),
103 );
104
105 const waitUntilServiceGone = (serviceId: string) =>
106 readServiceDeletedAt(serviceId).pipe(
107 Effect.map((service) => (service.deletedAt != null ? ("gone" as const) : ("found" as const))),
108 Effect.catchTag("RailwayNotFound", () => Effect.succeed("gone" as const)),
109 Effect.repeat({
110 schedule: Schedule.spaced("1 second"),
111 until: (status) => status === "gone",
112 times: 10,
113 }),
114 );
115
116 class NotReady extends Data.TaggedError("NotReady")<{ status: number; body?: unknown }> {
117 override get message() {
118 return this.body === undefined
119 ? `status ${this.status}`
120 : `status ${this.status}: ${JSON.stringify(this.body)}`;
121 }
122 }
123
124 const FixtureStack = Alchemy.Stack(
125 "RailwayMongoFixture",
126 { providers: Railway.providers(), state: Alchemy.localState() },
127 Effect.gen(function* () {
128 const project = yield* Site;
129 const db = yield* Db;
130 const api = yield* MongoApi;
131 return {
132 projectId: project.projectId,
133 environmentId: db.environmentId,
134 serviceId: api.serviceId,
135 url: api.url,
136 publicConnectionUri: db.publicConnectionUri,
137 mode: "effect" as const,
138 };
139 }),
140 );
141
142 test.provider(
143 "create, ping, update, list, and delete mongo",
144 (stack) =>
145 Effect.gen(function* () {
146 yield* stack.destroy();
147
148 const created = yield* stack.deploy(
149 Effect.gen(function* () {
150 const { project, environment } = yield* suitePartition;
151 const db = yield* Railway.mongo("Db", { project, environment });
152 return { project, environment, db };
153 }),
154 );
155
156 expect(created.db.serviceId).toEqual(expect.any(String));
157 expect(created.db.serviceId.length).toBeGreaterThan(0);
158 expect(created.db.projectId).toEqual(created.project.projectId);
159 expect(created.db.environmentId).toEqual(created.environment.environmentId);
160 expect(created.db.name).toEqual(expect.any(String));
161 expect(created.db.name.length).toBeGreaterThan(0);
162 expect(created.db.name.length).toBeLessThanOrEqual(32);
163 expect(created.db.name).toMatch(/^[a-z][a-z0-9-]*$/);
164 expect(created.db.user).toEqual("mongo");
165 expect(created.db.database).toEqual("railway");
166 expect(created.db.volumeId.length).toBeGreaterThan(0);
167 expect(created.db.volumeInstanceId.length).toBeGreaterThan(0);
168 expect(created.db.tcpProxyId).toEqual(expect.any(String));
169 expect(created.db.tcpProxyDomain).toEqual(expect.any(String));
170 expect(created.db.tcpProxyDomain).toContain("proxy.rlwy.net");
171 expect(created.db.tcpProxyPort).toEqual(expect.any(Number));
172 expect(created.db.tcpProxyPort).toBeGreaterThan(0);
173 expect(created.db.connectionUri.includes(`${created.db.name}.railway.internal`)).toEqual(
174 true,
175 );
176 expect(created.db.publicConnectionUri.includes(created.db.tcpProxyDomain!)).toEqual(true);
177
178 const fetched = yield* readService(created.db.serviceId);
179 expect(fetched.id).toEqual(created.db.serviceId);
180 expect(fetched.name).toEqual(created.db.name);
181 expect(fetched.projectId).toEqual(created.db.projectId);
182 expect(fetched.deletedAt).toBeNull();
183
184 const instance = yield* readServiceInstance(created.db.environmentId, created.db.serviceId);
185 expect(instance.serviceId).toEqual(created.db.serviceId);
186 expect(instance.image).toEqual(expect.stringContaining("mongo"));
187 expect(instance.startCommand ?? "").toContain("--ipv6");
188 expect(instance.startCommand ?? "").toContain("bind_ip");
189
190 const volume = yield* readVolumeInstance(created.db.volumeInstanceId);
191 expect(volume.id).toEqual(created.db.volumeInstanceId);
192 expect(volume.volumeId).toEqual(created.db.volumeId);
193 expect(volume.mountPath).toEqual("/data/db");
194 expect(volume.serviceId).toEqual(created.db.serviceId);
195
196 const proxies = yield* readTcpProxies(created.db.environmentId, created.db.serviceId);
197 const liveProxy = proxies.find(
198 (proxy) => proxy.deletedAt == null && proxy.syncStatus !== "DELETED",
199 );
200 expect(liveProxy).toBeDefined();
201 expect(liveProxy?.id).toEqual(created.db.tcpProxyId);
202 expect(liveProxy?.applicationPort).toEqual(27017);
203
204 const vars = yield* readServiceVariables(
205 created.db.projectId,
206 created.db.environmentId,
207 created.db.serviceId,
208 );
209 expect(vars.MONGO_INITDB_ROOT_USERNAME).toEqual("mongo");
210 expect((vars.MONGO_INITDB_ROOT_PASSWORD ?? "").length).toBeGreaterThan(0);
211 expect(vars[Railway.MONGO_URL_SECRET] ?? "").toContain(
212 "mongodb://${{MONGO_INITDB_ROOT_USERNAME}}",
213 );
214 expect(vars.MONGOHOST).toEqual("${{RAILWAY_PRIVATE_DOMAIN}}");
215 expect(vars.MONGOPORT).toEqual("27017");
216
217 const provider = yield* Provider.findProvider(Railway.Mongo);
218 const listed = yield* provider.list();
219 const found = listed.find((row) => row.serviceId === created.db.serviceId);
220 expect(found).toBeDefined();
221 expect(found?.name).toEqual(created.db.name);
222 expect(found?.projectId).toEqual(created.db.projectId);
223
224 const pong = yield* ping(created.db.publicConnectionUri);
225 expect(pong.ok).toEqual(1);
226
227 const nextName = created.db.name.slice(0, -1) + (created.db.name.endsWith("z") ? "y" : "z");
228
229 const updated = yield* stack.deploy(
230 Effect.gen(function* () {
231 const { project, environment } = yield* suitePartition;
232 const db = yield* Railway.mongo("Db", { project, environment, name: nextName });
233 return { project, environment, db };
234 }),
235 );
236
237 expect(updated.db.serviceId).toEqual(created.db.serviceId);
238 expect(updated.db.name).toEqual(nextName);
239 expect(updated.db.projectId).toEqual(created.db.projectId);
240 expect(updated.db.volumeId).toEqual(created.db.volumeId);
241 expect(updated.db.connectionUri.includes(`${nextName}.railway.internal`)).toEqual(true);
242
243 const fetchedUpdate = yield* readService(updated.db.serviceId);
244 expect(fetchedUpdate.id).toEqual(updated.db.serviceId);
245 expect(fetchedUpdate.name).toEqual(nextName);
246
247 const pongUpdate = yield* ping(updated.db.publicConnectionUri);
248 expect(pongUpdate.ok).toEqual(1);
249
250 yield* stack.destroy();
251
252 const gone = yield* waitUntilServiceGone(created.db.serviceId);
253 expect(gone).toEqual("gone");
254 const volumeGone = yield* waitUntilVolumeGone(created.db.volumeInstanceId);
255 expect(volumeGone).toEqual("gone");
256 }).pipe(logLevel),
257 {
258 tags: [
259 "provider:railway",
260 "provider:railway:mongo",
261 "provider:railway:project",
262 "provider:railway:projectenvironment",
263 "provider:railway:service",
264 "provider:railway:variable",
265 "live",
266 ],
267 timeout: 120_000,
268 },
269 );
270
271 // Runtime fixture failures must not prevent the independent resource lifecycle test.
272 describe(
273 "ConnectMongo runtime integrations",
274 {
275 tags: [
276 "provider:railway",
277 "provider:railway:mongo",
278 "provider:railway:project",
279 "provider:railway:projectenvironment",
280 "provider:railway:service",
281 "provider:railway:variable",
282 "live",
283 ],
284 },
285 () => {
286 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
287 providers: Railway.providers(),
288 });
289
290 // Db provisioning (32–60s) then the service build+deploy (58–90s+) run
291 // serially: 91–150s measured, so 120s timed out under full-suite load.
292 const fixture = beforeAll(deploy(FixtureStack), { timeout: 240_000 });
293 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(FixtureStack), { timeout: 120_000 });
294
295 test(
296 "a Service connects and pings through ConnectMongo",
297 Effect.gen(function* () {
298 const out = yield* fixture;
299 expect(out.serviceId).toEqual(expect.any(String));
300 expect(out.serviceId.length).toBeGreaterThan(0);
301 expect(out.url).toEqual(expect.any(String));
302 expect(out.url).toContain("up.railway.app");
303
304 const fetched = yield* distilled(readService(out.serviceId));
305 expect(fetched.id).toEqual(out.serviceId);
306 expect(fetched.deletedAt).toBeNull();
307
308 const vars = yield* distilled(
309 readServiceVariables(out.projectId, out.environmentId, out.serviceId),
310 );
311 expect((vars[Railway.MONGO_URL_SECRET] ?? "").length).toBeGreaterThan(0);
312
313 const client = yield* HttpClient.HttpClient;
314 const get = (path: string) =>
315 client.get(`${out.url}${path}`).pipe(
316 Effect.timeoutOrElse({
317 duration: "8 seconds",
318 orElse: () => Effect.fail(new NotReady({ status: 0 })),
319 }),
320 Effect.flatMap((res) =>
321 res.status === 200
322 ? res.json.pipe(Effect.mapError(() => new NotReady({ status: res.status })))
323 : Effect.fail(new NotReady({ status: res.status })),
324 ),
325 Effect.retry({
326 while: (e) =>
327 e._tag === "NotReady" &&
328 (e.status === 0 || e.status === 404 || e.status === 502 || e.status === 503),
329 schedule: Schedule.exponential("500 millis").pipe(
330 Schedule.upTo({ duration: "45 seconds" }),
331 ),
332 times: 10,
333 }),
334 );
335
336 const getText = client.get(out.url!).pipe(
337 Effect.timeoutOrElse({
338 duration: "8 seconds",
339 orElse: () => Effect.fail(new NotReady({ status: 0 })),
340 }),
341 Effect.flatMap((res) =>
342 res.status === 200
343 ? res.text.pipe(Effect.mapError(() => new NotReady({ status: res.status })))
344 : Effect.fail(new NotReady({ status: res.status })),
345 ),
346 Effect.retry({
347 while: (e) =>
348 e._tag === "NotReady" &&
349 (e.status === 0 || e.status === 404 || e.status === 502 || e.status === 503),
350 schedule: Schedule.exponential("500 millis").pipe(
351 Schedule.upTo({ duration: "45 seconds" }),
352 ),
353 times: 10,
354 }),
355 );
356
357 if (out.mode === "effect") {
358 const pingBody = (yield* get("/ping")) as { ok?: boolean };
359 expect(pingBody.ok).toEqual(true);
360
361 const health = (yield* get("/health")) as { ok?: number };
362 expect(health.ok).toEqual(1);
363 } else {
364 const body = yield* getText;
365 expect(typeof body).toEqual("string");
366 expect(body.length).toBeGreaterThan(0);
367 }
368
369 const pong = yield* ping(out.publicConnectionUri);
370 expect(pong.ok).toEqual(1);
371 }).pipe(logLevel),
372 { timeout: 120_000 },
373 );
374 },
375 );