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

main
ts 582 lines 18.1 KB
Raw
1 import type { Builder, RestartPolicyType } from "@distilled.cloud/railway";
2 import type { HttpEffect } from "alchemy/Http";
3 import { Platform, type Main, type MainRpc, type PlatformProps } from "alchemy/Platform";
4 import type { Resource } from "alchemy/Resource";
5 import type { ServerHost } from "alchemy/Runtime/Process";
6 import * as Effect from "effect/Effect";
7 import type * as Redacted from "effect/Redacted";
8 import {
9 createRailwayHostRuntimeContext,
10 type ExtraFile,
11 type RailwayBuildOptions,
12 type RailwayHostRuntimeContext,
13 } from "./hosted.ts";
14 import type { ServiceBinding } from "./MountVolume.ts";
15 import type { Project } from "./Project.ts";
16 import type { Providers } from "./Providers.ts";
17 import { serveRailwayRpc } from "./rpc-server.ts";
18 import { mintRpcToken } from "./rpc-token.ts";
19
20 /**
21 * A resource-valued prop: the resource itself, or an Effect that produces
22 * it (so `yield* Project(...)` and `Project(...)` both type-check).
23 */
24 type Ref<T> = T | Effect.Effect<T, never, Providers>;
25
26 export type { ExtraFile, RailwayBuildOptions };
27
28 /**
29 * Environment identity a Service is deployed into. Accepts a
30 * `Railway.Project` (its primary environment), a `Railway.Environment`,
31 * or an `{ environmentId }` stub.
32 */
33 export type ServiceEnvironment = {
34 readonly environmentId: string;
35 };
36
37 export interface ServiceProps extends PlatformProps {
38 /**
39 * Parent Railway Project. Accepts a `Railway.Project` or an Effect
40 * that produces one. Changing the Project replaces the Service.
41 */
42 project: Ref<Project>;
43 /**
44 * Environment to deploy the service instance into. Accepts a
45 * `Railway.Project` (primary environment), a `Railway.Environment`, or
46 * `{ environmentId }`. Defaults to the project's primary environment.
47 * Changing it replaces the Service.
48 */
49 environment?: Ref<ServiceEnvironment>;
50 /**
51 * Module entrypoint bundled with rolldown and packed into a generated
52 * Dockerfile. Railway builds that Dockerfile (`railway up`). Typically
53 * `import.meta.url`. Mutually exclusive with the public-image path
54 * (`image` without `main`). A content-hash change updates in place.
55 */
56 main?: string;
57 /**
58 * Local Docker context uploaded with Railway `up`. Paths are relative to the
59 * initial working directory. Limited to a 32 MiB archive, 10,000 entries,
60 * ASCII paths, and no symlinks; Docker ignore files apply.
61 */
62 context?: string;
63 /**
64 * Docker image Railway should run.
65 *
66 * When `main` is omitted this is `source.image` (e.g.
67 * `hashicorp/http-echo`). When `main` is set this is the generated
68 * Dockerfile's `FROM` (default `node:26-slim`).
69 */
70 image?: string;
71 /**
72 * Region the service runs in (`us-west2`, `europe-west4-drams3a`, …).
73 * Railway places replicas with `deploy.multiRegionConfig`. Omit this
74 * and the current placement is left alone (the workspace default on
75 * first create). Updating it moves the replicas in place and keeps
76 * the current replica count.
77 */
78 region?: string;
79 /**
80 * Port the process listens on. Written to `PORT` and used as the
81 * generated `*.up.railway.app` `targetPort`. Default is `3000` for
82 * Effect-native (`main`) Services. Pass `5678` for
83 * `hashicorp/http-echo`.
84 */
85 port?: number;
86 /**
87 * Whether to create and manage a generated `*.up.railway.app` domain.
88 * Existing unowned generated or custom domains are not removed.
89 * @default true
90 */
91 publicDomain?: boolean;
92 /**
93 * Additional environment variables. Merged after binding-injected
94 * `env`. Upserted as service-scoped Railway variables with
95 * `skipDeploys: true`; this Service owns the subsequent deploy.
96 */
97 env?: Record<string, any>;
98 /**
99 * Private-mesh RPC token. Minted by a child `Alchemy.Random`
100 * (`{logicalId}RpcToken`) and persisted in state. Set automatically.
101 */
102 rpcToken?: Redacted.Redacted<string>;
103 /**
104 * Bundler configuration for `main`: rolldown `input`/`output`
105 * overrides, plus `install` for packages that must ship as real
106 * `node_modules` (see {@link RailwayBuildOptions}).
107 */
108 build?: RailwayBuildOptions;
109 /**
110 * Extra files/directories copied into `/app` in the generated
111 * Dockerfile (`COPY dest /app/dest`). Website composites use this to
112 * bake the framework `clientDirectory` (or Next.js `.next`) so asset
113 * changes rebuild on Railway.
114 */
115 extraFiles?: ReadonlyArray<ExtraFile>;
116 /**
117 * Named export to load from `main`.
118 *
119 * @default "default"
120 */
121 handler?: string;
122 /**
123 * Service name. Unique per Project. If omitted, a unique name is
124 * generated from the stack, stage and logical ID. Changing it updates
125 * in place via `serviceUpdate`.
126 */
127 name?: string;
128 /**
129 * GitHub repository (`owner/repo`). Creates/syncs
130 * `serviceCreate.source.repo` / `serviceInstanceUpdate.source.repo`.
131 * Mutually exclusive with the public-image and `main` paths. Requires a
132 * GitHub connection on the Railway account.
133 */
134 repo?: string;
135 /**
136 * GitHub branch for {@link repo}. Passed as `serviceCreate.branch` and
137 * synced onto the deployment trigger.
138 */
139 branch?: string;
140 /**
141 * Monorepo subdirectory Railway builds from (`rootDirectory`).
142 */
143 rootDirectory?: string;
144 /**
145 * Build command (`pnpm build`). Distinct from hosted
146 * {@link RailwayBuildOptions} (`build.install`).
147 */
148 buildCommand?: string;
149 /**
150 * Pre-deploy step Railway runs after the image build and before
151 * start (migrations, seed). Omit to leave the current Railway setting
152 * unchanged. Pass `{ command: null }` to clear it.
153 *
154 * @see https://docs.railway.com/deployments/pre-deploy-command
155 */
156 preDeploy?: {
157 /**
158 * Shell command Railway executes in a separate container after
159 * build and before start. Must exit 0 or the deployment fails.
160 * Pass `null` to clear it.
161 */
162 command: string | null;
163 };
164 /**
165 * Start command (`pnpm start`).
166 */
167 startCommand?: string;
168 /**
169 * HTTP healthcheck path (`/health`). Synced via
170 * `serviceInstanceUpdate.healthcheckPath`. Alias of {@link healthcheck}
171 * (Railway IaC `healthcheck: "/health"`).
172 */
173 healthcheckPath?: string;
174 /**
175 * HTTP healthcheck path. Same as {@link healthcheckPath}; matches
176 * Railway IaC `healthcheck`.
177 */
178 healthcheck?: string;
179 /**
180 * Healthcheck timeout in seconds.
181 */
182 healthcheckTimeout?: number;
183 /**
184 * Cron expression (`cronSchedule`). Observed as `cronSchedule` /
185 * `nextCronRunAt`.
186 */
187 cronSchedule?: string;
188 /**
189 * Restart policy (`ALWAYS`, `NEVER`, `ON_FAILURE`).
190 */
191 restartPolicyType?: RestartPolicyType;
192 /**
193 * Max retries when {@link restartPolicyType} is `ON_FAILURE`.
194 */
195 restartPolicyMaxRetries?: number;
196 /**
197 * Drain window in seconds before a replica is stopped.
198 */
199 drainingSeconds?: number;
200 /**
201 * Overlap window in seconds while a new replica starts.
202 */
203 overlapSeconds?: number;
204 /**
205 * Sleep the application when idle.
206 */
207 sleepApplication?: boolean;
208 /**
209 * Auto-deploy on new commits / image tags
210 * (`serviceInstanceAutoDeployUpdate`).
211 */
212 autoUpdates?: boolean;
213 /**
214 * Dockerfile path relative to {@link rootDirectory}, or to {@link context}
215 * for a local context.
216 * @default "Dockerfile"
217 */
218 dockerfilePath?: string;
219 /**
220 * Builder (`RAILPACK`, `NIXPACKS`, `HEROKU`, `PAKETO`).
221 */
222 builder?: Builder;
223 /**
224 * Git watch patterns that trigger a rebuild.
225 */
226 watchPatterns?: string[];
227 }
228
229 export type Service = Resource<
230 "Railway.Service",
231 ServiceProps,
232 {
233 /** Railway service id. */
234 serviceId: string;
235 /** Physical service name (unique per project). */
236 name: string;
237 /** Parent Railway project id. */
238 projectId: string;
239 /** Environment the instance is deployed in. */
240 environmentId: string;
241 /** Observed `source.image`, if set. */
242 image: string | undefined;
243 /** Observed `source.repo` (`owner/repo`), if set. */
244 repo: string | undefined;
245 /** Observed healthcheck path. */
246 healthcheckPath: string | undefined;
247 /** Observed healthcheck timeout in seconds. */
248 healthcheckTimeout: number | undefined;
249 /**
250 * Observed replica count. Alchemy does not set this — Railway
251 * load-balances whatever is running (default 1).
252 */
253 replicas: number | undefined;
254 /** Observed build command. */
255 buildCommand: string | undefined;
256 /** Observed start command. */
257 startCommand: string | undefined;
258 /** Observed cron schedule. */
259 cronSchedule: string | undefined;
260 /** Observed root directory. */
261 rootDirectory: string | undefined;
262 /**
263 * Region the service is placed in. Set when
264 * `deploy.multiRegionConfig` has replicas in exactly one region.
265 */
266 region: string | undefined;
267 /** Port published on the generated service domain. */
268 port: number | undefined;
269 /** Public `https://{domain}` URL (`*.up.railway.app`). */
270 url: string | undefined;
271 /** Generated Railway service domain hostname. */
272 domain: string | undefined;
273 /**
274 * Internal DNS name on the default private mesh
275 * (`{name}.railway.internal`). Derived from the service name — no
276 * extra API call.
277 */
278 dnsName: string;
279 /**
280 * Shared token for private schemaless RPC. Value of the child
281 * `Alchemy.Random` resource. Packed onto callers by `bindService` /
282 * `bindFunction`; never send this to the public internet.
283 */
284 rpcToken: string;
285 /** Railway service domain id. */
286 domainId: string | undefined;
287 /** Latest deployment id, if one exists. */
288 deploymentId: string | undefined;
289 /** Latest deployment status (`SUCCESS`, `DEPLOYING`, …). */
290 deploymentStatus: string | undefined;
291 /** Content hash of the bundled program (empty for public images). */
292 code: {
293 hash: string;
294 };
295 },
296 ServiceBinding,
297 Providers
298 >;
299
300 export const isService = (value: unknown): value is Service =>
301 typeof value === "object" &&
302 value !== null &&
303 (value as { Type?: string }).Type === "Railway.Service";
304
305 export type ServiceServices = ServerHost;
306
307 export type ServiceShape = Main<ServiceServices> & MainRpc<ServiceServices>;
308
309 export type ServiceRuntimeContext = RailwayHostRuntimeContext;
310
311 const createServiceRuntimeContext = (id: string): ServiceRuntimeContext => {
312 const base = createRailwayHostRuntimeContext("Railway.Service")(id);
313 const inner = base.serve;
314 return Object.assign(base, {
315 serve: ((handler, options) =>
316 inner(
317 (options?.shape === undefined
318 ? handler
319 : // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- the RPC server provides the request service at call time
320 serveRailwayRpc(options.shape, handler as HttpEffect)) as typeof handler,
321 options,
322 )) as ServiceRuntimeContext["serve"],
323 });
324 };
325
326 /**
327 * A Railway.Service is a container in a Project. Point it at a public
328 * image (`hashicorp/http-echo`) or an Effect program (`main`). Alchemy
329 * stamps the name, creates a `*.up.railway.app` domain via
330 * `serviceDomainCreate`, and deploys.
331 *
332 * @see https://docs.railway.com/guides/services
333 *
334 * ### Image service
335 * Pass `image` without `main`. Railway pulls the image and runs it.
336 * `url` is the generated `*.up.railway.app` hostname.
337 *
338 * **Example:** Public image
339 * ```typescript
340 * const site = yield* Railway.Project("Site");
341 * const api = yield* Railway.Service("Api", {
342 * project: site,
343 * image: "hashicorp/http-echo",
344 * port: 5678,
345 * });
346 * ```
347 *
348 * :::caution[Changing `project` replaces the Service]
349 * The Service is created in the new Project. The old Service is deleted.
350 * :::
351 *
352 * ### Effect-native Service
353 * A Service is a class. `main: import.meta.url` is the bundle
354 * entrypoint. Alchemy bundles this file with Rolldown, generates a
355 * Dockerfile (`FROM node:26-slim`), and uploads the context. Railway
356 * builds the image. `build.install: ["pg"]` ships `pg` unbundled.
357 *
358 * **Example:** Class + Project + main
359 * ```typescript
360 * export default class Api extends Railway.Service<Api>()(
361 * "Api",
362 * {
363 * project: Site,
364 * main: import.meta.url,
365 * build: { install: ["pg"] },
366 * },
367 * Effect.gen(function* () {
368 * return {
369 * fetch: Effect.succeed(HttpServerResponse.text("hello")),
370 * };
371 * }),
372 * ) {}
373 * ```
374 *
375 * ### Local Docker context
376 * `context` is a directory Railway builds with `up`. Mutually exclusive
377 * with `image` (without `main`) and `repo`. Docker ignore files apply.
378 *
379 * **Example:** Upload a local Dockerfile
380 * ```typescript
381 * const api = yield* Railway.Service("Api", {
382 * project: site,
383 * context: "./api",
384 * port: 80,
385 * });
386 * ```
387 *
388 * ### The public URL
389 * Yield the Service in the Stack. `api.url` is
390 * `https://{name}.up.railway.app`.
391 *
392 * **Example:** Stack output
393 * ```typescript
394 * export default Alchemy.Stack(
395 * "MyApp",
396 * { providers: Railway.providers(), state: Alchemy.localState() },
397 * Effect.gen(function* () {
398 * const api = yield* Api;
399 * return { url: api.url };
400 * }),
401 * );
402 * ```
403 *
404 * ### Private service
405 * `publicDomain: false` skips the generated `*.up.railway.app` hostname.
406 * `url` / `domain` stay unset. Reach it on the private mesh at
407 * `{name}.railway.internal`. Unowned generated or custom domains are
408 * left alone.
409 *
410 * **Example:** Private-only service
411 * ```typescript
412 * const worker = yield* Railway.Service("Worker", {
413 * project: site,
414 * image: "hashicorp/http-echo",
415 * port: 5678,
416 * publicDomain: false,
417 * });
418 * ```
419 *
420 * ### Pin a region
421 * Omit `region` to leave placement alone. On first create that is the
422 * workspace default. Updating `region` moves the replicas in place.
423 *
424 * **Example:** Region
425 * ```typescript
426 * const api = yield* Railway.Service("Api", {
427 * project: site,
428 * image: "hashicorp/http-echo",
429 * port: 5678,
430 * region: "us-west2",
431 * });
432 * ```
433 *
434 * ### Healthcheck
435 * `healthcheckPath` (or `healthcheck`, matching Railway IaC) is the
436 * HTTP path Railway probes. Railway load-balances public traffic
437 * across whatever replicas are running. Alchemy does not pin a count.
438 *
439 * **Example:** Healthcheck
440 * ```typescript
441 * const api = yield* Railway.Service("Api", {
442 * project: site,
443 * image: "hashicorp/http-echo",
444 * port: 5678,
445 * healthcheck: "/health",
446 * });
447 * ```
448 *
449 * :::caution[One volume per service]
450 * Railway does not give each replica its own disk. A second volume
451 * on one Service fails with `Railway.MultipleVolumes`.
452 * :::
453 *
454 * ### GitHub source
455 * `repo` + `branch` is the third source, next to `image` and `main`.
456 * Railway must have GitHub connected to the account.
457 *
458 * **Example:** GitHub repo
459 * ```typescript
460 * const api = yield* Railway.Service("Api", {
461 * project: site,
462 * repo: "acme/web",
463 * branch: "main",
464 * rootDirectory: "apps/api",
465 * buildCommand: "pnpm build",
466 * startCommand: "pnpm start",
467 * });
468 * ```
469 *
470 * ### Pre-deploy
471 * Railway runs `preDeploy.command` after the image build and before
472 * start — the same setting as the dashboard Pre-deploy Command.
473 *
474 * **Example:** Run migrations before traffic
475 * ```typescript
476 * const api = yield* Railway.Service("Api", {
477 * project: site,
478 * image: "hashicorp/http-echo",
479 * preDeploy: { command: "bun --cwd apps/api migrate" },
480 * });
481 * ```
482 *
483 * ### Cron
484 * `cronSchedule` runs the service on a cron expression.
485 *
486 * **Example:** Cron schedule
487 * ```typescript
488 * const worker = yield* Railway.Service("Worker", {
489 * project: site,
490 * image: "hashicorp/http-echo",
491 * cronSchedule: "0 * * * *",
492 * });
493 * ```
494 *
495 * ### Mount a disk
496 * Bind {@link MountVolume} inside init. Provide {@link MountVolumeLive}.
497 *
498 * **Example:** Volume
499 * ```typescript
500 * export default class Api extends Railway.Service<Api>()(
501 * "Api",
502 * { project: Site, image: "hashicorp/http-echo", port: 5678 },
503 * Effect.gen(function* () {
504 * const disk = yield* Railway.MountVolume(Data, { path: "/data" });
505 * return {
506 * fetch: Effect.succeed(HttpServerResponse.text(disk.path)),
507 * };
508 * }).pipe(Effect.provide(Railway.MountVolumeLive)),
509 * ) {}
510 * ```
511 *
512 * ### Schemaless RPC
513 * Return methods next to `fetch`. Another Service or Function binds
514 * this class and calls them over `{name}.railway.internal` with a
515 * shared token. Public `*.up.railway.app` requests to `/__rpc__/*`
516 * get 401.
517 *
518 * **Example:** Bind a Service
519 * ```typescript
520 * export default class Query extends Railway.Service<Query>()(
521 * "Query",
522 * { project: Site, main: import.meta.url },
523 * Effect.gen(function* () {
524 * return {
525 * greet: (name: string) => Effect.succeed(`hello ${name}`),
526 * };
527 * }),
528 * ) {}
529 *
530 * export default class Api extends Railway.Function<Api>()(
531 * "Api",
532 * { project: Site, main: import.meta.url },
533 * Effect.gen(function* () {
534 * const query = yield* Railway.bindService(Query);
535 * return {
536 * fetch: query
537 * .greet("sam")
538 * .pipe(Effect.map((greeting) => HttpServerResponse.text(greeting))),
539 * };
540 * }),
541 * ) {}
542 * ```
543 *
544 * ### Module-scope declarations
545 * Declare the Project once. Pass it into every child. Resource-valued
546 * props accept the resource or an Effect producing it.
547 *
548 * **Example:** Module-scope Service
549 * ```typescript
550 * // src/api.ts
551 * import * as Railway from "@alchemy.run/railway";
552 *
553 * export const Site = Railway.Project("Site");
554 * export const Api = Railway.Service("Api", {
555 * project: Site,
556 * image: "hashicorp/http-echo",
557 * port: 5678,
558 * });
559 * ```
560 *
561 * @resource
562 * @product Service
563 */
564 export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> =
565 Platform("Railway.Service", {
566 createRuntimeContext: createServiceRuntimeContext,
567 transformProps: (id, props) =>
568 Effect.gen(function* () {
569 if (globalThis.__ALCHEMY_RUNTIME__) return props;
570 const project = Effect.isEffect(props.project)
571 ? yield* props.project as Effect.Effect<Project, never, Providers>
572 : props.project;
573 const environment =
574 props.environment === undefined
575 ? undefined
576 : Effect.isEffect(props.environment)
577 ? yield* props.environment as Effect.Effect<ServiceEnvironment, never, Providers>
578 : props.environment;
579 const rpcToken = yield* mintRpcToken(id);
580 return { ...props, project, environment, rpcToken };
581 }),
582 });