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

main
ts 458 lines 15 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import { Railway, type ServiceDomain as RailwayServiceDomain } from "@distilled.cloud/railway";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import { waitUntilDeleted } from "./GraphQL.ts";
7 import { sanitizeRailwayName } from "./Metadata.ts";
8 import { withEnvironmentConfigLock } from "./transient.ts";
9
10 const domainFields = <E>(domain: Query<RailwayServiceDomain, E>) => ({
11 id: domain.id,
12 domain: domain.domain,
13 serviceId: domain.serviceId,
14 environmentId: domain.environmentId,
15 projectId: domain.projectId,
16 targetPort: domain.targetPort,
17 suffix: domain.suffix,
18 deletedAt: domain.deletedAt,
19 syncStatus: domain.syncStatus,
20 });
21 type DomainsResponseServiceDomainsItem = UnwrapPlan<ReturnType<typeof domainFields>>;
22
23 const readServiceDomains = Query.fn((projectId: string, environmentId: string, serviceId: string) =>
24 Railway.domains({ environmentId, projectId, serviceId }).serviceDomains.pipe(
25 Query.map(domainFields),
26 ),
27 );
28
29 const serviceDomainCreate = Query.fn((input: { environmentId: string; serviceId: string }) =>
30 domainFields(Railway.serviceDomainCreate({ input })),
31 );
32
33 const serviceDomainUpdate = Query.fn(
34 (input: {
35 domain: string;
36 environmentId: string;
37 serviceDomainId: string;
38 serviceId: string;
39 targetPort?: number;
40 }) => Railway.serviceDomainUpdate({ input }),
41 );
42
43 const serviceDomainDelete = Query.fn((id: string) => Railway.serviceDomainDelete({ id }));
44
45 const environmentPatchCommit = Query.fn(
46 (input: { environmentId: string; commitMessage: string; patch: Record<string, unknown> }) =>
47 Railway.environmentPatchCommit(input),
48 );
49
50 /**
51 * A Railway-generated `*.up.railway.app` hostname on a Service. Created
52 * with `serviceDomainCreate`. Distinct from {@link CustomDomain} (a user
53 * hostname).
54 */
55 export type ServiceDomainRecord = {
56 id: string;
57 domain: string;
58 serviceId: string;
59 environmentId: string;
60 projectId: string | undefined;
61 targetPort: number | undefined;
62 syncStatus: string;
63 url: string;
64 };
65
66 export class ServiceDomainNotCreated extends Data.TaggedError("Railway.ServiceDomainNotCreated")<{
67 serviceId: string;
68 environmentId: string;
69 }> {}
70
71 type CloudDomain = DomainsResponseServiceDomainsItem;
72
73 const isGone = (domain: CloudDomain | undefined) =>
74 domain === undefined ||
75 domain.deletedAt != null ||
76 domain.syncStatus === "DELETED" ||
77 domain.syncStatus === "DELETING";
78
79 const toRecord = (domain: CloudDomain): ServiceDomainRecord => ({
80 id: domain.id,
81 domain: domain.domain,
82 serviceId: domain.serviceId,
83 environmentId: domain.environmentId,
84 projectId: domain.projectId ?? undefined,
85 targetPort: domain.targetPort ?? undefined,
86 syncStatus: domain.syncStatus,
87 url: `https://${domain.domain}`,
88 });
89
90 export const listServiceDomains = (projectId: string, environmentId: string, serviceId: string) =>
91 readServiceDomains(projectId, environmentId, serviceId).pipe(
92 Effect.map((serviceDomains) => serviceDomains.filter((domain) => !isGone(domain))),
93 Effect.catchTag("RailwayNotFound", () =>
94 Effect.succeed([] as DomainsResponseServiceDomainsItem[]),
95 ),
96 );
97
98 const findCloudDomainById = (input: {
99 projectId: string;
100 environmentId: string;
101 serviceId: string;
102 domainId: string;
103 }) =>
104 readServiceDomains(input.projectId, input.environmentId, input.serviceId).pipe(
105 Effect.map((serviceDomains) =>
106 serviceDomains.find((candidate) => candidate.id === input.domainId),
107 ),
108 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
109 );
110
111 export const findServiceDomainById = Effect.fn(function* (input: {
112 projectId: string;
113 environmentId: string;
114 serviceId: string;
115 domainId: string;
116 }) {
117 const domain = yield* findCloudDomainById(input);
118 return domain === undefined || isGone(domain) ? undefined : toRecord(domain);
119 });
120
121 export const deleteServiceDomainById = Effect.fn(function* (input: {
122 projectId: string;
123 environmentId: string;
124 serviceId: string;
125 domainId: string;
126 }) {
127 yield* deleteOwnedServiceDomain(input);
128 });
129
130 /**
131 * Remove the owned generated domain. Environment config is the source of
132 * truth (`serviceDomains[id]: null`); GraphQL delete is the fallback.
133 * Matches the recorded id and, if that id is missing from the live list,
134 * the recorded hostname — never every generated domain.
135 */
136 export const deleteOwnedServiceDomain = Effect.fn(function* (input: {
137 projectId: string;
138 environmentId: string;
139 serviceId: string;
140 domainId?: string;
141 domain?: string;
142 }) {
143 if (input.domainId === undefined && input.domain === undefined) return;
144
145 const live = yield* listServiceDomains(input.projectId, input.environmentId, input.serviceId);
146 const owned = live.filter(
147 (row) =>
148 (input.domainId !== undefined && row.id === input.domainId) ||
149 (input.domain !== undefined && row.domain === input.domain),
150 );
151 const keys = new Set<string>([
152 ...(input.domainId !== undefined ? [input.domainId] : []),
153 ...owned.map((row) => row.id),
154 ]);
155 if (keys.size === 0) return;
156
157 yield* withEnvironmentConfigLock(
158 input.environmentId,
159 environmentPatchCommit({
160 environmentId: input.environmentId,
161 commitMessage: "Remove Railway service domain",
162 patch: {
163 services: {
164 [input.serviceId]: {
165 networking: { serviceDomains: Object.fromEntries([...keys].map((id) => [id, null])) },
166 },
167 },
168 },
169 }),
170 ).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
171
172 for (const row of owned) {
173 if (row.syncStatus === "DELETING") continue;
174 yield* withEnvironmentConfigLock(input.environmentId, serviceDomainDelete(row.id)).pipe(
175 Effect.catchTag("RailwayNotFound", () => Effect.void),
176 Effect.asVoid,
177 );
178 }
179
180 yield* waitUntilDeleted(
181 "ServiceDomain",
182 [...keys].join(","),
183 listServiceDomains(input.projectId, input.environmentId, input.serviceId).pipe(
184 Effect.map(
185 (rows) =>
186 !rows.some(
187 (row) =>
188 keys.has(row.id) || (input.domain !== undefined && row.domain === input.domain),
189 ),
190 ),
191 ),
192 10,
193 );
194 });
195
196 const listedOrUndefined = (input: {
197 projectId: string;
198 environmentId: string;
199 serviceId: string;
200 domainId?: string | null;
201 }) =>
202 listServiceDomains(input.projectId, input.environmentId, input.serviceId).pipe(
203 Effect.map((rows) =>
204 input.domainId === undefined
205 ? (rows[0] as CloudDomain | undefined)
206 : input.domainId === null
207 ? undefined
208 : rows.find((domain) => domain.id === input.domainId),
209 ),
210 );
211
212 /**
213 * Railway's own IaC compiler writes generated domains through
214 * `environmentPatchCommit` as `services[id].networking.serviceDomains[uuid]`.
215 * The GraphQL `serviceDomainCreate` mutation is a convenience wrapper the
216 * CLI also uses; the patch is what `.railway/railway.ts` apply goes through
217 * (and what the environment schema documents as "make publicly accessible
218 * over HTTP").
219 *
220 * @see https://backboard.railway.com/schema/environment.schema.json
221 */
222 const createViaEnvironmentPatch = (input: { environmentId: string; serviceId: string }) =>
223 Effect.gen(function* () {
224 const domainKey = yield* Effect.sync(() => crypto.randomUUID());
225 yield* withEnvironmentConfigLock(
226 input.environmentId,
227 environmentPatchCommit({
228 environmentId: input.environmentId,
229 commitMessage: "Generate Railway service domain",
230 patch: {
231 services: { [input.serviceId]: { networking: { serviceDomains: { [domainKey]: {} } } } },
232 },
233 }),
234 );
235 return domainKey;
236 });
237
238 /**
239 * Official CLI / public-API mutation. Same input as
240 * `railway domain` (`environmentId` + `serviceId`; optional `targetPort`
241 * is omitted on create — pinning a port while PORT is set makes Railway
242 * reject the mutation).
243 *
244 * @see https://docs.railway.com/integrations/api/manage-domains
245 */
246 const waitForServiceDomainById = (input: {
247 projectId: string;
248 environmentId: string;
249 serviceId: string;
250 domainId: string;
251 }) =>
252 findCloudDomainById(input).pipe(
253 Effect.repeat({
254 schedule: Schedule.spaced("1 second"),
255 until: (domain) => domain !== undefined && !isGone(domain),
256 times: 8,
257 }),
258 Effect.map((domain) => (domain !== undefined && !isGone(domain) ? domain : undefined)),
259 );
260
261 /**
262 * The environment-config map key is supposed to be the GraphQL domain id,
263 * but the live `domains` list can lag or mint a different id. Prefer the
264 * patch key; otherwise take a domain that was not in the pre-patch set so
265 * we do not claim a foreign generated domain and do not `serviceDomainCreate`
266 * a second hostname.
267 */
268 const waitForNewServiceDomain = (input: {
269 projectId: string;
270 environmentId: string;
271 serviceId: string;
272 preferId: string;
273 preexistingIds: ReadonlySet<string>;
274 }) =>
275 listServiceDomains(input.projectId, input.environmentId, input.serviceId).pipe(
276 Effect.repeat({
277 schedule: Schedule.spaced("1 second"),
278 until: (rows) =>
279 rows.some((domain) => domain.id === input.preferId || !input.preexistingIds.has(domain.id)),
280 times: 10,
281 }),
282 Effect.map(
283 (rows) =>
284 rows.find((domain) => domain.id === input.preferId) ??
285 rows.find((domain) => !input.preexistingIds.has(domain.id)),
286 ),
287 );
288
289 const createViaMutation = (input: {
290 projectId: string;
291 environmentId: string;
292 serviceId: string;
293 domainId?: string;
294 }) => {
295 const listed =
296 input.domainId === undefined
297 ? listedOrUndefined(input)
298 : waitForServiceDomainById({ ...input, domainId: input.domainId });
299 const missing = () =>
300 new ServiceDomainNotCreated({ serviceId: input.serviceId, environmentId: input.environmentId });
301 const listedOrFail = <E>(error: E) =>
302 listed.pipe(
303 Effect.flatMap((row) => (row !== undefined ? Effect.succeed(row) : Effect.fail(error))),
304 );
305 const create = serviceDomainCreate({
306 environmentId: input.environmentId,
307 serviceId: input.serviceId,
308 }).pipe(
309 Effect.flatMap((created) =>
310 input.domainId === undefined ? listedOrFail(missing()) : Effect.succeed(created),
311 ),
312 Effect.catchTags({
313 RailwayServiceDomainCreateFailed: (error) => listedOrFail(error),
314 RailwayServiceInstanceNotFound: (error) =>
315 input.domainId !== undefined ? listedOrFail(error) : Effect.fail(error),
316 }),
317 Effect.catchTag("RailwayValidationError", (error) => listedOrFail(error)),
318 );
319
320 return withEnvironmentConfigLock(input.environmentId, create).pipe(
321 Effect.retry({
322 while: (error) =>
323 (input.domainId === undefined && error._tag === "RailwayServiceDomainCreateFailed") ||
324 error._tag === "RailwayServiceInstanceNotFound",
325 times: 10,
326 schedule: Schedule.spaced("5 seconds"),
327 }),
328 );
329 };
330
331 /**
332 * Terraform `railway_service_domain` requires `subdomain` and, after
333 * create, immediately `serviceDomainUpdate`s to `{subdomain}.{suffix}`.
334 * Create itself cannot take a subdomain — the GraphQL input only has
335 * `environmentId` / `serviceId` / optional `targetPort`.
336 *
337 * @see https://github.com/terraform-community-providers/terraform-provider-railway/blob/master/internal/provider/resource_service_domain.go
338 */
339 const desiredDomainName = (input: {
340 subdomain: string | undefined;
341 suffix: string | null | undefined;
342 }) => {
343 if (input.subdomain === undefined || input.subdomain.length === 0) {
344 return undefined;
345 }
346 if (input.suffix === undefined || input.suffix === null || input.suffix.length === 0) {
347 return undefined;
348 }
349 const subdomain = sanitizeRailwayName(input.subdomain);
350 return `${subdomain}.${input.suffix}`;
351 };
352
353 const syncDomain = (input: {
354 current: CloudDomain;
355 subdomain: string | undefined;
356 targetPort: number | undefined;
357 }) => {
358 const domainName = desiredDomainName({
359 subdomain: input.subdomain,
360 suffix: input.current.suffix,
361 });
362 const observedPort = input.current.targetPort ?? undefined;
363 const rename = domainName !== undefined && domainName !== input.current.domain;
364 const retarget = input.targetPort !== undefined && input.targetPort !== observedPort;
365 if (!rename && !retarget) return Effect.undefined;
366 return withEnvironmentConfigLock(
367 input.current.environmentId,
368 serviceDomainUpdate({
369 domain: domainName ?? input.current.domain,
370 environmentId: input.current.environmentId,
371 serviceDomainId: input.current.id,
372 serviceId: input.current.serviceId,
373 ...(retarget ? { targetPort: input.targetPort } : {}),
374 }),
375 );
376 };
377
378 /**
379 * Observe-ensure-sync a generated `*.up.railway.app` domain. Creates one
380 * when missing (environment-config patch, then the public mutation),
381 * claims a stable `{subdomain}.{suffix}` like Terraform, updates
382 * `targetPort` in place, and returns the live record.
383 *
384 * Create itself cannot take a subdomain — Railway assigns
385 * `{serviceName}-{environmentName}.up.railway.app`. That first DNS label
386 * must be ≤ 63 characters or the API returns "please try again". Extra
387 * environments are capped at 24 chars so a 32-char service still fits.
388 */
389 export const ensureServiceDomain = Effect.fn(function* (input: {
390 projectId: string;
391 environmentId: string;
392 serviceId: string;
393 domainId?: string | null;
394 /** DNS label claimed via `serviceDomainUpdate`, Terraform-style. */
395 subdomain?: string;
396 targetPort?: number;
397 }) {
398 let current: CloudDomain | undefined = yield* listedOrUndefined(input);
399
400 let createdDomainId: string | undefined;
401 if (current === undefined) {
402 const preexisting = yield* listServiceDomains(
403 input.projectId,
404 input.environmentId,
405 input.serviceId,
406 );
407 createdDomainId = yield* createViaEnvironmentPatch({
408 environmentId: input.environmentId,
409 serviceId: input.serviceId,
410 });
411 current = yield* waitForNewServiceDomain({
412 projectId: input.projectId,
413 environmentId: input.environmentId,
414 serviceId: input.serviceId,
415 preferId: createdDomainId,
416 preexistingIds: new Set(preexisting.map((domain) => domain.id)),
417 });
418 }
419
420 if (current === undefined) {
421 if (input.domainId === undefined) {
422 current = yield* createViaMutation({
423 projectId: input.projectId,
424 environmentId: input.environmentId,
425 serviceId: input.serviceId,
426 });
427 } else {
428 const domainId = createdDomainId;
429 if (domainId === undefined) {
430 return yield* new ServiceDomainNotCreated({
431 serviceId: input.serviceId,
432 environmentId: input.environmentId,
433 });
434 }
435 current = yield* createViaMutation({ ...input, domainId });
436 }
437 }
438
439 if (current === undefined || isGone(current)) {
440 return yield* new ServiceDomainNotCreated({
441 serviceId: input.serviceId,
442 environmentId: input.environmentId,
443 });
444 }
445
446 yield* syncDomain({ current, subdomain: input.subdomain, targetPort: input.targetPort });
447
448 current = (yield* listedOrUndefined({ ...input, domainId: current.id })) ?? current;
449
450 if (current === undefined || isGone(current)) {
451 return yield* new ServiceDomainNotCreated({
452 serviceId: input.serviceId,
453 environmentId: input.environmentId,
454 });
455 }
456
457 return toRecord(current);
458 });