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

main
ts 388 lines 13.6 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import { Railway, type TCPProxy } 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
14 const proxyFields = <E>(proxy: Query<TCPProxy, E>) => ({
15 id: proxy.id,
16 applicationPort: proxy.applicationPort,
17 deletedAt: proxy.deletedAt,
18 syncStatus: proxy.syncStatus,
19 domain: proxy.domain,
20 proxyPort: proxy.proxyPort,
21 serviceId: proxy.serviceId,
22 environmentId: proxy.environmentId,
23 });
24 type CloudProxy = UnwrapPlan<ReturnType<typeof proxyFields>>;
25
26 const readTcpProxies = Query.fn((environmentId: string, serviceId: string) =>
27 Railway.tcpProxies({ environmentId, serviceId }).pipe(Query.map(proxyFields)),
28 );
29
30 const tcpProxyCreate = Query.fn(
31 (input: { applicationPort: number; environmentId: string; serviceId: string }) =>
32 proxyFields(Railway.tcpProxyCreate({ input })),
33 );
34
35 const tcpProxyDelete = Query.fn((id: string) => Railway.tcpProxyDelete({ id }));
36
37 /**
38 * A resource-valued prop: the resource itself, or an Effect that produces
39 * it (so `yield* Service(...)` and `Service(...)` both type-check).
40 */
41 type Ref<T> = T | Effect.Effect<T, never, Providers>;
42
43 /**
44 * Service identity a TCP proxy attaches to. Accepts a `Railway.Service`,
45 * `Railway.Postgres`, `Railway.Redis`, or a `{ serviceId }` stub.
46 */
47 export type TcpProxyService = { readonly serviceId: string };
48
49 /**
50 * Environment identity a TCP proxy is created in. Accepts a
51 * `Railway.Project` (its primary environment), a `Railway.Environment`, or
52 * an `{ environmentId }` stub.
53 */
54 export type TcpProxyEnvironment = { readonly environmentId: string };
55
56 export interface TcpProxyProps {
57 /**
58 * Service to expose. Accepts a `Railway.Service` or `{ serviceId }`.
59 * Mutually exclusive with `postgres` / `redis`. Changing it replaces
60 * the proxy.
61 */
62 service?: Ref<TcpProxyService>;
63 /**
64 * Postgres service to expose. Same identity as `service`. Changing it
65 * replaces the proxy.
66 */
67 postgres?: Ref<TcpProxyService>;
68 /**
69 * Redis service to expose. Same identity as `service`. Changing it
70 * replaces the proxy.
71 */
72 redis?: Ref<TcpProxyService>;
73 /**
74 * Environment the proxy is created in. Accepts a `Railway.Project`
75 * (primary environment), a `Railway.Environment`, or `{ environmentId }`.
76 * Changing it replaces the proxy.
77 */
78 environment: Ref<TcpProxyEnvironment>;
79 /**
80 * Internal application port to proxy to (for example `5432` for
81 * Postgres, `6379` for Redis). Changing it replaces the proxy.
82 */
83 applicationPort: number;
84 }
85
86 export type TcpProxy = Resource<
87 "Railway.TcpProxy",
88 TcpProxyProps,
89 {
90 /** Railway TCP proxy id. */
91 id: string;
92 /** Public proxy hostname (`*.proxy.rlwy.net`). */
93 domain: string;
94 /** Public proxy port. Pair with `domain` to reach the service. */
95 proxyPort: number;
96 /** Internal application port being proxied. */
97 applicationPort: number;
98 /** Service the proxy is attached to. */
99 serviceId: string;
100 /** Environment the proxy lives in. */
101 environmentId: string;
102 /** Observed Railway sync status (`ACTIVE`, `CREATING`, …). */
103 syncStatus: string;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A Railway.TcpProxy exposes a service over public TCP. Identity is the
111 * Railway proxy id. There is no in-place update — changing `service`,
112 * `postgres`, `redis`, `environment`, or `applicationPort` replaces the
113 * proxy.
114 *
115 * Needed so laptop tests and `ConnectPostgres` from outside the private
116 * network can reach Postgres/Redis.
117 *
118 * @see https://docs.railway.com/networking/tcp-proxy
119 *
120 * ### Postgres
121 * Attach a proxy to a Postgres service on `5432`. `domain` and
122 * `proxyPort` are the public endpoint (`{domain}:{proxyPort}`).
123 *
124 * **Example:** Public TCP for Postgres
125 * ```typescript
126 * const site = yield* Railway.Project("Site");
127 * const db = yield* Railway.Postgres("Db", { project: site });
128 * const proxy = yield* Railway.TcpProxy("DbProxy", {
129 * postgres: db,
130 * environment: site,
131 * applicationPort: 5432,
132 * });
133 * ```
134 *
135 * :::caution[Changing `applicationPort` replaces the proxy]
136 * Railway has no TCP-proxy update API. A new proxy is created, then the
137 * old one is deleted.
138 * :::
139 *
140 * ### Redis
141 * Same shape on `6379`.
142 *
143 * **Example:** Public TCP for Redis
144 * ```typescript
145 * const site = yield* Railway.Project("Site");
146 * const cache = yield* Railway.Redis("Cache", { project: site });
147 * const proxy = yield* Railway.TcpProxy("CacheProxy", {
148 * redis: cache,
149 * environment: site,
150 * applicationPort: 6379,
151 * });
152 * ```
153 *
154 * ### Any service
155 * Pass a `Railway.Service` or a `{ serviceId }` stub.
156 *
157 * **Example:** Stub service id
158 * ```typescript
159 * const site = yield* Railway.Project("Site");
160 * const proxy = yield* Railway.TcpProxy("ApiProxy", {
161 * service: { serviceId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" },
162 * environment: site,
163 * applicationPort: 8080,
164 * });
165 * ```
166 *
167 * :::caution[Changing `service` or `environment` replaces the proxy]
168 * The proxy is created on the new service/environment. The old proxy is
169 * deleted.
170 * :::
171 *
172 * ### Module-scope declarations
173 * Resource-valued props accept the resource or an Effect producing it.
174 *
175 * **Example:** Module-scope Project and proxy
176 * ```typescript
177 * // src/db.ts
178 * import * as Railway from "@alchemy.run/railway";
179 *
180 * export const Site = Railway.Project("Site");
181 * export const Db = Railway.Postgres("Db", { project: Site });
182 * export const DbProxy = Railway.TcpProxy("DbProxy", {
183 * postgres: Db,
184 * environment: Site,
185 * applicationPort: 5432,
186 * });
187 * ```
188 *
189 * @resource
190 * @product Networking
191 */
192 export const TcpProxy = Resource<TcpProxy>("Railway.TcpProxy");
193
194 export class TcpProxyNotCreated extends Data.TaggedError("Railway.TcpProxyNotCreated")<{
195 serviceId: string;
196 environmentId: string;
197 applicationPort: number;
198 }> {}
199
200 export class TcpProxyTargetMissing extends Data.TaggedError("Railway.TcpProxyTargetMissing")<{
201 message: string;
202 }> {}
203
204 const isGone = (proxy: CloudProxy | undefined) =>
205 proxy === undefined || proxy.deletedAt != null || proxy.syncStatus === "DELETED";
206
207 const normalizeDomain = (domain: string) => domain.replace(/\.+$/, "");
208
209 const toAttrs = (proxy: CloudProxy): TcpProxy["Attributes"] => ({
210 id: proxy.id,
211 domain: normalizeDomain(proxy.domain),
212 proxyPort: proxy.proxyPort,
213 applicationPort: proxy.applicationPort,
214 serviceId: proxy.serviceId,
215 environmentId: proxy.environmentId,
216 syncStatus: proxy.syncStatus,
217 });
218
219 const serviceIdOf = (value: unknown): string | undefined => {
220 if (value === null || typeof value !== "object") return undefined;
221 const rec = value as { serviceId?: unknown };
222 if (typeof rec.serviceId === "string" && rec.serviceId.length > 0) {
223 return rec.serviceId;
224 }
225 return undefined;
226 };
227
228 const environmentIdOf = (value: unknown): string | undefined => {
229 if (value === null || typeof value !== "object") return undefined;
230 const rec = value as { environmentId?: unknown };
231 if (typeof rec.environmentId === "string" && rec.environmentId.length > 0) {
232 return rec.environmentId;
233 }
234 return undefined;
235 };
236
237 const targetOf = (props: Pick<TcpProxyProps, "service" | "postgres" | "redis">) =>
238 props.service ?? props.postgres ?? props.redis;
239
240 const listProxies = (environmentId: string, serviceId: string) =>
241 readTcpProxies(environmentId, serviceId).pipe(
242 Effect.map((items) => items.filter((proxy) => !isGone(proxy))),
243 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as ReadonlyArray<CloudProxy>)),
244 );
245
246 const findById = (environmentId: string, serviceId: string, id: string) =>
247 listProxies(environmentId, serviceId).pipe(
248 Effect.map((items) => items.find((proxy) => proxy.id === id)),
249 );
250
251 const findByPort = (environmentId: string, serviceId: string, applicationPort: number) =>
252 listProxies(environmentId, serviceId).pipe(
253 Effect.map((items) => items.find((proxy) => proxy.applicationPort === applicationPort)),
254 );
255
256 const observe = Effect.fn(function* (input: {
257 environmentId: string;
258 serviceId: string;
259 applicationPort?: number;
260 id?: string;
261 }) {
262 if (input.id !== undefined && input.id.length > 0) {
263 const byId = yield* findById(input.environmentId, input.serviceId, input.id);
264 if (byId !== undefined) return byId;
265 }
266 if (input.applicationPort !== undefined) {
267 return yield* findByPort(input.environmentId, input.serviceId, input.applicationPort);
268 }
269 return undefined;
270 });
271
272 const waitUntilGone = (environmentId: string, serviceId: string, id: string) =>
273 waitUntilDeleted(
274 "TcpProxy",
275 id,
276 findById(environmentId, serviceId, id).pipe(Effect.map((proxy) => proxy === undefined)),
277 );
278
279 export const TcpProxyProvider = () =>
280 Provider.succeed(TcpProxy, {
281 stables: ["id", "domain", "proxyPort", "serviceId", "environmentId"],
282 nuke: { dependsOn: ["Railway.Project"] },
283
284 list: Effect.fn(function* () {
285 const projects = yield* ownedProjects();
286 const rows = yield* Effect.forEach(projects, (project) =>
287 Effect.gen(function* () {
288 const live = yield* fetchProjectServices(project.projectId, (service) => ({
289 id: service.id,
290 name: service.name,
291 deletedAt: service.deletedAt,
292 })).pipe(Effect.catchTag("RailwayNotFound", () => Effect.undefined));
293 const services = (live ?? []).filter(
294 (service) => service.deletedAt == null && matchesAlchemyPhysicalName(service.name),
295 );
296 const envIds = yield* projectEnvironmentIds(project);
297 const nested = yield* Effect.forEach(services, (service) =>
298 Effect.forEach(envIds, (environmentId) =>
299 listProxies(environmentId, service.id).pipe(
300 Effect.map((proxies) => proxies.map((proxy) => toAttrs(proxy))),
301 ),
302 ).pipe(Effect.map((rows) => rows.flat())),
303 );
304 return nested.flat();
305 }),
306 );
307 return rows.flat();
308 }),
309
310 diff: Effect.fn(function* ({ news, output }) {
311 if (news === undefined || !isResolved(news)) return undefined;
312 if (output === undefined) return undefined;
313 const serviceId = serviceIdOf(targetOf(news));
314 const environmentId = environmentIdOf(news.environment);
315 const serviceChanged = serviceId !== undefined && serviceId !== output.serviceId;
316 const environmentChanged =
317 environmentId !== undefined && environmentId !== output.environmentId;
318 const portChanged = news.applicationPort !== output.applicationPort;
319 if (serviceChanged || environmentChanged || portChanged) {
320 return { action: "replace" as const };
321 }
322 return undefined;
323 }),
324
325 read: Effect.fn(function* ({ olds, output }) {
326 const serviceId = output?.serviceId ?? serviceIdOf(targetOf(olds ?? {}));
327 const environmentId = output?.environmentId ?? environmentIdOf(olds?.environment);
328 const applicationPort = output?.applicationPort ?? olds?.applicationPort;
329 if (serviceId === undefined || environmentId === undefined) {
330 return undefined;
331 }
332 const found = yield* observe({ environmentId, serviceId, applicationPort, id: output?.id });
333 if (found === undefined) return undefined;
334 return toAttrs(found);
335 }),
336
337 reconcile: Effect.fn(function* ({ news, output }) {
338 const props = news ?? ({} as TcpProxyProps);
339 const serviceId = serviceIdOf(targetOf(props)) ?? output?.serviceId;
340 const environmentId = environmentIdOf(props.environment) ?? output?.environmentId;
341 const applicationPort = props.applicationPort ?? output?.applicationPort;
342 if (serviceId === undefined || environmentId === undefined) {
343 return yield* new TcpProxyTargetMissing({
344 message: "TcpProxy requires a service (or postgres/redis) and an environment",
345 });
346 }
347 if (applicationPort === undefined) {
348 return yield* new TcpProxyNotCreated({ serviceId, environmentId, applicationPort: 0 });
349 }
350
351 let current = yield* observe({ environmentId, serviceId, applicationPort, id: output?.id });
352
353 if (current === undefined) {
354 const created = yield* tcpProxyCreate({ applicationPort, environmentId, serviceId }).pipe(
355 Effect.catchTag("RailwayValidationError", () => Effect.undefined),
356 );
357 current =
358 created !== undefined && !isGone(created)
359 ? created
360 : yield* observe({ environmentId, serviceId, applicationPort });
361 }
362
363 if (current === undefined || isGone(current)) {
364 return yield* new TcpProxyNotCreated({ serviceId, environmentId, applicationPort });
365 }
366
367 return toAttrs(current);
368 }),
369
370 delete: Effect.fn(function* ({ output }) {
371 const id = output.id;
372 if (id.length === 0) return;
373 yield* tcpProxyDelete(id).pipe(
374 // Railway serializes proxy mutations per environment: a delete
375 // racing an in-flight deploy fails with "Cannot delete TCP proxy:
376 // an operation is already in progress".
377 Effect.retry({
378 while: (e) => e._tag === "RailwayOperationInProgress",
379 schedule: Schedule.spaced("3 seconds"),
380 times: 10,
381 }),
382 Effect.catchTag("RailwayNotFound", () => Effect.void),
383 );
384 if (output.environmentId.length > 0 && output.serviceId.length > 0) {
385 yield* waitUntilGone(output.environmentId, output.serviceId, id);
386 }
387 }),
388 });