The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import { Query, type UnwrapPlan } from "@distilled.cloud/core/query"; |
| 2 | import { |
| 3 | Railway, |
| 4 | type Project as RailwayProject, |
| 5 | type Service as RailwayService, |
| 6 | type Template as RailwayTemplate, |
| 7 | type TemplateDeployV2Input, |
| 8 | } from "@distilled.cloud/railway"; |
| 9 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 10 | import { isResolved } from "alchemy/Diff"; |
| 11 | import * as Provider from "alchemy/Provider"; |
| 12 | import { Resource } from "alchemy/Resource"; |
| 13 | import * as Data from "effect/Data"; |
| 14 | import * as Effect from "effect/Effect"; |
| 15 | import * as Schedule from "effect/Schedule"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import { RailwayEnvironment } from "./Environment.ts"; |
| 18 | import { projectServices as fetchProjectServices } from "./GraphQL.ts"; |
| 19 | import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts"; |
| 20 | import { |
| 21 | createProject, |
| 22 | environmentIdOf as projectEnvironmentId, |
| 23 | ownedProjects, |
| 24 | workspaceIdOf as projectWorkspaceId, |
| 25 | } from "./Project.ts"; |
| 26 | import type { Providers } from "./Providers.ts"; |
| 27 | |
| 28 | const templateFields = <E>(template: Query<RailwayTemplate, E>) => ({ |
| 29 | id: template.id, |
| 30 | code: template.code, |
| 31 | name: template.name, |
| 32 | serializedConfig: template.serializedConfig, |
| 33 | }); |
| 34 | const templateSummaryFields = <E>(template: Query<RailwayTemplate, E>) => ({ |
| 35 | id: template.id, |
| 36 | code: template.code, |
| 37 | name: template.name, |
| 38 | }); |
| 39 | const projectFields = <E>(project: Query<RailwayProject, E>) => ({ |
| 40 | id: project.id, |
| 41 | name: project.name, |
| 42 | description: project.description, |
| 43 | workspaceId: project.workspaceId, |
| 44 | primaryEnvironmentId: project.primaryEnvironmentId, |
| 45 | baseEnvironmentId: project.baseEnvironmentId, |
| 46 | deletedAt: project.deletedAt, |
| 47 | }); |
| 48 | const serviceFields = <E>(service: Query<RailwayService, E>) => ({ |
| 49 | id: service.id, |
| 50 | name: service.name, |
| 51 | deletedAt: service.deletedAt, |
| 52 | templateId: service.templateId, |
| 53 | }); |
| 54 | type CloudTemplate = UnwrapPlan<ReturnType<typeof templateFields>>; |
| 55 | type CloudProject = UnwrapPlan<ReturnType<typeof projectFields>>; |
| 56 | type CloudService = UnwrapPlan<ReturnType<typeof serviceFields>>; |
| 57 | |
| 58 | /** |
| 59 | * A resource-valued prop: the resource itself, or an Effect that produces |
| 60 | * it (so `yield* Project(...)` and `Project(...)` both type-check). |
| 61 | */ |
| 62 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 63 | |
| 64 | /** |
| 65 | * Project identity a template deploys into. Accepts a `Railway.Project` |
| 66 | * or a `{ projectId }` stub. |
| 67 | */ |
| 68 | export type TemplateProject = { |
| 69 | readonly projectId: string; |
| 70 | readonly environmentId?: string; |
| 71 | readonly workspaceId?: string; |
| 72 | }; |
| 73 | |
| 74 | /** |
| 75 | * Environment identity a template deploys into. Accepts a |
| 76 | * `Railway.Project` (its primary environment), a `Railway.Environment`, |
| 77 | * or an `{ environmentId }` stub. |
| 78 | */ |
| 79 | export type TemplateEnvironment = { readonly environmentId: string }; |
| 80 | |
| 81 | export interface TemplateProps { |
| 82 | /** |
| 83 | * Marketplace template id (UUID) or template code (`postgres`, |
| 84 | * `redis`). Changing it replaces the deployment. |
| 85 | */ |
| 86 | templateId: string; |
| 87 | /** |
| 88 | * Project to deploy into. Accepts a `Railway.Project` or an Effect |
| 89 | * that produces one. If omitted, Alchemy creates an owned Project |
| 90 | * (serialized `createProject`) and deploys into it. Changing it |
| 91 | * replaces the deployment. |
| 92 | */ |
| 93 | project?: Ref<TemplateProject>; |
| 94 | /** |
| 95 | * Environment to deploy into. Accepts a `Railway.Project` (primary |
| 96 | * environment), a `Railway.Environment`, or `{ environmentId }`. |
| 97 | * Defaults to the project's primary environment. Changing it |
| 98 | * replaces the deployment. |
| 99 | */ |
| 100 | environment?: Ref<TemplateEnvironment>; |
| 101 | /** |
| 102 | * Serialized template config passed to `templateDeployV2`. If omitted, |
| 103 | * Alchemy fetches it from the marketplace template. Variables without |
| 104 | * a `value` are filled from `defaultValue`. |
| 105 | */ |
| 106 | serializedConfig?: unknown; |
| 107 | } |
| 108 | |
| 109 | export type Template = Resource< |
| 110 | "Railway.Template", |
| 111 | TemplateProps, |
| 112 | { |
| 113 | /** Canonical marketplace template id (UUID). */ |
| 114 | templateId: string; |
| 115 | /** Marketplace template code (`postgres`, …), when its metadata is accessible. */ |
| 116 | code: string | undefined; |
| 117 | /** Marketplace template display name, when its metadata is accessible. */ |
| 118 | name: string | undefined; |
| 119 | /** Project the template was deployed into. */ |
| 120 | projectId: string; |
| 121 | /** Environment the template was deployed into. */ |
| 122 | environmentId: string; |
| 123 | /** Workspace the project lives in. */ |
| 124 | workspaceId: string; |
| 125 | /** Latest `templateDeployV2` workflow id, if Railway returned one. */ |
| 126 | workflowId: string | undefined; |
| 127 | /** Service ids created from the template. */ |
| 128 | serviceIds: string[]; |
| 129 | /** |
| 130 | * True when Alchemy created the Project because `project` was |
| 131 | * omitted. Delete then removes that Project. |
| 132 | */ |
| 133 | ownsProject: boolean; |
| 134 | /** Dashboard URL (`https://railway.com/project/{projectId}`). */ |
| 135 | url: string; |
| 136 | }, |
| 137 | never, |
| 138 | Providers |
| 139 | >; |
| 140 | |
| 141 | const resolveTemplateProps = ( |
| 142 | props: TemplateProps | Effect.Effect<TemplateProps, never, Providers>, |
| 143 | ): Effect.Effect<TemplateProps, never, Providers> => |
| 144 | Effect.gen(function* () { |
| 145 | const resolved = Effect.isEffect(props) ? yield* props : props; |
| 146 | if (globalThis.__ALCHEMY_RUNTIME__) return resolved; |
| 147 | const project = |
| 148 | resolved.project === undefined |
| 149 | ? undefined |
| 150 | : Effect.isEffect(resolved.project) |
| 151 | ? yield* resolved.project as Effect.Effect<TemplateProject, never, Providers> |
| 152 | : resolved.project; |
| 153 | const environment = |
| 154 | resolved.environment === undefined |
| 155 | ? undefined |
| 156 | : Effect.isEffect(resolved.environment) |
| 157 | ? yield* resolved.environment as Effect.Effect<TemplateEnvironment, never, Providers> |
| 158 | : resolved.environment; |
| 159 | return { ...resolved, project, environment }; |
| 160 | }); |
| 161 | |
| 162 | const TemplateResource = Resource<Template>("Railway.Template"); |
| 163 | |
| 164 | /** |
| 165 | * A Railway.Template deploys a marketplace template into a Project. |
| 166 | * Alchemy looks up the template (`template` / `templates`), sends |
| 167 | * `templateDeployV2` with its `serializedConfig`, and adopts the |
| 168 | * project/services the workflow creates. |
| 169 | * |
| 170 | * Pass a Project to deploy into an existing one. Omit `project` and |
| 171 | * Alchemy creates an owned Project first (the workspace project-create |
| 172 | * cap is serialized). |
| 173 | * |
| 174 | * @see https://docs.railway.com/templates/deploy |
| 175 | * |
| 176 | * ### Deploy a marketplace template |
| 177 | * `templateId` is a marketplace UUID or code (`postgres`). Pass a |
| 178 | * Project to deploy into it. |
| 179 | * |
| 180 | * **Example:** Postgres into a Project |
| 181 | * ```typescript |
| 182 | * const site = yield* Railway.Project("Site"); |
| 183 | * const db = yield* Railway.Template("Postgres", { |
| 184 | * templateId: "postgres", |
| 185 | * project: site, |
| 186 | * }); |
| 187 | * ``` |
| 188 | * |
| 189 | * :::caution[Changing `templateId`, `project`, or `environment` replaces] |
| 190 | * The previous template services (and the owned Project, if Alchemy |
| 191 | * created it) are deleted. A new deploy runs. |
| 192 | * ::: |
| 193 | * |
| 194 | * ### Create the Project |
| 195 | * Omit `project` to let Alchemy create one. The name is stamped so |
| 196 | * nuke can reclaim it. |
| 197 | * |
| 198 | * **Example:** Generated Project |
| 199 | * ```typescript |
| 200 | * const db = yield* Railway.Template("Postgres", { |
| 201 | * templateId: "postgres", |
| 202 | * }); |
| 203 | * ``` |
| 204 | * |
| 205 | * ### Serialized config |
| 206 | * Omit `serializedConfig` to use the marketplace default. Pass a |
| 207 | * config (from `template.serializedConfig`, with service variable |
| 208 | * `value`s filled in) to override. |
| 209 | * |
| 210 | * **Example:** Override config |
| 211 | * ```typescript |
| 212 | * const db = yield* Railway.Template("Postgres", { |
| 213 | * templateId: "postgres", |
| 214 | * project: site, |
| 215 | * serializedConfig: config, |
| 216 | * }); |
| 217 | * ``` |
| 218 | * |
| 219 | * ### Environment |
| 220 | * Defaults to the Project's primary environment. |
| 221 | * |
| 222 | * **Example:** Extra environment |
| 223 | * ```typescript |
| 224 | * const staging = yield* Railway.Environment("Staging", { project: site }); |
| 225 | * const db = yield* Railway.Template("StagingPostgres", { |
| 226 | * templateId: "postgres", |
| 227 | * project: site, |
| 228 | * environment: staging, |
| 229 | * }); |
| 230 | * ``` |
| 231 | * |
| 232 | * ### Module-scope declarations |
| 233 | * Resource-valued props accept the resource or an Effect producing it. |
| 234 | * |
| 235 | * **Example:** Module-scope Template |
| 236 | * ```typescript |
| 237 | * // src/db.ts |
| 238 | * import * as Railway from "@alchemy.run/railway"; |
| 239 | * |
| 240 | * export const Site = Railway.Project("Site"); |
| 241 | * export const Postgres = Railway.Template("Postgres", { |
| 242 | * templateId: "postgres", |
| 243 | * project: Site, |
| 244 | * }); |
| 245 | * ``` |
| 246 | * |
| 247 | * @resource |
| 248 | * @product Project |
| 249 | */ |
| 250 | export const Template: typeof TemplateResource = Object.assign( |
| 251 | (id: string, props: TemplateProps | Effect.Effect<TemplateProps, never, Providers>) => |
| 252 | TemplateResource(id, resolveTemplateProps(props)), |
| 253 | TemplateResource, |
| 254 | ); |
| 255 | |
| 256 | export class TemplateNotFound extends Data.TaggedError("Railway.TemplateNotFound")<{ |
| 257 | templateId: string; |
| 258 | }> {} |
| 259 | |
| 260 | export class TemplateNotCreated extends Data.TaggedError("Railway.TemplateNotCreated")<{ |
| 261 | templateId: string; |
| 262 | projectId: string; |
| 263 | }> {} |
| 264 | |
| 265 | export class TemplateConfigRequired extends Data.TaggedError("Railway.TemplateConfigRequired")<{ |
| 266 | templateId: string; |
| 267 | }> {} |
| 268 | |
| 269 | export class TemplateWorkflowFailed extends Data.TaggedError("Railway.TemplateWorkflowFailed")<{ |
| 270 | workflowId: string; |
| 271 | error: string; |
| 272 | }> {} |
| 273 | |
| 274 | class TemplatePending extends Data.TaggedError("Railway.TemplatePending")<{ |
| 275 | projectId: string; |
| 276 | state: string; |
| 277 | }> {} |
| 278 | |
| 279 | const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; |
| 280 | |
| 281 | const projectIdOf = (value: unknown): string | undefined => { |
| 282 | if (value === null || typeof value !== "object") return undefined; |
| 283 | const rec = value as { projectId?: unknown }; |
| 284 | return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined; |
| 285 | }; |
| 286 | |
| 287 | const environmentIdOf = (value: unknown): string | undefined => { |
| 288 | if (value === null || typeof value !== "object") return undefined; |
| 289 | const rec = value as { environmentId?: unknown }; |
| 290 | return typeof rec.environmentId === "string" && rec.environmentId.length > 0 |
| 291 | ? rec.environmentId |
| 292 | : undefined; |
| 293 | }; |
| 294 | |
| 295 | const workspaceIdOf = (value: unknown): string | undefined => { |
| 296 | if (value === null || typeof value !== "object") return undefined; |
| 297 | const rec = value as { workspaceId?: unknown }; |
| 298 | return typeof rec.workspaceId === "string" && rec.workspaceId.length > 0 |
| 299 | ? rec.workspaceId |
| 300 | : undefined; |
| 301 | }; |
| 302 | |
| 303 | const isRecord = (value: unknown): value is Record<string, unknown> => |
| 304 | value !== null && typeof value === "object" && !Array.isArray(value); |
| 305 | |
| 306 | const isGoneProject = (project: CloudProject | undefined) => |
| 307 | project === undefined || project.deletedAt != null; |
| 308 | |
| 309 | const isGoneService = (service: CloudService | undefined) => |
| 310 | service === undefined || service.deletedAt != null; |
| 311 | |
| 312 | const currentWorkspaceId = Effect.fn(function* () { |
| 313 | const env = yield* yield* RailwayEnvironment; |
| 314 | return env.workspaceId; |
| 315 | }); |
| 316 | |
| 317 | const environmentIdFromProject = (project: CloudProject) => projectEnvironmentId(project); |
| 318 | |
| 319 | const toAttrs = (input: { |
| 320 | template: { id: string; code?: string; name?: string }; |
| 321 | project: CloudProject; |
| 322 | environmentId: string; |
| 323 | workspaceId: string; |
| 324 | serviceIds: string[]; |
| 325 | workflowId: string | undefined; |
| 326 | ownsProject: boolean; |
| 327 | }): Template["Attributes"] => ({ |
| 328 | templateId: input.template.id, |
| 329 | code: input.template.code, |
| 330 | name: input.template.name, |
| 331 | projectId: input.project.id, |
| 332 | environmentId: input.environmentId, |
| 333 | workspaceId: input.workspaceId || projectWorkspaceId(input.project) || "", |
| 334 | workflowId: input.workflowId, |
| 335 | serviceIds: input.serviceIds, |
| 336 | ownsProject: input.ownsProject, |
| 337 | url: `https://railway.com/project/${input.project.id}`, |
| 338 | }); |
| 339 | |
| 340 | const readProject = Query.fn((id: string) => projectFields(Railway.project({ id }))); |
| 341 | |
| 342 | const getProject = (projectId: string) => |
| 343 | readProject(projectId).pipe( |
| 344 | Effect.map((project) => (isGoneProject(project) ? undefined : project)), |
| 345 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 346 | ); |
| 347 | |
| 348 | const readTemplateById = Query.fn((id: string) => templateFields(Railway.template({ id }))); |
| 349 | |
| 350 | const readTemplateByCode = Query.fn((code: string) => templateFields(Railway.template({ code }))); |
| 351 | |
| 352 | const readTemplateSummary = Query.fn((id: string) => |
| 353 | templateSummaryFields(Railway.template({ id })), |
| 354 | ); |
| 355 | |
| 356 | const getTemplateById = (id: string) => |
| 357 | readTemplateById(id).pipe(Effect.map((template): CloudTemplate | undefined => template)); |
| 358 | |
| 359 | const getTemplateByCode = (code: string) => |
| 360 | readTemplateByCode(code).pipe(Effect.map((template): CloudTemplate | undefined => template)); |
| 361 | |
| 362 | const findPublished = (needle: string) => |
| 363 | Query.items( |
| 364 | Railway.templates({ first: 50 }).pipe( |
| 365 | Query.map((template) => ({ id: template.id, code: template.code })), |
| 366 | ), |
| 367 | ).pipe( |
| 368 | Stream.filter((template) => template.id === needle || template.code === needle), |
| 369 | Stream.take(1), |
| 370 | Stream.runHead, |
| 371 | Effect.flatMap((option) => |
| 372 | option._tag === "Some" ? getTemplateByCode(option.value.code) : Effect.undefined, |
| 373 | ), |
| 374 | ); |
| 375 | |
| 376 | const resolveMarketplaceTemplate = (templateId: string) => |
| 377 | Effect.gen(function* () { |
| 378 | const primary = UUID.test(templateId) |
| 379 | ? yield* getTemplateById(templateId).pipe( |
| 380 | Effect.catchTag("RailwayForbidden", (failure) => |
| 381 | findPublished(templateId).pipe( |
| 382 | Effect.flatMap((template) => |
| 383 | template === undefined ? Effect.fail(failure) : Effect.succeed(template), |
| 384 | ), |
| 385 | ), |
| 386 | ), |
| 387 | ) |
| 388 | : yield* getTemplateByCode(templateId); |
| 389 | if (primary != null) return primary; |
| 390 | const secondary = UUID.test(templateId) |
| 391 | ? yield* getTemplateByCode(templateId) |
| 392 | : yield* getTemplateById(templateId); |
| 393 | if (secondary != null) return secondary; |
| 394 | return yield* findPublished(templateId); |
| 395 | }); |
| 396 | |
| 397 | const readSourceForProject = Query.fn((projectId: string) => |
| 398 | Railway.templateSourceForProject({ projectId }).pipe( |
| 399 | Query.map((source) => ({ id: source.id, code: source.code, name: source.name })), |
| 400 | ), |
| 401 | ); |
| 402 | |
| 403 | const sourceForProject = (projectId: string) => |
| 404 | readSourceForProject(projectId).pipe( |
| 405 | Effect.map((value) => value ?? undefined), |
| 406 | Effect.catchTag("RailwayForbidden", () => Effect.undefined), |
| 407 | ); |
| 408 | |
| 409 | const listProjectServices = (projectId: string) => |
| 410 | fetchProjectServices(projectId, serviceFields).pipe( |
| 411 | Effect.map((services) => services.filter((node) => !isGoneService(node))), |
| 412 | Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudService[])), |
| 413 | ); |
| 414 | |
| 415 | const readService = Query.fn((id: string) => serviceFields(Railway.service({ id }))); |
| 416 | |
| 417 | const hydrateService = (serviceId: string) => |
| 418 | readService(serviceId).pipe( |
| 419 | Effect.map((service) => (isGoneService(service) ? undefined : service)), |
| 420 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 421 | ); |
| 422 | |
| 423 | const hydrateServices = (services: readonly CloudService[]) => |
| 424 | Effect.forEach(services, (service) => hydrateService(service.id), { concurrency: 4 }).pipe( |
| 425 | Effect.map((rows) => rows.filter((row): row is CloudService => row !== undefined)), |
| 426 | ); |
| 427 | |
| 428 | const matchingServices = (input: { |
| 429 | services: readonly CloudService[]; |
| 430 | templateId: string; |
| 431 | sourceId: string | undefined; |
| 432 | ownsProject: boolean; |
| 433 | }): CloudService[] => { |
| 434 | const byTemplate = input.services.filter((service) => service.templateId === input.templateId); |
| 435 | if (byTemplate.length > 0) return byTemplate; |
| 436 | if (input.sourceId === input.templateId || input.ownsProject) { |
| 437 | return [...input.services]; |
| 438 | } |
| 439 | return []; |
| 440 | }; |
| 441 | |
| 442 | const parseConfig = (config: unknown) => |
| 443 | Effect.sync(() => { |
| 444 | if (typeof config !== "string") return config; |
| 445 | try { |
| 446 | return JSON.parse(config) as unknown; |
| 447 | } catch { |
| 448 | return config; |
| 449 | } |
| 450 | }); |
| 451 | |
| 452 | const normalizeVariables = (variables: unknown): unknown => { |
| 453 | if (!isRecord(variables)) return variables; |
| 454 | const out: Record<string, unknown> = {}; |
| 455 | for (const [key, item] of Object.entries(variables)) { |
| 456 | if (!isRecord(item)) { |
| 457 | out[key] = item; |
| 458 | continue; |
| 459 | } |
| 460 | const value = |
| 461 | typeof item.value === "string" |
| 462 | ? item.value |
| 463 | : typeof item.defaultValue === "string" |
| 464 | ? item.defaultValue |
| 465 | : ""; |
| 466 | out[key] = { ...item, value }; |
| 467 | } |
| 468 | return out; |
| 469 | }; |
| 470 | |
| 471 | const normalizeConfig = (config: unknown): unknown => { |
| 472 | if (!isRecord(config) || !isRecord(config.services)) return config; |
| 473 | const services: Record<string, unknown> = {}; |
| 474 | for (const [id, service] of Object.entries(config.services)) { |
| 475 | if (!isRecord(service)) { |
| 476 | services[id] = service; |
| 477 | continue; |
| 478 | } |
| 479 | services[id] = |
| 480 | service.variables === undefined |
| 481 | ? service |
| 482 | : { ...service, variables: normalizeVariables(service.variables) }; |
| 483 | } |
| 484 | return { ...config, services }; |
| 485 | }; |
| 486 | |
| 487 | const readWorkflowStatus = Query.fn((workflowId: string) => { |
| 488 | const result = Railway.workflowStatus({ workflowId }); |
| 489 | return { status: result.status, error: result.error }; |
| 490 | }); |
| 491 | |
| 492 | const waitForWorkflow = (workflowId: string, projectId: string) => |
| 493 | Effect.gen(function* () { |
| 494 | const result = yield* readWorkflowStatus(workflowId); |
| 495 | if (result.status === "Complete") return result; |
| 496 | if (result.status === "Error") { |
| 497 | return yield* new TemplateWorkflowFailed({ |
| 498 | workflowId, |
| 499 | error: result.error ?? "template deploy failed", |
| 500 | }); |
| 501 | } |
| 502 | return yield* new TemplatePending({ projectId, state: result.status }); |
| 503 | }).pipe( |
| 504 | Effect.retry({ |
| 505 | while: (e) => e._tag === "Railway.TemplatePending", |
| 506 | times: 10, |
| 507 | schedule: Schedule.spaced("3 seconds"), |
| 508 | }), |
| 509 | ); |
| 510 | |
| 511 | const waitForServices = (input: { |
| 512 | projectId: string; |
| 513 | templateId: string; |
| 514 | sourceId: string | undefined; |
| 515 | ownsProject: boolean; |
| 516 | }) => |
| 517 | listProjectServices(input.projectId).pipe( |
| 518 | Effect.flatMap((listed) => hydrateServices(listed)), |
| 519 | Effect.flatMap((services) => { |
| 520 | const matched = matchingServices({ |
| 521 | services, |
| 522 | templateId: input.templateId, |
| 523 | sourceId: input.sourceId, |
| 524 | ownsProject: input.ownsProject, |
| 525 | }); |
| 526 | if (matched.length === 0) { |
| 527 | return Effect.fail(new TemplatePending({ projectId: input.projectId, state: "services" })); |
| 528 | } |
| 529 | return Effect.succeed(matched); |
| 530 | }), |
| 531 | Effect.retry({ |
| 532 | while: (e) => e._tag === "Railway.TemplatePending", |
| 533 | times: 8, |
| 534 | schedule: Schedule.spaced("2 seconds"), |
| 535 | }), |
| 536 | ); |
| 537 | |
| 538 | const waitUntilServiceGone = (serviceId: string, projectId: string) => |
| 539 | hydrateService(serviceId).pipe( |
| 540 | Effect.flatMap((service) => |
| 541 | service === undefined |
| 542 | ? Effect.void |
| 543 | : Effect.fail(new TemplatePending({ projectId, state: `service ${serviceId} deletion` })), |
| 544 | ), |
| 545 | Effect.retry({ |
| 546 | schedule: Schedule.spaced("1 second"), |
| 547 | while: (error) => error._tag === "Railway.TemplatePending", |
| 548 | times: 8, |
| 549 | }), |
| 550 | ); |
| 551 | |
| 552 | const waitUntilProjectGone = (projectId: string) => |
| 553 | getProject(projectId).pipe( |
| 554 | Effect.flatMap((project) => |
| 555 | project === undefined |
| 556 | ? Effect.void |
| 557 | : Effect.fail(new TemplatePending({ projectId, state: "project deletion" })), |
| 558 | ), |
| 559 | Effect.retry({ |
| 560 | schedule: Schedule.spaced("1 second"), |
| 561 | while: (error) => error._tag === "Railway.TemplatePending", |
| 562 | times: 8, |
| 563 | }), |
| 564 | ); |
| 565 | |
| 566 | const templateDeploy = Query.fn((input: TemplateDeployV2Input) => { |
| 567 | const deployed = Railway.templateDeployV2({ input }); |
| 568 | return { projectId: deployed.projectId, workflowId: deployed.workflowId }; |
| 569 | }); |
| 570 | |
| 571 | const serviceDelete = Query.fn((id: string) => Railway.serviceDelete({ id })); |
| 572 | |
| 573 | const projectDelete = Query.fn((id: string) => Railway.projectDelete({ id })); |
| 574 | |
| 575 | const observeDeployment = Effect.fn(function* (input: { |
| 576 | projectId: string; |
| 577 | templateId: string; |
| 578 | ownsProject: boolean; |
| 579 | }) { |
| 580 | const project = yield* getProject(input.projectId); |
| 581 | if (project === undefined) { |
| 582 | return undefined; |
| 583 | } |
| 584 | const source = yield* sourceForProject(input.projectId); |
| 585 | const listed = yield* listProjectServices(input.projectId); |
| 586 | const services = yield* hydrateServices(listed); |
| 587 | const matched = matchingServices({ |
| 588 | services, |
| 589 | templateId: input.templateId, |
| 590 | sourceId: source?.id, |
| 591 | ownsProject: input.ownsProject, |
| 592 | }); |
| 593 | return { project, source, services: matched }; |
| 594 | }); |
| 595 | |
| 596 | export const TemplateProvider = () => |
| 597 | Provider.succeed(Template, { |
| 598 | stables: ["templateId", "code", "projectId", "workspaceId"], |
| 599 | nuke: { dependsOn: ["Railway.Project"] }, |
| 600 | |
| 601 | diff: Effect.fn(function* ({ news, output }) { |
| 602 | if (news === undefined || !isResolved(news)) return undefined; |
| 603 | if (output === undefined) return undefined; |
| 604 | const templateChanged = |
| 605 | news.templateId !== output.templateId && news.templateId !== output.code; |
| 606 | const nextProject = projectIdOf(news.project); |
| 607 | const projectChanged = nextProject !== undefined && nextProject !== output.projectId; |
| 608 | const nextEnv = environmentIdOf(news.environment); |
| 609 | const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId; |
| 610 | if (templateChanged || projectChanged || environmentChanged) { |
| 611 | return { action: "replace" as const }; |
| 612 | } |
| 613 | return undefined; |
| 614 | }), |
| 615 | |
| 616 | read: Effect.fn(function* ({ olds, output }) { |
| 617 | const templateRef = output?.templateId ?? olds?.templateId; |
| 618 | if (templateRef === undefined || templateRef.length === 0) { |
| 619 | return undefined; |
| 620 | } |
| 621 | const marketplace = yield* resolveMarketplaceTemplate(templateRef); |
| 622 | const templateId = marketplace?.id ?? output?.templateId ?? templateRef; |
| 623 | const projectId = |
| 624 | output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined); |
| 625 | if (projectId === undefined) return undefined; |
| 626 | const ownsProject = output?.ownsProject ?? olds?.project === undefined; |
| 627 | const observed = yield* observeDeployment({ projectId, templateId, ownsProject }); |
| 628 | if (observed === undefined || observed.services.length === 0) { |
| 629 | return undefined; |
| 630 | } |
| 631 | const template = marketplace ?? observed.source; |
| 632 | if (template === undefined) return undefined; |
| 633 | const environmentId = |
| 634 | output?.environmentId ?? |
| 635 | (olds !== undefined |
| 636 | ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project)) |
| 637 | : undefined) ?? |
| 638 | environmentIdFromProject(observed.project); |
| 639 | const workspaceId = |
| 640 | output?.workspaceId ?? |
| 641 | (olds !== undefined ? workspaceIdOf(olds.project) : undefined) ?? |
| 642 | projectWorkspaceId(observed.project); |
| 643 | const attrs = toAttrs({ |
| 644 | template, |
| 645 | project: observed.project, |
| 646 | environmentId, |
| 647 | workspaceId, |
| 648 | serviceIds: observed.services.map((service) => service.id), |
| 649 | workflowId: output?.workflowId, |
| 650 | ownsProject, |
| 651 | }); |
| 652 | if (output !== undefined) return attrs; |
| 653 | return matchesAlchemyPhysicalName(observed.project.name) ? attrs : Unowned(attrs); |
| 654 | }), |
| 655 | |
| 656 | list: Effect.fn(function* () { |
| 657 | const projects = yield* ownedProjects(); |
| 658 | const rows = yield* Effect.forEach(projects, (project) => |
| 659 | Effect.gen(function* () { |
| 660 | const live = yield* readProject(project.projectId).pipe( |
| 661 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 662 | ); |
| 663 | if (live === undefined || live.deletedAt != null) { |
| 664 | return [] as Template["Attributes"][]; |
| 665 | } |
| 666 | const services = yield* listProjectServices(project.projectId); |
| 667 | const source = yield* sourceForProject(project.projectId); |
| 668 | const deployments = new Map<string, CloudService[]>(); |
| 669 | for (const service of services) { |
| 670 | const templateId = service.templateId ?? source?.id; |
| 671 | if (templateId == null) continue; |
| 672 | const group = deployments.get(templateId) ?? []; |
| 673 | group.push(service); |
| 674 | deployments.set(templateId, group); |
| 675 | } |
| 676 | return yield* Effect.forEach(deployments, ([templateId, members]) => |
| 677 | Effect.gen(function* () { |
| 678 | const template = |
| 679 | source?.id === templateId |
| 680 | ? source |
| 681 | : yield* readTemplateSummary(templateId).pipe( |
| 682 | Effect.catchTag("RailwayForbidden", () => Effect.succeed({ id: templateId })), |
| 683 | ); |
| 684 | return toAttrs({ |
| 685 | template: template ?? { id: templateId }, |
| 686 | project: live, |
| 687 | environmentId: project.environmentId, |
| 688 | workspaceId: project.workspaceId, |
| 689 | serviceIds: members.map((service) => service.id), |
| 690 | workflowId: undefined, |
| 691 | ownsProject: false, |
| 692 | }); |
| 693 | }), |
| 694 | ); |
| 695 | }), |
| 696 | ); |
| 697 | const seen = new Set<string>(); |
| 698 | const unique: Template["Attributes"][] = []; |
| 699 | for (const row of rows.flat()) { |
| 700 | const key = `${row.projectId}:${row.templateId}`; |
| 701 | if (seen.has(key)) continue; |
| 702 | seen.add(key); |
| 703 | unique.push(row); |
| 704 | } |
| 705 | return unique; |
| 706 | }), |
| 707 | |
| 708 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 709 | const props = news ?? ({} as TemplateProps); |
| 710 | const templateRef = props.templateId ?? output?.templateId; |
| 711 | if (templateRef === undefined || templateRef.length === 0) { |
| 712 | return yield* new TemplateNotFound({ templateId: "" }); |
| 713 | } |
| 714 | const marketplace = yield* resolveMarketplaceTemplate(templateRef); |
| 715 | if (marketplace === undefined) { |
| 716 | return yield* new TemplateNotFound({ templateId: templateRef }); |
| 717 | } |
| 718 | |
| 719 | const providedProject = props.project !== undefined; |
| 720 | let ownsProject = providedProject ? false : (output?.ownsProject ?? true); |
| 721 | let projectId = projectIdOf(props.project) ?? output?.projectId; |
| 722 | let environmentId = |
| 723 | environmentIdOf(props.environment) ?? |
| 724 | environmentIdOf(props.project) ?? |
| 725 | output?.environmentId; |
| 726 | let workspaceId = |
| 727 | workspaceIdOf(props.project) ?? output?.workspaceId ?? (yield* currentWorkspaceId()); |
| 728 | |
| 729 | let current: CloudProject | undefined = |
| 730 | projectId !== undefined && projectId.length > 0 ? yield* getProject(projectId) : undefined; |
| 731 | |
| 732 | if (current === undefined && !providedProject) { |
| 733 | const name = yield* createRailwayName(id); |
| 734 | const created = yield* createProject({ name, workspaceId }).pipe( |
| 735 | Effect.catchTag("RailwayValidationError", () => Effect.undefined), |
| 736 | ); |
| 737 | current = created; |
| 738 | ownsProject = true; |
| 739 | } |
| 740 | |
| 741 | if (current === undefined || isGoneProject(current)) { |
| 742 | return yield* new TemplateNotCreated({ |
| 743 | templateId: marketplace.id, |
| 744 | projectId: projectId ?? "", |
| 745 | }); |
| 746 | } |
| 747 | |
| 748 | projectId = current.id; |
| 749 | environmentId = |
| 750 | environmentId && environmentId.length > 0 |
| 751 | ? environmentId |
| 752 | : environmentIdFromProject(current); |
| 753 | workspaceId = projectWorkspaceId(current, workspaceId); |
| 754 | |
| 755 | const observed = yield* observeDeployment({ |
| 756 | projectId, |
| 757 | templateId: marketplace.id, |
| 758 | ownsProject, |
| 759 | }); |
| 760 | let services = observed?.services ?? []; |
| 761 | let workflowId = output?.workflowId; |
| 762 | |
| 763 | if (services.length === 0) { |
| 764 | const rawConfig = props.serializedConfig ?? marketplace.serializedConfig; |
| 765 | if (rawConfig == null) { |
| 766 | return yield* new TemplateConfigRequired({ templateId: marketplace.id }); |
| 767 | } |
| 768 | const parsed = yield* parseConfig(rawConfig); |
| 769 | const serializedConfig = normalizeConfig(parsed); |
| 770 | const deployed = yield* templateDeploy({ |
| 771 | templateId: marketplace.id, |
| 772 | serializedConfig, |
| 773 | projectId, |
| 774 | ...(environmentId.length > 0 ? { environmentId } : {}), |
| 775 | workspaceId, |
| 776 | }); |
| 777 | projectId = deployed.projectId || projectId; |
| 778 | workflowId = deployed.workflowId ?? workflowId; |
| 779 | if (deployed.projectId.length > 0 && deployed.projectId !== current.id) { |
| 780 | const created = yield* getProject(deployed.projectId); |
| 781 | if (created !== undefined) current = created; |
| 782 | } |
| 783 | if (workflowId !== undefined && workflowId.length > 0) { |
| 784 | yield* waitForWorkflow(workflowId, projectId); |
| 785 | } |
| 786 | const source = yield* sourceForProject(projectId); |
| 787 | services = yield* waitForServices({ |
| 788 | projectId, |
| 789 | templateId: marketplace.id, |
| 790 | sourceId: source?.id, |
| 791 | ownsProject, |
| 792 | }); |
| 793 | } |
| 794 | |
| 795 | if (services.length === 0) { |
| 796 | return yield* new TemplateNotCreated({ templateId: marketplace.id, projectId }); |
| 797 | } |
| 798 | |
| 799 | const live = (yield* getProject(projectId)) ?? current; |
| 800 | if (environmentId.length === 0) { |
| 801 | environmentId = environmentIdFromProject(live); |
| 802 | } |
| 803 | |
| 804 | return toAttrs({ |
| 805 | template: marketplace, |
| 806 | project: live, |
| 807 | environmentId, |
| 808 | workspaceId, |
| 809 | serviceIds: services.map((service) => service.id), |
| 810 | workflowId, |
| 811 | ownsProject, |
| 812 | }); |
| 813 | }), |
| 814 | |
| 815 | delete: Effect.fn(function* ({ output }) { |
| 816 | const serviceIds = output.serviceIds ?? []; |
| 817 | for (const serviceId of serviceIds) { |
| 818 | if (serviceId.length === 0) continue; |
| 819 | yield* serviceDelete(serviceId).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void)); |
| 820 | yield* waitUntilServiceGone(serviceId, output.projectId); |
| 821 | } |
| 822 | if (!output.ownsProject) return; |
| 823 | const projectId = output.projectId; |
| 824 | if (projectId.length === 0) return; |
| 825 | yield* projectDelete(projectId).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void)); |
| 826 | yield* waitUntilProjectGone(projectId); |
| 827 | }), |
| 828 | }); |