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

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