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

main
ts 996 lines 37.1 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import {
3 Railway,
4 type PrivateNetwork as RailwayPrivateNetwork,
5 type PrivateNetworkEndpoint as RailwayPrivateNetworkEndpoint,
6 type PrivateNetworkEndpointSyncStatus,
7 } from "@distilled.cloud/railway";
8 import { isResolved } from "alchemy/Diff";
9 import * as Provider from "alchemy/Provider";
10 import { Resource } from "alchemy/Resource";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as Schedule from "effect/Schedule";
14 import * as Schema from "effect/Schema";
15 import { projectServices as fetchProjectServices } from "./GraphQL.ts";
16 import { sanitizeRailwayName } from "./Metadata.ts";
17 import { ownedProjects, projectEnvironmentIds } from "./Project.ts";
18 import type { Providers } from "./Providers.ts";
19 import { withEnvironmentConfigLock } from "./transient.ts";
20
21 const networkFields = <E>(network: Query<RailwayPrivateNetwork, E>) => ({
22 createdAt: network.createdAt,
23 deletedAt: network.deletedAt,
24 dnsName: network.dnsName,
25 environmentId: network.environmentId,
26 name: network.name,
27 networkId: network.networkId,
28 projectId: network.projectId,
29 publicId: network.publicId,
30 tags: network.tags,
31 });
32 type PrivateNetworksResultItem = UnwrapPlan<ReturnType<typeof networkFields>>;
33
34 const endpointFields = <E>(endpoint: Query<RailwayPrivateNetworkEndpoint, E>) => ({
35 createdAt: endpoint.createdAt,
36 deletedAt: endpoint.deletedAt,
37 dnsName: endpoint.dnsName,
38 newDnsName: endpoint.newDnsName,
39 privateIps: endpoint.privateIps,
40 publicId: endpoint.publicId,
41 serviceInstanceId: endpoint.serviceInstanceId,
42 syncStatus: endpoint.syncStatus,
43 tags: endpoint.tags,
44 });
45 type PrivateNetworkEndpointValue = UnwrapPlan<ReturnType<typeof endpointFields>>;
46
47 const readEnvironmentConfig = Query.fn((id: string) => ({
48 config: Railway.environment({ id }).config,
49 }));
50
51 const readPrivateNetworks = Query.fn((environmentId: string) =>
52 Railway.privateNetworks({ environmentId }).pipe(Query.map(networkFields)),
53 );
54
55 const readPrivateNetworkEndpoint = Query.fn(
56 (input: { environmentId: string; privateNetworkId: string; serviceId: string }) =>
57 Railway.privateNetworkEndpoint(input).pipe(Query.map(endpointFields)),
58 );
59
60 const readServiceName = Query.fn((id: string) => ({ name: Railway.service({ id }).name }));
61
62 const endpointNameAvailable = Query.fn(
63 (input: { environmentId: string; privateNetworkId: string; prefix: string }) =>
64 Railway.privateNetworkEndpointNameAvailable(input),
65 );
66
67 const environmentPatchCommit = Query.fn(
68 (input: { environmentId: string; commitMessage: string; patch: unknown }) =>
69 Railway.environmentPatchCommit(input),
70 );
71
72 /**
73 * A resource-valued prop: the resource itself, or an Effect that produces
74 * it (so `yield* Project(...)` and `Project(...)` both type-check).
75 */
76 type Ref<T> = T | Effect.Effect<T, never, Providers>;
77
78 const PLATFORM_NETWORK_NAME = "railway";
79
80 const NetworkConfig = Schema.Struct({
81 privateNetworkDisabled: Schema.Boolean.pipe(Schema.NullOr, Schema.optional),
82 services: Schema.Record(
83 Schema.String,
84 Schema.NullOr(
85 Schema.Struct({
86 networking: Schema.Struct({
87 privateNetworkEndpoint: Schema.String.pipe(Schema.NullOr, Schema.optional),
88 }).pipe(Schema.NullOr, Schema.optional),
89 }),
90 ),
91 ).pipe(Schema.NullOr, Schema.optional),
92 });
93
94 const readNetworkConfig = Effect.fn(function* (environmentId: string) {
95 const environment = yield* readEnvironmentConfig(environmentId);
96 return yield* Schema.decodeUnknownEffect(NetworkConfig)(environment.config);
97 });
98
99 export class PrivateNetworkConfigPending extends Data.TaggedError(
100 "Railway.PrivateNetworkConfigPending",
101 )<{ environmentId: string; message: string }> {}
102
103 const waitForNetworkConfig = (
104 environmentId: string,
105 ready: (config: typeof NetworkConfig.Type) => boolean,
106 ) =>
107 readNetworkConfig(environmentId).pipe(
108 Effect.flatMap((config) =>
109 ready(config)
110 ? Effect.void
111 : Effect.fail(
112 new PrivateNetworkConfigPending({
113 environmentId,
114 message: "Waiting for Railway private-network configuration",
115 }),
116 ),
117 ),
118 Effect.retry({
119 while: (error) => error._tag === "Railway.PrivateNetworkConfigPending",
120 // Committed patches usually apply in ~4s but stall for 10s+ while the
121 // environment is applying an earlier change.
122 schedule: Schedule.spaced("3 seconds"),
123 times: 10,
124 }),
125 );
126
127 export class PrivateNetworkNameUnsupported extends Data.TaggedError(
128 "Railway.PrivateNetworkNameUnsupported",
129 )<{ resourceName: string }> {
130 override get message() {
131 return `Railway manages one private network per environment. Custom network '${this.resourceName}' is no longer supported; remove the legacy declaration and use PrivateNetwork without a name.`;
132 }
133 }
134
135 /**
136 * Environment identity a private network lives in. Accepts a
137 * `Railway.Project` (its primary environment), a `Railway.Environment`,
138 * or an `{ environmentId, projectId? }` stub.
139 */
140 export type PrivateNetworkEnvironment = {
141 readonly environmentId: string;
142 readonly projectId?: string;
143 };
144
145 export interface PrivateNetworkProps {
146 /**
147 * Environment whose platform-managed private network is enabled. Accepts a
148 * `Railway.Project`, `Railway.Environment`, or `{ environmentId, projectId }`.
149 * Changing it replaces the configuration resource.
150 */
151 environment: Ref<PrivateNetworkEnvironment>;
152 /**
153 * Only the platform name `railway` is supported. Custom names are rejected.
154 * @deprecated Omit this property; Railway names the environment's network.
155 */
156 name?: string;
157 }
158
159 export type PrivateNetwork = Resource<
160 "Railway.PrivateNetwork",
161 PrivateNetworkProps,
162 {
163 /** Railway public network id (string identity used by endpoint APIs). */
164 publicId: string;
165 /** Private-networking setting to restore when this resource is removed. */
166 previousPrivateNetworkDisabled?: boolean;
167 /** Numeric WireGuard network id, as a decimal string. */
168 networkId: string;
169 /** Physical network name (unique per environment). */
170 name: string;
171 /** Network DNS label reported by Railway. */
172 dnsName: string;
173 /** Parent Railway project id. */
174 projectId: string;
175 /** Environment the network lives in. */
176 environmentId: string;
177 /** Observed tags. */
178 tags: string[];
179 /** RFC3339 creation timestamp, if Railway reported one. */
180 createdAt: string | undefined;
181 },
182 never,
183 Providers
184 >;
185
186 const resolvePrivateNetworkProps = (
187 props: PrivateNetworkProps | Effect.Effect<PrivateNetworkProps, never, Providers>,
188 ): Effect.Effect<PrivateNetworkProps, never, Providers> =>
189 Effect.gen(function* () {
190 const resolved = Effect.isEffect(props) ? yield* props : props;
191 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
192 const environment = Effect.isEffect(resolved.environment)
193 ? yield* resolved.environment as Effect.Effect<PrivateNetworkEnvironment, never, Providers>
194 : resolved.environment;
195 return { ...resolved, environment };
196 });
197
198 const PrivateNetworkResource = Resource<PrivateNetwork>("Railway.PrivateNetwork");
199
200 /**
201 * Enable Railway's platform-managed private network for an environment.
202 * This resource manages the environment's networking setting, not a separately
203 * created network. Use one PrivateNetwork resource per environment.
204 *
205 * Destroy restores the setting captured before reconciliation. A network that
206 * was already enabled stays enabled; one enabled by this resource is disabled.
207 * Platform network objects follow the environment's lifecycle.
208 *
209 * :::caution[Named networks are no longer supported]
210 * Railway removed named-network creation. Remove legacy named-network
211 * declarations before adding this environment-managed resource. Custom names
212 * are rejected rather than silently mapped to the platform network.
213 * :::
214 *
215 * ### Enable private networking
216 * Pass a Project or Environment. `dnsName` is Railway's network DNS label.
217 *
218 * **Example:** Environment-managed network
219 * ```typescript
220 * const site = yield* Railway.Project("Site");
221 * const net = yield* Railway.PrivateNetwork("Mesh", {
222 * environment: site,
223 * });
224 * ```
225 *
226 * ### Endpoints
227 * Configure a deployed service's DNS prefix via
228 * {@link PrivateNetworkEndpoint}.
229 *
230 * **Example:** Endpoint on the network
231 * ```typescript
232 * const endpoint = yield* Railway.PrivateNetworkEndpoint("ApiDns", {
233 * network: net,
234 * service: { serviceId: "deployed-service-id" },
235 * name: "api",
236 * });
237 * ```
238 *
239 * ### Module-scope declarations
240 * Resource-valued props accept the resource or an Effect producing it.
241 *
242 * **Example:** Module-scope network
243 * ```typescript
244 * // src/network.ts
245 * import * as Railway from "@alchemy.run/railway";
246 *
247 * export const Site = Railway.Project("Site");
248 * export const Mesh = Railway.PrivateNetwork("Mesh", {
249 * environment: Site,
250 * });
251 * ```
252 *
253 * @resource
254 * @product Networking
255 */
256 export const PrivateNetwork: typeof PrivateNetworkResource = Object.assign(
257 (id: string, props: PrivateNetworkProps | Effect.Effect<PrivateNetworkProps, never, Providers>) =>
258 PrivateNetworkResource(id, resolvePrivateNetworkProps(props)),
259 PrivateNetworkResource,
260 );
261
262 export class PrivateNetworkNotCreated extends Data.TaggedError("Railway.PrivateNetworkNotCreated")<{
263 resourceName: string;
264 environmentId: string;
265 }> {}
266
267 export class PrivateNetworkEnvironmentRequired extends Data.TaggedError(
268 "Railway.PrivateNetworkEnvironmentRequired",
269 )<{ message: string }> {}
270
271 type CloudNetwork = PrivateNetworksResultItem;
272
273 const environmentIdOf = (value: unknown): string | undefined => {
274 if (value === null || typeof value !== "object") return undefined;
275 const rec = value as { environmentId?: unknown };
276 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
277 ? rec.environmentId
278 : undefined;
279 };
280
281 const projectIdOf = (value: unknown): string | undefined => {
282 if (value === null || typeof value !== "object") return undefined;
283 const rec = value as { projectId?: unknown };
284 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
285 };
286
287 const publicIdOf = (value: unknown): string | undefined => {
288 if (value === null || typeof value !== "object") return undefined;
289 const rec = value as { publicId?: unknown };
290 return typeof rec.publicId === "string" && rec.publicId.length > 0 ? rec.publicId : undefined;
291 };
292
293 const isGoneNetwork = (network: CloudNetwork | undefined) =>
294 network === undefined || network.deletedAt != null;
295
296 const toNetworkAttrs = (
297 network: CloudNetwork,
298 fallback?: { name?: string; projectId?: string },
299 ): PrivateNetwork["Attributes"] => ({
300 publicId: network.publicId,
301 networkId: String(network.networkId),
302 name: network.name || fallback?.name || "",
303 dnsName: network.dnsName,
304 projectId: network.projectId || fallback?.projectId || "",
305 environmentId: network.environmentId,
306 tags: [...network.tags],
307 createdAt: network.createdAt ?? undefined,
308 });
309
310 const resolveNetworkName = Effect.fn(function* (name?: string) {
311 if (name !== undefined && name !== PLATFORM_NETWORK_NAME) {
312 return yield* new PrivateNetworkNameUnsupported({ resourceName: name });
313 }
314 return PLATFORM_NETWORK_NAME;
315 });
316
317 const listNetworks = (environmentId: string) =>
318 readPrivateNetworks(environmentId).pipe(
319 Effect.map((items) => items.filter((network) => !isGoneNetwork(network))),
320 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as PrivateNetworksResultItem[])),
321 );
322
323 const findNetwork = (environmentId: string, match: (network: CloudNetwork) => boolean) =>
324 listNetworks(environmentId).pipe(Effect.map((networks) => networks.find(match)));
325
326 const observeNetwork = Effect.fn(function* (input: {
327 environmentId: string;
328 publicId?: string;
329 name?: string;
330 }) {
331 if (input.publicId !== undefined && input.publicId.length > 0) {
332 const byId = yield* findNetwork(
333 input.environmentId,
334 (network) => network.publicId === input.publicId,
335 );
336 if (byId !== undefined) return byId;
337 }
338 if (input.name !== undefined && input.name.length > 0) {
339 return yield* findNetwork(input.environmentId, (network) => network.name === input.name);
340 }
341 return undefined;
342 });
343
344 const ensureNetwork = Effect.fn(function* (environmentId: string) {
345 const previousPrivateNetworkDisabled = yield* withEnvironmentConfigLock(
346 environmentId,
347 Effect.gen(function* () {
348 const config = yield* readNetworkConfig(environmentId);
349 const network = yield* observeNetwork({ environmentId, name: PLATFORM_NETWORK_NAME });
350 if (config.privateNetworkDisabled === true || network === undefined) {
351 yield* environmentPatchCommit({
352 environmentId,
353 commitMessage: "Enable private networking",
354 patch: { privateNetworkDisabled: false },
355 });
356 yield* waitForNetworkConfig(
357 environmentId,
358 (observed) => observed.privateNetworkDisabled === false,
359 );
360 }
361 return config.privateNetworkDisabled === true;
362 }),
363 );
364 const network = yield* observeNetwork({ environmentId, name: PLATFORM_NETWORK_NAME }).pipe(
365 Effect.flatMap((network) =>
366 network === undefined
367 ? Effect.fail(
368 new PrivateNetworkNotCreated({ resourceName: PLATFORM_NETWORK_NAME, environmentId }),
369 )
370 : Effect.succeed(network),
371 ),
372 Effect.retry({
373 while: (error) => error._tag === "Railway.PrivateNetworkNotCreated",
374 schedule: Schedule.spaced("1 second"),
375 times: 8,
376 }),
377 );
378 return { network, previousPrivateNetworkDisabled };
379 });
380
381 export const PrivateNetworkProvider = () =>
382 Provider.succeed(PrivateNetwork, {
383 stables: ["projectId", "environmentId"],
384 // Platform-managed networking is released, never independently deleted.
385 nuke: { skip: true, dependsOn: ["Railway.Project"] },
386
387 diff: Effect.fn(function* ({ news, output }) {
388 if (news === undefined || !isResolved(news)) return undefined;
389 if (output === undefined) return undefined;
390 const environmentId = environmentIdOf(news.environment);
391 const environmentChanged =
392 environmentId !== undefined && environmentId !== output.environmentId;
393 if (environmentChanged) {
394 return { action: "replace" as const };
395 }
396 return undefined;
397 }),
398
399 read: Effect.fn(function* ({ olds, output }) {
400 const environmentId = output?.environmentId ?? environmentIdOf(olds?.environment);
401 const name = output?.name ?? olds?.name ?? PLATFORM_NETWORK_NAME;
402 if (environmentId === undefined) return undefined;
403 const config = yield* readNetworkConfig(environmentId).pipe(
404 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
405 );
406 if (config === undefined || config.privateNetworkDisabled === true) {
407 return undefined;
408 }
409 const found = yield* observeNetwork({ environmentId, publicId: output?.publicId, name });
410 if (found === undefined) return undefined;
411 const attrs = toNetworkAttrs(found, {
412 name,
413 projectId: output?.projectId ?? projectIdOf(olds?.environment),
414 });
415 return { ...attrs, previousPrivateNetworkDisabled: output?.previousPrivateNetworkDisabled };
416 }),
417
418 list: Effect.fn(function* () {
419 const projects = yield* ownedProjects();
420 const rows = yield* Effect.forEach(projects, (project) =>
421 Effect.gen(function* () {
422 const envIds = yield* projectEnvironmentIds(project);
423 const nested = yield* Effect.forEach(envIds, (environmentId) =>
424 listNetworks(environmentId).pipe(
425 Effect.map((networks) =>
426 networks
427 .filter((network) => network.name === PLATFORM_NETWORK_NAME)
428 .map((network) => toNetworkAttrs(network, { projectId: project.projectId })),
429 ),
430 ),
431 );
432 return nested.flat();
433 }),
434 );
435 const seen = new Set<string>();
436 const unique: PrivateNetwork["Attributes"][] = [];
437 for (const row of rows.flat()) {
438 if (seen.has(row.publicId)) continue;
439 seen.add(row.publicId);
440 unique.push(row);
441 }
442 return unique;
443 }),
444
445 reconcile: Effect.fn(function* ({ news, output }) {
446 const props = news ?? ({} as PrivateNetworkProps);
447 const environmentId = environmentIdOf(props.environment) ?? output?.environmentId;
448 const projectId = projectIdOf(props.environment) ?? output?.projectId;
449 if (environmentId === undefined || projectId === undefined) {
450 return yield* new PrivateNetworkEnvironmentRequired({
451 message:
452 "PrivateNetwork requires an environment with environmentId and projectId (pass a Railway.Project or Railway.Environment)",
453 });
454 }
455 const name = yield* resolveNetworkName(props.name ?? output?.name);
456 const current = yield* ensureNetwork(environmentId);
457 return {
458 ...toNetworkAttrs(current.network, { name, projectId }),
459 previousPrivateNetworkDisabled:
460 output?.previousPrivateNetworkDisabled ?? current.previousPrivateNetworkDisabled,
461 };
462 }),
463
464 delete: Effect.fn(function* ({ output }) {
465 // Legacy named-network state has no environment setting to restore.
466 if (output.previousPrivateNetworkDisabled !== true) return;
467 yield* withEnvironmentConfigLock(
468 output.environmentId,
469 Effect.gen(function* () {
470 const config = yield* readNetworkConfig(output.environmentId);
471 if (config.privateNetworkDisabled === true) return;
472 yield* environmentPatchCommit({
473 environmentId: output.environmentId,
474 commitMessage: "Restore private networking setting",
475 patch: { privateNetworkDisabled: true },
476 });
477 // Since 2026-10 Railway commits `privateNetworkDisabled: true` but
478 // never applies it (config stays `false`). That refusal is terminal,
479 // so failing here would only block the environment's own delete.
480 yield* waitForNetworkConfig(
481 output.environmentId,
482 (observed) => observed.privateNetworkDisabled === true,
483 ).pipe(
484 Effect.catchTag("Railway.PrivateNetworkConfigPending", () =>
485 Effect.logWarning(
486 `Railway kept private networking enabled for environment ${output.environmentId}; it could not be restored to disabled.`,
487 ),
488 ),
489 );
490 }),
491 ).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
492 }),
493 });
494
495 /**
496 * Network identity an endpoint attaches to. Accepts a
497 * `Railway.PrivateNetwork` or a `{ publicId, environmentId? }` stub.
498 */
499 export type PrivateNetworkEndpointNetwork = {
500 readonly publicId: string;
501 readonly environmentId?: string;
502 readonly projectId?: string;
503 readonly dnsName?: string;
504 };
505
506 /**
507 * Service identity an endpoint attaches to. Accepts a `Railway.Service`
508 * or a `{ serviceId, name? }` stub.
509 */
510 export type PrivateNetworkEndpointService = { readonly serviceId: string; readonly name?: string };
511
512 export interface PrivateNetworkEndpointProps {
513 /**
514 * Platform-managed network. Accepts a `Railway.PrivateNetwork` or
515 * `{ publicId, environmentId }`. Changing it replaces the configuration resource.
516 */
517 network: Ref<PrivateNetworkEndpointNetwork>;
518 /**
519 * Service the endpoint advertises. Accepts a `Railway.Service` or
520 * `{ serviceId }`. Changing it replaces the endpoint.
521 */
522 service: Ref<PrivateNetworkEndpointService>;
523 /**
524 * Service DNS prefix. Defaults to the service name.
525 * Updates the service's environment configuration without replacing its endpoint.
526 */
527 name?: string;
528 }
529
530 export type PrivateNetworkEndpoint = Resource<
531 "Railway.PrivateNetworkEndpoint",
532 PrivateNetworkEndpointProps,
533 {
534 /** Railway public endpoint id. */
535 publicId: string;
536 /** Observed DNS prefix, not a fully qualified hostname. */
537 dnsName: string;
538 /** Pending DNS name while a rename is in flight, if any. */
539 newDnsName: string | undefined;
540 /** Internal IPs advertised on the mesh. */
541 privateIps: string[];
542 /** Service instance the endpoint is bound to. */
543 serviceInstanceId: string;
544 /** Previous DNS override to restore on removal; null restores the platform default. */
545 previousDnsPrefix?: string | null;
546 /** Parent service id. */
547 serviceId: string;
548 /** Parent network public id. */
549 privateNetworkId: string;
550 /** Environment the endpoint lives in. */
551 environmentId: string;
552 /** Parent Railway project id, if known. */
553 projectId: string | undefined;
554 /** Observed Railway sync status (`ACTIVE`, `CREATING`, …). */
555 syncStatus: PrivateNetworkEndpointSyncStatus;
556 /** Observed tags. */
557 tags: string[];
558 /** RFC3339 creation timestamp, if Railway reported one. */
559 createdAt: string | undefined;
560 },
561 never,
562 Providers
563 >;
564
565 const resolvePrivateNetworkEndpointProps = (
566 props: PrivateNetworkEndpointProps | Effect.Effect<PrivateNetworkEndpointProps, never, Providers>,
567 ): Effect.Effect<PrivateNetworkEndpointProps, never, Providers> =>
568 Effect.gen(function* () {
569 const resolved = Effect.isEffect(props) ? yield* props : props;
570 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
571 const network = Effect.isEffect(resolved.network)
572 ? yield* resolved.network as Effect.Effect<PrivateNetworkEndpointNetwork, never, Providers>
573 : resolved.network;
574 const service = Effect.isEffect(resolved.service)
575 ? yield* resolved.service as Effect.Effect<PrivateNetworkEndpointService, never, Providers>
576 : resolved.service;
577 return { ...resolved, network, service };
578 });
579
580 const PrivateNetworkEndpointResource = Resource<PrivateNetworkEndpoint>(
581 "Railway.PrivateNetworkEndpoint",
582 );
583
584 /**
585 * Configure the DNS prefix of a service's platform-managed endpoint on a
586 * {@link PrivateNetwork}. The service must already have an instance in the
587 * environment. Use one endpoint configuration resource per service/environment.
588 *
589 * Destroy restores the previous DNS override if the current override still
590 * matches this resource's value. Unrelated or externally changed settings are
591 * preserved. The platform endpoint itself follows the service's lifecycle.
592 * Legacy state without a captured DNS override cannot be restored: deletion
593 * fails explicitly while the endpoint exists, rather than silently forgetting it.
594 *
595 * ### Configure a service
596 * Pass the network and service. Omit `name` to use the service name
597 * as the DNS prefix.
598 *
599 * **Example:** Default prefix
600 * ```typescript
601 * const endpoint = yield* Railway.PrivateNetworkEndpoint("ApiDns", {
602 * network: net,
603 * service: api,
604 * });
605 * ```
606 *
607 * ### Custom DNS name
608 * `name` sets the service's private DNS prefix.
609 * Updating it renames in place.
610 *
611 * **Example:** Custom prefix
612 * ```typescript
613 * const endpoint = yield* Railway.PrivateNetworkEndpoint("ApiDns", {
614 * network: net,
615 * service: api,
616 * name: "api",
617 * });
618 * ```
619 *
620 * :::caution[Changing the target replaces the configuration resource]
621 * Changing `network` or `service` restores the old target's prior DNS override
622 * and applies the desired prefix to the new target. It does not delete either
623 * platform-managed endpoint.
624 * :::
625 *
626 * @resource
627 * @product Networking
628 */
629 export const PrivateNetworkEndpoint: typeof PrivateNetworkEndpointResource = Object.assign(
630 (
631 id: string,
632 props:
633 | PrivateNetworkEndpointProps
634 | Effect.Effect<PrivateNetworkEndpointProps, never, Providers>,
635 ) => PrivateNetworkEndpointResource(id, resolvePrivateNetworkEndpointProps(props)),
636 PrivateNetworkEndpointResource,
637 );
638
639 export class PrivateNetworkEndpointNotCreated extends Data.TaggedError(
640 "Railway.PrivateNetworkEndpointNotCreated",
641 )<{
642 privateNetworkId: string;
643 serviceId: string;
644 expectedPrefix?: string;
645 observedPrefix?: string;
646 pendingPrefix?: string;
647 }> {
648 override get message() {
649 return `Private endpoint for ${this.serviceId} is not ready: expected ${this.expectedPrefix ?? "an endpoint"}, observed ${this.observedPrefix ?? "missing"}, pending ${this.pendingPrefix ?? "none"}`;
650 }
651 }
652
653 export class PrivateNetworkEndpointRestoreUnavailable extends Data.TaggedError(
654 "Railway.PrivateNetworkEndpointRestoreUnavailable",
655 )<{ serviceId: string; environmentId: string }> {
656 override get message() {
657 return "Cannot restore this endpoint: legacy state has no previous DNS configuration and Railway removed endpoint deletion. Remove its service instance or explicitly release the resource from Alchemy state.";
658 }
659 }
660
661 export class PrivateNetworkEndpointTargetMissing extends Data.TaggedError(
662 "Railway.PrivateNetworkEndpointTargetMissing",
663 )<{ message: string }> {}
664
665 type CloudEndpoint = PrivateNetworkEndpointValue;
666
667 const serviceIdOf = (value: unknown): string | undefined => {
668 if (value === null || typeof value !== "object") return undefined;
669 const rec = value as { serviceId?: unknown };
670 return typeof rec.serviceId === "string" && rec.serviceId.length > 0 ? rec.serviceId : undefined;
671 };
672
673 const serviceNameOf = (value: unknown): string | undefined => {
674 if (value === null || typeof value !== "object") return undefined;
675 const rec = value as { name?: unknown };
676 return typeof rec.name === "string" && rec.name.length > 0 ? rec.name : undefined;
677 };
678
679 const goneEndpointStatus = (status: PrivateNetworkEndpointSyncStatus) =>
680 status === "DELETED" || status === "DELETING";
681
682 const isGoneEndpoint = (endpoint: CloudEndpoint | null | undefined) =>
683 endpoint == null || endpoint.deletedAt != null || goneEndpointStatus(endpoint.syncStatus);
684
685 const dnsPrefix = (dnsName: string) =>
686 dnsName
687 .replace(/\.+$/, "")
688 .replace(/\.railway\.internal$/i, "")
689 .split(".")
690 .filter((part) => part.length > 0)[0] ?? dnsName;
691
692 const toEndpointAttrs = (
693 endpoint: NonNullable<CloudEndpoint>,
694 fallback: {
695 serviceId: string;
696 privateNetworkId: string;
697 environmentId: string;
698 projectId?: string;
699 },
700 ): PrivateNetworkEndpoint["Attributes"] => ({
701 publicId: endpoint.publicId,
702 dnsName: endpoint.dnsName,
703 newDnsName: endpoint.newDnsName ?? undefined,
704 privateIps: [...endpoint.privateIps],
705 serviceInstanceId: endpoint.serviceInstanceId,
706 serviceId: fallback.serviceId,
707 privateNetworkId: fallback.privateNetworkId,
708 environmentId: fallback.environmentId,
709 projectId: fallback.projectId,
710 syncStatus: endpoint.syncStatus,
711 tags: [...endpoint.tags],
712 createdAt: endpoint.createdAt ?? undefined,
713 });
714
715 const getEndpoint = (input: {
716 environmentId: string;
717 privateNetworkId: string;
718 serviceId: string;
719 }) =>
720 readPrivateNetworkEndpoint({
721 environmentId: input.environmentId,
722 privateNetworkId: input.privateNetworkId,
723 serviceId: input.serviceId,
724 }).pipe(
725 Effect.map((endpoint) => (endpoint == null || isGoneEndpoint(endpoint) ? undefined : endpoint)),
726 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
727 );
728
729 const resolveServiceName = (serviceId: string, hint?: string) =>
730 hint !== undefined && hint.length > 0
731 ? Effect.succeed(hint)
732 : readServiceName(serviceId).pipe(
733 Effect.map((service) => service.name),
734 Effect.catchTag("RailwayNotFound", () => Effect.succeed(sanitizeRailwayName(serviceId))),
735 );
736
737 export class PrivateNetworkEndpointNameUnavailable extends Data.TaggedError(
738 "Railway.PrivateNetworkEndpointNameUnavailable",
739 )<{ endpointName: string; privateNetworkId: string; serviceId: string }> {}
740
741 const waitUntilEndpointNamed = (input: {
742 environmentId: string;
743 privateNetworkId: string;
744 serviceId: string;
745 prefix: string;
746 }) =>
747 getEndpoint(input).pipe(
748 Effect.flatMap((endpoint) => {
749 if (endpoint == null || dnsPrefix(endpoint.dnsName) !== input.prefix) {
750 return Effect.fail(
751 new PrivateNetworkEndpointNotCreated({
752 privateNetworkId: input.privateNetworkId,
753 serviceId: input.serviceId,
754 expectedPrefix: input.prefix,
755 observedPrefix: endpoint?.dnsName,
756 pendingPrefix: endpoint?.newDnsName ?? undefined,
757 }),
758 );
759 }
760 return Effect.succeed(endpoint);
761 }),
762 Effect.retry({
763 while: (e) => e._tag === "Railway.PrivateNetworkEndpointNotCreated",
764 // DNS renames are observed through the endpoint and can lag the config
765 // commit by 10s+.
766 times: 10,
767 schedule: Schedule.spaced("3 seconds"),
768 }),
769 );
770
771 export const PrivateNetworkEndpointProvider = () =>
772 Provider.succeed(PrivateNetworkEndpoint, {
773 stables: ["publicId", "serviceId", "privateNetworkId", "environmentId", "serviceInstanceId"],
774 nuke: {
775 skip: true,
776 dependsOn: ["Railway.PrivateNetwork", "Railway.Service", "Railway.Project"],
777 },
778
779 diff: Effect.fn(function* ({ news, output }) {
780 if (news === undefined || !isResolved(news)) return undefined;
781 if (output === undefined) return undefined;
782 const serviceId = serviceIdOf(news.service);
783 const serviceChanged = serviceId !== undefined && serviceId !== output.serviceId;
784 const networkId = publicIdOf(news.network);
785 const networkChanged = networkId !== undefined && networkId !== output.privateNetworkId;
786 if (serviceChanged || networkChanged) {
787 return { action: "replace" as const };
788 }
789 return undefined;
790 }),
791
792 read: Effect.fn(function* ({ olds, output }) {
793 const serviceId = output?.serviceId ?? serviceIdOf(olds?.service);
794 const privateNetworkId = output?.privateNetworkId ?? publicIdOf(olds?.network);
795 const environmentId =
796 output?.environmentId ?? environmentIdOf(olds?.network) ?? environmentIdOf(olds);
797 if (
798 serviceId === undefined ||
799 privateNetworkId === undefined ||
800 environmentId === undefined
801 ) {
802 return undefined;
803 }
804 const found = yield* getEndpoint({ environmentId, privateNetworkId, serviceId });
805 if (found === undefined) return undefined;
806 return {
807 ...toEndpointAttrs(found, {
808 serviceId,
809 privateNetworkId,
810 environmentId,
811 projectId: output?.projectId ?? projectIdOf(olds?.network),
812 }),
813 previousDnsPrefix: output?.previousDnsPrefix,
814 };
815 }),
816
817 list: Effect.fn(function* () {
818 const projects = yield* ownedProjects();
819 const rows = yield* Effect.forEach(projects, (project) =>
820 Effect.gen(function* () {
821 const environmentIds = yield* projectEnvironmentIds(project);
822 const networks = (yield* Effect.forEach(environmentIds, listNetworks)).flat();
823 const owned = networks.filter((network) => network.name === PLATFORM_NETWORK_NAME);
824 const live = yield* fetchProjectServices(project.projectId, (service) => ({
825 id: service.id,
826 name: service.name,
827 deletedAt: service.deletedAt,
828 })).pipe(Effect.catchTag("RailwayNotFound", () => Effect.undefined));
829 const services = (live ?? []).filter((service) => service.deletedAt == null);
830 const nested = yield* Effect.forEach(owned, (network) =>
831 Effect.forEach(services, (service) =>
832 getEndpoint({
833 environmentId: network.environmentId,
834 privateNetworkId: network.publicId,
835 serviceId: service.id,
836 }).pipe(
837 Effect.map((endpoint) =>
838 endpoint === undefined
839 ? undefined
840 : toEndpointAttrs(endpoint, {
841 serviceId: service.id,
842 privateNetworkId: network.publicId,
843 environmentId: network.environmentId,
844 projectId: project.projectId,
845 }),
846 ),
847 ),
848 ).pipe(
849 Effect.map((items) =>
850 items.filter(
851 (item): item is PrivateNetworkEndpoint["Attributes"] => item !== undefined,
852 ),
853 ),
854 ),
855 );
856 return nested.flat();
857 }),
858 );
859 return rows.flat();
860 }),
861
862 reconcile: Effect.fn(function* ({ news, output }) {
863 const props = news ?? ({} as PrivateNetworkEndpointProps);
864 const serviceId = serviceIdOf(props.service) ?? output?.serviceId;
865 const privateNetworkId = publicIdOf(props.network) ?? output?.privateNetworkId;
866 const environmentId = environmentIdOf(props.network) ?? output?.environmentId;
867 const projectId = projectIdOf(props.network) ?? output?.projectId;
868 if (
869 serviceId === undefined ||
870 privateNetworkId === undefined ||
871 environmentId === undefined
872 ) {
873 return yield* new PrivateNetworkEndpointTargetMissing({
874 message:
875 "PrivateNetworkEndpoint requires a network (publicId + environmentId) and a service",
876 });
877 }
878
879 const serviceName = yield* resolveServiceName(serviceId, serviceNameOf(props.service));
880 const desiredOverride = props.name === undefined ? null : sanitizeRailwayName(props.name);
881 const desiredPrefix = desiredOverride ?? sanitizeRailwayName(serviceName);
882
883 const network = yield* observeNetwork({ environmentId, publicId: privateNetworkId });
884 if (network?.name !== PLATFORM_NETWORK_NAME) {
885 return yield* new PrivateNetworkEndpointTargetMissing({
886 message:
887 "PrivateNetworkEndpoint requires the platform-managed Railway network; legacy named networks are no longer supported",
888 });
889 }
890
891 const previousDnsPrefix = yield* withEnvironmentConfigLock(
892 environmentId,
893 Effect.gen(function* () {
894 const config = yield* readNetworkConfig(environmentId);
895 if (config.privateNetworkDisabled === true) {
896 return yield* new PrivateNetworkEndpointTargetMissing({
897 message:
898 "Enable private networking with PrivateNetwork before configuring an endpoint",
899 });
900 }
901 const configuredPrefix = config.services?.[serviceId]?.networking?.privateNetworkEndpoint;
902 const current = yield* getEndpoint({ environmentId, privateNetworkId, serviceId });
903 const hasDesiredName =
904 current !== undefined && dnsPrefix(current.dnsName) === desiredPrefix;
905 if ((configuredPrefix ?? null) === desiredOverride) {
906 return configuredPrefix ?? null;
907 }
908 if (!hasDesiredName && dnsPrefix(current?.newDnsName ?? "") !== desiredPrefix) {
909 const available = yield* endpointNameAvailable({
910 environmentId,
911 privateNetworkId,
912 prefix: desiredPrefix,
913 });
914 if (!available) {
915 return yield* new PrivateNetworkEndpointNameUnavailable({
916 endpointName: desiredPrefix,
917 privateNetworkId,
918 serviceId,
919 });
920 }
921 }
922 yield* environmentPatchCommit({
923 environmentId,
924 commitMessage: "Configure private networking DNS prefix",
925 patch: {
926 services: {
927 [serviceId]: { networking: { privateNetworkEndpoint: desiredOverride } },
928 },
929 },
930 });
931 return configuredPrefix ?? null;
932 }),
933 );
934 const current = yield* waitUntilEndpointNamed({
935 environmentId,
936 privateNetworkId,
937 serviceId,
938 prefix: desiredPrefix,
939 });
940
941 return {
942 ...toEndpointAttrs(current, { serviceId, privateNetworkId, environmentId, projectId }),
943 previousDnsPrefix:
944 output?.previousDnsPrefix !== undefined ? output.previousDnsPrefix : previousDnsPrefix,
945 };
946 }),
947
948 delete: Effect.fn(function* ({ olds, output }) {
949 if (output.previousDnsPrefix === undefined) {
950 const endpoint = yield* getEndpoint({
951 environmentId: output.environmentId,
952 privateNetworkId: output.privateNetworkId,
953 serviceId: output.serviceId,
954 });
955 if (endpoint === undefined) return;
956 return yield* new PrivateNetworkEndpointRestoreUnavailable({
957 serviceId: output.serviceId,
958 environmentId: output.environmentId,
959 });
960 }
961 const previousDnsPrefix = output.previousDnsPrefix;
962 const managedPrefix = olds.name === undefined ? null : sanitizeRailwayName(olds.name);
963 yield* withEnvironmentConfigLock(
964 output.environmentId,
965 Effect.gen(function* () {
966 const config = yield* readNetworkConfig(output.environmentId);
967 const serviceConfig = config.services?.[output.serviceId];
968 // The service instance is gone from the environment: its endpoint
969 // went with it and there is no DNS override left to restore.
970 if (serviceConfig == null) return;
971 const configuredPrefix = serviceConfig.networking?.privateNetworkEndpoint;
972 if (
973 (configuredPrefix ?? null) !== managedPrefix ||
974 (configuredPrefix ?? null) === previousDnsPrefix
975 ) {
976 return;
977 }
978 yield* environmentPatchCommit({
979 environmentId: output.environmentId,
980 commitMessage: "Restore private networking DNS prefix",
981 patch: {
982 services: {
983 [output.serviceId]: { networking: { privateNetworkEndpoint: previousDnsPrefix } },
984 },
985 },
986 });
987 yield* waitForNetworkConfig(
988 output.environmentId,
989 (observed) =>
990 (observed.services?.[output.serviceId]?.networking?.privateNetworkEndpoint ??
991 null) === previousDnsPrefix,
992 );
993 }),
994 ).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
995 }),
996 });