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 { Railway, type Project as RailwayProject } from "@distilled.cloud/railway"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { RailwayEnvironment } from "./Environment.ts"; |
| 11 | import { waitUntilDeleted } from "./GraphQL.ts"; |
| 12 | import { createRailwayName, matchesAlchemyPhysicalName, sanitizeRailwayName } from "./Metadata.ts"; |
| 13 | import type { Providers } from "./Providers.ts"; |
| 14 | import { waitOutCreateRateLimit } from "./transient.ts"; |
| 15 | |
| 16 | const projectFields = <E>(project: Query<RailwayProject, E>) => ({ |
| 17 | id: project.id, |
| 18 | name: project.name, |
| 19 | description: project.description, |
| 20 | workspaceId: project.workspaceId, |
| 21 | primaryEnvironmentId: project.primaryEnvironmentId, |
| 22 | baseEnvironmentId: project.baseEnvironmentId, |
| 23 | deletedAt: project.deletedAt, |
| 24 | }); |
| 25 | type CloudProject = UnwrapPlan<ReturnType<typeof projectFields>>; |
| 26 | |
| 27 | export interface ProjectProps { |
| 28 | /** |
| 29 | * Project name. Unique per workspace. If omitted, a unique name is |
| 30 | * generated from the stack, stage and logical ID. Changing it updates |
| 31 | * the project in place. |
| 32 | */ |
| 33 | name?: string; |
| 34 | /** |
| 35 | * Workspace to create the project in. Defaults to the current token's |
| 36 | * workspace (`me.workspace ?? me.workspaces[0]`). Changing it replaces |
| 37 | * the project. |
| 38 | */ |
| 39 | workspaceId?: string; |
| 40 | /** |
| 41 | * Human-readable description. Updates in place. |
| 42 | */ |
| 43 | description?: string; |
| 44 | /** |
| 45 | * Name of the environment created with the project (Railway's default |
| 46 | * is `production`). Create-only; ignored on update. |
| 47 | */ |
| 48 | defaultEnvironmentName?: string; |
| 49 | } |
| 50 | |
| 51 | export type Project = Resource< |
| 52 | "Railway.Project", |
| 53 | ProjectProps, |
| 54 | { |
| 55 | /** Railway project id. */ |
| 56 | projectId: string; |
| 57 | /** Physical project name (unique per workspace). */ |
| 58 | name: string; |
| 59 | /** Workspace the project lives in. */ |
| 60 | workspaceId: string; |
| 61 | /** Primary / base environment id created with the project. */ |
| 62 | environmentId: string; |
| 63 | /** Dashboard URL (`https://railway.com/project/{projectId}`). */ |
| 64 | url: string; |
| 65 | }, |
| 66 | never, |
| 67 | Providers |
| 68 | >; |
| 69 | |
| 70 | /** |
| 71 | * A Railway.Project is a workspace-scoped namespace. It owns environments |
| 72 | * and services. Names are unique per workspace. |
| 73 | * |
| 74 | * @see https://docs.railway.com/guides/projects |
| 75 | * |
| 76 | * ### Create a Project |
| 77 | * Alchemy generates a unique name unless you pass one. `url` is the |
| 78 | * dashboard URL. A production environment is created with the project — |
| 79 | * do not recreate it as an Environment resource. |
| 80 | * |
| 81 | * **Example:** Generated name |
| 82 | * ```typescript |
| 83 | * const site = yield* Railway.Project("Site"); |
| 84 | * ``` |
| 85 | * |
| 86 | * :::note |
| 87 | * Prefer omitting `name` in tests and CI so names stay unique and |
| 88 | * reclaimable. |
| 89 | * ::: |
| 90 | * |
| 91 | * ### A stable name |
| 92 | * Pass `name` when you need a stable project name. Changing it later |
| 93 | * updates the project in place. |
| 94 | * |
| 95 | * **Example:** Explicit name |
| 96 | * ```typescript |
| 97 | * const site = yield* Railway.Project("Site", { |
| 98 | * name: "my-site", |
| 99 | * }); |
| 100 | * ``` |
| 101 | * |
| 102 | * ### Description |
| 103 | * `description` is optional and updates in place. |
| 104 | * |
| 105 | * **Example:** With description |
| 106 | * ```typescript |
| 107 | * const site = yield* Railway.Project("Site", { |
| 108 | * description: "production web app", |
| 109 | * }); |
| 110 | * ``` |
| 111 | * |
| 112 | * ### Workspace |
| 113 | * Workspace defaults to the current token. Pass `workspaceId` to pin it. |
| 114 | * |
| 115 | * **Example:** Pin a workspace |
| 116 | * ```typescript |
| 117 | * const site = yield* Railway.Project("Site", { |
| 118 | * workspaceId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", |
| 119 | * }); |
| 120 | * ``` |
| 121 | * |
| 122 | * :::caution[Changing `workspaceId` replaces the Project] |
| 123 | * The Project is created in the new workspace. The old Project is deleted. |
| 124 | * ::: |
| 125 | * |
| 126 | * ### Default environment name |
| 127 | * `defaultEnvironmentName` is create-only. Railway's default is |
| 128 | * `production`. Extra environments (staging) are a separate Environment |
| 129 | * resource. |
| 130 | * |
| 131 | * **Example:** Custom default environment |
| 132 | * ```typescript |
| 133 | * const site = yield* Railway.Project("Site", { |
| 134 | * defaultEnvironmentName: "production", |
| 135 | * }); |
| 136 | * ``` |
| 137 | * |
| 138 | * ### Module-scope declarations |
| 139 | * Declare the Project once. Pass it into every child. Resource-valued |
| 140 | * props accept the resource or an Effect producing it. |
| 141 | * |
| 142 | * **Example:** Module-scope Project |
| 143 | * ```typescript |
| 144 | * // src/project.ts |
| 145 | * import * as Railway from "@alchemy.run/railway"; |
| 146 | * |
| 147 | * export const Site = Railway.Project("Site"); |
| 148 | * ``` |
| 149 | * |
| 150 | * @resource |
| 151 | * @product Project |
| 152 | */ |
| 153 | export const Project = Resource<Project>("Railway.Project"); |
| 154 | |
| 155 | export class ProjectNotCreated extends Data.TaggedError("Railway.ProjectNotCreated")<{ |
| 156 | resourceName: string; |
| 157 | }> {} |
| 158 | |
| 159 | /** Workspace id from a get-by-id or list-node Project payload. */ |
| 160 | export const workspaceIdOf = ( |
| 161 | project: { |
| 162 | readonly workspaceId?: string | null; |
| 163 | readonly workspace?: { readonly id?: string | null } | null; |
| 164 | }, |
| 165 | fallback?: string, |
| 166 | ): string => project.workspaceId ?? project.workspace?.id ?? fallback ?? ""; |
| 167 | |
| 168 | /** Primary environment id from a get-by-id or list-node Project payload. */ |
| 169 | export const environmentIdOf = (project: { |
| 170 | readonly primaryEnvironmentId?: string | null; |
| 171 | readonly baseEnvironmentId?: string | null; |
| 172 | readonly baseEnvironment?: { readonly id?: string | null } | null; |
| 173 | }): string => |
| 174 | project.primaryEnvironmentId ?? project.baseEnvironmentId ?? project.baseEnvironment?.id ?? ""; |
| 175 | |
| 176 | const toAttrs = ( |
| 177 | project: CloudProject, |
| 178 | fallback?: { name?: string; workspaceId?: string; environmentId?: string }, |
| 179 | ): Project["Attributes"] => { |
| 180 | const name = project.name || fallback?.name || ""; |
| 181 | return { |
| 182 | projectId: project.id, |
| 183 | name, |
| 184 | workspaceId: workspaceIdOf(project, fallback?.workspaceId), |
| 185 | environmentId: environmentIdOf(project) || fallback?.environmentId || "", |
| 186 | url: `https://railway.com/project/${project.id}`, |
| 187 | }; |
| 188 | }; |
| 189 | |
| 190 | const liveEnvironments = (projectId: string, first: number) => |
| 191 | Query.items( |
| 192 | Railway.environments({ projectId, first }).pipe( |
| 193 | Query.map((env) => ({ id: env.id, deletedAt: env.deletedAt })), |
| 194 | ), |
| 195 | ); |
| 196 | |
| 197 | const fillEnvironmentId = (attrs: Project["Attributes"]) => { |
| 198 | if (attrs.environmentId.length > 0) return Effect.succeed(attrs); |
| 199 | return liveEnvironments(attrs.projectId, 5).pipe( |
| 200 | Stream.filter((env) => env.deletedAt == null), |
| 201 | Stream.take(1), |
| 202 | Stream.runHead, |
| 203 | Effect.map((option) => |
| 204 | option._tag === "Some" ? { ...attrs, environmentId: option.value.id } : attrs, |
| 205 | ), |
| 206 | Effect.catchTag("RailwayNotFound", () => Effect.succeed(attrs)), |
| 207 | ); |
| 208 | }; |
| 209 | |
| 210 | const resolveName = (id: string, name: string | undefined, existing?: string) => |
| 211 | Effect.gen(function* () { |
| 212 | if (name !== undefined) return sanitizeRailwayName(name); |
| 213 | if (existing !== undefined) return existing; |
| 214 | return yield* createRailwayName(id); |
| 215 | }); |
| 216 | |
| 217 | const isGone = (project: CloudProject | undefined) => |
| 218 | project === undefined || project.deletedAt != null; |
| 219 | |
| 220 | const readProject = Query.fn((id: string) => projectFields(Railway.project({ id }))); |
| 221 | |
| 222 | const getById = (projectId: string) => |
| 223 | readProject(projectId).pipe( |
| 224 | Effect.map((project) => (isGone(project) ? undefined : project)), |
| 225 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 226 | ); |
| 227 | |
| 228 | const currentWorkspaceId = Effect.fn(function* () { |
| 229 | const env = yield* yield* RailwayEnvironment; |
| 230 | return env.workspaceId; |
| 231 | }); |
| 232 | |
| 233 | const projectCreate = Query.fn( |
| 234 | (input: { |
| 235 | name: string; |
| 236 | workspaceId: string; |
| 237 | description?: string; |
| 238 | defaultEnvironmentName?: string; |
| 239 | }) => projectFields(Railway.projectCreate({ input })), |
| 240 | ); |
| 241 | |
| 242 | export const createProject = (input: { |
| 243 | name: string; |
| 244 | workspaceId: string; |
| 245 | description?: string; |
| 246 | defaultEnvironmentName?: string; |
| 247 | }) => |
| 248 | waitOutCreateRateLimit( |
| 249 | projectCreate({ |
| 250 | name: input.name, |
| 251 | workspaceId: input.workspaceId, |
| 252 | ...(input.description !== undefined ? { description: input.description } : {}), |
| 253 | ...(input.defaultEnvironmentName !== undefined |
| 254 | ? { defaultEnvironmentName: input.defaultEnvironmentName } |
| 255 | : {}), |
| 256 | }), |
| 257 | ); |
| 258 | |
| 259 | const projectUpdate = Query.fn((id: string, input: { name?: string; description?: string }) => |
| 260 | projectFields(Railway.projectUpdate({ id, input })), |
| 261 | ); |
| 262 | |
| 263 | const projectDelete = Query.fn((id: string) => Railway.projectDelete({ id })); |
| 264 | |
| 265 | const workspaceProjects = (workspaceId: string) => |
| 266 | Query.items( |
| 267 | Railway.projects({ workspaceId, first: 50, includeDeleted: false }).pipe( |
| 268 | Query.map(projectFields), |
| 269 | ), |
| 270 | ); |
| 271 | |
| 272 | const findByName = (workspaceId: string, name: string) => |
| 273 | workspaceProjects(workspaceId).pipe( |
| 274 | Stream.filter((project) => !isGone(project) && project.name === name), |
| 275 | Stream.take(1), |
| 276 | Stream.runHead, |
| 277 | Effect.map((option) => (option._tag === "Some" ? option.value : undefined)), |
| 278 | ); |
| 279 | |
| 280 | /** |
| 281 | * Workspace projects Alchemy owns. Distilled `projects.items` plus the |
| 282 | * physical-name filter — Railway has no tags. No lock, no retry override. |
| 283 | */ |
| 284 | export const ownedProjects = Effect.fn(function* () { |
| 285 | const workspaceId = yield* currentWorkspaceId(); |
| 286 | const projects = yield* workspaceProjects(workspaceId).pipe(Stream.runCollect); |
| 287 | return Array.from(projects) |
| 288 | .filter((project) => !isGone(project) && matchesAlchemyPhysicalName(project.name)) |
| 289 | .map((project) => toAttrs(project, { workspaceId })); |
| 290 | }); |
| 291 | |
| 292 | export const listOwnedProjects = ownedProjects; |
| 293 | |
| 294 | /** |
| 295 | * Live environment ids under a project, including the stamped primary. |
| 296 | * `list()` walks these so partition environments are not invisible. |
| 297 | */ |
| 298 | export const projectEnvironmentIds = (project: { projectId: string; environmentId: string }) => |
| 299 | liveEnvironments(project.projectId, 50).pipe( |
| 300 | Stream.filter((env) => env.deletedAt == null), |
| 301 | Stream.map((env) => env.id), |
| 302 | Stream.runCollect, |
| 303 | Effect.map((ids) => { |
| 304 | const set = new Set(Array.from(ids)); |
| 305 | if (project.environmentId.length > 0) { |
| 306 | set.add(project.environmentId); |
| 307 | } |
| 308 | return Array.from(set); |
| 309 | }), |
| 310 | Effect.catchTag("RailwayNotFound", () => |
| 311 | Effect.succeed(project.environmentId.length > 0 ? [project.environmentId] : []), |
| 312 | ), |
| 313 | ); |
| 314 | |
| 315 | export const ProjectProvider = () => |
| 316 | Provider.succeed(Project, { |
| 317 | stables: ["projectId", "workspaceId", "environmentId"], |
| 318 | |
| 319 | diff: Effect.fn(function* ({ news, output }) { |
| 320 | if (news === undefined || !isResolved(news)) return undefined; |
| 321 | if (output === undefined) return undefined; |
| 322 | const workspaceChanged = |
| 323 | news.workspaceId !== undefined && news.workspaceId !== output.workspaceId; |
| 324 | if (workspaceChanged) { |
| 325 | return { action: "replace" as const }; |
| 326 | } |
| 327 | return undefined; |
| 328 | }), |
| 329 | |
| 330 | read: Effect.fn(function* ({ id, olds, output }) { |
| 331 | const name = yield* resolveName(id, olds?.name, output?.name); |
| 332 | const workspaceId = output?.workspaceId ?? olds?.workspaceId ?? (yield* currentWorkspaceId()); |
| 333 | const found = |
| 334 | (output?.projectId !== undefined ? yield* getById(output.projectId) : undefined) ?? |
| 335 | (yield* findByName(workspaceId, name)); |
| 336 | if (found === undefined) return undefined; |
| 337 | const attrs = yield* fillEnvironmentId( |
| 338 | toAttrs(found, { name, workspaceId, environmentId: output?.environmentId }), |
| 339 | ); |
| 340 | if (output !== undefined) return attrs; |
| 341 | return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs); |
| 342 | }), |
| 343 | |
| 344 | list: listOwnedProjects, |
| 345 | |
| 346 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 347 | const props = news ?? {}; |
| 348 | const name = yield* resolveName(id, props.name, output?.name); |
| 349 | const workspaceId = props.workspaceId ?? output?.workspaceId ?? (yield* currentWorkspaceId()); |
| 350 | |
| 351 | let current: CloudProject | undefined = |
| 352 | output?.projectId !== undefined ? yield* getById(output.projectId) : undefined; |
| 353 | if (current === undefined) { |
| 354 | current = yield* findByName(workspaceId, name); |
| 355 | } |
| 356 | |
| 357 | if (current === undefined) { |
| 358 | const created = yield* createProject({ |
| 359 | name, |
| 360 | workspaceId, |
| 361 | ...(props.description !== undefined ? { description: props.description } : {}), |
| 362 | ...(props.defaultEnvironmentName !== undefined |
| 363 | ? { defaultEnvironmentName: props.defaultEnvironmentName } |
| 364 | : {}), |
| 365 | }).pipe(Effect.catchTag("RailwayValidationError", () => Effect.undefined)); |
| 366 | current = created ?? (yield* findByName(workspaceId, name)); |
| 367 | } |
| 368 | |
| 369 | if (current === undefined || isGone(current)) { |
| 370 | return yield* new ProjectNotCreated({ resourceName: name }); |
| 371 | } |
| 372 | |
| 373 | const nameChanged = current.name !== name; |
| 374 | const observedDescription = current.description ?? undefined; |
| 375 | const descriptionChanged = |
| 376 | props.description !== undefined && props.description !== observedDescription; |
| 377 | if (nameChanged || descriptionChanged) { |
| 378 | current = yield* projectUpdate(current.id, { |
| 379 | ...(nameChanged ? { name } : {}), |
| 380 | ...(descriptionChanged ? { description: props.description } : {}), |
| 381 | }); |
| 382 | } |
| 383 | |
| 384 | return yield* fillEnvironmentId( |
| 385 | toAttrs(current, { name, workspaceId, environmentId: output?.environmentId }), |
| 386 | ); |
| 387 | }), |
| 388 | |
| 389 | delete: Effect.fn(function* ({ output }) { |
| 390 | const projectId = output.projectId; |
| 391 | if (projectId.length === 0) return; |
| 392 | yield* projectDelete(projectId).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void)); |
| 393 | yield* waitUntilDeleted( |
| 394 | "Project", |
| 395 | projectId, |
| 396 | getById(projectId).pipe(Effect.map((project) => project === undefined)), |
| 397 | ); |
| 398 | }), |
| 399 | }); |