@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 515 lines 20.6 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 { noopSession } from "alchemy/Report";
8 import * as Effect from "effect/Effect";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import * as Schema from "effect/Schema";
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 NetworkConfig = Schema.Struct({
19 privateNetworkDisabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
20 services: Schema.optional(
21 Schema.NullOr(
22 Schema.Record(
23 Schema.String,
24 Schema.NullOr(
25 Schema.Struct({
26 networking: Schema.optional(
27 Schema.NullOr(
28 Schema.Struct({
29 privateNetworkEndpoint: Schema.optional(Schema.NullOr(Schema.String)),
30 serviceDomains: Schema.optional(
31 Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown)),
32 ),
33 }),
34 ),
35 ),
36 }),
37 ),
38 ),
39 ),
40 ),
41 });
42
43 const readEnvironmentConfig = Query.fn((id: string) => {
44 const environment = RailwayApi.environment({ id });
45 return { config: environment.config, configEtag: environment.configEtag };
46 });
47
48 const createService = Query.fn(
49 (input: { projectId: string; environmentId: string; name: string; image: string }) => {
50 const service = RailwayApi.serviceCreate({
51 input: {
52 projectId: input.projectId,
53 environmentId: input.environmentId,
54 name: input.name,
55 source: { image: input.image },
56 },
57 });
58 return { id: service.id, name: service.name };
59 },
60 );
61
62 const deleteService = Query.fn((id: string) => RailwayApi.serviceDelete({ id }));
63
64 const commitEnvironmentPatch = Query.fn((environmentId: string, patch: unknown) =>
65 RailwayApi.environmentPatchCommit({ environmentId, patch }),
66 );
67
68 const deployServiceInstance = Query.fn((environmentId: string, serviceId: string) =>
69 RailwayApi.serviceInstanceDeploy({ environmentId, serviceId }),
70 );
71
72 const readPrivateNetworks = Query.fn((environmentId: string) =>
73 RailwayApi.privateNetworks({ environmentId }).pipe(
74 Query.map((network) => ({
75 publicId: network.publicId,
76 name: network.name,
77 dnsName: network.dnsName,
78 deletedAt: network.deletedAt,
79 })),
80 ),
81 );
82
83 const readEnvironmentPatches = Query.fn((environmentId: string) =>
84 RailwayApi.environmentPatches({ environmentId, first: 5 }).pipe(
85 Query.map((patch) => ({ status: patch.status, lastAppliedError: patch.lastAppliedError })),
86 ),
87 );
88
89 const readPrivateNetworkEndpoint = Query.fn(
90 (input: { environmentId: string; privateNetworkId: string; serviceId: string }) =>
91 RailwayApi.privateNetworkEndpoint(input).pipe(
92 Query.map((endpoint) => ({
93 publicId: endpoint.publicId,
94 dnsName: endpoint.dnsName,
95 deletedAt: endpoint.deletedAt,
96 syncStatus: endpoint.syncStatus,
97 })),
98 ),
99 );
100
101 const readConfig = Effect.fn(function* (environmentId: string) {
102 const environment = yield* readEnvironmentConfig(environmentId);
103 return {
104 config: yield* Schema.decodeUnknownEffect(NetworkConfig)(environment.config),
105 etag: environment.configEtag,
106 };
107 });
108
109 const lifecycle = (id: string) => ({
110 id,
111 fqn: id,
112 instanceId: id,
113 bindings: [],
114 session: { ...noopSession, note: () => Effect.void },
115 });
116
117 const networkStack = Effect.gen(function* () {
118 const { project, environment } = yield* suitePartition;
119 const network = yield* Railway.PrivateNetwork("Mesh", { environment });
120 return { project, environment, network };
121 });
122
123 const readEndpoint = (input: {
124 environmentId: string;
125 privateNetworkId: string;
126 serviceId: string;
127 }) =>
128 readPrivateNetworkEndpoint(input).pipe(
129 Effect.catchTag("RailwayNotFound", () => Effect.succeed(null)),
130 Effect.map((endpoint) =>
131 endpoint?.deletedAt == null &&
132 endpoint?.syncStatus !== "DELETED" &&
133 endpoint?.syncStatus !== "DELETING"
134 ? endpoint
135 : null,
136 ),
137 );
138
139 const waitForEndpoint = (input: Parameters<typeof readEndpoint>[0], dnsName?: string) =>
140 readEndpoint(input).pipe(
141 Effect.repeat({
142 schedule: Schedule.spaced("2 seconds"),
143 times: 8,
144 until: (endpoint) =>
145 endpoint != null && (dnsName === undefined || endpoint.dnsName === dnsName),
146 }),
147 Effect.tap((endpoint) =>
148 Effect.sync(() => {
149 expect(endpoint).not.toBeNull();
150 if (dnsName !== undefined) expect(endpoint?.dnsName).toBe(dnsName);
151 }),
152 ),
153 );
154
155 const setPrefix = (environmentId: string, serviceId: string, prefix: string | null) =>
156 commitEnvironmentPatch(environmentId, {
157 services: { [serviceId]: { networking: { privateNetworkEndpoint: prefix } } },
158 });
159
160 const tags = [
161 "provider:railway",
162 "provider:railway:privatenetwork",
163 "provider:railway:project",
164 "provider:railway:projectenvironment",
165 "live",
166 ];
167
168 test.provider(
169 "private network manages an already-enabled environment and leaves it enabled",
170 (stack) =>
171 Effect.gen(function* () {
172 yield* stack.destroy();
173 const partition = yield* stack.deploy(suitePartition);
174 const environmentId = partition.environment.environmentId;
175 const before = yield* readConfig(environmentId);
176 expect(before.config.privateNetworkDisabled ?? false).toBe(false);
177
178 const provider = yield* Provider.findProvider(Railway.PrivateNetwork);
179 for (const name of ["backend", "legacy-network"]) {
180 const rejected = yield* provider
181 .reconcile({
182 ...lifecycle("UnsupportedMesh"),
183 news: { environment: partition.environment, name },
184 olds: undefined,
185 output: undefined,
186 })
187 .pipe(Effect.result);
188 expect(rejected).toMatchObject({
189 _tag: "Failure",
190 failure: { _tag: "Railway.PrivateNetworkNameUnsupported", resourceName: name },
191 });
192 }
193
194 const created = yield* stack.deploy(networkStack);
195 expect(created.network.name).toBe("railway");
196 expect(created.network.environmentId).toBe(environmentId);
197 expect(created.network.projectId).toBe(partition.project.projectId);
198 expect(created.network.previousPrivateNetworkDisabled).toBe(false);
199 const enabled = yield* readConfig(environmentId);
200 expect(enabled.config.privateNetworkDisabled ?? false).toBe(false);
201 const networks = yield* readPrivateNetworks(environmentId);
202 expect(
203 networks.find(
204 (network) => network.publicId === created.network.publicId && network.deletedAt == null,
205 ),
206 ).toMatchObject({ name: "railway", dnsName: created.network.dnsName });
207
208 const repeated = yield* stack.deploy(networkStack);
209 expect(repeated.network.publicId).toBe(created.network.publicId);
210 expect((yield* readConfig(environmentId)).etag).toBe(enabled.etag);
211
212 // Removing the resource restores the captured (enabled) setting: no patch.
213 const retained = yield* stack.deploy(suitePartition);
214 expect(retained.environment.environmentId).toBe(environmentId);
215 const after = yield* readConfig(environmentId);
216 expect(after.etag).toBe(enabled.etag);
217 expect(after.config.privateNetworkDisabled ?? false).toBe(false);
218 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie)), logLevel),
219 { tags, timeout: 120_000 },
220 );
221
222 // Gated: since 2026-10 Railway accepts `environmentPatchCommit({ patch: {
223 // privateNetworkDisabled: true } })` (patch status COMMITTED, no
224 // lastAppliedError) but the environment config keeps
225 // `privateNetworkDisabled: false`, so the disabled precondition this test
226 // needs cannot be established. Set RAILWAY_TEST_PRIVATE_NETWORK_DISABLE=1 if
227 // Railway starts honoring the flag again.
228 test.provider.skipIf(!process.env.RAILWAY_TEST_PRIVATE_NETWORK_DISABLE)(
229 "private network enables the environment and restores its previous disabled flag",
230 (stack) =>
231 Effect.gen(function* () {
232 yield* stack.destroy();
233 const partition = yield* stack.deploy(suitePartition);
234 const environmentId = partition.environment.environmentId;
235 const service = yield* Effect.acquireRelease(
236 createService({
237 projectId: partition.project.projectId,
238 environmentId,
239 name: "private-network-disable-fixture",
240 image: "nginx:alpine",
241 }),
242 (service) =>
243 deleteService(service.id).pipe(
244 Effect.catchTag("RailwayNotFound", () => Effect.void),
245 Effect.orDie,
246 ),
247 );
248 const [platformNetwork] = yield* readPrivateNetworks(environmentId);
249 yield* waitForEndpoint({
250 environmentId,
251 privateNetworkId: platformNetwork!.publicId,
252 serviceId: service.id,
253 });
254 const disablePatch = yield* commitEnvironmentPatch(environmentId, {
255 privateNetworkDisabled: true,
256 });
257 yield* Effect.logInfo("Private-network disable commit", { disablePatch });
258 const disabled = yield* readConfig(environmentId).pipe(
259 Effect.repeat({
260 schedule: Schedule.spaced("1 second"),
261 times: 8,
262 until: ({ config }) => config.privateNetworkDisabled === true,
263 }),
264 );
265 yield* Effect.logInfo("Private-network disabled state", {
266 privateNetworkDisabled: disabled.config.privateNetworkDisabled,
267 patches: yield* readEnvironmentPatches(environmentId),
268 networks: yield* readPrivateNetworks(environmentId),
269 });
270 expect(disabled.config.privateNetworkDisabled).toBe(true);
271
272 const provider = yield* Provider.findProvider(Railway.PrivateNetwork);
273 for (const name of ["backend", "legacy-network"]) {
274 const rejected = yield* provider
275 .reconcile({
276 ...lifecycle("UnsupportedMesh"),
277 news: { environment: partition.environment, name },
278 olds: undefined,
279 output: undefined,
280 })
281 .pipe(Effect.result);
282 expect(rejected).toMatchObject({
283 _tag: "Failure",
284 failure: { _tag: "Railway.PrivateNetworkNameUnsupported", resourceName: name },
285 });
286 }
287 expect((yield* readConfig(environmentId)).etag).toBe(disabled.etag);
288
289 const created = yield* stack.deploy(networkStack);
290 expect(created.network.name).toBe("railway");
291 expect(created.network.environmentId).toBe(environmentId);
292 expect(created.network.projectId).toBe(partition.project.projectId);
293 expect(created.network.previousPrivateNetworkDisabled).toBe(true);
294 const enabled = yield* readConfig(environmentId);
295 expect(enabled.config.privateNetworkDisabled).toBe(false);
296 const networks = yield* readPrivateNetworks(environmentId);
297 expect(
298 networks.find(
299 (network) => network.publicId === created.network.publicId && network.deletedAt == null,
300 ),
301 ).toMatchObject({ name: "railway", dnsName: created.network.dnsName });
302
303 const props = { environment: partition.environment };
304 const refreshed = yield* provider.read!({
305 ...lifecycle("Mesh"),
306 olds: props,
307 output: created.network,
308 });
309 expect(refreshed?.previousPrivateNetworkDisabled).toBe(true);
310 const repeated = yield* stack.deploy(networkStack);
311 expect(repeated.network.publicId).toBe(created.network.publicId);
312 expect(repeated.network.previousPrivateNetworkDisabled).toBe(true);
313 expect((yield* readConfig(environmentId)).etag).toBe(enabled.etag);
314
315 // Legacy state cannot establish what the environment used to contain.
316 const { previousPrivateNetworkDisabled: _, ...legacy } = repeated.network;
317 yield* provider.delete({ ...lifecycle("Mesh"), olds: props, output: legacy });
318 expect((yield* readConfig(environmentId)).etag).toBe(enabled.etag);
319 expect((yield* readConfig(environmentId)).config.privateNetworkDisabled).toBe(false);
320
321 const retained = yield* stack.deploy(suitePartition);
322 expect(retained.environment.environmentId).toBe(environmentId);
323 const restored = yield* readConfig(environmentId);
324 expect(restored.config.privateNetworkDisabled).toBe(true);
325 for (let attempt = 0; attempt < 2; attempt++) {
326 yield* provider.delete({ ...lifecycle("Mesh"), olds: props, output: repeated.network });
327 }
328 expect((yield* readConfig(environmentId)).etag).toBe(restored.etag);
329 }).pipe(Effect.scoped, Effect.ensuring(stack.destroy().pipe(Effect.orDie)), logLevel),
330 {
331 tags: [
332 "provider:railway",
333 "provider:railway:privatenetwork",
334 "provider:railway:project",
335 "provider:railway:projectenvironment",
336 "live",
337 ],
338 timeout: 120_000,
339 },
340 );
341
342 test.provider(
343 "private endpoint updates platform DNS and restores only its own changes",
344 (stack) =>
345 Effect.gen(function* () {
346 yield* stack.destroy();
347 const base = yield* stack.deploy(networkStack);
348 const environmentId = base.environment.environmentId;
349
350 yield* Effect.acquireUseRelease(
351 createService({
352 projectId: base.project.projectId,
353 environmentId,
354 name: "private-network-fixture",
355 image: "nginx:alpine",
356 }),
357 (service) =>
358 Effect.gen(function* () {
359 const serviceRef = { serviceId: service.id, name: service.name };
360 const input = {
361 environmentId,
362 privateNetworkId: base.network.publicId,
363 serviceId: service.id,
364 };
365 if ((yield* readEndpoint(input)) === null) {
366 yield* deployServiceInstance(environmentId, service.id);
367 }
368 const platformEndpoint = yield* waitForEndpoint(input);
369 const domainKey = yield* Effect.sync(() => crypto.randomUUID());
370 yield* commitEnvironmentPatch(environmentId, {
371 services: {
372 [service.id]: {
373 networking: {
374 privateNetworkEndpoint: "original",
375 serviceDomains: { [domainKey]: {} },
376 },
377 },
378 },
379 });
380 yield* waitForEndpoint(input, "original");
381 const baseline = yield* readConfig(environmentId);
382 const baselineDomains =
383 baseline.config.services?.[service.id]?.networking?.serviceDomains;
384 expect(baselineDomains).toBeDefined();
385 expect(Object.keys(baselineDomains ?? {}).length).toBeGreaterThan(0);
386
387 const deployEndpoint = (name?: string) =>
388 stack
389 .deploy(
390 Effect.gen(function* () {
391 const partition = yield* networkStack;
392 const endpoint = yield* Railway.PrivateNetworkEndpoint("ApiDns", {
393 network: partition.network,
394 service: serviceRef,
395 ...(name === undefined ? {} : { name }),
396 });
397 return { ...partition, endpoint };
398 }),
399 )
400 .pipe(
401 Effect.tapError(() =>
402 readConfig(environmentId).pipe(
403 Effect.tap(({ config }) =>
404 Effect.logInfo("Endpoint configuration after failure", {
405 requested: name ?? null,
406 observed:
407 config.services?.[service.id]?.networking?.privateNetworkEndpoint ??
408 null,
409 }),
410 ),
411 ),
412 ),
413 );
414 const assertConfig = (prefix: string | null) =>
415 Effect.gen(function* () {
416 const { config } = yield* readConfig(environmentId);
417 const networking = config.services?.[service.id]?.networking;
418 expect(networking?.privateNetworkEndpoint ?? null).toBe(prefix);
419 expect(networking?.serviceDomains).toEqual(baselineDomains);
420 expect(config.privateNetworkDisabled).toBe(baseline.config.privateNetworkDisabled);
421 });
422 const provider = yield* Provider.findProvider(Railway.PrivateNetworkEndpoint);
423 const created = yield* deployEndpoint("api");
424 expect(created.endpoint.publicId).toBe(platformEndpoint?.publicId);
425 expect(created.endpoint.serviceId).toBe(service.id);
426 expect(created.endpoint.environmentId).toBe(environmentId);
427 expect(created.endpoint.privateNetworkId).toBe(base.network.publicId);
428 expect(created.endpoint.previousDnsPrefix).toBe("original");
429 expect(created.endpoint.dnsName).toBe("api");
430 yield* waitForEndpoint(input, created.endpoint.dnsName);
431 yield* assertConfig("api");
432
433 const props = { network: created.network, service: serviceRef, name: "api" };
434 const refreshed = yield* provider.read!({
435 ...lifecycle("ApiDns"),
436 olds: props,
437 output: created.endpoint,
438 });
439 expect(refreshed?.previousDnsPrefix).toBe("original");
440 const repeated = yield* deployEndpoint("api");
441 expect(repeated.endpoint.publicId).toBe(created.endpoint.publicId);
442 expect(repeated.endpoint.previousDnsPrefix).toBe("original");
443 yield* assertConfig("api");
444
445 const beforeLegacyDelete = yield* readConfig(environmentId);
446 const { previousDnsPrefix: _, ...legacy } = repeated.endpoint;
447 const legacyDeletion = yield* provider
448 .delete({ ...lifecycle("ApiDns"), olds: props, output: legacy })
449 .pipe(Effect.result);
450 expect(legacyDeletion).toMatchObject({
451 _tag: "Failure",
452 failure: { _tag: "Railway.PrivateNetworkEndpointRestoreUnavailable" },
453 });
454 expect((yield* readConfig(environmentId)).etag).toBe(beforeLegacyDelete.etag);
455 yield* assertConfig("api");
456
457 const renamed = yield* deployEndpoint("gateway");
458 expect(renamed.endpoint.publicId).toBe(created.endpoint.publicId);
459 expect(renamed.endpoint.previousDnsPrefix).toBe("original");
460 expect(renamed.endpoint.dnsName).toBe("gateway");
461 yield* waitForEndpoint(input, renamed.endpoint.dnsName);
462 yield* assertConfig("gateway");
463
464 const reset = yield* deployEndpoint();
465 expect(reset.endpoint.publicId).toBe(created.endpoint.publicId);
466 expect(reset.endpoint.previousDnsPrefix).toBe("original");
467 expect(reset.endpoint.dnsName).toBe(service.name);
468 yield* waitForEndpoint(input, reset.endpoint.dnsName);
469 yield* assertConfig(null);
470
471 const retained = yield* stack.deploy(networkStack);
472 expect(retained.environment.environmentId).toBe(environmentId);
473 expect(retained.network.publicId).toBe(base.network.publicId);
474 yield* assertConfig("original");
475 const restored = yield* waitForEndpoint(input, "original");
476 expect(restored?.publicId).toBe(created.endpoint.publicId);
477
478 const afterRestore = yield* readConfig(environmentId);
479 for (let attempt = 0; attempt < 2; attempt++) {
480 yield* provider.delete({
481 ...lifecycle("ApiDns"),
482 olds: { network: reset.network, service: serviceRef },
483 output: reset.endpoint,
484 });
485 }
486 expect((yield* readConfig(environmentId)).etag).toBe(afterRestore.etag);
487 yield* assertConfig("original");
488
489 const managedAgain = yield* deployEndpoint("api");
490 expect(managedAgain.endpoint.previousDnsPrefix).toBe("original");
491 yield* setPrefix(environmentId, service.id, "external");
492 yield* waitForEndpoint(input, "external");
493 yield* stack.deploy(networkStack);
494 yield* assertConfig("external");
495 const external = yield* waitForEndpoint(input, "external");
496 expect(external?.publicId).toBe(created.endpoint.publicId);
497 }),
498 (service) =>
499 deleteService(service.id).pipe(
500 Effect.catchTag("RailwayNotFound", () => Effect.void),
501 Effect.orDie,
502 ),
503 );
504 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie)), logLevel),
505 {
506 tags: [
507 "provider:railway",
508 "provider:railway:privatenetwork",
509 "provider:railway:project",
510 "provider:railway:projectenvironment",
511 "live",
512 ],
513 timeout: 120_000,
514 },
515 );