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

main
ts 588 lines 20.4 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import { Railway, type CustomDomain as RailwayCustomDomain } from "@distilled.cloud/railway";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { waitUntilDeleted, projectServices as fetchProjectServices } from "./GraphQL.ts";
10 import { matchesAlchemyPhysicalName } from "./Metadata.ts";
11 import { ownedProjects, projectEnvironmentIds } from "./Project.ts";
12 import type { Providers } from "./Providers.ts";
13 import { withEnvironmentConfigLock } from "./transient.ts";
14
15 const domainFields = <E>(domain: Query<RailwayCustomDomain, E>) => ({
16 id: domain.id,
17 domain: domain.domain,
18 serviceId: domain.serviceId,
19 environmentId: domain.environmentId,
20 projectId: domain.projectId,
21 targetPort: domain.targetPort,
22 deletedAt: domain.deletedAt,
23 syncStatus: domain.syncStatus,
24 status: {
25 verified: domain.status.verified,
26 certificateStatus: domain.status.certificateStatus,
27 certificateErrorMessage: domain.status.certificateErrorMessage,
28 verificationDnsHost: domain.status.verificationDnsHost,
29 verificationToken: domain.status.verificationToken,
30 dnsRecords: domain.status.dnsRecords.pipe(
31 Query.map((record) => ({
32 fqdn: record.fqdn,
33 zone: record.zone,
34 recordType: record.recordType,
35 requiredValue: record.requiredValue,
36 })),
37 ),
38 },
39 });
40 type CloudDomain = UnwrapPlan<ReturnType<typeof domainFields>>;
41
42 const readCustomDomain = Query.fn((id: string, projectId: string) =>
43 domainFields(Railway.customDomain({ id, projectId })),
44 );
45
46 const readCustomDomains = Query.fn((projectId: string, environmentId: string, serviceId: string) =>
47 Railway.domains({ environmentId, projectId, serviceId }).customDomains.pipe(
48 Query.map(domainFields),
49 ),
50 );
51
52 const customDomainCreate = Query.fn(
53 (input: {
54 domain: string;
55 environmentId: string;
56 projectId: string;
57 serviceId: string;
58 targetPort?: number;
59 }) => domainFields(Railway.customDomainCreate({ input })),
60 );
61
62 const customDomainUpdate = Query.fn(
63 (input: { environmentId: string; id: string; targetPort: number }) =>
64 Railway.customDomainUpdate(input),
65 );
66
67 const customDomainDelete = Query.fn((id: string) => Railway.customDomainDelete({ id }));
68
69 /**
70 * A DNS record Railway requires for a custom domain.
71 */
72 export interface CustomDomainDnsRecord {
73 /** Fully qualified record name, e.g. `www.example.com`. */
74 name: string;
75 /** Record type. */
76 type: "A" | "CNAME" | "TXT";
77 /** Value Railway expects, e.g. the `*.up.railway.app` CNAME target. */
78 value: string;
79 }
80
81 /**
82 * A resource-valued prop: the resource itself, or an Effect that produces
83 * it (so `yield* Service(...)` and `Service(...)` both type-check).
84 */
85 type Ref<T> = T | Effect.Effect<T, never, Providers>;
86
87 /**
88 * Parent Service identity. A `Railway.Service` resource satisfies this
89 * via `serviceId`. Tests may pass a `{ serviceId }` stub created out of
90 * band. `projectId` is optional when the environment carries it (a
91 * `Railway.Project`).
92 */
93 export type CustomDomainService = { readonly serviceId: string; readonly projectId?: string };
94
95 /**
96 * Environment identity a custom domain is created in. Accepts a
97 * `Railway.Project` (its primary environment), a `Railway.Environment`,
98 * or an `{ environmentId }` stub.
99 */
100 export type CustomDomainEnvironment = {
101 readonly environmentId: string;
102 readonly projectId?: string;
103 };
104
105 export interface CustomDomainProps {
106 /**
107 * Parent Railway Service. Accepts a `Railway.Service` resource or a
108 * `{ serviceId }` stub. Changing the Service replaces the CustomDomain.
109 */
110 service: Ref<CustomDomainService>;
111 /**
112 * Environment to attach the hostname in. Accepts a `Railway.Project`
113 * (primary environment), a `Railway.Environment`, or `{ environmentId }`.
114 * Changing it replaces the CustomDomain.
115 */
116 environment: Ref<CustomDomainEnvironment>;
117 /**
118 * User hostname (`www.example.com`). Identity of the resource.
119 * Changing it replaces the CustomDomain.
120 */
121 domain: string;
122 /**
123 * Service port Railway's edge should target. Updates in place via
124 * `customDomainUpdate`. Omit to let Railway pick the service's public
125 * port.
126 */
127 targetPort?: number;
128 }
129
130 export type CustomDomain = Resource<
131 "Railway.CustomDomain",
132 CustomDomainProps,
133 {
134 /** Railway custom domain id. */
135 customDomainId: string;
136 /** User hostname. */
137 domain: string;
138 /** Parent Railway service id. */
139 serviceId: string;
140 /** Parent Railway project id. */
141 projectId: string;
142 /** Environment the hostname is attached in. */
143 environmentId: string;
144 /** Observed target port, if set. */
145 targetPort: number | undefined;
146 /** Whether DNS ownership has been verified. */
147 verified: boolean | undefined;
148 /** ACME certificate issuance status, if the API returned one. */
149 certificateStatus: string | undefined;
150 /** Human-readable ACME error, if issuance failed. */
151 certificateErrorMessage: string | undefined;
152 /** DNS host Railway expects for the verification TXT record. */
153 verificationDnsHost: string | undefined;
154 /** DNS token Railway expects for the verification TXT record. */
155 verificationToken: string | undefined;
156 /**
157 * Every record Railway requires for the hostname, with fully qualified
158 * names: the routing `CNAME` (or `A`), any ACME challenge `CNAME`, and
159 * the ownership verification `TXT`. Publish them with a DNS adapter
160 * (see [DNS Adapters](/infrastructure-as-code/dns-adapters)).
161 */
162 dnsRecords: CustomDomainDnsRecord[];
163 /** Observed sync status (`ACTIVE`, `CREATING`, …). */
164 syncStatus: string | undefined;
165 /** `https://{domain}`. */
166 url: string;
167 },
168 never,
169 Providers
170 >;
171
172 /**
173 * A Railway.CustomDomain is a user hostname on a {@link CustomDomainService}.
174 * Railway issues a Let's Encrypt certificate once DNS is verified.
175 *
176 * @see https://docs.railway.com/guides/public-networking
177 *
178 * ### Attach a hostname
179 * Pass the parent Service, the environment id, and the hostname. Yield the
180 * CustomDomain next to the Service. Publish the records listed in
181 * `dnsRecords` (the routing `CNAME` and the `verificationDnsHost` /
182 * `verificationToken` TXT) at your DNS host.
183 *
184 * **Example:** Basic CustomDomain
185 * ```typescript
186 * const site = yield* Railway.Project("Site");
187 * const api = yield* Railway.Service("Api", {
188 * project: site,
189 * image: "hashicorp/http-echo",
190 * });
191 * const www = yield* Railway.CustomDomain("Www", {
192 * service: api,
193 * environment: site,
194 * domain: "www.example.com",
195 * });
196 * ```
197 *
198 * :::caution[Changing `domain`, `service`, or `environment` replaces the CustomDomain]
199 * The old hostname is deleted. The new hostname is created.
200 * :::
201 *
202 * ### Target port
203 * `targetPort` is optional and updates in place. Railway's edge forwards
204 * HTTPS on 443 to this port on the Service.
205 *
206 * **Example:** Explicit target port
207 * ```typescript
208 * const www = yield* Railway.CustomDomain("Www", {
209 * service: api,
210 * environment: site,
211 * domain: "www.example.com",
212 * targetPort: 8080,
213 * });
214 * ```
215 *
216 * ### Module-scope declarations
217 * Declare the CustomDomain once. Resource-valued props accept the resource
218 * or an Effect producing it.
219 *
220 * **Example:** Module-scope CustomDomain
221 * ```typescript
222 * // src/domain.ts
223 * import * as Railway from "@alchemy.run/railway";
224 * import { Api } from "./api.ts";
225 * import { Site } from "./project.ts";
226 *
227 * export const Www = Railway.CustomDomain("Www", {
228 * service: Api,
229 * environment: Site,
230 * domain: "www.example.com",
231 * });
232 * ```
233 *
234 * @resource
235 * @product Networking
236 */
237 export const CustomDomain = Resource<CustomDomain>("Railway.CustomDomain");
238
239 export class CustomDomainNotCreated extends Data.TaggedError("Railway.CustomDomainNotCreated")<{
240 domain: string;
241 serviceId: string;
242 }> {}
243
244 export class CustomDomainServiceMissing extends Data.TaggedError(
245 "Railway.CustomDomainServiceMissing",
246 )<{ domain: string }> {}
247
248 const serviceIdOf = (value: unknown): string | undefined => {
249 if (value === null || typeof value !== "object") return undefined;
250 const rec = value as { serviceId?: unknown };
251 if (typeof rec.serviceId === "string" && rec.serviceId.length > 0) {
252 return rec.serviceId;
253 }
254 return undefined;
255 };
256
257 const projectIdOf = (value: unknown): string | undefined => {
258 if (value === null || typeof value !== "object") return undefined;
259 const rec = value as { projectId?: unknown };
260 if (typeof rec.projectId === "string" && rec.projectId.length > 0) {
261 return rec.projectId;
262 }
263 return undefined;
264 };
265
266 const environmentIdOf = (value: unknown): string | undefined => {
267 if (value === null || typeof value !== "object") return undefined;
268 const rec = value as { environmentId?: unknown };
269 if (typeof rec.environmentId === "string" && rec.environmentId.length > 0) {
270 return rec.environmentId;
271 }
272 return undefined;
273 };
274
275 const isGone = (domain: CloudDomain | undefined) =>
276 domain === undefined || domain.deletedAt != null || domain.syncStatus === "DELETED";
277
278 const RECORD_TYPES = {
279 DNS_RECORD_TYPE_A: "A",
280 DNS_RECORD_TYPE_CNAME: "CNAME",
281 DNS_RECORD_TYPE_TXT: "TXT",
282 } as const satisfies Record<string, CustomDomainDnsRecord["type"]>;
283
284 const trimDot = (name: string) => name.replace(/\.$/, "");
285
286 /** Qualify a (possibly zone-relative) host label with its zone. */
287 const qualify = (host: string, zone: string | undefined) => {
288 const name = trimDot(host);
289 if (zone === undefined || zone.length === 0) return name;
290 const apex = trimDot(zone);
291 if (name === "@" || name === "") return apex;
292 const lower = name.toLowerCase();
293 const lowerApex = apex.toLowerCase();
294 return lower === lowerApex || lower.endsWith(`.${lowerApex}`) ? name : `${name}.${apex}`;
295 };
296
297 const toDnsRecords = (
298 status:
299 | {
300 verificationDnsHost?: string | null;
301 verificationToken?: string | null;
302 dnsRecords?: ReadonlyArray<{
303 fqdn: string;
304 zone: string;
305 recordType: string;
306 requiredValue: string;
307 }>;
308 }
309 | undefined,
310 ): CustomDomainDnsRecord[] => {
311 const observed = status?.dnsRecords ?? [];
312 const records: CustomDomainDnsRecord[] = [];
313 for (const record of observed) {
314 // NS / unspecified records are not publishable by a DNS adapter.
315 const type = (RECORD_TYPES as Record<string, CustomDomainDnsRecord["type"] | undefined>)[
316 record.recordType
317 ];
318 if (type === undefined || record.requiredValue.length === 0) continue;
319 records.push({
320 name: qualify(record.fqdn, record.zone),
321 type,
322 value: record.requiredValue,
323 });
324 }
325 const host = status?.verificationDnsHost ?? undefined;
326 const token = status?.verificationToken ?? undefined;
327 if (host !== undefined && host.length > 0 && token !== undefined) {
328 const name = qualify(host, observed[0]?.zone);
329 const listed = records.some(
330 (record) => record.type === "TXT" && record.name.toLowerCase() === name.toLowerCase(),
331 );
332 if (!listed) records.push({ name, type: "TXT", value: token });
333 }
334 return records;
335 };
336
337 const toAttrs = (
338 domain: CloudDomain,
339 fallback?: { projectId?: string; environmentId?: string },
340 ): CustomDomain["Attributes"] => {
341 const status = domain.status;
342 const name = domain.domain;
343 return {
344 customDomainId: domain.id,
345 domain: name,
346 serviceId: domain.serviceId,
347 projectId: domain.projectId ?? fallback?.projectId ?? "",
348 environmentId: domain.environmentId || fallback?.environmentId || "",
349 targetPort: domain.targetPort ?? undefined,
350 verified: status.verified,
351 certificateStatus: status.certificateStatus,
352 certificateErrorMessage: status.certificateErrorMessage ?? undefined,
353 verificationDnsHost: status.verificationDnsHost ?? undefined,
354 verificationToken: status.verificationToken ?? undefined,
355 dnsRecords: toDnsRecords(status),
356 syncStatus: domain.syncStatus,
357 url: `https://${name}`,
358 };
359 };
360
361 const getById = (customDomainId: string, projectId: string) =>
362 readCustomDomain(customDomainId, projectId).pipe(
363 Effect.map((domain) => (isGone(domain) ? undefined : domain)),
364 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
365 );
366
367 const listServiceDomains = (projectId: string, environmentId: string, serviceId: string) =>
368 readCustomDomains(projectId, environmentId, serviceId).pipe(
369 Effect.map((customDomains) => customDomains.filter((domain) => !isGone(domain))),
370 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as ReadonlyArray<CloudDomain>)),
371 );
372
373 const findByDomain = (
374 projectId: string,
375 environmentId: string,
376 serviceId: string,
377 domain: string,
378 ) =>
379 listServiceDomains(projectId, environmentId, serviceId).pipe(
380 Effect.map((domains) =>
381 domains.find((item) => item.domain.toLowerCase() === domain.toLowerCase()),
382 ),
383 );
384
385 const observe = Effect.fn(function* (input: {
386 customDomainId?: string;
387 projectId: string;
388 environmentId: string;
389 serviceId: string;
390 domain: string;
391 }) {
392 if (
393 input.customDomainId !== undefined &&
394 input.customDomainId.length > 0 &&
395 input.projectId.length > 0
396 ) {
397 const byId = yield* getById(input.customDomainId, input.projectId);
398 if (byId !== undefined) return byId;
399 }
400 const listed = yield* findByDomain(
401 input.projectId,
402 input.environmentId,
403 input.serviceId,
404 input.domain,
405 );
406 if (listed === undefined) return undefined;
407 if (listed.projectId !== null && listed.projectId.length > 0) {
408 const full = yield* getById(listed.id, listed.projectId);
409 if (full !== undefined) return full;
410 }
411 return listed;
412 });
413
414 const waitUntilGone = (customDomainId: string, projectId: string) =>
415 waitUntilDeleted(
416 "CustomDomain",
417 customDomainId,
418 getById(customDomainId, projectId).pipe(Effect.map((domain) => domain === undefined)),
419 );
420
421 export const CustomDomainProvider = () =>
422 Provider.succeed(CustomDomain, {
423 stables: ["customDomainId", "serviceId", "projectId", "environmentId", "domain"],
424 nuke: { dependsOn: ["Railway.Project"] },
425
426 list: Effect.fn(function* () {
427 const projects = yield* ownedProjects();
428 const rows = yield* Effect.forEach(projects, (project) =>
429 Effect.gen(function* () {
430 const live = yield* fetchProjectServices(project.projectId, (service) => ({
431 id: service.id,
432 name: service.name,
433 deletedAt: service.deletedAt,
434 })).pipe(Effect.catchTag("RailwayNotFound", () => Effect.undefined));
435 const services = (live ?? []).filter(
436 (service) => service.deletedAt == null && matchesAlchemyPhysicalName(service.name),
437 );
438 const envIds = yield* projectEnvironmentIds(project);
439 const nested = yield* Effect.forEach(services, (service) =>
440 Effect.forEach(envIds, (environmentId) =>
441 listServiceDomains(project.projectId, environmentId, service.id).pipe(
442 Effect.map((domains) =>
443 domains.map((domain) =>
444 toAttrs(domain, { projectId: project.projectId, environmentId }),
445 ),
446 ),
447 ),
448 ).pipe(Effect.map((rows) => rows.flat())),
449 );
450 return nested.flat();
451 }),
452 );
453 return rows.flat();
454 }),
455
456 diff: Effect.fn(function* ({ news, output }) {
457 if (news === undefined || !isResolved(news)) return undefined;
458 if (output === undefined) return undefined;
459 const serviceId = serviceIdOf(news.service);
460 const serviceChanged = serviceId !== undefined && serviceId !== output.serviceId;
461 const environmentId = environmentIdOf(news.environment);
462 const environmentChanged =
463 environmentId !== undefined && environmentId !== output.environmentId;
464 const domainChanged = news.domain.toLowerCase() !== output.domain.toLowerCase();
465 if (serviceChanged || environmentChanged || domainChanged) {
466 return { action: "replace" as const, deleteFirst: !domainChanged };
467 }
468 return undefined;
469 }),
470
471 read: Effect.fn(function* ({ olds, output }) {
472 const serviceId = output?.serviceId ?? serviceIdOf(olds?.service) ?? "";
473 const projectId =
474 output?.projectId ?? projectIdOf(olds?.service) ?? projectIdOf(olds?.environment) ?? "";
475 const environmentId = output?.environmentId ?? environmentIdOf(olds?.environment) ?? "";
476 const domain = output?.domain ?? olds?.domain;
477 if (
478 serviceId.length === 0 ||
479 projectId.length === 0 ||
480 environmentId.length === 0 ||
481 domain === undefined ||
482 domain.length === 0
483 ) {
484 return undefined;
485 }
486 const found = yield* observe({
487 customDomainId: output?.customDomainId,
488 projectId,
489 environmentId,
490 serviceId,
491 domain,
492 });
493 if (found === undefined) return undefined;
494 return toAttrs(found, { projectId, environmentId });
495 }),
496
497 reconcile: Effect.fn(function* ({ news, output }) {
498 const props = news ?? ({} as CustomDomainProps);
499 const serviceId = serviceIdOf(props.service) ?? output?.serviceId ?? "";
500 const projectId =
501 projectIdOf(props.service) ?? projectIdOf(props.environment) ?? output?.projectId ?? "";
502 const environmentId = environmentIdOf(props.environment) ?? output?.environmentId ?? "";
503 const domain = props.domain ?? output?.domain ?? "";
504 if (serviceId.length === 0 || projectId.length === 0) {
505 return yield* new CustomDomainServiceMissing({ domain });
506 }
507 if (domain.length === 0 || environmentId.length === 0) {
508 return yield* new CustomDomainNotCreated({ domain, serviceId });
509 }
510
511 let current = yield* observe({
512 customDomainId: output?.customDomainId,
513 projectId,
514 environmentId,
515 serviceId,
516 domain: output?.domain ?? domain,
517 });
518 if (
519 current === undefined &&
520 (output?.domain !== domain ||
521 output?.serviceId !== serviceId ||
522 output?.environmentId !== environmentId)
523 ) {
524 current = yield* observe({ projectId, environmentId, serviceId, domain });
525 }
526
527 if (current === undefined) {
528 const ensureDomain = Effect.gen(function* () {
529 // A previous attempt may have created the hostname before its response failed.
530 const observed = yield* observe({ projectId, environmentId, serviceId, domain });
531 if (observed !== undefined) return observed;
532 return yield* customDomainCreate({
533 domain,
534 environmentId,
535 projectId,
536 serviceId,
537 ...(props.targetPort !== undefined ? { targetPort: props.targetPort } : {}),
538 }).pipe(
539 Effect.catchTag(
540 ["RailwayCustomDomainCreateFailed", "RailwayValidationError"],
541 (failure) =>
542 observe({ projectId, environmentId, serviceId, domain }).pipe(
543 Effect.flatMap((found) =>
544 found !== undefined ? Effect.succeed(found) : Effect.fail(failure),
545 ),
546 ),
547 ),
548 );
549 });
550 current = yield* withEnvironmentConfigLock(environmentId, ensureDomain).pipe(
551 Effect.retry({
552 while: (error) => error._tag === "RailwayCustomDomainCreateFailed",
553 times: 8,
554 schedule: Schedule.spaced("2 seconds"),
555 }),
556 );
557 }
558
559 if (current === undefined || isGone(current)) {
560 return yield* new CustomDomainNotCreated({ domain, serviceId });
561 }
562
563 const observedPort = current.targetPort ?? undefined;
564 const desiredPort = props.targetPort;
565 if (desiredPort !== undefined && desiredPort !== observedPort) {
566 yield* customDomainUpdate({
567 environmentId: current.environmentId,
568 id: current.id,
569 targetPort: desiredPort,
570 });
571 current = (yield* getById(current.id, current.projectId ?? projectId)) ?? current;
572 }
573
574 return toAttrs(current, { projectId, environmentId });
575 }),
576
577 delete: Effect.fn(function* ({ output }) {
578 const customDomainId = output.customDomainId;
579 const projectId = output.projectId;
580 if (customDomainId.length === 0) return;
581 yield* customDomainDelete(customDomainId).pipe(
582 Effect.catchTag("RailwayNotFound", () => Effect.void),
583 );
584 if (projectId.length > 0) {
585 yield* waitUntilGone(customDomainId, projectId);
586 }
587 }),
588 });