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 Builder, |
| 5 | type DeploymentTriggerCreateInput, |
| 6 | type DeploymentTriggerUpdateInput, |
| 7 | type RestartPolicyType, |
| 8 | type Service as RailwayService, |
| 9 | type ServiceCreateInput, |
| 10 | type ServiceInstance as RailwayServiceInstance, |
| 11 | type ServiceInstanceAutoDeployUpdateInput, |
| 12 | type ServiceInstanceUpdateInput, |
| 13 | type VariableUpsertInput, |
| 14 | } from "@distilled.cloud/railway"; |
| 15 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 16 | import { AlchemyContext } from "alchemy/AlchemyContext"; |
| 17 | import * as Bundle from "alchemy/Bundle/Bundle"; |
| 18 | import { deepEqual, isResolved, stripEffects } from "alchemy/Diff"; |
| 19 | import * as Provider from "alchemy/Provider"; |
| 20 | import { Stack } from "alchemy/Stack"; |
| 21 | import { tarGzipDirectory } from "alchemy/Util/tarGzip"; |
| 22 | import * as Data from "effect/Data"; |
| 23 | import * as Effect from "effect/Effect"; |
| 24 | import * as Schedule from "effect/Schedule"; |
| 25 | import * as Stream from "effect/Stream"; |
| 26 | import type * as Types from "effect/Types"; |
| 27 | import { waitUntilDeleted, projectServices } from "./GraphQL.ts"; |
| 28 | import { |
| 29 | collectBindingState, |
| 30 | createRailwayHostedSupport, |
| 31 | DEFAULT_PORT, |
| 32 | plainEnvValue, |
| 33 | toEnvRecord, |
| 34 | } from "./hosted.ts"; |
| 35 | import { |
| 36 | hashRailwayLocalContext, |
| 37 | prepareRailwayLocalContext, |
| 38 | resolveRailwayServiceSource, |
| 39 | ServiceSourceInvalid, |
| 40 | type RailwayLocalContextSource, |
| 41 | } from "./local-context.ts"; |
| 42 | import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts"; |
| 43 | import { assertHostDisk, type MountSpec } from "./MountVolume.ts"; |
| 44 | import { ownedProjects } from "./Project.ts"; |
| 45 | import { RPC_TOKEN_ENV } from "./rpc-token.ts"; |
| 46 | import { Service } from "./Service.ts"; |
| 47 | import { |
| 48 | deleteOwnedServiceDomain, |
| 49 | ensureServiceDomain, |
| 50 | findServiceDomainById, |
| 51 | type ServiceDomainRecord, |
| 52 | } from "./ServiceDomain.ts"; |
| 53 | import { readServiceRegion, syncServiceRegion } from "./ServiceRegion.ts"; |
| 54 | import { withEnvironmentConfigLock } from "./transient.ts"; |
| 55 | import { uploadDeployTarball } from "./Up.ts"; |
| 56 | import { attachVolumeToService, listServiceVolumes } from "./Volume.ts"; |
| 57 | |
| 58 | export { ServiceRegionNotApplied } from "./ServiceRegion.ts"; |
| 59 | |
| 60 | const serviceFields = <E>(service: Query<RailwayService, E>) => ({ |
| 61 | id: service.id, |
| 62 | name: service.name, |
| 63 | deletedAt: service.deletedAt, |
| 64 | }); |
| 65 | type CloudService = UnwrapPlan<ReturnType<typeof serviceFields>>; |
| 66 | |
| 67 | const instanceFields = <E>(instance: Query<RailwayServiceInstance, E>) => ({ |
| 68 | deletedAt: instance.deletedAt, |
| 69 | source: instance.source.pipe(Query.map((source) => ({ image: source.image, repo: source.repo }))), |
| 70 | region: instance.region, |
| 71 | sleepApplication: instance.sleepApplication, |
| 72 | latestDeployment: instance.latestDeployment.pipe( |
| 73 | Query.map((deployment) => ({ id: deployment.id, status: deployment.status })), |
| 74 | ), |
| 75 | activeDeployments: instance.activeDeployments.pipe( |
| 76 | Query.map((deployment) => ({ id: deployment.id, status: deployment.status })), |
| 77 | ), |
| 78 | buildCommand: instance.buildCommand, |
| 79 | builder: instance.builder, |
| 80 | cronSchedule: instance.cronSchedule, |
| 81 | dockerfilePath: instance.dockerfilePath, |
| 82 | drainingSeconds: instance.drainingSeconds, |
| 83 | healthcheckPath: instance.healthcheckPath, |
| 84 | healthcheckTimeout: instance.healthcheckTimeout, |
| 85 | numReplicas: instance.numReplicas, |
| 86 | overlapSeconds: instance.overlapSeconds, |
| 87 | preDeployCommand: instance.preDeployCommand, |
| 88 | restartPolicyMaxRetries: instance.restartPolicyMaxRetries, |
| 89 | restartPolicyType: instance.restartPolicyType, |
| 90 | rootDirectory: instance.rootDirectory, |
| 91 | startCommand: instance.startCommand, |
| 92 | watchPatterns: instance.watchPatterns, |
| 93 | }); |
| 94 | type ServiceInstanceResponse = UnwrapPlan<ReturnType<typeof instanceFields>>; |
| 95 | |
| 96 | /** Mutable builder for a {@link ServiceInstanceUpdateInput} delta. */ |
| 97 | type InstanceSettingsDelta = Types.Mutable<ServiceInstanceUpdateInput>; |
| 98 | |
| 99 | export { |
| 100 | ServiceContextPathInvalid, |
| 101 | ServiceContextPathUnsupported, |
| 102 | ServiceContextSymlinkUnsupported, |
| 103 | ServiceContextTooLarge, |
| 104 | ServiceDockerfileOutsideContext, |
| 105 | ServiceDockerfilePathInvalid, |
| 106 | ServiceImageOrMainRequired, |
| 107 | ServiceSourceInvalid, |
| 108 | } from "./local-context.ts"; |
| 109 | |
| 110 | export class ServiceNotCreated extends Data.TaggedError("Railway.ServiceNotCreated")<{ |
| 111 | resourceName: string; |
| 112 | projectId: string; |
| 113 | }> {} |
| 114 | |
| 115 | export class ServiceProjectRequired extends Data.TaggedError("Railway.ServiceProjectRequired")<{ |
| 116 | message: string; |
| 117 | }> {} |
| 118 | |
| 119 | export class ServiceDeployFailed extends Data.TaggedError("Railway.ServiceDeployFailed")<{ |
| 120 | serviceId: string; |
| 121 | status: string; |
| 122 | deploymentId: string | undefined; |
| 123 | logs: string; |
| 124 | }> { |
| 125 | override get message() { |
| 126 | return this.logs.length > 0 |
| 127 | ? `Service deploy ${this.status}: ${this.logs}` |
| 128 | : `Service deploy ${this.status}`; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | class ServicePending extends Data.TaggedError("Railway.ServicePending")<{ |
| 133 | serviceId: string; |
| 134 | status: string; |
| 135 | }> {} |
| 136 | |
| 137 | class ServiceDeployPending extends Data.TaggedError("Railway.ServiceDeployPending")<{ |
| 138 | serviceId: string; |
| 139 | status: string; |
| 140 | }> { |
| 141 | override get message() { |
| 142 | return `deployment still ${this.status}`; |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | const projectIdOf = (value: unknown): string | undefined => { |
| 147 | if (value === null || typeof value !== "object") return undefined; |
| 148 | const rec = value as { projectId?: unknown }; |
| 149 | return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined; |
| 150 | }; |
| 151 | |
| 152 | const environmentIdOf = (value: unknown): string | undefined => { |
| 153 | if (value === null || typeof value !== "object") return undefined; |
| 154 | const rec = value as { environmentId?: unknown }; |
| 155 | return typeof rec.environmentId === "string" && rec.environmentId.length > 0 |
| 156 | ? rec.environmentId |
| 157 | : undefined; |
| 158 | }; |
| 159 | |
| 160 | const isGoneService = (service: CloudService | undefined) => |
| 161 | service === undefined || service.deletedAt != null; |
| 162 | |
| 163 | const isGoneInstance = (instance: ServiceInstanceResponse | undefined) => |
| 164 | instance === undefined || instance.deletedAt != null; |
| 165 | |
| 166 | const resolveName = (id: string, name: string | undefined, existing?: string) => |
| 167 | Effect.gen(function* () { |
| 168 | if (name !== undefined) return name; |
| 169 | if (existing !== undefined) return existing; |
| 170 | return yield* createRailwayName(id); |
| 171 | }); |
| 172 | |
| 173 | const readService = Query.fn((id: string) => serviceFields(Railway.service({ id }))); |
| 174 | |
| 175 | const readInstance = Query.fn((environmentId: string, serviceId: string) => |
| 176 | instanceFields(Railway.serviceInstance({ environmentId, serviceId })), |
| 177 | ); |
| 178 | |
| 179 | const getById = (serviceId: string) => |
| 180 | readService(serviceId).pipe( |
| 181 | Effect.map((service) => (isGoneService(service) ? undefined : service)), |
| 182 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 183 | ); |
| 184 | |
| 185 | const getInstance = (environmentId: string, serviceId: string) => |
| 186 | readInstance(environmentId, serviceId).pipe( |
| 187 | Effect.map((instance) => (isGoneInstance(instance) ? undefined : instance)), |
| 188 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 189 | ); |
| 190 | |
| 191 | const listProjectServices = (projectId: string) => |
| 192 | projectServices(projectId, serviceFields).pipe( |
| 193 | Effect.map((services) => services.filter((node) => !isGoneService(node))), |
| 194 | Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudService[])), |
| 195 | ); |
| 196 | |
| 197 | const findByName = (projectId: string, name: string) => |
| 198 | listProjectServices(projectId).pipe( |
| 199 | Effect.map((services) => services.find((service) => service.name === name)), |
| 200 | ); |
| 201 | |
| 202 | const sameImage = (observed: string | null | undefined, desired: string) => { |
| 203 | if (observed == null || observed.length === 0) return false; |
| 204 | if (observed === desired) return true; |
| 205 | if (observed === `${desired}:latest` || desired === `${observed}:latest`) { |
| 206 | return true; |
| 207 | } |
| 208 | return observed.endsWith(`/${desired}`) || observed.endsWith(`/${desired}:latest`); |
| 209 | }; |
| 210 | |
| 211 | const deployReady = (status: string | undefined) => status === "SUCCESS" || status === "SLEEPING"; |
| 212 | |
| 213 | const deployFailed = (status: string | undefined) => |
| 214 | status === "FAILED" || status === "CRASHED" || status === "REMOVED"; |
| 215 | |
| 216 | const undef = <T>(value: T | null | undefined): T | undefined => |
| 217 | value == null ? undefined : value; |
| 218 | |
| 219 | const sameWatchPatterns = ( |
| 220 | observed: readonly string[] | null | undefined, |
| 221 | desired: readonly string[] | undefined, |
| 222 | ) => desired === undefined || deepEqual([...(observed ?? [])], [...desired]); |
| 223 | |
| 224 | const samePreDeployCommand = (observed: unknown, desired: string | null | undefined) => |
| 225 | desired === undefined || |
| 226 | (desired === null |
| 227 | ? observed == null || (Array.isArray(observed) && observed.length === 0) |
| 228 | : observed === desired || |
| 229 | (Array.isArray(observed) && observed.length === 1 && observed[0] === desired)); |
| 230 | |
| 231 | const assignIfChanged = <K extends keyof InstanceSettingsDelta>( |
| 232 | input: InstanceSettingsDelta, |
| 233 | key: K, |
| 234 | desired: InstanceSettingsDelta[K] | undefined, |
| 235 | observed: unknown, |
| 236 | ): boolean => { |
| 237 | if (desired === undefined) return false; |
| 238 | if (desired === null ? observed == null : deepEqual(undef(observed as never), desired)) { |
| 239 | return false; |
| 240 | } |
| 241 | input[key] = desired; |
| 242 | return true; |
| 243 | }; |
| 244 | |
| 245 | const instanceSettingsDelta = (input: { |
| 246 | instance: ServiceInstanceResponse | undefined; |
| 247 | sourceImage: string | undefined; |
| 248 | sourceRepo: string | undefined; |
| 249 | registryCredentials: { username: string; password: string } | undefined; |
| 250 | props: { |
| 251 | rootDirectory?: string; |
| 252 | buildCommand?: string; |
| 253 | preDeploy?: { command: string | null }; |
| 254 | startCommand?: string; |
| 255 | healthcheckPath?: string; |
| 256 | healthcheck?: string; |
| 257 | healthcheckTimeout?: number; |
| 258 | cronSchedule?: string; |
| 259 | restartPolicyType?: RestartPolicyType; |
| 260 | restartPolicyMaxRetries?: number; |
| 261 | drainingSeconds?: number; |
| 262 | overlapSeconds?: number; |
| 263 | sleepApplication?: boolean; |
| 264 | dockerfilePath?: string | null; |
| 265 | builder?: Builder; |
| 266 | watchPatterns?: string[]; |
| 267 | }; |
| 268 | }): ServiceInstanceUpdateInput | undefined => { |
| 269 | const instance = input.instance; |
| 270 | const delta: InstanceSettingsDelta = {}; |
| 271 | let changed = false; |
| 272 | |
| 273 | if (input.sourceRepo !== undefined) { |
| 274 | if (undef(instance?.source?.repo) !== input.sourceRepo) { |
| 275 | delta.source = { repo: input.sourceRepo }; |
| 276 | changed = true; |
| 277 | } |
| 278 | } else if ( |
| 279 | input.sourceImage !== undefined && |
| 280 | !sameImage(instance?.source?.image, input.sourceImage) |
| 281 | ) { |
| 282 | delta.source = { image: input.sourceImage }; |
| 283 | changed = true; |
| 284 | } |
| 285 | |
| 286 | if (input.registryCredentials !== undefined) { |
| 287 | delta.registryCredentials = input.registryCredentials; |
| 288 | changed = true; |
| 289 | } |
| 290 | |
| 291 | // Placement is `deploy.multiRegionConfig`, not ServiceInstance.region. |
| 292 | // Writing `region` here leaves the workspace default in place. |
| 293 | changed = |
| 294 | assignIfChanged(delta, "rootDirectory", input.props.rootDirectory, instance?.rootDirectory) || |
| 295 | changed; |
| 296 | changed = |
| 297 | assignIfChanged(delta, "buildCommand", input.props.buildCommand, instance?.buildCommand) || |
| 298 | changed; |
| 299 | const preDeployCommand = |
| 300 | input.props.preDeploy === undefined ? undefined : input.props.preDeploy.command; |
| 301 | if ( |
| 302 | preDeployCommand !== undefined && |
| 303 | !samePreDeployCommand(instance?.preDeployCommand, preDeployCommand) |
| 304 | ) { |
| 305 | // Railway's GraphQL field is `[String]`. `null` is a no-op; `[]` clears. |
| 306 | delta.preDeployCommand = preDeployCommand === null ? [] : [preDeployCommand]; |
| 307 | changed = true; |
| 308 | } |
| 309 | changed = |
| 310 | assignIfChanged(delta, "startCommand", input.props.startCommand, instance?.startCommand) || |
| 311 | changed; |
| 312 | changed = |
| 313 | assignIfChanged( |
| 314 | delta, |
| 315 | "healthcheckPath", |
| 316 | input.props.healthcheckPath ?? input.props.healthcheck, |
| 317 | instance?.healthcheckPath, |
| 318 | ) || changed; |
| 319 | changed = |
| 320 | assignIfChanged( |
| 321 | delta, |
| 322 | "healthcheckTimeout", |
| 323 | input.props.healthcheckTimeout, |
| 324 | instance?.healthcheckTimeout, |
| 325 | ) || changed; |
| 326 | changed = |
| 327 | assignIfChanged(delta, "cronSchedule", input.props.cronSchedule, instance?.cronSchedule) || |
| 328 | changed; |
| 329 | changed = |
| 330 | assignIfChanged( |
| 331 | delta, |
| 332 | "restartPolicyType", |
| 333 | input.props.restartPolicyType, |
| 334 | instance?.restartPolicyType, |
| 335 | ) || changed; |
| 336 | changed = |
| 337 | assignIfChanged( |
| 338 | delta, |
| 339 | "restartPolicyMaxRetries", |
| 340 | input.props.restartPolicyMaxRetries, |
| 341 | instance?.restartPolicyMaxRetries, |
| 342 | ) || changed; |
| 343 | changed = |
| 344 | assignIfChanged( |
| 345 | delta, |
| 346 | "drainingSeconds", |
| 347 | input.props.drainingSeconds, |
| 348 | instance?.drainingSeconds, |
| 349 | ) || changed; |
| 350 | changed = |
| 351 | assignIfChanged( |
| 352 | delta, |
| 353 | "overlapSeconds", |
| 354 | input.props.overlapSeconds, |
| 355 | instance?.overlapSeconds, |
| 356 | ) || changed; |
| 357 | changed = |
| 358 | assignIfChanged( |
| 359 | delta, |
| 360 | "sleepApplication", |
| 361 | input.props.sleepApplication, |
| 362 | instance?.sleepApplication, |
| 363 | ) || changed; |
| 364 | changed = |
| 365 | assignIfChanged( |
| 366 | delta, |
| 367 | "dockerfilePath", |
| 368 | input.props.dockerfilePath, |
| 369 | instance?.dockerfilePath, |
| 370 | ) || changed; |
| 371 | changed = assignIfChanged(delta, "builder", input.props.builder, instance?.builder) || changed; |
| 372 | |
| 373 | const watchPatterns = input.props.watchPatterns; |
| 374 | if (watchPatterns !== undefined && !sameWatchPatterns(instance?.watchPatterns, watchPatterns)) { |
| 375 | delta.watchPatterns = watchPatterns; |
| 376 | changed = true; |
| 377 | } |
| 378 | |
| 379 | // `serviceInstanceUpdate` defaults `numReplicas` to 1 when omitted. |
| 380 | // Pass through the observed count so a dashboard/CLI scale is not |
| 381 | // reset on an unrelated settings update. |
| 382 | if (changed && instance?.numReplicas != null) { |
| 383 | delta.numReplicas = instance.numReplicas; |
| 384 | } |
| 385 | |
| 386 | return changed ? delta : undefined; |
| 387 | }; |
| 388 | |
| 389 | const listDeploymentTriggers = (projectId: string, environmentId: string, serviceId: string) => |
| 390 | Query.items( |
| 391 | Railway.deploymentTriggers({ projectId, environmentId, serviceId, first: 50 }).pipe( |
| 392 | Query.map((trigger) => ({ |
| 393 | id: trigger.id, |
| 394 | branch: trigger.branch, |
| 395 | repository: trigger.repository, |
| 396 | provider: trigger.provider, |
| 397 | })), |
| 398 | ), |
| 399 | ).pipe( |
| 400 | Stream.runCollect, |
| 401 | Effect.map((triggers) => Array.from(triggers)), |
| 402 | ); |
| 403 | |
| 404 | const deploymentTriggerCreate = Query.fn((input: DeploymentTriggerCreateInput) => ({ |
| 405 | id: Railway.deploymentTriggerCreate({ input }).id, |
| 406 | })); |
| 407 | |
| 408 | const deploymentTriggerUpdate = Query.fn( |
| 409 | (args: { id: string; input: DeploymentTriggerUpdateInput }) => ({ |
| 410 | id: Railway.deploymentTriggerUpdate(args).id, |
| 411 | }), |
| 412 | ); |
| 413 | |
| 414 | const deploymentTriggerDelete = Query.fn((id: string) => Railway.deploymentTriggerDelete({ id })); |
| 415 | |
| 416 | const syncBranch = Effect.fn(function* (input: { |
| 417 | projectId: string; |
| 418 | environmentId: string; |
| 419 | serviceId: string; |
| 420 | repo: string; |
| 421 | branch: string | undefined; |
| 422 | }) { |
| 423 | if (input.branch === undefined) return false; |
| 424 | const triggers = yield* listDeploymentTriggers( |
| 425 | input.projectId, |
| 426 | input.environmentId, |
| 427 | input.serviceId, |
| 428 | ); |
| 429 | const current = triggers[0]; |
| 430 | if (current === undefined) { |
| 431 | yield* deploymentTriggerCreate({ |
| 432 | branch: input.branch, |
| 433 | environmentId: input.environmentId, |
| 434 | projectId: input.projectId, |
| 435 | provider: "github", |
| 436 | repository: input.repo, |
| 437 | serviceId: input.serviceId, |
| 438 | }); |
| 439 | return true; |
| 440 | } |
| 441 | const branchChanged = current.branch !== input.branch; |
| 442 | const repoChanged = current.repository !== input.repo; |
| 443 | if (!branchChanged && !repoChanged) return false; |
| 444 | yield* deploymentTriggerUpdate({ |
| 445 | id: current.id, |
| 446 | input: { |
| 447 | ...(branchChanged ? { branch: input.branch } : {}), |
| 448 | ...(repoChanged ? { repository: input.repo } : {}), |
| 449 | }, |
| 450 | }); |
| 451 | return true; |
| 452 | }); |
| 453 | |
| 454 | const clearDeploymentTriggers = Effect.fn(function* (input: { |
| 455 | projectId: string; |
| 456 | environmentId: string; |
| 457 | serviceId: string; |
| 458 | }) { |
| 459 | const triggers = yield* listDeploymentTriggers( |
| 460 | input.projectId, |
| 461 | input.environmentId, |
| 462 | input.serviceId, |
| 463 | ); |
| 464 | const github = triggers.filter((trigger) => trigger.provider === "github"); |
| 465 | yield* Effect.forEach(github, (trigger) => deploymentTriggerDelete(trigger.id)); |
| 466 | return github.length > 0; |
| 467 | }); |
| 468 | |
| 469 | const autoDeployStatus = Query.fn( |
| 470 | (args: { environmentId: string; projectId: string; serviceId: string }) => ({ |
| 471 | enabled: Railway.serviceInstanceAutoDeployStatus(args).enabled, |
| 472 | }), |
| 473 | ); |
| 474 | |
| 475 | const autoDeployUpdate = Query.fn((input: ServiceInstanceAutoDeployUpdateInput) => ({ |
| 476 | enabled: Railway.serviceInstanceAutoDeployUpdate({ input }).enabled, |
| 477 | })); |
| 478 | |
| 479 | const syncAutoUpdates = Effect.fn(function* (input: { |
| 480 | projectId: string; |
| 481 | environmentId: string; |
| 482 | serviceId: string; |
| 483 | enabled: boolean | undefined; |
| 484 | }) { |
| 485 | if (input.enabled === undefined) return; |
| 486 | const status = yield* autoDeployStatus({ |
| 487 | environmentId: input.environmentId, |
| 488 | projectId: input.projectId, |
| 489 | serviceId: input.serviceId, |
| 490 | }); |
| 491 | if (status.enabled === input.enabled) return; |
| 492 | yield* autoDeployUpdate({ |
| 493 | enabled: input.enabled, |
| 494 | environmentId: input.environmentId, |
| 495 | projectId: input.projectId, |
| 496 | serviceId: input.serviceId, |
| 497 | }); |
| 498 | }); |
| 499 | |
| 500 | const waitForInstance = (environmentId: string, serviceId: string) => |
| 501 | getInstance(environmentId, serviceId).pipe( |
| 502 | Effect.flatMap((instance) => { |
| 503 | if (instance === undefined) { |
| 504 | return Effect.fail(new ServicePending({ serviceId, status: "creating" })); |
| 505 | } |
| 506 | return Effect.succeed(instance); |
| 507 | }), |
| 508 | Effect.retry({ |
| 509 | while: (e) => e._tag === "Railway.ServicePending", |
| 510 | // serviceCreate fans the instance out to each environment |
| 511 | // asynchronously; wait a bounded interval for it to appear. |
| 512 | times: 10, |
| 513 | schedule: Schedule.spaced("2 seconds"), |
| 514 | }), |
| 515 | Effect.catchTag("Railway.ServicePending", () => getInstance(environmentId, serviceId)), |
| 516 | ); |
| 517 | |
| 518 | const deploymentLogs = Query.fn((deploymentId: string) => |
| 519 | Railway.deploymentLogs({ deploymentId, limit: 80 }).pipe( |
| 520 | Query.map((row) => ({ message: row.message, severity: row.severity })), |
| 521 | ), |
| 522 | ); |
| 523 | |
| 524 | const fetchDeployLogs = (deploymentId: string | undefined) => |
| 525 | deploymentId === undefined || deploymentId.length === 0 |
| 526 | ? Effect.succeed("") |
| 527 | : deploymentLogs(deploymentId).pipe( |
| 528 | Effect.map((rows) => |
| 529 | rows |
| 530 | .map((row) => (row.severity != null ? `[${row.severity}] ${row.message}` : row.message)) |
| 531 | .join("\n"), |
| 532 | ), |
| 533 | Effect.orElseSucceed(() => ""), |
| 534 | ); |
| 535 | |
| 536 | // Railway builds routinely take 60–90s and exceed 90s when its build queue is |
| 537 | // busy (observed 2026-10: a small bundled service stuck BUILDING past 90s), so |
| 538 | // a 90s cap failed healthy deploys. Allow up to 150 seconds while bounding |
| 539 | // both the retry count and time spent in API requests. |
| 540 | const waitForDeployment = (environmentId: string, serviceId: string) => |
| 541 | Effect.gen(function* () { |
| 542 | const instance = yield* getInstance(environmentId, serviceId); |
| 543 | const latest = instance?.latestDeployment; |
| 544 | const status = latest?.status; |
| 545 | if (status !== undefined && deployFailed(status)) { |
| 546 | const logs = yield* fetchDeployLogs(latest?.id); |
| 547 | return yield* new ServiceDeployFailed({ serviceId, status, deploymentId: latest?.id, logs }); |
| 548 | } |
| 549 | if (instance !== undefined && deployReady(status)) { |
| 550 | return instance; |
| 551 | } |
| 552 | return yield* new ServiceDeployPending({ serviceId, status: status ?? "pending" }); |
| 553 | }).pipe( |
| 554 | Effect.retry({ |
| 555 | while: (e) => e._tag === "Railway.ServiceDeployPending", |
| 556 | times: 15, |
| 557 | schedule: Schedule.spaced("10 seconds"), |
| 558 | }), |
| 559 | Effect.timeoutOrElse({ |
| 560 | duration: "150 seconds", |
| 561 | orElse: () => Effect.fail(new ServiceDeployPending({ serviceId, status: "pending" })), |
| 562 | }), |
| 563 | ); |
| 564 | |
| 565 | type DeployRef = { id: string; status: string | undefined }; |
| 566 | |
| 567 | const asDeployRef = ( |
| 568 | row: { id: string; status?: string | null } | undefined, |
| 569 | ): DeployRef | undefined => |
| 570 | row === undefined ? undefined : { id: row.id, status: row.status ?? undefined }; |
| 571 | |
| 572 | const matchUploadedDeployment = ( |
| 573 | instance: ServiceInstanceResponse | undefined, |
| 574 | deploymentId: string, |
| 575 | ): DeployRef | undefined => { |
| 576 | const latest = instance?.latestDeployment; |
| 577 | if (latest?.id === deploymentId) return asDeployRef(latest); |
| 578 | return asDeployRef( |
| 579 | (instance?.activeDeployments ?? []).find((deployment) => deployment.id === deploymentId), |
| 580 | ); |
| 581 | }; |
| 582 | |
| 583 | const listUploadedDeployment = (input: { |
| 584 | deploymentId: string; |
| 585 | serviceId: string; |
| 586 | environmentId: string; |
| 587 | }) => |
| 588 | Query.items( |
| 589 | Railway.deployments({ |
| 590 | first: 10, |
| 591 | input: { serviceId: input.serviceId, environmentId: input.environmentId }, |
| 592 | }).pipe(Query.map((deployment) => ({ id: deployment.id, status: deployment.status }))), |
| 593 | ).pipe( |
| 594 | Stream.filter((row) => row.id === input.deploymentId), |
| 595 | Stream.take(1), |
| 596 | Stream.runCollect, |
| 597 | Effect.map((chunk) => Array.from(chunk)[0]), |
| 598 | Effect.timeoutOrElse({ duration: "8 seconds", orElse: () => Effect.undefined }), |
| 599 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 600 | ); |
| 601 | |
| 602 | const waitForDeploymentById = (input: { |
| 603 | deploymentId: string; |
| 604 | serviceId: string; |
| 605 | environmentId: string; |
| 606 | }) => |
| 607 | Effect.gen(function* () { |
| 608 | // Poll the instance, not `deployment(id)`. Distilled's deployment |
| 609 | // query is a huge nested selection that 404s/times out for /up ids; |
| 610 | // `serviceInstance.latestDeployment` is the same record the rest of |
| 611 | // reconcile already uses. The placeholder `hashicorp/http-echo` |
| 612 | // deploy often FAILED (wrong port / no `/health`) before `railway up` |
| 613 | // replaces it — do not inherit that FAILED onto this wait. |
| 614 | const instance = yield* getInstance(input.environmentId, input.serviceId); |
| 615 | const match = |
| 616 | matchUploadedDeployment(instance, input.deploymentId) ?? |
| 617 | asDeployRef(yield* listUploadedDeployment(input)); |
| 618 | if (match === undefined) { |
| 619 | return yield* new ServiceDeployPending({ serviceId: input.serviceId, status: "pending" }); |
| 620 | } |
| 621 | const status = match.status; |
| 622 | if (status !== undefined && deployFailed(status)) { |
| 623 | const logs = yield* fetchDeployLogs(match.id); |
| 624 | return yield* new ServiceDeployFailed({ |
| 625 | serviceId: input.serviceId, |
| 626 | status, |
| 627 | deploymentId: match.id, |
| 628 | logs, |
| 629 | }); |
| 630 | } |
| 631 | if (instance !== undefined && deployReady(status)) { |
| 632 | return instance; |
| 633 | } |
| 634 | return yield* new ServiceDeployPending({ |
| 635 | serviceId: input.serviceId, |
| 636 | status: status ?? "pending", |
| 637 | }); |
| 638 | }).pipe( |
| 639 | Effect.retry({ |
| 640 | while: (e) => e._tag === "Railway.ServiceDeployPending", |
| 641 | times: 15, |
| 642 | schedule: Schedule.spaced("10 seconds"), |
| 643 | }), |
| 644 | // Surface the budget as a pending deploy so the final check below still |
| 645 | // reports a ready instance, or a failed deploy with its logs. |
| 646 | Effect.timeoutOrElse({ |
| 647 | duration: "150 seconds", |
| 648 | orElse: () => |
| 649 | Effect.fail(new ServiceDeployPending({ serviceId: input.serviceId, status: "pending" })), |
| 650 | }), |
| 651 | Effect.catchTag("Railway.ServiceDeployPending", (pending) => |
| 652 | Effect.gen(function* () { |
| 653 | const instance = yield* getInstance(input.environmentId, input.serviceId); |
| 654 | const match = |
| 655 | matchUploadedDeployment(instance, input.deploymentId) ?? |
| 656 | asDeployRef(yield* listUploadedDeployment(input)); |
| 657 | const status = match?.status; |
| 658 | if (match !== undefined && status !== undefined && deployFailed(status)) { |
| 659 | const logs = yield* fetchDeployLogs(match.id); |
| 660 | return yield* new ServiceDeployFailed({ |
| 661 | serviceId: input.serviceId, |
| 662 | status, |
| 663 | deploymentId: match.id, |
| 664 | logs, |
| 665 | }); |
| 666 | } |
| 667 | if (instance !== undefined && deployReady(status)) { |
| 668 | return instance; |
| 669 | } |
| 670 | return yield* new ServiceDeployPending({ |
| 671 | serviceId: input.serviceId, |
| 672 | status: status ?? pending.status, |
| 673 | }); |
| 674 | }).pipe(Effect.timeoutOrElse({ duration: "10 seconds", orElse: () => Effect.fail(pending) })), |
| 675 | ), |
| 676 | ); |
| 677 | |
| 678 | const variableUpsert = Query.fn((input: VariableUpsertInput) => Railway.variableUpsert({ input })); |
| 679 | |
| 680 | const readVariables = Query.fn( |
| 681 | (args: { projectId: string; environmentId: string; serviceId: string; unrendered: boolean }) => |
| 682 | Railway.variables(args), |
| 683 | ); |
| 684 | |
| 685 | const upsertVariable = (input: { |
| 686 | projectId: string; |
| 687 | environmentId: string; |
| 688 | serviceId: string; |
| 689 | name: string; |
| 690 | value: string; |
| 691 | }) => |
| 692 | variableUpsert({ |
| 693 | projectId: input.projectId, |
| 694 | environmentId: input.environmentId, |
| 695 | serviceId: input.serviceId, |
| 696 | name: input.name, |
| 697 | value: input.value, |
| 698 | skipDeploys: true, |
| 699 | }); |
| 700 | |
| 701 | const asVariableMap = (value: unknown): Record<string, string> => { |
| 702 | if (value === null || typeof value !== "object" || Array.isArray(value)) { |
| 703 | return {}; |
| 704 | } |
| 705 | const out: Record<string, string> = {}; |
| 706 | for (const [key, item] of Object.entries(value)) { |
| 707 | if (typeof item === "string") { |
| 708 | out[key] = item; |
| 709 | } |
| 710 | } |
| 711 | return out; |
| 712 | }; |
| 713 | |
| 714 | const listVariableMap = (projectId: string, environmentId: string, serviceId: string) => |
| 715 | readVariables({ projectId, environmentId, serviceId, unrendered: true }).pipe( |
| 716 | Effect.map(asVariableMap), |
| 717 | Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as Record<string, string>)), |
| 718 | ); |
| 719 | |
| 720 | const syncEnv = Effect.fn(function* (input: { |
| 721 | projectId: string; |
| 722 | environmentId: string; |
| 723 | serviceId: string; |
| 724 | desired: Record<string, string>; |
| 725 | }) { |
| 726 | if (Object.keys(input.desired).length === 0) return false; |
| 727 | const observed = yield* listVariableMap(input.projectId, input.environmentId, input.serviceId); |
| 728 | let changed = false; |
| 729 | for (const [name, value] of Object.entries(input.desired)) { |
| 730 | if (observed[name] !== value) { |
| 731 | yield* upsertVariable({ |
| 732 | projectId: input.projectId, |
| 733 | environmentId: input.environmentId, |
| 734 | serviceId: input.serviceId, |
| 735 | name, |
| 736 | value, |
| 737 | }); |
| 738 | changed = true; |
| 739 | } |
| 740 | } |
| 741 | return changed; |
| 742 | }); |
| 743 | |
| 744 | const syncMounts = Effect.fn(function* (input: { |
| 745 | environmentId: string; |
| 746 | projectId: string; |
| 747 | serviceId: string; |
| 748 | mounts: MountSpec[]; |
| 749 | }) { |
| 750 | for (const mount of input.mounts) { |
| 751 | yield* attachVolumeToService({ |
| 752 | environmentId: input.environmentId, |
| 753 | projectId: input.projectId, |
| 754 | serviceId: input.serviceId, |
| 755 | volumeId: mount.volumeId, |
| 756 | mountPath: mount.path, |
| 757 | }); |
| 758 | } |
| 759 | }); |
| 760 | |
| 761 | const serviceCreate = Query.fn((input: ServiceCreateInput) => |
| 762 | serviceFields(Railway.serviceCreate({ input })), |
| 763 | ); |
| 764 | |
| 765 | const serviceUpdate = Query.fn((id: string, name: string) => |
| 766 | serviceFields(Railway.serviceUpdate({ id, input: { name } })), |
| 767 | ); |
| 768 | |
| 769 | const serviceDisconnect = Query.fn((id: string) => ({ id: Railway.serviceDisconnect({ id }).id })); |
| 770 | |
| 771 | const serviceInstanceUpdate = Query.fn( |
| 772 | (args: { environmentId: string; serviceId: string; input: ServiceInstanceUpdateInput }) => |
| 773 | Railway.serviceInstanceUpdate(args), |
| 774 | ); |
| 775 | |
| 776 | const serviceInstanceDeploy = Query.fn((environmentId: string, serviceId: string) => |
| 777 | Railway.serviceInstanceDeployV2({ environmentId, serviceId }), |
| 778 | ); |
| 779 | |
| 780 | // Railway keeps one service per project with an instance per environment. |
| 781 | // Scoping by `environmentId` removes only that instance; Railway drops the |
| 782 | // service once no instances remain. Omitting it deletes every environment. |
| 783 | const environmentPatchCommit = Query.fn( |
| 784 | (input: { environmentId: string; commitMessage: string; patch: unknown }) => |
| 785 | Railway.environmentPatchCommit(input), |
| 786 | ); |
| 787 | |
| 788 | // Railway does not fan an existing service out to other environments, so a |
| 789 | // Service attaching to one in a new environment adds its instance through |
| 790 | // the environment config, as Railway's own IaC does. |
| 791 | const ensureInstance = (input: { |
| 792 | environmentId: string; |
| 793 | serviceId: string; |
| 794 | source: { image: string } | { repo: string }; |
| 795 | }) => |
| 796 | Effect.gen(function* () { |
| 797 | const existing = yield* getInstance(input.environmentId, input.serviceId); |
| 798 | if (existing !== undefined) return existing; |
| 799 | yield* withEnvironmentConfigLock( |
| 800 | input.environmentId, |
| 801 | environmentPatchCommit({ |
| 802 | environmentId: input.environmentId, |
| 803 | commitMessage: "Add service instance", |
| 804 | patch: { services: { [input.serviceId]: { source: input.source } } }, |
| 805 | }), |
| 806 | ); |
| 807 | return yield* waitForInstance(input.environmentId, input.serviceId); |
| 808 | }); |
| 809 | |
| 810 | const serviceDelete = Query.fn((id: string, environmentId: string | undefined) => |
| 811 | Railway.serviceDelete({ id, environmentId }), |
| 812 | ); |
| 813 | |
| 814 | const toAttrs = (input: { |
| 815 | service: CloudService; |
| 816 | instance: ServiceInstanceResponse | undefined; |
| 817 | domain: ServiceDomainRecord | undefined; |
| 818 | projectId: string; |
| 819 | environmentId: string; |
| 820 | port: number | undefined; |
| 821 | codeHash: string; |
| 822 | rpcToken: string; |
| 823 | region: string | undefined; |
| 824 | }): Service["Attributes"] => ({ |
| 825 | serviceId: input.service.id, |
| 826 | name: input.service.name, |
| 827 | projectId: input.projectId, |
| 828 | environmentId: input.environmentId, |
| 829 | image: input.instance?.source?.image ?? undefined, |
| 830 | repo: input.instance?.source?.repo ?? undefined, |
| 831 | healthcheckPath: input.instance?.healthcheckPath ?? undefined, |
| 832 | healthcheckTimeout: input.instance?.healthcheckTimeout ?? undefined, |
| 833 | replicas: input.instance?.numReplicas ?? undefined, |
| 834 | buildCommand: input.instance?.buildCommand ?? undefined, |
| 835 | startCommand: input.instance?.startCommand ?? undefined, |
| 836 | cronSchedule: input.instance?.cronSchedule ?? undefined, |
| 837 | rootDirectory: input.instance?.rootDirectory ?? undefined, |
| 838 | region: input.region, |
| 839 | port: input.port, |
| 840 | url: input.domain?.url, |
| 841 | domain: input.domain?.domain, |
| 842 | dnsName: `${input.service.name}.railway.internal`, |
| 843 | rpcToken: input.rpcToken, |
| 844 | domainId: input.domain?.id, |
| 845 | deploymentId: input.instance?.latestDeployment?.id, |
| 846 | deploymentStatus: input.instance?.latestDeployment?.status, |
| 847 | code: { hash: input.codeHash }, |
| 848 | }); |
| 849 | |
| 850 | export const ServiceProvider = () => |
| 851 | Provider.effect( |
| 852 | Service, |
| 853 | Effect.gen(function* () { |
| 854 | const stack = yield* Stack; |
| 855 | const { dotAlchemy } = yield* AlchemyContext; |
| 856 | const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin; |
| 857 | const hosted = createRailwayHostedSupport({ |
| 858 | stackName: stack.name, |
| 859 | stage: stack.stage, |
| 860 | virtualEntryPlugin, |
| 861 | dotAlchemy, |
| 862 | }); |
| 863 | |
| 864 | return Service.Provider.of({ |
| 865 | stables: ["serviceId", "projectId", "environmentId"], |
| 866 | nuke: { dependsOn: ["Railway.Project"] }, |
| 867 | |
| 868 | diff: Effect.fn(function* ({ news: desired, output }) { |
| 869 | // Runtime exports contain Effects that remain unevaluated during |
| 870 | // planning. The bundle hash covers their code; they must not prevent |
| 871 | // code-only changes from reaching the hash comparison below. |
| 872 | const news = stripEffects(desired); |
| 873 | if (news === undefined || !isResolved(news)) return undefined; |
| 874 | if (output === undefined) return undefined; |
| 875 | const nextProject = projectIdOf(news.project); |
| 876 | const projectChanged = nextProject !== undefined && nextProject !== output.projectId; |
| 877 | const nextEnv = environmentIdOf(news.environment); |
| 878 | const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId; |
| 879 | if (projectChanged || environmentChanged) { |
| 880 | return { action: "replace" as const }; |
| 881 | } |
| 882 | const source = yield* resolveRailwayServiceSource(news); |
| 883 | if (source.mode === "main") { |
| 884 | const hash = yield* hosted.hash({ |
| 885 | main: source.main, |
| 886 | handler: news.handler, |
| 887 | port: news.port, |
| 888 | image: news.image, |
| 889 | env: news.env, |
| 890 | isExternal: news.isExternal, |
| 891 | build: news.build, |
| 892 | extraFiles: news.extraFiles, |
| 893 | }); |
| 894 | if (hash !== output.code.hash) { |
| 895 | return { action: "update" as const }; |
| 896 | } |
| 897 | } else if (source.mode === "context") { |
| 898 | const hash = yield* hashRailwayLocalContext(source); |
| 899 | if (hash !== output.code.hash) { |
| 900 | return { action: "update" as const }; |
| 901 | } |
| 902 | } |
| 903 | return undefined; |
| 904 | }), |
| 905 | |
| 906 | read: Effect.fn(function* ({ id, olds, output }) { |
| 907 | const projectId = |
| 908 | output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined); |
| 909 | const environmentId = |
| 910 | output?.environmentId ?? |
| 911 | (olds !== undefined |
| 912 | ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project)) |
| 913 | : undefined); |
| 914 | const name = yield* resolveName(id, olds?.name, output?.name); |
| 915 | const byId = |
| 916 | output?.serviceId !== undefined && output.serviceId.length > 0 |
| 917 | ? yield* getById(output.serviceId) |
| 918 | : undefined; |
| 919 | const found = |
| 920 | byId ?? (projectId !== undefined ? yield* findByName(projectId, name) : undefined); |
| 921 | if (found === undefined) return undefined; |
| 922 | const resolvedProjectId = projectIdOf(found) ?? projectId ?? ""; |
| 923 | const resolvedEnvId = |
| 924 | environmentId ?? environmentIdOf(olds?.project) ?? output?.environmentId ?? ""; |
| 925 | const instance = |
| 926 | resolvedEnvId.length > 0 ? yield* getInstance(resolvedEnvId, found.id) : undefined; |
| 927 | // A recorded domain id is the ownership boundary. Refresh an owned |
| 928 | // domain, but do not claim a generated domain found during adoption. |
| 929 | const domain = |
| 930 | output?.domainId !== undefined && |
| 931 | resolvedProjectId.length > 0 && |
| 932 | resolvedEnvId.length > 0 |
| 933 | ? yield* findServiceDomainById({ |
| 934 | projectId: resolvedProjectId, |
| 935 | environmentId: resolvedEnvId, |
| 936 | serviceId: found.id, |
| 937 | domainId: output.domainId, |
| 938 | }) |
| 939 | : undefined; |
| 940 | const region = |
| 941 | resolvedEnvId.length > 0 |
| 942 | ? yield* readServiceRegion({ |
| 943 | environmentId: resolvedEnvId, |
| 944 | projectId: resolvedProjectId, |
| 945 | serviceId: found.id, |
| 946 | legacy: instance?.region, |
| 947 | }) |
| 948 | : undefined; |
| 949 | const attrs = toAttrs({ |
| 950 | service: found, |
| 951 | instance, |
| 952 | domain, |
| 953 | projectId: resolvedProjectId, |
| 954 | environmentId: resolvedEnvId, |
| 955 | port: output?.port ?? olds?.port, |
| 956 | codeHash: output?.code.hash ?? "", |
| 957 | rpcToken: output?.rpcToken ?? "", |
| 958 | region, |
| 959 | }); |
| 960 | if (output !== undefined) { |
| 961 | // Keep the recorded ownership id even if the live list lags. |
| 962 | // Wiping it makes `publicDomain: false` a no-op. |
| 963 | if (domain === undefined && output.domainId !== undefined) { |
| 964 | return { |
| 965 | ...attrs, |
| 966 | domainId: output.domainId, |
| 967 | domain: output.domain, |
| 968 | url: output.url, |
| 969 | }; |
| 970 | } |
| 971 | return attrs; |
| 972 | } |
| 973 | return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs); |
| 974 | }), |
| 975 | |
| 976 | list: Effect.fn(function* () { |
| 977 | const projects = yield* ownedProjects(); |
| 978 | const rows = yield* Effect.forEach(projects, (project) => |
| 979 | listProjectServices(project.projectId).pipe( |
| 980 | Effect.map((services) => |
| 981 | services |
| 982 | .filter((service) => matchesAlchemyPhysicalName(service.name)) |
| 983 | .map((service) => |
| 984 | toAttrs({ |
| 985 | service, |
| 986 | instance: undefined, |
| 987 | domain: undefined, |
| 988 | projectId: project.projectId, |
| 989 | environmentId: project.environmentId, |
| 990 | port: undefined, |
| 991 | codeHash: "", |
| 992 | rpcToken: "", |
| 993 | region: undefined, |
| 994 | }), |
| 995 | ), |
| 996 | ), |
| 997 | ), |
| 998 | ); |
| 999 | return rows.flat(); |
| 1000 | }), |
| 1001 | |
| 1002 | // Circular Service↔Function RPC binds `dnsName` / `port` / `rpcToken`. |
| 1003 | // Those are knowable from the physical name and props; the cloud |
| 1004 | // service is created in reconcile (and re-synced in converge). |
| 1005 | precreate: Effect.fn(function* ({ id, news }) { |
| 1006 | const name = yield* resolveName( |
| 1007 | id, |
| 1008 | typeof news.name === "string" ? news.name : undefined, |
| 1009 | ); |
| 1010 | const port = typeof news.port === "number" ? news.port : DEFAULT_PORT; |
| 1011 | return { |
| 1012 | serviceId: "", |
| 1013 | name, |
| 1014 | projectId: "", |
| 1015 | environmentId: "", |
| 1016 | image: undefined, |
| 1017 | repo: undefined, |
| 1018 | healthcheckPath: undefined, |
| 1019 | healthcheckTimeout: undefined, |
| 1020 | replicas: undefined, |
| 1021 | buildCommand: undefined, |
| 1022 | startCommand: undefined, |
| 1023 | cronSchedule: undefined, |
| 1024 | rootDirectory: undefined, |
| 1025 | region: undefined, |
| 1026 | port, |
| 1027 | url: undefined, |
| 1028 | domain: undefined, |
| 1029 | dnsName: `${name}.railway.internal`, |
| 1030 | rpcToken: plainEnvValue(news.rpcToken) ?? "", |
| 1031 | domainId: undefined, |
| 1032 | deploymentId: undefined, |
| 1033 | deploymentStatus: undefined, |
| 1034 | code: { hash: "" }, |
| 1035 | } satisfies Service["Attributes"]; |
| 1036 | }), |
| 1037 | |
| 1038 | reconcile: Effect.fn(function* ({ id, news, olds, output, bindings, session }) { |
| 1039 | const props = news; |
| 1040 | const projectId = projectIdOf(props.project) ?? output?.projectId; |
| 1041 | if (projectId === undefined) { |
| 1042 | return yield* new ServiceProjectRequired({ |
| 1043 | message: "Service requires a resolved Railway.Project", |
| 1044 | }); |
| 1045 | } |
| 1046 | const environmentId = |
| 1047 | environmentIdOf(props.environment) ?? |
| 1048 | environmentIdOf(props.project) ?? |
| 1049 | output?.environmentId; |
| 1050 | if (environmentId === undefined) { |
| 1051 | return yield* new ServiceProjectRequired({ |
| 1052 | message: |
| 1053 | "Service requires a Railway environment (pass environment or a Project with environmentId)", |
| 1054 | }); |
| 1055 | } |
| 1056 | const name = yield* resolveName(id, props.name, output?.name); |
| 1057 | const source = yield* resolveRailwayServiceSource(props); |
| 1058 | const hostedMain = source.mode === "main" ? source.main : undefined; |
| 1059 | const localContext: RailwayLocalContextSource | undefined = |
| 1060 | source.mode === "context" ? source : undefined; |
| 1061 | const bound = collectBindingState(bindings ?? []); |
| 1062 | yield* assertHostDisk({ name, mounts: bound.mounts }); |
| 1063 | const port = hostedMain !== undefined ? (props.port ?? DEFAULT_PORT) : props.port; |
| 1064 | const rpcToken = plainEnvValue(props.rpcToken) ?? output?.rpcToken ?? ""; |
| 1065 | const env = { |
| 1066 | ...bound.env, |
| 1067 | ...(hostedMain !== undefined ? hosted.alchemyEnv : {}), |
| 1068 | ...(port !== undefined ? { PORT: String(port) } : {}), |
| 1069 | ...toEnvRecord(props.env), |
| 1070 | [RPC_TOKEN_ENV]: rpcToken, |
| 1071 | }; |
| 1072 | |
| 1073 | let sourceImage: string | undefined; |
| 1074 | let sourceRepo: string | undefined; |
| 1075 | let localPrepared: |
| 1076 | | { codeHash: string; dockerfilePath: string; tarball: Uint8Array } |
| 1077 | | undefined; |
| 1078 | let codeHash = output?.code.hash ?? ""; |
| 1079 | let hashed: |
| 1080 | | { |
| 1081 | bundled: { files: ReadonlyArray<{ path: string; content: string | Uint8Array }> }; |
| 1082 | dockerfile: string; |
| 1083 | codeHash: string; |
| 1084 | packageJson: string | undefined; |
| 1085 | } |
| 1086 | | undefined; |
| 1087 | if (source.mode === "main") { |
| 1088 | yield* (session?.note ?? ((_message: string) => Effect.void))( |
| 1089 | `Bundling ${id} program...`, |
| 1090 | ); |
| 1091 | hashed = yield* hosted.computeCodeHash({ |
| 1092 | main: source.main, |
| 1093 | handler: props.handler, |
| 1094 | port, |
| 1095 | image: props.image, |
| 1096 | env: props.env, |
| 1097 | isExternal: props.isExternal, |
| 1098 | build: props.build, |
| 1099 | extraFiles: props.extraFiles, |
| 1100 | }); |
| 1101 | codeHash = hashed.codeHash; |
| 1102 | } else if (source.mode === "context") { |
| 1103 | localPrepared = yield* prepareRailwayLocalContext(source); |
| 1104 | codeHash = localPrepared.codeHash; |
| 1105 | } else if (source.mode === "image") { |
| 1106 | sourceImage = source.image; |
| 1107 | } else { |
| 1108 | sourceRepo = source.repo; |
| 1109 | } |
| 1110 | |
| 1111 | let current: CloudService | undefined = |
| 1112 | output?.serviceId !== undefined && output.serviceId.length > 0 |
| 1113 | ? yield* getById(output.serviceId) |
| 1114 | : undefined; |
| 1115 | if (current === undefined) { |
| 1116 | current = yield* findByName(projectId, name); |
| 1117 | } |
| 1118 | |
| 1119 | const initialSource = |
| 1120 | sourceRepo !== undefined |
| 1121 | ? { repo: sourceRepo } |
| 1122 | : { image: sourceImage ?? "hashicorp/http-echo" }; |
| 1123 | const existed = current !== undefined; |
| 1124 | if (current === undefined) { |
| 1125 | const created = yield* serviceCreate({ |
| 1126 | projectId, |
| 1127 | environmentId, |
| 1128 | name, |
| 1129 | source: initialSource, |
| 1130 | ...(sourceRepo !== undefined && props.branch !== undefined |
| 1131 | ? { branch: props.branch } |
| 1132 | : {}), |
| 1133 | }).pipe(Effect.catchTag("RailwayValidationError", () => Effect.undefined)); |
| 1134 | current = created ?? (yield* findByName(projectId, name)); |
| 1135 | } |
| 1136 | |
| 1137 | if (current === undefined || isGoneService(current)) { |
| 1138 | return yield* new ServiceNotCreated({ resourceName: name, projectId }); |
| 1139 | } |
| 1140 | |
| 1141 | if (current.name !== name) { |
| 1142 | current = yield* serviceUpdate(current.id, name); |
| 1143 | } |
| 1144 | |
| 1145 | // The service instance must exist in this environment before a |
| 1146 | // domain can be generated (`railway domain` / Terraform both |
| 1147 | // operate on a live service instance). A fresh `serviceCreate` |
| 1148 | // instance lands asynchronously; an existing service may have |
| 1149 | // no instance in this environment yet. |
| 1150 | let instance = existed |
| 1151 | ? yield* ensureInstance({ |
| 1152 | environmentId, |
| 1153 | serviceId: current.id, |
| 1154 | source: initialSource, |
| 1155 | }) |
| 1156 | : yield* waitForInstance(environmentId, current.id); |
| 1157 | |
| 1158 | const publicDomain = props.publicDomain !== false; |
| 1159 | let domain: ServiceDomainRecord | undefined; |
| 1160 | if (publicDomain) { |
| 1161 | // Railway's generated-domain API refuses a service that already |
| 1162 | // has PORT (or other env) set — it returns "please try again" |
| 1163 | // forever. Create the hostname on a bare service, then sync env. |
| 1164 | yield* (session?.note ?? ((_message: string) => Effect.void))( |
| 1165 | `Creating service domain for ${id}...`, |
| 1166 | ); |
| 1167 | domain = yield* ensureServiceDomain({ |
| 1168 | projectId, |
| 1169 | environmentId, |
| 1170 | serviceId: current.id, |
| 1171 | domainId: output?.domainId ?? null, |
| 1172 | }); |
| 1173 | } else { |
| 1174 | // Only the recorded generated domain belongs to this resource. |
| 1175 | // Adoption does not populate domainId/domain, so a foreign |
| 1176 | // domain stays. Null the environment-config key — GraphQL |
| 1177 | // delete alone is not enough; Railway recreates from config. |
| 1178 | yield* deleteOwnedServiceDomain({ |
| 1179 | projectId, |
| 1180 | environmentId, |
| 1181 | serviceId: current.id, |
| 1182 | domainId: output?.domainId, |
| 1183 | domain: output?.domain, |
| 1184 | }); |
| 1185 | } |
| 1186 | |
| 1187 | const attached = yield* listServiceVolumes(environmentId, projectId, current.id); |
| 1188 | yield* assertHostDisk({ |
| 1189 | name, |
| 1190 | mounts: [ |
| 1191 | ...bound.mounts, |
| 1192 | ...attached.map((row) => ({ volumeId: row.volumeId, path: row.mountPath })), |
| 1193 | ], |
| 1194 | }); |
| 1195 | let needsDeploy = false; |
| 1196 | let localSourceChanged = |
| 1197 | localContext !== undefined && |
| 1198 | (instance?.source?.repo != null || instance?.source?.image != null); |
| 1199 | |
| 1200 | if (localSourceChanged) { |
| 1201 | yield* serviceDisconnect(current.id); |
| 1202 | needsDeploy = true; |
| 1203 | instance = (yield* getInstance(environmentId, current.id)) ?? instance; |
| 1204 | } |
| 1205 | |
| 1206 | const leavingContext = olds?.context !== undefined && olds.context.length > 0; |
| 1207 | const clearsDockerfilePath = |
| 1208 | leavingContext && |
| 1209 | (source.mode === "image" || |
| 1210 | (source.mode === "repo" && props.dockerfilePath === undefined)); |
| 1211 | const dockerfilePath = |
| 1212 | localPrepared?.dockerfilePath ?? (clearsDockerfilePath ? null : props.dockerfilePath); |
| 1213 | const instanceDelta = instanceSettingsDelta({ |
| 1214 | instance, |
| 1215 | sourceImage, |
| 1216 | sourceRepo, |
| 1217 | registryCredentials: undefined, |
| 1218 | props: { |
| 1219 | ...props, |
| 1220 | dockerfilePath, |
| 1221 | // Effect-native images must answer HTTP before Railway |
| 1222 | // stamps SUCCESS — otherwise waitForDeploymentById returns |
| 1223 | // while `/up` is still building and public GET hangs. |
| 1224 | // Default `/health`, not `/`: user fetch handlers often 404 |
| 1225 | // `/` (BucketApi) and Railway treats that as FAILED. |
| 1226 | healthcheckPath: |
| 1227 | props.healthcheckPath ?? |
| 1228 | props.healthcheck ?? |
| 1229 | (hostedMain !== undefined ? "/health" : undefined), |
| 1230 | healthcheckTimeout: |
| 1231 | props.healthcheckTimeout ?? (hostedMain !== undefined ? 300 : undefined), |
| 1232 | }, |
| 1233 | }); |
| 1234 | if (instanceDelta !== undefined) { |
| 1235 | yield* serviceInstanceUpdate({ |
| 1236 | environmentId, |
| 1237 | serviceId: current.id, |
| 1238 | input: instanceDelta, |
| 1239 | }); |
| 1240 | needsDeploy = true; |
| 1241 | instance = (yield* getInstance(environmentId, current.id)) ?? instance; |
| 1242 | } |
| 1243 | |
| 1244 | // Pin `deploy.multiRegionConfig` before the build, then again after, |
| 1245 | // in case the deploy wrote the workspace default back. |
| 1246 | const serviceId = current.id; |
| 1247 | const placeRegion = () => |
| 1248 | syncServiceRegion({ |
| 1249 | environmentId, |
| 1250 | projectId, |
| 1251 | serviceId, |
| 1252 | region: props.region, |
| 1253 | legacy: instance?.region, |
| 1254 | fallbackReplicas: instance?.numReplicas, |
| 1255 | }); |
| 1256 | let region = yield* placeRegion(); |
| 1257 | |
| 1258 | if (sourceRepo !== undefined) { |
| 1259 | const branchChanged = yield* syncBranch({ |
| 1260 | projectId, |
| 1261 | environmentId, |
| 1262 | serviceId: current.id, |
| 1263 | repo: sourceRepo, |
| 1264 | branch: props.branch, |
| 1265 | }); |
| 1266 | if (branchChanged) needsDeploy = true; |
| 1267 | } |
| 1268 | |
| 1269 | if (localContext !== undefined) { |
| 1270 | const triggersChanged = yield* clearDeploymentTriggers({ |
| 1271 | projectId, |
| 1272 | environmentId, |
| 1273 | serviceId: current.id, |
| 1274 | }); |
| 1275 | if (triggersChanged) { |
| 1276 | needsDeploy = true; |
| 1277 | localSourceChanged = true; |
| 1278 | } |
| 1279 | } |
| 1280 | |
| 1281 | yield* syncAutoUpdates({ |
| 1282 | projectId, |
| 1283 | environmentId, |
| 1284 | serviceId: current.id, |
| 1285 | enabled: props.autoUpdates, |
| 1286 | }); |
| 1287 | |
| 1288 | const envChanged = yield* syncEnv({ |
| 1289 | projectId, |
| 1290 | environmentId, |
| 1291 | serviceId: current.id, |
| 1292 | desired: env, |
| 1293 | }); |
| 1294 | if (envChanged) needsDeploy = true; |
| 1295 | |
| 1296 | if (publicDomain && port !== undefined) { |
| 1297 | domain = yield* ensureServiceDomain({ |
| 1298 | projectId, |
| 1299 | environmentId, |
| 1300 | serviceId: current.id, |
| 1301 | domainId: domain?.id, |
| 1302 | targetPort: port, |
| 1303 | }); |
| 1304 | } |
| 1305 | |
| 1306 | yield* syncMounts({ |
| 1307 | environmentId, |
| 1308 | projectId, |
| 1309 | serviceId: current.id, |
| 1310 | mounts: bound.mounts, |
| 1311 | }); |
| 1312 | |
| 1313 | const uploadSource = hostedMain !== undefined || localContext !== undefined; |
| 1314 | const latestOk = deployReady(instance?.latestDeployment?.status); |
| 1315 | const shouldUpload = |
| 1316 | uploadSource && (codeHash !== output?.code.hash || !latestOk || localSourceChanged); |
| 1317 | |
| 1318 | if (shouldUpload) { |
| 1319 | const note = session?.note ?? ((_message: string) => Effect.void); |
| 1320 | yield* note(`Preparing ${id} build context...`); |
| 1321 | const tarball = |
| 1322 | localPrepared !== undefined |
| 1323 | ? localPrepared.tarball |
| 1324 | : hostedMain !== undefined && hashed !== undefined |
| 1325 | ? yield* hosted |
| 1326 | .writeContext({ |
| 1327 | id, |
| 1328 | props: { |
| 1329 | main: hostedMain, |
| 1330 | handler: props.handler, |
| 1331 | port, |
| 1332 | image: props.image, |
| 1333 | env: props.env, |
| 1334 | isExternal: props.isExternal, |
| 1335 | build: props.build, |
| 1336 | extraFiles: props.extraFiles, |
| 1337 | }, |
| 1338 | hashed, |
| 1339 | }) |
| 1340 | .pipe(Effect.flatMap(tarGzipDirectory)) |
| 1341 | : yield* new ServiceSourceInvalid({ |
| 1342 | message: "Railway.Service upload source was not prepared", |
| 1343 | }); |
| 1344 | yield* note(`Uploading ${id} build context to Railway...`); |
| 1345 | const uploaded = yield* uploadDeployTarball({ |
| 1346 | projectId, |
| 1347 | environmentId, |
| 1348 | serviceId: current.id, |
| 1349 | tarball, |
| 1350 | message: `alchemy ${id} ${codeHash}`, |
| 1351 | }); |
| 1352 | yield* note(`Queued Railway build ${uploaded.deploymentId}`); |
| 1353 | instance = |
| 1354 | (yield* waitForDeploymentById({ |
| 1355 | deploymentId: uploaded.deploymentId, |
| 1356 | serviceId: current.id, |
| 1357 | environmentId, |
| 1358 | })) ?? instance; |
| 1359 | } else if (!uploadSource && (needsDeploy || instance?.latestDeployment == null)) { |
| 1360 | yield* serviceInstanceDeploy(environmentId, current.id).pipe( |
| 1361 | Effect.catchTag("RailwayValidationError", () => Effect.void), |
| 1362 | ); |
| 1363 | instance = |
| 1364 | sourceRepo !== undefined |
| 1365 | ? ((yield* getInstance(environmentId, current.id)) ?? instance) |
| 1366 | : ((yield* waitForDeployment(environmentId, current.id)) ?? instance); |
| 1367 | } else if (uploadSource && needsDeploy) { |
| 1368 | yield* serviceInstanceDeploy(environmentId, current.id).pipe( |
| 1369 | Effect.catchTag("RailwayValidationError", () => Effect.void), |
| 1370 | ); |
| 1371 | instance = (yield* waitForDeployment(environmentId, current.id)) ?? instance; |
| 1372 | } |
| 1373 | |
| 1374 | region = yield* placeRegion(); |
| 1375 | |
| 1376 | return toAttrs({ |
| 1377 | service: current, |
| 1378 | instance, |
| 1379 | domain, |
| 1380 | projectId, |
| 1381 | environmentId, |
| 1382 | port, |
| 1383 | codeHash, |
| 1384 | rpcToken, |
| 1385 | region, |
| 1386 | }); |
| 1387 | }), |
| 1388 | |
| 1389 | delete: Effect.fn(function* ({ output }) { |
| 1390 | const serviceId = output.serviceId; |
| 1391 | if (serviceId.length === 0) return; |
| 1392 | const environmentId = output.environmentId.length > 0 ? output.environmentId : undefined; |
| 1393 | yield* serviceDelete(serviceId, environmentId).pipe( |
| 1394 | Effect.catchTag("RailwayNotFound", () => Effect.void), |
| 1395 | ); |
| 1396 | // Other environments may still hold instances of this service, so |
| 1397 | // wait on this environment's instance rather than the service. |
| 1398 | yield* waitUntilDeleted( |
| 1399 | "Service", |
| 1400 | serviceId, |
| 1401 | environmentId !== undefined |
| 1402 | ? getInstance(environmentId, serviceId).pipe( |
| 1403 | Effect.map((instance) => instance === undefined), |
| 1404 | ) |
| 1405 | : getById(serviceId).pipe(Effect.map((service) => service === undefined)), |
| 1406 | ); |
| 1407 | }), |
| 1408 | }); |
| 1409 | }), |
| 1410 | ); |