The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Query, type UnwrapPlan } from "@distilled.cloud/core/query"; |
| 2 | import { |
| 3 | Railway, |
| 4 | type Sandbox as RailwaySandbox, |
| 5 | type SandboxCheckpoint as RailwaySandboxCheckpoint, |
| 6 | type SandboxNetworkIsolation, |
| 7 | type SandboxStatus, |
| 8 | type SandboxCreateInput, |
| 9 | type SandboxTemplateInput, |
| 10 | } from "@distilled.cloud/railway"; |
| 11 | import * as Binding from "alchemy/Binding"; |
| 12 | import { isResolved } from "alchemy/Diff"; |
| 13 | import * as Provider from "alchemy/Provider"; |
| 14 | import { Resource } from "alchemy/Resource"; |
| 15 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 16 | import * as Data from "effect/Data"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as Schedule from "effect/Schedule"; |
| 20 | import * as Stream from "effect/Stream"; |
| 21 | import { waitUntilDeleted } from "./GraphQL.ts"; |
| 22 | import { ownedProjects, projectEnvironmentIds } from "./Project.ts"; |
| 23 | import type { Providers } from "./Providers.ts"; |
| 24 | |
| 25 | const sandboxFields = <E>(sandbox: Query<RailwaySandbox, E>) => ({ |
| 26 | id: sandbox.id, |
| 27 | environmentId: sandbox.environmentId, |
| 28 | region: sandbox.region, |
| 29 | status: sandbox.status, |
| 30 | idleTimeoutMinutes: sandbox.idleTimeoutMinutes, |
| 31 | networkIsolation: sandbox.networkIsolation, |
| 32 | createdAt: sandbox.createdAt, |
| 33 | domains: sandbox.domains.pipe( |
| 34 | Query.map((domain) => ({ prefix: domain.prefix, port: domain.port, domain: domain.domain })), |
| 35 | ), |
| 36 | }); |
| 37 | type CloudSandbox = UnwrapPlan<ReturnType<typeof sandboxFields>>; |
| 38 | |
| 39 | const checkpointFields = <E>(checkpoint: Query<RailwaySandboxCheckpoint, E>) => ({ |
| 40 | createdAt: checkpoint.createdAt, |
| 41 | environmentId: checkpoint.environmentId, |
| 42 | id: checkpoint.id, |
| 43 | key: checkpoint.key, |
| 44 | }); |
| 45 | type SandboxCheckpointsResultItem = UnwrapPlan<ReturnType<typeof checkpointFields>>; |
| 46 | |
| 47 | /** |
| 48 | * A resource-valued prop: the resource itself, or an Effect that produces |
| 49 | * it (so `yield* Project(...)` and `Project(...)` both type-check). |
| 50 | */ |
| 51 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 52 | |
| 53 | /** |
| 54 | * Environment identity a Sandbox is created in. Accepts a |
| 55 | * `Railway.Project` (its primary environment), a `Railway.Environment`, |
| 56 | * or an `{ environmentId }` stub. |
| 57 | */ |
| 58 | export type SandboxEnvironment = { readonly environmentId: string; readonly projectId?: string }; |
| 59 | |
| 60 | /** |
| 61 | * Sandbox identity for {@link Exec} / helpers. Accepts a |
| 62 | * `Railway.Sandbox` or a `{ sandboxId, environmentId }` stub. |
| 63 | */ |
| 64 | export type SandboxIdentity = { readonly sandboxId: string; readonly environmentId: string }; |
| 65 | |
| 66 | /** |
| 67 | * Create-time template for a sandbox. Mutually exclusive `instructions` |
| 68 | * (build a recipe) and `name` (boot from a named checkpoint). |
| 69 | */ |
| 70 | export interface SandboxTemplate { |
| 71 | /** Region in which to build the template. Checkpoints retain their captured region. */ |
| 72 | region?: string; |
| 73 | /** |
| 74 | * Build a template by running these shell instructions on the base |
| 75 | * image. Mutually exclusive with `name`. |
| 76 | */ |
| 77 | instructions?: readonly string[]; |
| 78 | /** |
| 79 | * Boot from a saved checkpoint with this name. Mutually exclusive |
| 80 | * with `instructions`. |
| 81 | */ |
| 82 | name?: string; |
| 83 | /** |
| 84 | * Environment variables available to the template's build |
| 85 | * instructions. Values may contain Railway variable references. |
| 86 | */ |
| 87 | variables?: Record<string, string>; |
| 88 | } |
| 89 | |
| 90 | export interface SandboxDomain { |
| 91 | /** Port of the HTTP server listening on `0.0.0.0`, from 1 to 65535. */ |
| 92 | port: number; |
| 93 | /** Unique domain prefix. Railway generates one when omitted. */ |
| 94 | prefix?: string; |
| 95 | } |
| 96 | |
| 97 | export interface SandboxResources { |
| 98 | /** Maximum vCPU allocation. Fractional values are supported. */ |
| 99 | cpu?: number; |
| 100 | /** Maximum memory allocation in GB. Subject to the workspace plan limit. */ |
| 101 | memoryGB?: number; |
| 102 | } |
| 103 | |
| 104 | export interface SandboxProps { |
| 105 | /** |
| 106 | * Environment to create the sandbox in. Accepts a `Railway.Project` |
| 107 | * (primary environment), a `Railway.Environment`, or |
| 108 | * `{ environmentId }`. Changing it replaces the Sandbox. |
| 109 | */ |
| 110 | environment: Ref<SandboxEnvironment>; |
| 111 | /** |
| 112 | * Region to place the sandbox in (`us-west2`, `us-east4-eqdc4a`, …). |
| 113 | * Defaults to US West when omitted. Changing it replaces the Sandbox. |
| 114 | */ |
| 115 | region?: string; |
| 116 | /** |
| 117 | * Minutes of idle time before Railway auto-destroys the sandbox. |
| 118 | * Plan-dependent default and maximum. Changing it replaces the |
| 119 | * Sandbox — there is no update API. |
| 120 | */ |
| 121 | idleTimeoutMinutes?: number; |
| 122 | /** |
| 123 | * Network access. `ISOLATED` (default) has outbound internet only. |
| 124 | * `PRIVATE` also joins the environment's private network. Changing |
| 125 | * it replaces the Sandbox. |
| 126 | */ |
| 127 | networkIsolation?: SandboxNetworkIsolation; |
| 128 | /** |
| 129 | * Public HTTPS routes, up to ten unique ports. Requires `networkIsolation: |
| 130 | * "PRIVATE"`. Changing or removing routes replaces the sandbox. |
| 131 | */ |
| 132 | publicDomains?: SandboxDomain[]; |
| 133 | /** |
| 134 | * VM allocation, bounded by the workspace plan. Omit for the plan default. |
| 135 | * Changing or removing it replaces the sandbox. |
| 136 | */ |
| 137 | resources?: SandboxResources; |
| 138 | /** |
| 139 | * Running sandbox whose disk to fork. The source must be in this environment; |
| 140 | * the fork inherits its region, but not variables, routes or idle timeout. |
| 141 | * Mutually exclusive with `template`. Changing it replaces the sandbox. |
| 142 | */ |
| 143 | sourceSandboxId?: string; |
| 144 | /** |
| 145 | * Template to boot from: build instructions, or a named checkpoint. |
| 146 | * Changing it replaces the Sandbox. |
| 147 | */ |
| 148 | template?: SandboxTemplate; |
| 149 | /** |
| 150 | * Environment variables baked into the sandbox, available to every |
| 151 | * command. Values may contain Railway variable references, resolved |
| 152 | * at create time. Changing them replaces the Sandbox. |
| 153 | */ |
| 154 | variables?: Record<string, string>; |
| 155 | } |
| 156 | |
| 157 | export type Sandbox = Resource< |
| 158 | "Railway.Sandbox", |
| 159 | SandboxProps, |
| 160 | { |
| 161 | /** Railway sandbox id. */ |
| 162 | sandboxId: string; |
| 163 | /** Environment the sandbox lives in. */ |
| 164 | environmentId: string; |
| 165 | /** Parent Railway project id, if known. */ |
| 166 | projectId: string | undefined; |
| 167 | /** Region the sandbox was placed in. */ |
| 168 | region: string; |
| 169 | /** Observed status (`CREATING`, `RUNNING`, `FAILED`, …). */ |
| 170 | status: SandboxStatus; |
| 171 | /** Idle timeout in minutes, or `undefined` when Railway omitted it. */ |
| 172 | idleTimeoutMinutes: number | undefined; |
| 173 | /** Network isolation mode. */ |
| 174 | networkIsolation: SandboxNetworkIsolation; |
| 175 | /** RFC3339 creation timestamp. */ |
| 176 | createdAt: string; |
| 177 | /** Published HTTPS routes. Empty when no public domains were requested. */ |
| 178 | domains: { |
| 179 | /** Domain prefix assigned by Railway. */ |
| 180 | prefix: string; |
| 181 | /** HTTP server port. */ |
| 182 | port: number; |
| 183 | /** Hostname served over HTTPS. */ |
| 184 | domain: string; |
| 185 | }[]; |
| 186 | }, |
| 187 | never, |
| 188 | Providers |
| 189 | >; |
| 190 | |
| 191 | const resolveSandboxProps = ( |
| 192 | props: SandboxProps | Effect.Effect<SandboxProps, never, Providers>, |
| 193 | ): Effect.Effect<SandboxProps, never, Providers> => |
| 194 | Effect.gen(function* () { |
| 195 | const resolved = Effect.isEffect(props) ? yield* props : props; |
| 196 | if (globalThis.__ALCHEMY_RUNTIME__) return resolved; |
| 197 | const environment = Effect.isEffect(resolved.environment) |
| 198 | ? yield* resolved.environment as Effect.Effect<SandboxEnvironment, never, Providers> |
| 199 | : resolved.environment; |
| 200 | return { ...resolved, environment }; |
| 201 | }); |
| 202 | |
| 203 | const SandboxResource = Resource<Sandbox>("Railway.Sandbox"); |
| 204 | |
| 205 | /** |
| 206 | * A Railway.Sandbox is an ephemeral Linux VM in an environment. Create |
| 207 | * it, {@link execSandbox} commands, snapshot with checkpoints, and |
| 208 | * destroy it when the task is done. Sandboxes are available on every plan. |
| 209 | * |
| 210 | * Railway has no labels and sandboxes have no names. Identity is the |
| 211 | * Railway sandbox id. There is no in-place update — changing |
| 212 | * `environment`, `region`, `idleTimeoutMinutes`, `networkIsolation`, |
| 213 | * `template`, `variables`, `publicDomains`, `resources`, or `sourceSandboxId` |
| 214 | * replaces the Sandbox. Removing a previously configured option also replaces it. |
| 215 | * |
| 216 | * @see https://docs.railway.com/sandboxes |
| 217 | * @see https://docs.railway.com/guides/code-execution-sandboxes |
| 218 | * |
| 219 | * ### Create a Sandbox |
| 220 | * Pass a Project (or Environment). Alchemy waits until the sandbox is |
| 221 | * `RUNNING` and ready to exec. |
| 222 | * |
| 223 | * **Example:** From a Project |
| 224 | * ```typescript |
| 225 | * const site = yield* Railway.Project("Site"); |
| 226 | * const box = yield* Railway.Sandbox("Box", { |
| 227 | * environment: site, |
| 228 | * }); |
| 229 | * ``` |
| 230 | * |
| 231 | * :::caution[Changing `environment` or `region` replaces the Sandbox] |
| 232 | * A new VM is created. The old sandbox is destroyed. |
| 233 | * ::: |
| 234 | * |
| 235 | * ### Idle timeout |
| 236 | * Railway auto-destroys a sandbox after it sits idle. Active exec sessions |
| 237 | * and SSH foreground work defer teardown; background processes alone do not. |
| 238 | * Hobby/Pro default is 30 minutes (max 120), with `0` disabling idle teardown. |
| 239 | * Trial/Free default and max is 5 minutes. A sandbox with idle teardown disabled |
| 240 | * remains billable until explicitly destroyed. |
| 241 | * |
| 242 | * **Example:** Short idle timeout |
| 243 | * ```typescript |
| 244 | * const box = yield* Railway.Sandbox("Box", { |
| 245 | * environment: site, |
| 246 | * idleTimeoutMinutes: 5, |
| 247 | * }); |
| 248 | * ``` |
| 249 | * |
| 250 | * :::caution[Changing `idleTimeoutMinutes` replaces the Sandbox] |
| 251 | * There is no sandbox update API. |
| 252 | * ::: |
| 253 | * |
| 254 | * ### Variables |
| 255 | * Baked into the sandbox at create time. Available to every command. |
| 256 | * |
| 257 | * **Example:** Create-time env |
| 258 | * ```typescript |
| 259 | * const box = yield* Railway.Sandbox("Box", { |
| 260 | * environment: site, |
| 261 | * variables: { NODE_ENV: "production" }, |
| 262 | * }); |
| 263 | * ``` |
| 264 | * |
| 265 | * ### Template |
| 266 | * Boot from a named checkpoint, or from build instructions. |
| 267 | * |
| 268 | * **Example:** Checkpoint |
| 269 | * ```typescript |
| 270 | * const box = yield* Railway.Sandbox("Box", { |
| 271 | * environment: site, |
| 272 | * template: { name: "after-deps" }, |
| 273 | * }); |
| 274 | * ``` |
| 275 | * |
| 276 | * ### Publish HTTP ports |
| 277 | * **Example:** Private-network sandbox with an HTTPS route |
| 278 | * ```typescript |
| 279 | * const preview = yield* Railway.Sandbox("Preview", { |
| 280 | * environment: site, |
| 281 | * networkIsolation: "PRIVATE", |
| 282 | * publicDomains: [{ port: 3000 }], |
| 283 | * resources: { cpu: 1, memoryGB: 1 }, |
| 284 | * }); |
| 285 | * ``` |
| 286 | * Start the HTTP server on `0.0.0.0:3000`. Published hostnames are available |
| 287 | * in `preview.domains`; creating a route does not start the server. |
| 288 | * |
| 289 | * ### Fork a sandbox |
| 290 | * **Example:** Independent copy of a running sandbox's disk |
| 291 | * ```typescript |
| 292 | * const fork = yield* Railway.Sandbox("Attempt", { |
| 293 | * environment: site, |
| 294 | * sourceSandboxId: box.sandboxId, |
| 295 | * idleTimeoutMinutes: 5, |
| 296 | * }); |
| 297 | * ``` |
| 298 | * Files are copied, but running processes and memory are not. Keep the source |
| 299 | * declared while replacing a fork. For a reusable named disk snapshot, use |
| 300 | * `Railway.SandboxCheckpoint` and pass its `name` as `template.name`. |
| 301 | * |
| 302 | * ### Exec |
| 303 | * Run a command after deploy with {@link execSandbox} or {@link Exec}. |
| 304 | * |
| 305 | * **Example:** Echo |
| 306 | * ```typescript |
| 307 | * const result = yield* Railway.execSandbox({ |
| 308 | * sandboxId: box.sandboxId, |
| 309 | * environmentId: box.environmentId, |
| 310 | * command: "echo hello", |
| 311 | * }); |
| 312 | * ``` |
| 313 | * |
| 314 | * ### Module-scope declarations |
| 315 | * Resource-valued props accept the resource or an Effect producing it. |
| 316 | * |
| 317 | * **Example:** Module-scope Sandbox |
| 318 | * ```typescript |
| 319 | * // src/box.ts |
| 320 | * import * as Railway from "@alchemy.run/railway"; |
| 321 | * |
| 322 | * export const Site = Railway.Project("Site"); |
| 323 | * export const Box = Railway.Sandbox("Box", { |
| 324 | * environment: Site, |
| 325 | * idleTimeoutMinutes: 10, |
| 326 | * }); |
| 327 | * ``` |
| 328 | * |
| 329 | * @resource |
| 330 | * @product Sandbox |
| 331 | */ |
| 332 | export const Sandbox: typeof SandboxResource = Object.assign( |
| 333 | (id: string, props: SandboxProps | Effect.Effect<SandboxProps, never, Providers>) => |
| 334 | SandboxResource(id, resolveSandboxProps(props)), |
| 335 | SandboxResource, |
| 336 | ); |
| 337 | |
| 338 | export class SandboxNotCreated extends Data.TaggedError("Railway.SandboxNotCreated")<{ |
| 339 | environmentId: string; |
| 340 | }> {} |
| 341 | |
| 342 | export class SandboxEnvironmentRequired extends Data.TaggedError( |
| 343 | "Railway.SandboxEnvironmentRequired", |
| 344 | )<{ message: string }> {} |
| 345 | |
| 346 | export class SandboxFailed extends Data.TaggedError("Railway.SandboxFailed")<{ |
| 347 | sandboxId: string; |
| 348 | status: string; |
| 349 | }> {} |
| 350 | |
| 351 | export class SandboxCheckpointNotFound extends Data.TaggedError( |
| 352 | "Railway.SandboxCheckpointNotFound", |
| 353 | )<{ environmentId: string; checkpointName: string }> {} |
| 354 | |
| 355 | class SandboxPending extends Data.TaggedError("Railway.SandboxPending")<{ |
| 356 | sandboxId: string; |
| 357 | status: string; |
| 358 | }> {} |
| 359 | |
| 360 | const environmentIdOf = (value: unknown): string | undefined => { |
| 361 | if (value === null || typeof value !== "object") return undefined; |
| 362 | const rec = value as { environmentId?: unknown }; |
| 363 | return typeof rec.environmentId === "string" && rec.environmentId.length > 0 |
| 364 | ? rec.environmentId |
| 365 | : undefined; |
| 366 | }; |
| 367 | |
| 368 | const projectIdOf = (value: unknown): string | undefined => { |
| 369 | if (value === null || typeof value !== "object") return undefined; |
| 370 | const rec = value as { projectId?: unknown }; |
| 371 | return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined; |
| 372 | }; |
| 373 | |
| 374 | const isGone = (sandbox: CloudSandbox | undefined) => |
| 375 | sandbox === undefined || sandbox.status === "DESTROYED"; |
| 376 | |
| 377 | const toAttrs = ( |
| 378 | sandbox: CloudSandbox, |
| 379 | fallback?: { projectId?: string }, |
| 380 | ): Sandbox["Attributes"] => ({ |
| 381 | sandboxId: sandbox.id, |
| 382 | environmentId: sandbox.environmentId, |
| 383 | projectId: fallback?.projectId, |
| 384 | region: sandbox.region, |
| 385 | status: sandbox.status, |
| 386 | idleTimeoutMinutes: sandbox.idleTimeoutMinutes ?? undefined, |
| 387 | networkIsolation: sandbox.networkIsolation, |
| 388 | createdAt: sandbox.createdAt, |
| 389 | domains: [...sandbox.domains], |
| 390 | }); |
| 391 | |
| 392 | const toTemplateInput = (template: SandboxTemplate): SandboxTemplateInput => ({ |
| 393 | ...(template.region !== undefined ? { region: template.region } : {}), |
| 394 | ...(template.instructions !== undefined ? { instructions: [...template.instructions] } : {}), |
| 395 | ...(template.name !== undefined ? { name: template.name } : {}), |
| 396 | ...(template.variables !== undefined ? { variables: template.variables } : {}), |
| 397 | }); |
| 398 | |
| 399 | const varsKey = (vars: Record<string, string> | undefined) => { |
| 400 | if (vars === undefined) return undefined; |
| 401 | const entries = Object.entries(vars).sort(([a], [b]) => a.localeCompare(b)); |
| 402 | return JSON.stringify(Object.fromEntries(entries)); |
| 403 | }; |
| 404 | |
| 405 | const templateKey = (template: SandboxTemplate | undefined) => { |
| 406 | if (template === undefined) return undefined; |
| 407 | return JSON.stringify({ |
| 408 | region: template.region ?? null, |
| 409 | instructions: template.instructions ?? null, |
| 410 | name: template.name ?? null, |
| 411 | variables: varsKey(template.variables) ?? null, |
| 412 | }); |
| 413 | }; |
| 414 | |
| 415 | const domainsKey = (domains: SandboxDomain[] | undefined) => |
| 416 | JSON.stringify( |
| 417 | (domains ?? []) |
| 418 | .map(({ port, prefix }) => ({ port, prefix: prefix ?? null })) |
| 419 | .sort((a, b) => a.port - b.port), |
| 420 | ); |
| 421 | |
| 422 | const readSandbox = Query.fn((environmentId: string, id: string) => |
| 423 | Railway.sandbox({ environmentId, id }).pipe(Query.map(sandboxFields)), |
| 424 | ); |
| 425 | |
| 426 | /** Railway answers a missing sandbox with `null`, not an error. */ |
| 427 | const getById = (environmentId: string, sandboxId: string) => |
| 428 | readSandbox(environmentId, sandboxId).pipe( |
| 429 | Effect.map((sandbox) => (sandbox == null || isGone(sandbox) ? undefined : sandbox)), |
| 430 | ); |
| 431 | |
| 432 | const listSandboxes = (environmentId: string) => |
| 433 | Query.items(Railway.sandboxes({ environmentId, first: 50 }).pipe(Query.map(sandboxFields))).pipe( |
| 434 | Stream.filter((sandbox) => !isGone(sandbox)), |
| 435 | Stream.runCollect, |
| 436 | Effect.map((chunk) => Array.from(chunk)), |
| 437 | Effect.catchTag(["RailwayForbidden", "RailwayPlanLimitExceeded"], () => |
| 438 | Effect.succeed([] as CloudSandbox[]), |
| 439 | ), |
| 440 | ); |
| 441 | |
| 442 | const waitUntilRunning = (environmentId: string, sandboxId: string) => |
| 443 | Effect.gen(function* () { |
| 444 | const sandbox = yield* getById(environmentId, sandboxId); |
| 445 | if (sandbox === undefined) { |
| 446 | return yield* new SandboxPending({ sandboxId, status: "missing" }); |
| 447 | } |
| 448 | if (sandbox.status === "FAILED") { |
| 449 | return yield* new SandboxFailed({ sandboxId, status: sandbox.status }); |
| 450 | } |
| 451 | if (sandbox.status !== "RUNNING") { |
| 452 | return yield* new SandboxPending({ sandboxId, status: sandbox.status }); |
| 453 | } |
| 454 | return sandbox; |
| 455 | }).pipe( |
| 456 | Effect.retry({ |
| 457 | while: (e) => e._tag === "Railway.SandboxPending", |
| 458 | times: 10, |
| 459 | schedule: Schedule.spaced("3 seconds"), |
| 460 | }), |
| 461 | ); |
| 462 | |
| 463 | const waitUntilGone = (environmentId: string, sandboxId: string) => |
| 464 | waitUntilDeleted( |
| 465 | "Sandbox", |
| 466 | sandboxId, |
| 467 | getById(environmentId, sandboxId).pipe(Effect.map((sandbox) => sandbox === undefined)), |
| 468 | 10, |
| 469 | ); |
| 470 | |
| 471 | const sandboxExec = Query.fn( |
| 472 | (input: { command: string; environmentId: string; id: string; timeoutSec?: number }) => { |
| 473 | const result = Railway.sandboxExec(input); |
| 474 | return { |
| 475 | exitCode: result.exitCode, |
| 476 | stderr: result.stderr, |
| 477 | stdout: result.stdout, |
| 478 | timedOut: result.timedOut, |
| 479 | truncated: result.truncated, |
| 480 | }; |
| 481 | }, |
| 482 | ); |
| 483 | |
| 484 | const sandboxHeartbeat = Query.fn((environmentId: string, id: string) => |
| 485 | Railway.sandboxHeartbeat({ environmentId, id }).pipe(Query.map(sandboxFields)), |
| 486 | ); |
| 487 | |
| 488 | const sandboxCheckpointCreate = Query.fn( |
| 489 | (input: { environmentId: string; name: string; sandboxId: string }) => |
| 490 | checkpointFields(Railway.sandboxCheckpointCreate(input)), |
| 491 | ); |
| 492 | |
| 493 | const sandboxCheckpoints = Query.fn((environmentId: string) => |
| 494 | Railway.sandboxCheckpoints({ environmentId }).pipe(Query.map(checkpointFields)), |
| 495 | ); |
| 496 | |
| 497 | const sandboxCheckpointRename = Query.fn( |
| 498 | (input: { environmentId: string; id: string; name: string }) => |
| 499 | checkpointFields(Railway.sandboxCheckpointRename(input)), |
| 500 | ); |
| 501 | |
| 502 | const sandboxCheckpointDelete = Query.fn((input: { environmentId: string; id: string }) => |
| 503 | Railway.sandboxCheckpointDelete(input), |
| 504 | ); |
| 505 | |
| 506 | const sandboxCreate = Query.fn((input: SandboxCreateInput) => |
| 507 | sandboxFields(Railway.sandboxCreate({ input })), |
| 508 | ); |
| 509 | |
| 510 | const sandboxDestroy = Query.fn((environmentId: string, id: string) => |
| 511 | Railway.sandboxDestroy({ environmentId, id }).pipe(Query.map(sandboxFields)), |
| 512 | ); |
| 513 | |
| 514 | /** |
| 515 | * Execute a command inside a running sandbox. Does not fail on a |
| 516 | * non-zero exit code — inspect `exitCode`. |
| 517 | */ |
| 518 | export const execSandbox = Effect.fn(function* (input: { |
| 519 | sandboxId: string; |
| 520 | environmentId: string; |
| 521 | command: string; |
| 522 | timeoutSec?: number; |
| 523 | }) { |
| 524 | return yield* sandboxExec({ |
| 525 | command: input.command, |
| 526 | environmentId: input.environmentId, |
| 527 | id: input.sandboxId, |
| 528 | ...(input.timeoutSec !== undefined ? { timeoutSec: input.timeoutSec } : {}), |
| 529 | }); |
| 530 | }); |
| 531 | |
| 532 | /** |
| 533 | * Extend a sandbox's idle timeout from the last interaction. |
| 534 | */ |
| 535 | export const heartbeatSandbox = Effect.fn(function* (input: { |
| 536 | sandboxId: string; |
| 537 | environmentId: string; |
| 538 | }) { |
| 539 | return yield* sandboxHeartbeat(input.environmentId, input.sandboxId); |
| 540 | }); |
| 541 | |
| 542 | /** |
| 543 | * Capture a running sandbox's disk as a named checkpoint. Synchronous: |
| 544 | * the checkpoint is ready when this returns. Reusing a name replaces |
| 545 | * the previous checkpoint. |
| 546 | */ |
| 547 | export const createSandboxCheckpoint = Effect.fn(function* (input: { |
| 548 | sandboxId: string; |
| 549 | environmentId: string; |
| 550 | name: string; |
| 551 | }) { |
| 552 | return yield* sandboxCheckpointCreate({ |
| 553 | environmentId: input.environmentId, |
| 554 | name: input.name, |
| 555 | sandboxId: input.sandboxId, |
| 556 | }); |
| 557 | }); |
| 558 | |
| 559 | /** |
| 560 | * List named sandbox checkpoints in an environment (newest first). |
| 561 | */ |
| 562 | export const listSandboxCheckpoints = Effect.fn(function* (input: { environmentId: string }) { |
| 563 | return yield* sandboxCheckpoints(input.environmentId); |
| 564 | }); |
| 565 | |
| 566 | const findCheckpoint = (items: readonly SandboxCheckpointsResultItem[], name: string) => |
| 567 | items.find((item) => item.key === name); |
| 568 | |
| 569 | /** |
| 570 | * Rename a sandbox checkpoint by its current name (`key`). |
| 571 | */ |
| 572 | export const renameSandboxCheckpoint = Effect.fn(function* (input: { |
| 573 | environmentId: string; |
| 574 | name: string; |
| 575 | newName: string; |
| 576 | }) { |
| 577 | const items = yield* sandboxCheckpoints(input.environmentId); |
| 578 | const found = findCheckpoint(items, input.name); |
| 579 | if (found === undefined) { |
| 580 | return yield* new SandboxCheckpointNotFound({ |
| 581 | environmentId: input.environmentId, |
| 582 | checkpointName: input.name, |
| 583 | }); |
| 584 | } |
| 585 | return yield* sandboxCheckpointRename({ |
| 586 | environmentId: input.environmentId, |
| 587 | id: found.id, |
| 588 | name: input.newName, |
| 589 | }); |
| 590 | }); |
| 591 | |
| 592 | /** |
| 593 | * Delete a sandbox checkpoint by name (`key`). Idempotent if missing: |
| 594 | * Railway answers a missing checkpoint with `false`, not an error. |
| 595 | */ |
| 596 | export const deleteSandboxCheckpoint = Effect.fn(function* (input: { |
| 597 | environmentId: string; |
| 598 | name: string; |
| 599 | }) { |
| 600 | const items = yield* sandboxCheckpoints(input.environmentId); |
| 601 | const found = findCheckpoint(items, input.name); |
| 602 | if (found === undefined) return; |
| 603 | yield* sandboxCheckpointDelete({ environmentId: input.environmentId, id: found.id }); |
| 604 | }); |
| 605 | |
| 606 | export type ExecRequest = { command: string; timeoutSec?: number }; |
| 607 | |
| 608 | export type ExecResult = Effect.Success<ReturnType<typeof execSandbox>>; |
| 609 | |
| 610 | /** |
| 611 | * Run a command inside a {@link Sandbox}. Control-plane GraphQL — |
| 612 | * provide {@link ExecHttp}. The inner Effect requires |
| 613 | * {@link RuntimeContext} so it is typed as runtime-only; from tests |
| 614 | * prefer {@link execSandbox}. |
| 615 | * |
| 616 | * |
| 617 | * ### Exec |
| 618 | * **Example:** Echo |
| 619 | * ```typescript |
| 620 | * const run = yield* Railway.Exec(box); |
| 621 | * const result = yield* run({ command: "echo hello" }); |
| 622 | * ``` |
| 623 | * |
| 624 | * @binding |
| 625 | * @product Sandbox |
| 626 | */ |
| 627 | export interface Exec extends Binding.Service< |
| 628 | Exec, |
| 629 | "Railway.Sandbox.Exec", |
| 630 | (sandbox: SandboxIdentity) => Effect.Effect<ExecClient> |
| 631 | > {} |
| 632 | |
| 633 | export const Exec = Binding.Service<Exec>("Railway.Sandbox.Exec"); |
| 634 | |
| 635 | export interface ExecClient { |
| 636 | ( |
| 637 | request: ExecRequest, |
| 638 | ): Effect.Effect<ExecResult, Effect.Error<ReturnType<typeof execSandbox>>, RuntimeContext>; |
| 639 | } |
| 640 | |
| 641 | /** |
| 642 | * HTTP / GraphQL implementation of {@link Exec}. |
| 643 | * |
| 644 | * @layer |
| 645 | * @product Sandbox |
| 646 | * @provides Railway.Sandbox.Exec |
| 647 | */ |
| 648 | export const ExecHttp = Layer.effect( |
| 649 | Exec, |
| 650 | Effect.succeed( |
| 651 | Effect.fn(function* (sandbox: SandboxIdentity) { |
| 652 | const sandboxId = sandbox.sandboxId; |
| 653 | const environmentId = sandbox.environmentId; |
| 654 | return ((request: ExecRequest) => |
| 655 | execSandbox({ |
| 656 | sandboxId, |
| 657 | environmentId, |
| 658 | command: request.command, |
| 659 | ...(request.timeoutSec !== undefined ? { timeoutSec: request.timeoutSec } : {}), |
| 660 | })) as unknown as ExecClient; |
| 661 | }), |
| 662 | ), |
| 663 | ); |
| 664 | |
| 665 | export const SandboxProvider = () => |
| 666 | Provider.succeed(Sandbox, { |
| 667 | stables: ["sandboxId", "environmentId", "createdAt", "region"], |
| 668 | nuke: { dependsOn: ["Railway.Project"] }, |
| 669 | |
| 670 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 671 | if (news === undefined || !isResolved(news)) return undefined; |
| 672 | if (output === undefined) return undefined; |
| 673 | const nextEnv = environmentIdOf(news.environment); |
| 674 | const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId; |
| 675 | const regionChanged = |
| 676 | olds !== undefined |
| 677 | ? news.region !== olds.region |
| 678 | : news.region !== undefined && news.region !== output.region; |
| 679 | const idleChanged = |
| 680 | olds !== undefined |
| 681 | ? news.idleTimeoutMinutes !== olds.idleTimeoutMinutes |
| 682 | : news.idleTimeoutMinutes !== undefined && |
| 683 | news.idleTimeoutMinutes !== output.idleTimeoutMinutes; |
| 684 | const isolationChanged = |
| 685 | olds !== undefined |
| 686 | ? news.networkIsolation !== olds.networkIsolation |
| 687 | : news.networkIsolation !== undefined && |
| 688 | news.networkIsolation !== output.networkIsolation; |
| 689 | const templateChanged = templateKey(news.template) !== templateKey(olds?.template); |
| 690 | const variablesChanged = varsKey(news.variables) !== varsKey(olds?.variables); |
| 691 | const domainsChanged = domainsKey(news.publicDomains) !== domainsKey(olds?.publicDomains); |
| 692 | const resourcesChanged = |
| 693 | news.resources?.cpu !== olds?.resources?.cpu || |
| 694 | news.resources?.memoryGB !== olds?.resources?.memoryGB; |
| 695 | const sourceChanged = news.sourceSandboxId !== olds?.sourceSandboxId; |
| 696 | if ( |
| 697 | environmentChanged || |
| 698 | regionChanged || |
| 699 | idleChanged || |
| 700 | isolationChanged || |
| 701 | templateChanged || |
| 702 | variablesChanged || |
| 703 | domainsChanged || |
| 704 | resourcesChanged || |
| 705 | sourceChanged |
| 706 | ) { |
| 707 | return { action: "replace" as const }; |
| 708 | } |
| 709 | return undefined; |
| 710 | }), |
| 711 | |
| 712 | read: Effect.fn(function* ({ olds, output }) { |
| 713 | const environmentId = |
| 714 | output?.environmentId ?? |
| 715 | (olds !== undefined ? environmentIdOf(olds.environment) : undefined); |
| 716 | const sandboxId = output?.sandboxId; |
| 717 | if (environmentId === undefined || sandboxId === undefined) { |
| 718 | return undefined; |
| 719 | } |
| 720 | const found = yield* getById(environmentId, sandboxId); |
| 721 | if (found === undefined) return undefined; |
| 722 | return toAttrs(found, { |
| 723 | projectId: |
| 724 | output?.projectId ?? (olds !== undefined ? projectIdOf(olds.environment) : undefined), |
| 725 | }); |
| 726 | }), |
| 727 | |
| 728 | list: Effect.fn(function* () { |
| 729 | const projects = yield* ownedProjects(); |
| 730 | const rows = yield* Effect.forEach(projects, (project) => |
| 731 | Effect.gen(function* () { |
| 732 | const envIds = yield* projectEnvironmentIds(project); |
| 733 | const nested = yield* Effect.forEach(envIds, (environmentId) => |
| 734 | listSandboxes(environmentId).pipe( |
| 735 | Effect.map((items) => |
| 736 | items.map((item) => toAttrs(item, { projectId: project.projectId })), |
| 737 | ), |
| 738 | ), |
| 739 | ); |
| 740 | return nested.flat(); |
| 741 | }), |
| 742 | ); |
| 743 | const seen = new Set<string>(); |
| 744 | const unique: Sandbox["Attributes"][] = []; |
| 745 | for (const row of rows.flat()) { |
| 746 | if (seen.has(row.sandboxId)) continue; |
| 747 | seen.add(row.sandboxId); |
| 748 | unique.push(row); |
| 749 | } |
| 750 | return unique; |
| 751 | }), |
| 752 | |
| 753 | reconcile: Effect.fn(function* ({ news, output }) { |
| 754 | const props = news ?? ({} as SandboxProps); |
| 755 | const environmentId = environmentIdOf(props.environment) ?? output?.environmentId; |
| 756 | if (environmentId === undefined) { |
| 757 | return yield* new SandboxEnvironmentRequired({ |
| 758 | message: |
| 759 | "Sandbox requires a Railway environment (pass a Project, Environment, or { environmentId })", |
| 760 | }); |
| 761 | } |
| 762 | const projectId = projectIdOf(props.environment) ?? output?.projectId; |
| 763 | |
| 764 | let current: CloudSandbox | undefined = |
| 765 | output?.sandboxId !== undefined && output.sandboxId.length > 0 |
| 766 | ? yield* getById(environmentId, output.sandboxId) |
| 767 | : undefined; |
| 768 | |
| 769 | if (current === undefined) { |
| 770 | const created = yield* sandboxCreate({ |
| 771 | environmentId, |
| 772 | ...(props.idleTimeoutMinutes !== undefined |
| 773 | ? { idleTimeoutMinutes: props.idleTimeoutMinutes } |
| 774 | : {}), |
| 775 | ...(props.networkIsolation !== undefined |
| 776 | ? { networkIsolation: props.networkIsolation } |
| 777 | : {}), |
| 778 | ...(props.region !== undefined ? { region: props.region } : {}), |
| 779 | ...(props.publicDomains !== undefined ? { publicDomains: props.publicDomains } : {}), |
| 780 | ...(props.resources !== undefined ? { resources: props.resources } : {}), |
| 781 | ...(props.sourceSandboxId !== undefined |
| 782 | ? { sourceSandboxId: props.sourceSandboxId } |
| 783 | : {}), |
| 784 | ...(props.template !== undefined ? { template: toTemplateInput(props.template) } : {}), |
| 785 | ...(props.variables !== undefined ? { variables: props.variables } : {}), |
| 786 | }); |
| 787 | current = isGone(created) |
| 788 | ? undefined |
| 789 | : created.status === "RUNNING" |
| 790 | ? created |
| 791 | : yield* waitUntilRunning(environmentId, created.id); |
| 792 | } else if (current.status !== "RUNNING" && current.status !== "FAILED") { |
| 793 | current = yield* waitUntilRunning(environmentId, current.id); |
| 794 | } |
| 795 | |
| 796 | if (current === undefined || isGone(current)) { |
| 797 | return yield* new SandboxNotCreated({ environmentId }); |
| 798 | } |
| 799 | if (current.status === "FAILED") { |
| 800 | return yield* new SandboxFailed({ sandboxId: current.id, status: current.status }); |
| 801 | } |
| 802 | |
| 803 | return toAttrs(current, { projectId }); |
| 804 | }), |
| 805 | |
| 806 | delete: Effect.fn(function* ({ output }) { |
| 807 | const sandboxId = output.sandboxId; |
| 808 | const environmentId = output.environmentId; |
| 809 | if (sandboxId.length === 0 || environmentId.length === 0) return; |
| 810 | // A missing sandbox is answered with `null`, not an error. |
| 811 | yield* sandboxDestroy(environmentId, sandboxId); |
| 812 | yield* waitUntilGone(environmentId, sandboxId); |
| 813 | }), |
| 814 | }); |