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

main
ts 1,286 lines 45 KB
Raw
1 import { createHash } from "node:crypto";
2 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
3 import {
4 Railway,
5 type Service as RailwayService,
6 type ServiceCreateInput,
7 type ServiceInstance as RailwayServiceInstance,
8 type ServiceInstanceUpdateInput,
9 type VariableUpsertInput,
10 } from "@distilled.cloud/railway";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import * as Bundle from "alchemy/Bundle/Bundle";
13 import { isResolved, stripEffects } from "alchemy/Diff";
14 import type { InputProps } from "alchemy/Input";
15 import { Platform, type Main, type MainRpc, type PlatformProps } from "alchemy/Platform";
16 import * as Provider from "alchemy/Provider";
17 import type { Resource } from "alchemy/Resource";
18 import type { ServerHost } from "alchemy/Runtime/Process";
19 import { Stack } from "alchemy/Stack";
20 import * as Data from "effect/Data";
21 import * as Effect from "effect/Effect";
22 import * as FileSystem from "effect/FileSystem";
23 import type * as Redacted from "effect/Redacted";
24 import * as Schedule from "effect/Schedule";
25 import type * as Types from "effect/Types";
26 import {
27 environmentServiceInstances,
28 waitUntilDeleted,
29 projectServices as fetchProjectServices,
30 } from "./GraphQL.ts";
31 import {
32 collectBindingState,
33 createRailwayFunctionSupport,
34 createRailwayFunctionRuntimeContext,
35 DEFAULT_PORT,
36 plainEnvValue,
37 toEnvRecord,
38 type HostedProgramProps,
39 type RailwayBuildOptions,
40 type RailwayHostRuntimeContext,
41 } from "./hosted.ts";
42 import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts";
43 import { assertHostDisk, type MountSpec, type ServiceBinding } from "./MountVolume.ts";
44 import { ownedProjects, projectEnvironmentIds, type Project } from "./Project.ts";
45 import type { Providers } from "./Providers.ts";
46 import { mintRpcToken, RPC_TOKEN_ENV } from "./rpc-token.ts";
47 import { ensureServiceDomain, type ServiceDomainRecord } from "./ServiceDomain.ts";
48 import { readServiceRegion, syncServiceRegion } from "./ServiceRegion.ts";
49 import { attachVolumeToService } from "./Volume.ts";
50
51 const serviceFields = <E>(service: Query<RailwayService, E>) => ({
52 id: service.id,
53 name: service.name,
54 deletedAt: service.deletedAt,
55 });
56 type CloudService = UnwrapPlan<ReturnType<typeof serviceFields>>;
57
58 const attributeInstanceFields = <E>(instance: Query<RailwayServiceInstance, E>) => ({
59 source: instance.source.pipe(Query.map((s) => ({ image: s.image }))),
60 region: instance.region,
61 numReplicas: instance.numReplicas,
62 sleepApplication: instance.sleepApplication,
63 latestDeployment: instance.latestDeployment.pipe(
64 Query.map((d) => ({ id: d.id, status: d.status })),
65 ),
66 cronSchedule: instance.cronSchedule,
67 nextCronRunAt: instance.nextCronRunAt,
68 });
69 const instanceFields = <E>(instance: Query<RailwayServiceInstance, E>) => ({
70 ...attributeInstanceFields(instance),
71 deletedAt: instance.deletedAt,
72 startCommand: instance.startCommand,
73 });
74 type AttributeInstance = UnwrapPlan<ReturnType<typeof attributeInstanceFields>>;
75 type ServiceInstanceResponse = UnwrapPlan<ReturnType<typeof instanceFields>>;
76
77 export { FunctionBundleNotSingleFile } from "./hosted.ts";
78 export type { InferEnv } from "./InferEnv.ts";
79
80 /**
81 * A resource-valued prop: the resource itself, or an Effect that produces
82 * it (so `yield* Project(...)` and `Project(...)` both type-check).
83 */
84 type Ref<T> = T | Effect.Effect<T, never, Providers>;
85
86 /**
87 * Environment identity a Function is deployed into. Accepts a
88 * `Railway.Project` (its primary environment), a `Railway.Environment`,
89 * or an `{ environmentId }` stub.
90 */
91 export type FunctionEnvironment = { readonly environmentId: string };
92
93 /** Canvas Functions run on the Bun function runtime. */
94 export const FUNCTION_RUNTIME_NAME = "bun" as const;
95
96 /** Start-command prefix the Bun function runtime uses to decode source. */
97 export const FUNCTION_START_PREFIX = "./run.sh ";
98
99 /**
100 * Canvas Functions are capped at 96KB (the encoded start command, which
101 * includes `./run.sh ` plus standard base64 of the TypeScript file).
102 */
103 export const FUNCTION_MAX_BYTES = 96 * 1024;
104
105 /**
106 * Railway function-runtime images (`ghcr.io/railwayapp/function-*`).
107 * Canvas Functions are ordinary Services whose `source.image` uses this
108 * prefix — the same check the Railway CLI uses.
109 */
110 export const isFunctionImage = (image: string | null | undefined): boolean =>
111 image != null && image.startsWith("ghcr.io/railwayapp/function");
112
113 export interface FunctionProps<
114 Env extends Record<string, any> = Record<string, any>,
115 > extends PlatformProps {
116 /**
117 * Parent Railway Project. Accepts a `Railway.Project` or an Effect
118 * that produces one. Changing the Project replaces the Function.
119 */
120 project: Ref<Project>;
121 /**
122 * Environment to deploy the function instance into. Accepts a
123 * `Railway.Project` (primary environment), a `Railway.Environment`, or
124 * `{ environmentId }`. Defaults to the project's primary environment.
125 * Changing it replaces the Function.
126 */
127 environment?: Ref<FunctionEnvironment>;
128 /**
129 * Service name. Unique per Project. If omitted, a unique name is
130 * generated from the stack, stage and logical ID. Changing it updates
131 * in place via `serviceUpdate`.
132 */
133 name?: string;
134 /**
135 * Module entrypoint bundled with rolldown into a **single file** and
136 * deployed as a canvas Function. Typically `import.meta.url`. No
137 * Docker. No registry — that is {@link Service}. Mutually exclusive
138 * with {@link source} / {@link path}.
139 */
140 main?: string;
141 /**
142 * Named export to load from {@link main}.
143 *
144 * @default "default"
145 */
146 handler?: string;
147 /**
148 * Bundler configuration for {@link main}: rolldown `input`/`output`
149 * overrides, plus `install` for packages Railway should `bun install`
150 * from the function's imports (`pg`).
151 */
152 build?: RailwayBuildOptions;
153 /**
154 * Inline TypeScript source (one file). Mutually preferred over
155 * {@link path}. Max 96KB once base64-encoded into the start command.
156 */
157 source?: string;
158 /**
159 * Path to a single TypeScript file (`railway functions new --path`).
160 * Read at plan/reconcile time. Distinct from Effect-native
161 * {@link main}, which bundles first, and from `Service({ main })`,
162 * which pushes a Docker image.
163 */
164 path?: string;
165 /**
166 * Cron expression (`cronSchedule`). Observed as `cronSchedule` /
167 * `nextCronRunAt`. `railway functions new --cron`.
168 */
169 cronSchedule?: string;
170 /**
171 * Create a generated `*.up.railway.app` domain (`--http`). Defaults
172 * to `true` when {@link cronSchedule} is omitted, `false` otherwise.
173 */
174 http?: boolean;
175 /**
176 * Sleep the application when idle (`--serverless` /
177 * `sleepApplication`). Updates in place.
178 */
179 sleepApplication?: boolean;
180 /**
181 * Region the function runs in (`us-west2`, `europe-west4-drams3a`, …).
182 * Railway places replicas with `deploy.multiRegionConfig`. Omit this
183 * and the current placement is left alone (the workspace default on
184 * first create). Updating it moves the replicas in place and keeps
185 * the current replica count.
186 */
187 region?: string;
188 /**
189 * Port published on the generated service domain. Passed as
190 * `serviceDomainCreate.targetPort`. Omit to let Railway detect it.
191 */
192 port?: number;
193 /**
194 * Additional environment variables. Merged after binding-injected
195 * `env`. Upserted as service-scoped Railway variables with
196 * `skipDeploys: true`; this Function owns the subsequent deploy.
197 *
198 * On an async Function, {@link InferEnv} types the handler's second
199 * argument from these keys. Railway has no native bindings — every
200 * value is a `string` at runtime (`process.env`).
201 */
202 env?: Env;
203 /**
204 * Private-mesh RPC token. Minted by a child `Alchemy.Random`
205 * (`{logicalId}RpcToken`) and persisted in state. Set automatically.
206 */
207 rpcToken?: Redacted.Redacted<string>;
208 }
209
210 export type Function<Env extends Record<string, any> = Record<string, any>> = Resource<
211 "Railway.Function",
212 FunctionProps<Env>,
213 {
214 /** Railway service id. */
215 serviceId: string;
216 /** Physical service name (unique per project). */
217 name: string;
218 /** Parent Railway project id. */
219 projectId: string;
220 /** Environment the instance is deployed in. */
221 environmentId: string;
222 /** Observed function-runtime image. */
223 image: string;
224 /** Function runtime name (`bun`). */
225 runtime: typeof FUNCTION_RUNTIME_NAME;
226 /** Observed cron schedule, if set. */
227 cronSchedule: string | undefined;
228 /** Observed `sleepApplication`. */
229 sleepApplication: boolean | undefined;
230 /**
231 * Region the function is placed in. Set when
232 * `deploy.multiRegionConfig` has replicas in exactly one region.
233 */
234 region: string | undefined;
235 /** Port published on the generated service domain. */
236 port: number | undefined;
237 /**
238 * Internal DNS name on the default private mesh
239 * (`{name}.railway.internal`). Derived from the service name.
240 */
241 dnsName: string;
242 /**
243 * Shared token for private schemaless RPC. Value of the child
244 * `Alchemy.Random` resource. Packed onto callers by
245 * {@link bindFunction}; never send this to the public internet.
246 */
247 rpcToken: string;
248 /** Public `https://{domain}` URL (`*.up.railway.app`). */
249 url: string | undefined;
250 /** Generated Railway service domain hostname. */
251 domain: string | undefined;
252 /** Railway service domain id. */
253 domainId: string | undefined;
254 /** Latest deployment id, if one exists. */
255 deploymentId: string | undefined;
256 /** Latest deployment status (`SUCCESS`, `DEPLOYING`, …). */
257 deploymentStatus: string | undefined;
258 /** Next cron fire time, if scheduled. */
259 nextCronRunAt: string | undefined;
260 /** Content hash of the TypeScript source. */
261 code: { hash: string };
262 },
263 ServiceBinding,
264 Providers
265 >;
266
267 export const isFunction = (value: unknown): value is Function =>
268 typeof value === "object" &&
269 value !== null &&
270 (value as { Type?: string }).Type === "Railway.Function";
271
272 export type FunctionServices = ServerHost;
273
274 export type FunctionShape = Main<FunctionServices> & MainRpc<FunctionServices>;
275
276 export type FunctionRuntimeContext = RailwayHostRuntimeContext;
277
278 const resolveFunctionProps = (
279 id: string,
280 props: FunctionProps | Effect.Effect<FunctionProps, never, Providers>,
281 ) =>
282 Effect.gen(function* () {
283 const resolved = Effect.isEffect(props) ? yield* props : props;
284 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
285 const project = Effect.isEffect(resolved.project)
286 ? yield* resolved.project as Effect.Effect<Project, never, Providers>
287 : resolved.project;
288 const environment =
289 resolved.environment === undefined
290 ? undefined
291 : Effect.isEffect(resolved.environment)
292 ? yield* resolved.environment as Effect.Effect<FunctionEnvironment, never, Providers>
293 : resolved.environment;
294 const rpcToken = yield* mintRpcToken(id);
295 return { ...resolved, project, environment, rpcToken };
296 });
297
298 /**
299 * A Railway.Function is a **single TypeScript file** on Railway's Bun
300 * canvas runtime. No GitHub repo. No Docker. No registry. Alchemy
301 * queries `functionRuntime(bun)`, creates the Service with that image,
302 * and writes the source as `startCommand` (`./run.sh` + base64).
303 *
304 * There are two ways to define a Function. Prefer **async** (`main` +
305 * `export default { fetch }`, no Effect) — Effect-native canvas
306 * Functions pull the Effect runtime into the 96KB encoded start-command
307 * cap and fail {@link FunctionTooLarge} for anything non-trivial. Use
308 * {@link Service} when you need an Effect program or a real image.
309 *
310 * Distinct from Effect-native {@link Service} (`main`), which bundles
311 * with Rolldown and uploads a generated Dockerfile for Railway to
312 * build.
313 *
314 * @see https://docs.railway.com/reference/functions
315 *
316 * ### Async Functions
317 * You don't have to use Effect. Declare the Function with `main`
318 * pointing at a file and **no** `Effect.gen` implementation — Alchemy
319 * bundles that file as-is (no Effect runtime) and deploys it as a
320 * canvas Function. The handler is a plain `async fetch`. Use the `env`
321 * prop to declare variables, and {@link InferEnv} to type the second
322 * argument (Railway bindings are environment variables).
323 *
324 * **Example:** Defining an async Function in your stack
325 * ```typescript
326 * const db = yield* Railway.Postgres("Db", { project: site });
327 *
328 * export const Ping = Railway.Function("Ping", {
329 * project: site,
330 * main: "./src/ping.ts",
331 * env: { DATABASE_URL: db.connectionUri },
332 * });
333 *
334 * export type PingEnv = Railway.InferEnv<typeof Ping>;
335 * ```
336 *
337 * **Example:** Writing the async handler
338 * ```typescript
339 * import type { PingEnv } from "../alchemy.run.ts";
340 *
341 * export default {
342 * async fetch(_request: Request, env: PingEnv) {
343 * return new Response(env.DATABASE_URL ? "ok" : "missing");
344 * },
345 * };
346 * ```
347 *
348 * ### Effect-native Function
349 * A Function is a class. Props describe the canvas Function. The Effect
350 * is the program that runs in it. `main: import.meta.url` is the bundle
351 * entrypoint — Alchemy bundles this file into one JS file and deploys
352 * it. No `registry`. Stay tiny: the encoded start command maxes out at
353 * 96KB (`effect` plus handlers overflows it).
354 *
355 * **Example:** Class + Project + main
356 * ```typescript
357 * export default class Ping extends Railway.Function<Ping>()(
358 * "Ping",
359 * {
360 * project: Site,
361 * main: import.meta.url,
362 * },
363 * Effect.gen(function* () {
364 * return {
365 * fetch: Effect.succeed(HttpServerResponse.text("ok")),
366 * };
367 * }),
368 * ) {}
369 * ```
370 *
371 * :::caution[Changing `project` replaces the Function]
372 * The Function is created in the new Project. The old Function is deleted.
373 * :::
374 *
375 * ### Inline source
376 * Pass inline `source` (or `path` to a `.ts` file) instead of `main`
377 * when the Function is not an Effect class. Alchemy generates a
378 * `*.up.railway.app` domain unless `http: false` or a cron schedule is
379 * set.
380 *
381 * **Example:** Inline source
382 * ```typescript
383 * const site = yield* Railway.Project("Site");
384 * const ping = yield* Railway.Function("Ping", {
385 * project: site,
386 * source: `
387 * Bun.serve({
388 * hostname: "0.0.0.0",
389 * port: Number(process.env.PORT ?? 3000),
390 * fetch() { return new Response("ok"); },
391 * });
392 * `,
393 * });
394 * ```
395 *
396 * ### File path
397 * `path` is the CLI `--path` equivalent. The file is read at
398 * plan/reconcile. Content changes update in place.
399 *
400 * **Example:** Path
401 * ```typescript
402 * const ping = yield* Railway.Function("Ping", {
403 * project: site,
404 * path: "./fn.ts",
405 * });
406 * ```
407 *
408 * ### Cron
409 * `cronSchedule` runs the Function on a cron expression (`--cron`).
410 * HTTP domains are skipped unless `http: true` is set explicitly.
411 *
412 * **Example:** Cron schedule
413 * ```typescript
414 * const job = yield* Railway.Function("Cleanup", {
415 * project: site,
416 * source: `console.log("tick");`,
417 * cronSchedule: "0 * * * *",
418 * });
419 * ```
420 *
421 * ### Serverless
422 * `sleepApplication` sleeps the Function when idle (`--serverless`).
423 *
424 * **Example:** Sleep when idle
425 * ```typescript
426 * const ping = yield* Railway.Function("Ping", {
427 * project: site,
428 * source: `console.log("hi");`,
429 * http: false,
430 * sleepApplication: true,
431 * });
432 * ```
433 *
434 * ### Schemaless RPC
435 * Return methods next to `fetch`. Call `enableRailwayRpc()` in init
436 * (canvas Functions are capped at 96KB; the dispatcher is opt-in).
437 * Another Function or Service binds this class and calls them over
438 * `{name}.railway.internal` with a shared token. Public
439 * `*.up.railway.app` requests to `/__rpc__/*` get 401.
440 *
441 * **Example:** Bind a Function
442 * ```typescript
443 * export default class Query extends Railway.Function<Query>()(
444 * "Query",
445 * { project: Site, main: import.meta.url },
446 * Effect.gen(function* () {
447 * Railway.enableRailwayRpc();
448 * return {
449 * greet: (name: string) => Effect.succeed(`hello ${name}`),
450 * };
451 * }),
452 * ) {}
453 *
454 * export default class Api extends Railway.Service<Api>()(
455 * "Api",
456 * { project: Site, main: import.meta.url },
457 * Effect.gen(function* () {
458 * const query = yield* Railway.bindFunction(Query);
459 * return {
460 * fetch: query
461 * .greet("sam")
462 * .pipe(Effect.map((greeting) => HttpServerResponse.text(greeting))),
463 * };
464 * }),
465 * ) {}
466 * ```
467 *
468 * ### Module-scope declarations
469 * Resource-valued props accept the resource or an Effect producing it.
470 *
471 * **Example:** Module-scope Function
472 * ```typescript
473 * // src/ping.ts
474 * import * as Railway from "@alchemy.run/railway";
475 *
476 * export const Site = Railway.Project("Site");
477 * export const Ping = Railway.Function("Ping", {
478 * project: Site,
479 * source: `console.log("hello");`,
480 * http: false,
481 * });
482 * ```
483 *
484 * @resource
485 * @product Function
486 */
487 export const Function: Platform<
488 Function,
489 FunctionServices,
490 FunctionShape,
491 FunctionRuntimeContext
492 > & {
493 /**
494 * Async (no-impl) constructor — captures the `env` literal so
495 * {@link InferEnv} types the handler's second argument.
496 */
497 <const Env extends Record<string, any>, PropsReq = never>(
498 id: string,
499 props:
500 | InputProps<FunctionProps<Env>>
501 | Effect.Effect<InputProps<FunctionProps<Env>>, never, PropsReq>,
502 ): Effect.Effect<Function<Env>, never, Providers | PropsReq>;
503 } = Platform("Railway.Function", {
504 createRuntimeContext: createRailwayFunctionRuntimeContext("Railway.Function"),
505 transformProps: (id, props) => resolveFunctionProps(id, props),
506 });
507
508 export class FunctionNotCreated extends Data.TaggedError("Railway.FunctionNotCreated")<{
509 resourceName: string;
510 projectId: string;
511 }> {}
512
513 export class FunctionProjectRequired extends Data.TaggedError("Railway.FunctionProjectRequired")<{
514 message: string;
515 }> {}
516
517 export class FunctionSourceRequired extends Data.TaggedError("Railway.FunctionSourceRequired")<{
518 message: string;
519 }> {}
520
521 export class FunctionTooLarge extends Data.TaggedError("Railway.FunctionTooLarge")<{
522 bytes: number;
523 maxBytes: number;
524 }> {
525 get message() {
526 return `canvas Function is ${this.bytes} bytes (max ${this.maxBytes})`;
527 }
528 }
529
530 export class FunctionRuntimeImageMissing extends Data.TaggedError(
531 "Railway.FunctionRuntimeImageMissing",
532 )<{ message: string }> {}
533
534 export class FunctionDeployFailed extends Data.TaggedError("Railway.FunctionDeployFailed")<{
535 serviceId: string;
536 status: string;
537 deploymentId: string | undefined;
538 logs: string;
539 }> {
540 override get message() {
541 return this.logs.length > 0
542 ? `Function deploy ${this.status}: ${this.logs}`
543 : `Function deploy ${this.status}`;
544 }
545 }
546
547 class FunctionPending extends Data.TaggedError("Railway.FunctionPending")<{
548 serviceId: string;
549 status: string;
550 }> {}
551
552 class FunctionDeployPending extends Data.TaggedError("Railway.FunctionDeployPending")<{
553 serviceId: string;
554 status: string;
555 }> {}
556
557 const projectIdOf = (value: unknown): string | undefined => {
558 if (value === null || typeof value !== "object") return undefined;
559 const rec = value as { projectId?: unknown };
560 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
561 };
562
563 const environmentIdOf = (value: unknown): string | undefined => {
564 if (value === null || typeof value !== "object") return undefined;
565 const rec = value as { environmentId?: unknown };
566 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
567 ? rec.environmentId
568 : undefined;
569 };
570
571 const isGoneService = (service: CloudService | undefined) =>
572 service === undefined || service.deletedAt != null;
573
574 const isGoneInstance = (instance: ServiceInstanceResponse | undefined) =>
575 instance === undefined || instance.deletedAt != null;
576
577 const resolveName = (id: string, name: string | undefined, existing?: string) =>
578 Effect.gen(function* () {
579 if (name !== undefined) return name;
580 if (existing !== undefined) return existing;
581 return yield* createRailwayName(id);
582 });
583
584 const wantsHttp = (props: FunctionProps) =>
585 props.http === true || (props.http !== false && props.cronSchedule === undefined);
586
587 const hashSource = (source: string) =>
588 Effect.sync(() => createHash("sha256").update(source).digest("hex"));
589
590 const startCommandOf = (source: string) =>
591 Effect.gen(function* () {
592 const encoded = yield* Effect.sync(() => Buffer.from(source, "utf8").toString("base64"));
593 const cmd = `${FUNCTION_START_PREFIX}${encoded}`;
594 if (cmd.length > FUNCTION_MAX_BYTES) {
595 return yield* new FunctionTooLarge({ bytes: cmd.length, maxBytes: FUNCTION_MAX_BYTES });
596 }
597 return cmd;
598 });
599
600 const resolveSource = (props: FunctionProps) =>
601 Effect.gen(function* () {
602 if (props.source !== undefined && props.source.length > 0) {
603 return props.source;
604 }
605 if (props.path !== undefined && props.path.length > 0) {
606 const fs = yield* FileSystem.FileSystem;
607 return yield* fs.readFileString(props.path);
608 }
609 return yield* new FunctionSourceRequired({
610 message:
611 "Railway.Function requires `source` (inline TypeScript), `path` to a single file, or `main` (Effect-native).",
612 });
613 });
614
615 const readRuntimeImage = Query.fn(() => ({
616 image: Railway.functionRuntime({ name: FUNCTION_RUNTIME_NAME }).latestVersion.image,
617 }));
618
619 const latestRuntimeImage = () =>
620 readRuntimeImage().pipe(
621 Effect.flatMap(({ image }) => {
622 if (image.length === 0) {
623 return new FunctionRuntimeImageMissing({
624 message: "functionRuntime(bun) returned an empty latestVersion.image",
625 });
626 }
627 return Effect.succeed(image);
628 }),
629 );
630
631 const sameImage = (observed: string | null | undefined, desired: string) => {
632 if (observed == null || observed.length === 0) return false;
633 if (observed === desired) return true;
634 if (observed === `${desired}:latest` || desired === `${observed}:latest`) {
635 return true;
636 }
637 return observed.endsWith(`/${desired}`) || observed.endsWith(`/${desired}:latest`);
638 };
639
640 const deployReady = (status: string | undefined) => status === "SUCCESS" || status === "SLEEPING";
641
642 const deployFailed = (status: string | undefined) =>
643 status === "FAILED" || status === "CRASHED" || status === "REMOVED";
644
645 const readService = Query.fn((id: string) => serviceFields(Railway.service({ id })));
646
647 const getById = (serviceId: string) =>
648 readService(serviceId).pipe(
649 Effect.map((service) => (isGoneService(service) ? undefined : service)),
650 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
651 );
652
653 const readInstance = Query.fn((environmentId: string, serviceId: string) =>
654 instanceFields(Railway.serviceInstance({ environmentId, serviceId })),
655 );
656
657 const getInstance = (environmentId: string, serviceId: string) =>
658 readInstance(environmentId, serviceId).pipe(
659 Effect.map((instance) => (isGoneInstance(instance) ? undefined : instance)),
660 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
661 );
662
663 const listProjectServices = (projectId: string) =>
664 fetchProjectServices(projectId, serviceFields).pipe(
665 Effect.map((services) => services.filter((node) => !isGoneService(node))),
666 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudService[])),
667 );
668
669 const findByName = (projectId: string, name: string) =>
670 listProjectServices(projectId).pipe(
671 Effect.map((services) => services.find((service) => service.name === name)),
672 );
673
674 const waitForInstance = (environmentId: string, serviceId: string) =>
675 getInstance(environmentId, serviceId).pipe(
676 Effect.flatMap((instance) => {
677 if (instance === undefined) {
678 return Effect.fail(new FunctionPending({ serviceId, status: "creating" }));
679 }
680 return Effect.succeed(instance);
681 }),
682 Effect.retry({
683 while: (e) => e._tag === "Railway.FunctionPending",
684 times: 10,
685 schedule: Schedule.spaced("2 seconds"),
686 }),
687 Effect.catchTag("Railway.FunctionPending", () => getInstance(environmentId, serviceId)),
688 );
689
690 const readDeployLogs = Query.fn((deploymentId: string) =>
691 Railway.deploymentLogs({ deploymentId, limit: 80 }).pipe(
692 Query.map((row) => ({ severity: row.severity, message: row.message })),
693 ),
694 );
695
696 const fetchDeployLogs = (deploymentId: string | undefined) =>
697 deploymentId === undefined || deploymentId.length === 0
698 ? Effect.succeed("")
699 : readDeployLogs(deploymentId).pipe(
700 Effect.map((rows) =>
701 rows
702 .map((row) => (row.severity != null ? `[${row.severity}] ${row.message}` : row.message))
703 .join("\n"),
704 ),
705 Effect.orElseSucceed(() => ""),
706 );
707
708 const waitForDeployment = (environmentId: string, serviceId: string) =>
709 Effect.gen(function* () {
710 const instance = yield* getInstance(environmentId, serviceId);
711 const latest = instance?.latestDeployment;
712 const status = latest?.status;
713 if (status !== undefined && deployFailed(status)) {
714 const logs = yield* fetchDeployLogs(latest?.id);
715 return yield* new FunctionDeployFailed({ serviceId, status, deploymentId: latest?.id, logs });
716 }
717 if (instance !== undefined && deployReady(status)) {
718 return instance;
719 }
720 return yield* new FunctionDeployPending({ serviceId, status: status ?? "pending" });
721 }).pipe(
722 Effect.retry({
723 while: (e) => e._tag === "Railway.FunctionDeployPending",
724 // Queued builds under full-suite load can exceed 3 minutes — allow ~8.
725 times: 10,
726 schedule: Schedule.spaced("5 seconds"),
727 }),
728 );
729
730 const asVariableMap = (value: unknown): Record<string, string> => {
731 if (value === null || typeof value !== "object" || Array.isArray(value)) {
732 return {};
733 }
734 const out: Record<string, string> = {};
735 for (const [key, item] of Object.entries(value)) {
736 if (typeof item === "string") {
737 out[key] = item;
738 }
739 }
740 return out;
741 };
742
743 const readVariables = Query.fn((projectId: string, environmentId: string, serviceId: string) =>
744 Railway.variables({ projectId, environmentId, serviceId, unrendered: true }),
745 );
746
747 const variableUpsert = Query.fn((input: VariableUpsertInput) => Railway.variableUpsert({ input }));
748
749 const listVariableMap = (projectId: string, environmentId: string, serviceId: string) =>
750 readVariables(projectId, environmentId, serviceId).pipe(
751 Effect.map(asVariableMap),
752 Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as Record<string, string>)),
753 );
754
755 const upsertVariable = (input: {
756 projectId: string;
757 environmentId: string;
758 serviceId: string;
759 name: string;
760 value: string;
761 }) =>
762 variableUpsert({
763 projectId: input.projectId,
764 environmentId: input.environmentId,
765 serviceId: input.serviceId,
766 name: input.name,
767 value: input.value,
768 skipDeploys: true,
769 });
770
771 const serviceCreate = Query.fn((input: ServiceCreateInput) =>
772 serviceFields(Railway.serviceCreate({ input })),
773 );
774
775 const serviceUpdate = Query.fn((id: string, name: string) =>
776 serviceFields(Railway.serviceUpdate({ id, input: { name } })),
777 );
778
779 const serviceInstanceUpdate = Query.fn(
780 (environmentId: string, serviceId: string, input: ServiceInstanceUpdateInput) =>
781 Railway.serviceInstanceUpdate({ environmentId, serviceId, input }),
782 );
783
784 const serviceInstanceDeploy = Query.fn((environmentId: string, serviceId: string) =>
785 Railway.serviceInstanceDeployV2({ environmentId, serviceId }),
786 );
787
788 const serviceDelete = Query.fn((id: string) => Railway.serviceDelete({ id }));
789
790 const hostedProgramProps = (
791 props: FunctionProps,
792 port: number | undefined,
793 ): HostedProgramProps | undefined => {
794 if (props.main === undefined || props.main.length === 0) return undefined;
795 return {
796 main: props.main,
797 handler: props.handler,
798 port,
799 env: props.env,
800 isExternal: props.isExternal,
801 build: props.build,
802 };
803 };
804
805 const syncEnv = Effect.fn(function* (input: {
806 projectId: string;
807 environmentId: string;
808 serviceId: string;
809 desired: Record<string, string>;
810 }) {
811 if (Object.keys(input.desired).length === 0) return false;
812 const observed = yield* listVariableMap(input.projectId, input.environmentId, input.serviceId);
813 let changed = false;
814 for (const [name, value] of Object.entries(input.desired)) {
815 if (observed[name] !== value) {
816 yield* upsertVariable({
817 projectId: input.projectId,
818 environmentId: input.environmentId,
819 serviceId: input.serviceId,
820 name,
821 value,
822 });
823 changed = true;
824 }
825 }
826 return changed;
827 });
828
829 const syncMounts = Effect.fn(function* (input: {
830 environmentId: string;
831 projectId: string;
832 serviceId: string;
833 mounts: MountSpec[];
834 }) {
835 for (const mount of input.mounts) {
836 yield* attachVolumeToService({
837 environmentId: input.environmentId,
838 projectId: input.projectId,
839 serviceId: input.serviceId,
840 volumeId: mount.volumeId,
841 mountPath: mount.path,
842 });
843 }
844 });
845
846 const toAttrs = (input: {
847 service: CloudService;
848 instance: AttributeInstance | undefined;
849 domain: ServiceDomainRecord | undefined;
850 projectId: string;
851 environmentId: string;
852 image: string;
853 port: number | undefined;
854 codeHash: string;
855 rpcToken: string;
856 region: string | undefined;
857 }): Function["Attributes"] => ({
858 serviceId: input.service.id,
859 name: input.service.name,
860 projectId: input.projectId,
861 environmentId: input.environmentId,
862 image: input.instance?.source?.image ?? input.image,
863 runtime: FUNCTION_RUNTIME_NAME,
864 cronSchedule: input.instance?.cronSchedule ?? undefined,
865 sleepApplication: input.instance?.sleepApplication ?? undefined,
866 region: input.region,
867 port: input.port ?? input.domain?.targetPort,
868 dnsName: `${input.service.name}.railway.internal`,
869 rpcToken: input.rpcToken,
870 url: input.domain?.url,
871 domain: input.domain?.domain,
872 domainId: input.domain?.id,
873 deploymentId: input.instance?.latestDeployment?.id,
874 deploymentStatus: input.instance?.latestDeployment?.status,
875 nextCronRunAt: input.instance?.nextCronRunAt ?? undefined,
876 code: { hash: input.codeHash },
877 });
878
879 const instanceSettingsDelta = (input: {
880 instance: ServiceInstanceResponse | undefined;
881 sourceImage: string;
882 startCommand: string;
883 props: FunctionProps;
884 }): ServiceInstanceUpdateInput | undefined => {
885 const instance = input.instance;
886 const delta: Types.Mutable<ServiceInstanceUpdateInput> = {};
887 let changed = false;
888
889 if (!sameImage(instance?.source?.image, input.sourceImage)) {
890 delta.source = { image: input.sourceImage };
891 changed = true;
892 }
893 if ((instance?.startCommand ?? undefined) !== input.startCommand) {
894 delta.startCommand = input.startCommand;
895 changed = true;
896 }
897 if (
898 input.props.cronSchedule !== undefined &&
899 (instance?.cronSchedule ?? undefined) !== input.props.cronSchedule
900 ) {
901 delta.cronSchedule = input.props.cronSchedule;
902 changed = true;
903 }
904 if (
905 input.props.sleepApplication !== undefined &&
906 instance?.sleepApplication !== input.props.sleepApplication
907 ) {
908 delta.sleepApplication = input.props.sleepApplication;
909 changed = true;
910 }
911 return changed ? delta : undefined;
912 };
913
914 export const FunctionProvider = () =>
915 Provider.effect(
916 Function,
917 Effect.gen(function* () {
918 const stack = yield* Stack;
919 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
920 const hosted = createRailwayFunctionSupport({
921 stackName: stack.name,
922 stage: stack.stage,
923 virtualEntryPlugin,
924 });
925
926 return Function.Provider.of({
927 stables: ["serviceId", "projectId", "environmentId"],
928 nuke: { dependsOn: ["Railway.Project"] },
929
930 diff: Effect.fn(function* ({ news: desired, output }) {
931 // Runtime exports are covered by the bundle hash, not evaluated
932 // as infrastructure inputs during planning.
933 const news = stripEffects(desired);
934 if (news === undefined || !isResolved(news)) return undefined;
935 if (output === undefined) return undefined;
936 const nextProject = projectIdOf(news.project);
937 const projectChanged = nextProject !== undefined && nextProject !== output.projectId;
938 const nextEnv = environmentIdOf(news.environment);
939 const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId;
940 if (projectChanged || environmentChanged) {
941 return { action: "replace" as const };
942 }
943 const program = hostedProgramProps(news, news.port);
944 if (program !== undefined) {
945 const hash = yield* hosted.hash(program);
946 if (hash !== output.code.hash) {
947 return { action: "update" as const };
948 }
949 return undefined;
950 }
951 const hasSource =
952 (news.source !== undefined && news.source.length > 0) ||
953 (news.path !== undefined && news.path.length > 0);
954 if (hasSource) {
955 const source = yield* resolveSource(news);
956 const hash = yield* hashSource(source);
957 if (hash !== output.code.hash) {
958 return { action: "update" as const };
959 }
960 }
961 return undefined;
962 }),
963
964 read: Effect.fn(function* ({ id, olds, output }) {
965 const projectId =
966 output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined);
967 const environmentId =
968 output?.environmentId ??
969 (olds !== undefined
970 ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project))
971 : undefined);
972 const name = yield* resolveName(id, olds?.name, output?.name);
973 const byId =
974 output?.serviceId !== undefined && output.serviceId.length > 0
975 ? yield* getById(output.serviceId)
976 : undefined;
977 const found =
978 byId ?? (projectId !== undefined ? yield* findByName(projectId, name) : undefined);
979 if (found === undefined) return undefined;
980 const resolvedProjectId = projectIdOf(found) ?? projectId ?? "";
981 const resolvedEnvId =
982 environmentId ?? environmentIdOf(olds?.project) ?? output?.environmentId ?? "";
983 const instance =
984 resolvedEnvId.length > 0 ? yield* getInstance(resolvedEnvId, found.id) : undefined;
985 const region =
986 resolvedEnvId.length > 0
987 ? yield* readServiceRegion({
988 environmentId: resolvedEnvId,
989 projectId: resolvedProjectId,
990 serviceId: found.id,
991 legacy: instance?.region,
992 })
993 : undefined;
994 const attrs = toAttrs({
995 service: found,
996 instance,
997 domain: undefined,
998 projectId: resolvedProjectId,
999 environmentId: resolvedEnvId,
1000 image: instance?.source?.image ?? output?.image ?? "",
1001 port: output?.port ?? olds?.port,
1002 codeHash: output?.code.hash ?? "",
1003 rpcToken: output?.rpcToken ?? "",
1004 region,
1005 });
1006 if (output !== undefined) return attrs;
1007 return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs);
1008 }),
1009
1010 list: Effect.fn(function* () {
1011 const projects = yield* ownedProjects();
1012 const rows = yield* Effect.forEach(projects, (project) =>
1013 Effect.gen(function* () {
1014 const services = new Map(
1015 (yield* listProjectServices(project.projectId))
1016 .filter((service) => matchesAlchemyPhysicalName(service.name))
1017 .map((service) => [service.id, service]),
1018 );
1019 if (services.size === 0) return [];
1020 const envIds = yield* projectEnvironmentIds(project);
1021 const items = yield* Effect.forEach(envIds, (environmentId) =>
1022 environmentServiceInstances(environmentId, project.projectId, (instance) => ({
1023 ...attributeInstanceFields(instance),
1024 serviceId: instance.serviceId,
1025 deletedAt: instance.deletedAt,
1026 })).pipe(
1027 Effect.map((instances) =>
1028 instances.flatMap((instance) => {
1029 const service = services.get(instance.serviceId);
1030 const image = instance.source?.image;
1031 if (
1032 instance.deletedAt != null ||
1033 service === undefined ||
1034 !isFunctionImage(image)
1035 )
1036 return [];
1037 return [
1038 toAttrs({
1039 service,
1040 instance,
1041 domain: undefined,
1042 projectId: project.projectId,
1043 environmentId,
1044 image: image ?? "",
1045 port: undefined,
1046 codeHash: "",
1047 rpcToken: "",
1048 region: instance.region ?? undefined,
1049 }),
1050 ];
1051 }),
1052 ),
1053 ),
1054 );
1055 return items.flat();
1056 }),
1057 );
1058 return rows.flat();
1059 }),
1060
1061 // Circular Service↔Function RPC binds `dnsName` / `port` / `rpcToken`.
1062 // Those are knowable from the physical name and props; the cloud
1063 // service is created in reconcile (and re-synced in converge).
1064 precreate: Effect.fn(function* ({ id, news }) {
1065 const name = yield* resolveName(
1066 id,
1067 typeof news.name === "string" ? news.name : undefined,
1068 );
1069 const port = typeof news.port === "number" ? news.port : DEFAULT_PORT;
1070 return {
1071 serviceId: "",
1072 name,
1073 projectId: "",
1074 environmentId: "",
1075 image: "",
1076 runtime: FUNCTION_RUNTIME_NAME,
1077 cronSchedule: undefined,
1078 sleepApplication: undefined,
1079 region: undefined,
1080 port,
1081 dnsName: `${name}.railway.internal`,
1082 rpcToken: plainEnvValue(news.rpcToken) ?? "",
1083 url: undefined,
1084 domain: undefined,
1085 domainId: undefined,
1086 deploymentId: undefined,
1087 deploymentStatus: undefined,
1088 nextCronRunAt: undefined,
1089 code: { hash: "" },
1090 } satisfies Function["Attributes"];
1091 }),
1092
1093 reconcile: Effect.fn(function* ({ id, news, output, bindings }) {
1094 const props = news ?? ({} as FunctionProps);
1095 const projectId = projectIdOf(props.project) ?? output?.projectId;
1096 if (projectId === undefined) {
1097 return yield* new FunctionProjectRequired({
1098 message: "Function requires a resolved Railway.Project",
1099 });
1100 }
1101 const environmentId =
1102 environmentIdOf(props.environment) ??
1103 environmentIdOf(props.project) ??
1104 output?.environmentId;
1105 if (environmentId === undefined) {
1106 return yield* new FunctionProjectRequired({
1107 message:
1108 "Function requires a Railway environment (pass environment or a Project with environmentId)",
1109 });
1110 }
1111 const name = yield* resolveName(id, props.name, output?.name);
1112 const bound = collectBindingState(bindings ?? []);
1113 yield* assertHostDisk({ name, mounts: bound.mounts });
1114 const program = hostedProgramProps(
1115 props,
1116 props.port ?? (props.main !== undefined ? DEFAULT_PORT : undefined),
1117 );
1118 let source: string;
1119 let codeHash: string;
1120 if (program !== undefined) {
1121 const bundled = yield* hosted.bundleToSource(program);
1122 source = bundled.source;
1123 codeHash = bundled.hash;
1124 } else {
1125 source = yield* resolveSource(props);
1126 codeHash = yield* hashSource(source);
1127 }
1128 const startCommand = yield* startCommandOf(source);
1129 const image = yield* latestRuntimeImage();
1130 // Effect-native Functions listen on PORT (canvas default 3000).
1131 // Pin PORT and the generated domain's targetPort together so
1132 // private-mesh RPC and public HTTP hit the same listener.
1133 const port = program !== undefined ? (props.port ?? DEFAULT_PORT) : props.port;
1134 const rpcToken = plainEnvValue(props.rpcToken) ?? output?.rpcToken ?? "";
1135 const env = {
1136 ...bound.env,
1137 ...(program !== undefined ? hosted.alchemyEnv : {}),
1138 ...(port !== undefined ? { PORT: String(port) } : {}),
1139 ...toEnvRecord(props.env),
1140 [RPC_TOKEN_ENV]: rpcToken,
1141 };
1142
1143 let current: CloudService | undefined =
1144 output?.serviceId !== undefined && output.serviceId.length > 0
1145 ? yield* getById(output.serviceId)
1146 : undefined;
1147 if (current === undefined) {
1148 current = yield* findByName(projectId, name);
1149 }
1150
1151 if (current === undefined) {
1152 const created = yield* serviceCreate({
1153 projectId,
1154 environmentId,
1155 name,
1156 source: { image },
1157 }).pipe(Effect.catchTag("RailwayValidationError", () => Effect.undefined));
1158 current = created ?? (yield* findByName(projectId, name));
1159 }
1160
1161 if (current === undefined || isGoneService(current)) {
1162 return yield* new FunctionNotCreated({ resourceName: name, projectId });
1163 }
1164
1165 if (current.name !== name) {
1166 current = yield* serviceUpdate(current.id, name);
1167 }
1168
1169 // The service instance must exist in this environment before a
1170 // domain can be generated. Extra non-fork environments lag.
1171 let instance = yield* waitForInstance(environmentId, current.id);
1172
1173 // Domain before PORT — Railway refuses serviceDomainCreate on a
1174 // service that already has PORT set ("please try again").
1175 let domain = wantsHttp(props)
1176 ? yield* ensureServiceDomain({ projectId, environmentId, serviceId: current.id })
1177 : undefined;
1178 let needsDeploy = false;
1179
1180 const instanceDelta = instanceSettingsDelta({
1181 instance,
1182 sourceImage: image,
1183 startCommand,
1184 props,
1185 });
1186 if (instanceDelta !== undefined) {
1187 yield* serviceInstanceUpdate(environmentId, current.id, instanceDelta);
1188 needsDeploy = true;
1189 instance = (yield* getInstance(environmentId, current.id)) ?? instance;
1190 }
1191
1192 // Pin `deploy.multiRegionConfig` before the build, then again after,
1193 // in case the deploy wrote the workspace default back.
1194 const serviceId = current.id;
1195 const placeRegion = () =>
1196 syncServiceRegion({
1197 environmentId,
1198 projectId,
1199 serviceId,
1200 region: props.region,
1201 legacy: instance?.region,
1202 fallbackReplicas: instance?.numReplicas,
1203 });
1204 let region = yield* placeRegion();
1205
1206 const envChanged = yield* syncEnv({
1207 projectId,
1208 environmentId,
1209 serviceId: current.id,
1210 desired: env,
1211 });
1212 if (envChanged) needsDeploy = true;
1213
1214 if (wantsHttp(props) && port !== undefined) {
1215 domain = yield* ensureServiceDomain({
1216 projectId,
1217 environmentId,
1218 serviceId: current.id,
1219 targetPort: port,
1220 });
1221 }
1222
1223 yield* syncMounts({
1224 environmentId,
1225 projectId,
1226 serviceId: current.id,
1227 mounts: bound.mounts,
1228 });
1229
1230 if (needsDeploy || instance?.latestDeployment == null) {
1231 yield* serviceInstanceDeploy(environmentId, current.id).pipe(
1232 Effect.catchTag("RailwayValidationError", () => Effect.void),
1233 );
1234 }
1235
1236 // Cron-only Functions sleep until the schedule. Waiting for
1237 // SUCCESS queues behind sibling Docker builds and can sit in
1238 // QUEUED/BUILDING for the full retry budget. HTTP Functions
1239 // still wait — they have a public URL to serve.
1240 if (wantsHttp(props)) {
1241 instance = (yield* waitForDeployment(environmentId, current.id)) ?? instance;
1242 } else {
1243 instance = (yield* getInstance(environmentId, current.id)) ?? instance;
1244 const status = instance?.latestDeployment?.status;
1245 if (status !== undefined && deployFailed(status)) {
1246 const logs = yield* fetchDeployLogs(instance?.latestDeployment?.id);
1247 return yield* new FunctionDeployFailed({
1248 serviceId: current.id,
1249 status,
1250 deploymentId: instance?.latestDeployment?.id,
1251 logs,
1252 });
1253 }
1254 }
1255
1256 region = yield* placeRegion();
1257
1258 return toAttrs({
1259 service: current,
1260 instance,
1261 domain,
1262 projectId,
1263 environmentId,
1264 image,
1265 port,
1266 codeHash,
1267 rpcToken,
1268 region,
1269 });
1270 }),
1271
1272 delete: Effect.fn(function* ({ output }) {
1273 const serviceId = output.serviceId;
1274 if (serviceId.length === 0) return;
1275 yield* serviceDelete(serviceId).pipe(
1276 Effect.catchTag("RailwayNotFound", () => Effect.void),
1277 );
1278 yield* waitUntilDeleted(
1279 "Service",
1280 serviceId,
1281 getById(serviceId).pipe(Effect.map((service) => service === undefined)),
1282 );
1283 }),
1284 });
1285 }),
1286 );