@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 1,132 lines 38 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import {
3 Railway,
4 type Bucket as RailwayBucket,
5 type Group as RailwayGroup,
6 type Service as RailwayService,
7 type VolumeInstance as RailwayVolumeInstance,
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 {
18 waitUntilDeleted,
19 projectServices as fetchProjectServices,
20 projectBuckets as fetchProjectBuckets,
21 projectGroups as fetchProjectGroups,
22 environmentVolumes,
23 } from "./GraphQL.ts";
24 import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts";
25 import { ownedProjects, type Project } from "./Project.ts";
26 import type { Providers } from "./Providers.ts";
27 import { withEnvironmentConfigLock } from "./transient.ts";
28
29 const groupSelection = (group: Query<RailwayGroup>) => ({
30 id: group.id,
31 name: group.name,
32 color: group.color,
33 icon: group.icon,
34 isCollapsed: group.isCollapsed,
35 });
36 const serviceSelection = (service: Query<RailwayService>) => ({
37 id: service.id,
38 groupId: service.groupId,
39 deletedAt: service.deletedAt,
40 });
41 const bucketSelection = (bucket: Query<RailwayBucket>) => ({
42 id: bucket.id,
43 groupId: bucket.groupId,
44 });
45 const volumeSelection = (volume: Query<RailwayVolumeInstance>) => ({
46 id: volume.id,
47 volumeId: volume.volumeId,
48 deletedAt: volume.deletedAt,
49 state: volume.state,
50 volume: { id: volume.volume.id },
51 });
52 type ProjectResponseBucketsEdgesItemNode = UnwrapPlan<ReturnType<typeof bucketSelection>>;
53 type ProjectResponseGroupsEdgesItemNode = UnwrapPlan<ReturnType<typeof groupSelection>>;
54 type ProjectResponseServicesEdgesItemNode = UnwrapPlan<ReturnType<typeof serviceSelection>>;
55 type EnvironmentVolumeNode = UnwrapPlan<ReturnType<typeof volumeSelection>>;
56 type ProjectResponse = {
57 readonly deletedAt: string | null;
58 readonly services: readonly ProjectResponseServicesEdgesItemNode[];
59 readonly buckets: readonly ProjectResponseBucketsEdgesItemNode[];
60 readonly groups: readonly ProjectResponseGroupsEdgesItemNode[];
61 };
62 type EnvironmentResponse = {
63 readonly deletedAt: string | null;
64 readonly config: unknown;
65 readonly canvasGroupRefs: unknown;
66 readonly volumeInstances: readonly EnvironmentVolumeNode[];
67 };
68
69 const readProjectDeletedAt = Query.fn((id: string) => ({
70 deletedAt: Railway.project({ id }).deletedAt,
71 }));
72
73 const readEnvironment = Query.fn((id: string, projectId: string) => {
74 const environment = Railway.environment({ id, projectId });
75 return {
76 deletedAt: environment.deletedAt,
77 config: environment.config,
78 canvasGroupRefs: environment.canvasGroupRefs,
79 };
80 });
81
82 const environmentPatchCommit = Query.fn(
83 (input: { environmentId: string; commitMessage: string; patch: unknown }) =>
84 Railway.environmentPatchCommit(input),
85 );
86
87 const canvasViewMergePreview = Query.fn(
88 (sourceEnvironmentId: string, targetEnvironmentId: string) => ({
89 mutations: Railway.canvasViewMergePreview({ sourceEnvironmentId, targetEnvironmentId })
90 .mutations,
91 }),
92 );
93
94 const canvasViewMerge = Query.fn((sourceEnvironmentId: string, targetEnvironmentId: string) =>
95 Railway.canvasViewMerge({ sourceEnvironmentId, targetEnvironmentId }),
96 );
97
98 /**
99 * A resource-valued prop: the resource itself, or an Effect that produces
100 * it (so `yield* Project(...)` and `Project(...)` both type-check).
101 */
102 type Ref<T> = T | Effect.Effect<T, never, Providers>;
103
104 /**
105 * Environment identity a Group is drawn on. Accepts a `Railway.Project`
106 * (its primary environment), a `Railway.Environment`, or an
107 * `{ environmentId }` stub.
108 */
109 export type GroupEnvironment = { readonly environmentId: string };
110
111 /**
112 * A canvas-group member. Accepts a `Railway.Service` / Postgres / Redis /
113 * MySQL / Mongo (`serviceId`), a `Railway.Volume` (`volumeId`), a
114 * `Railway.Bucket` (`bucketId`), or a stub with those ids.
115 */
116 export type GroupMember = {
117 readonly serviceId?: string;
118 readonly volumeId?: string;
119 readonly bucketId?: string;
120 };
121
122 export interface GroupProps {
123 /**
124 * Parent Railway Project. Changing it replaces the Group.
125 */
126 project: Ref<Project>;
127 /**
128 * Environment whose canvas this group lives on. Accepts a
129 * `Railway.Project` (primary environment), a `Railway.Environment`, or
130 * `{ environmentId }`. Defaults to the project's primary environment.
131 * Changing it replaces the Group.
132 */
133 environment?: Ref<GroupEnvironment>;
134 /**
135 * Canvas group name. If omitted, a unique name is generated from the
136 * stack, stage and logical ID. Updates in place.
137 */
138 name?: string;
139 /**
140 * Members to place in the group — services, databases, volumes, and
141 * buckets. Service membership is persisted as `groupId`; volume ids
142 * are observed from `canvasGroupRefs`; bucket ids from `Bucket.groupId`.
143 */
144 resources: ReadonlyArray<Ref<GroupMember>>;
145 /**
146 * Optional canvas color. Updates in place.
147 */
148 color?: string;
149 /**
150 * Optional canvas icon. Updates in place.
151 */
152 icon?: string;
153 /**
154 * Whether the group is collapsed on the canvas.
155 *
156 * @default false
157 */
158 collapsed?: boolean;
159 }
160
161 export type Group = Resource<
162 "Railway.Group",
163 GroupProps,
164 {
165 /** Railway group id (EnvironmentConfig key / Group.id). */
166 groupId: string;
167 /** Parent Railway project id. */
168 projectId: string;
169 /** Environment whose canvas this group is on. */
170 environmentId: string;
171 /** Canvas group name. */
172 name: string;
173 /** Canvas color, if set. */
174 color: string | undefined;
175 /** Canvas icon, if set. */
176 icon: string | undefined;
177 /** Whether the group is collapsed on the canvas. */
178 collapsed: boolean;
179 /** Member service ids (`Service.groupId` / Postgres / Redis / …). */
180 serviceIds: string[];
181 /** Member volume ids. */
182 volumeIds: string[];
183 /** Member bucket ids (`Bucket.groupId`). */
184 bucketIds: string[];
185 },
186 never,
187 Providers
188 >;
189
190 const resolveGroupProps = (
191 props: GroupProps | Effect.Effect<GroupProps, never, Providers>,
192 ): Effect.Effect<GroupProps, never, Providers> =>
193 Effect.gen(function* () {
194 const resolved = Effect.isEffect(props) ? yield* props : props;
195 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
196 const project = Effect.isEffect(resolved.project)
197 ? yield* resolved.project as Effect.Effect<Project, never, Providers>
198 : resolved.project;
199 const environment =
200 resolved.environment === undefined
201 ? undefined
202 : Effect.isEffect(resolved.environment)
203 ? yield* resolved.environment as Effect.Effect<GroupEnvironment, never, Providers>
204 : resolved.environment;
205 const resources = yield* Effect.forEach(resolved.resources, (item) =>
206 Effect.isEffect(item)
207 ? (item as Effect.Effect<GroupMember, never, Providers>)
208 : Effect.succeed(item),
209 );
210 return { ...resolved, project, environment, resources };
211 });
212
213 const GroupResource = Resource<Group>("Railway.Group");
214
215 /**
216 * A Railway.Group organizes services, databases, volumes, and buckets on
217 * the project canvas. IaC parity with `group("Backend", [api, worker, db])`.
218 *
219 * Groups have no dedicated create/delete mutation. Alchemy writes
220 * `EnvironmentConfig.groups` (and `services[id].groupId`) via
221 * `environmentPatchCommit`, matching Railway's own IaC compiler. Volume
222 * membership is observed from `environment.canvasGroupRefs`. When Railway
223 * does not persist a first-class Group id, the resource still records
224 * member service/volume/bucket ids. `canvasViewMerge` /
225 * `canvasViewMergePreview` copy canvas layout between environments.
226 *
227 * @see https://docs.railway.com/infrastructure-as-code/reference
228 *
229 * ### Create a Group
230 * Pass a Project and the members to group. Alchemy generates a unique
231 * name unless you pass one.
232 *
233 * **Example:** Group two services
234 * ```typescript
235 * const site = yield* Railway.Project("Site");
236 * const api = yield* Railway.Service("Api", {
237 * project: site,
238 * image: "hashicorp/http-echo",
239 * });
240 * const worker = yield* Railway.Service("Worker", {
241 * project: site,
242 * image: "hashicorp/http-echo",
243 * });
244 * const backend = yield* Railway.Group("Backend", {
245 * project: site,
246 * resources: [api, worker],
247 * });
248 * ```
249 *
250 * :::caution[Changing `project` replaces the Group]
251 * The Group is created in the new Project. The old Group is deleted.
252 * :::
253 *
254 * ### Environment
255 * Defaults to the Project's primary environment. Pass a
256 * `Railway.Environment` (or `{ environmentId }`) to target another one.
257 *
258 * **Example:** Extra environment
259 * ```typescript
260 * const staging = yield* Railway.Environment("Staging", { project: site });
261 * const backend = yield* Railway.Group("Backend", {
262 * project: site,
263 * environment: staging,
264 * resources: [api],
265 * });
266 * ```
267 *
268 * :::caution[Changing `environment` replaces the Group]
269 * The Group is created on the new environment's canvas. The old Group is
270 * deleted.
271 * :::
272 *
273 * ### Databases, volumes, and buckets
274 * Postgres/Redis/MySQL/Mongo group as services (`serviceId`). Volumes and
275 * buckets are accepted as members (`volumeId` / `bucketId`).
276 *
277 * **Example:** Group a database and API
278 * ```typescript
279 * const db = yield* Railway.Postgres("Db", { project: site });
280 * const backend = yield* Railway.Group("Backend", {
281 * project: site,
282 * resources: [api, db],
283 * });
284 * ```
285 *
286 * ### Module-scope declarations
287 * Declare the Project once. Pass it into every child. Resource-valued
288 * props accept the resource or an Effect producing it.
289 *
290 * **Example:** Module-scope Group
291 * ```typescript
292 * // src/backend.ts
293 * import * as Railway from "@alchemy.run/railway";
294 *
295 * export const Site = Railway.Project("Site");
296 * export const Api = Railway.Service("Api", {
297 * project: Site,
298 * image: "hashicorp/http-echo",
299 * });
300 * export const Backend = Railway.Group("Backend", {
301 * project: Site,
302 * resources: [Api],
303 * });
304 * ```
305 *
306 * @resource
307 * @product Project
308 */
309 export const Group: typeof GroupResource = Object.assign(
310 (id: string, props: GroupProps | Effect.Effect<GroupProps, never, Providers>) =>
311 GroupResource(id, resolveGroupProps(props)),
312 GroupResource,
313 );
314
315 export class GroupProjectRequired extends Data.TaggedError("Railway.GroupProjectRequired")<{
316 message: string;
317 }> {}
318
319 export class GroupEnvironmentRequired extends Data.TaggedError("Railway.GroupEnvironmentRequired")<{
320 message: string;
321 }> {}
322
323 class GroupPending extends Data.TaggedError("Railway.GroupPending")<{
324 groupId: string;
325 state: string;
326 }> {}
327
328 type GroupConfig = {
329 name?: string | null;
330 color?: string | null;
331 icon?: string | null;
332 isCollapsed?: boolean | null;
333 isDeleted?: boolean | null;
334 isCreated?: boolean | null;
335 groupId?: string | null;
336 };
337
338 type ServiceConfig = { groupId?: string | null; isDeleted?: boolean | null };
339
340 type BucketConfig = { groupId?: string | null; isDeleted?: boolean | null };
341
342 type EnvironmentConfigShape = {
343 groups?: Record<string, GroupConfig | null> | null;
344 services?: Record<string, ServiceConfig | null> | null;
345 buckets?: Record<string, BucketConfig | null> | null;
346 };
347
348 type CloudGroup = {
349 groupId: string;
350 name: string;
351 color: string | undefined;
352 icon: string | undefined;
353 collapsed: boolean;
354 serviceIds: string[];
355 volumeIds: string[];
356 bucketIds: string[];
357 };
358
359 const projectIdOf = (value: unknown): string | undefined => {
360 if (value === null || typeof value !== "object") return undefined;
361 const rec = value as { projectId?: unknown };
362 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
363 };
364
365 const environmentIdOf = (value: unknown): string | undefined => {
366 if (value === null || typeof value !== "object") return undefined;
367 const rec = value as { environmentId?: unknown };
368 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
369 ? rec.environmentId
370 : undefined;
371 };
372
373 const uniqueSorted = (ids: readonly string[]): string[] =>
374 Array.from(new Set(ids.filter((id) => id.length > 0))).sort();
375
376 const sameIds = (left: readonly string[], right: readonly string[]) =>
377 uniqueSorted(left).join("\0") === uniqueSorted(right).join("\0");
378
379 const classifyMember = (
380 member: GroupMember | null | undefined,
381 ):
382 | { kind: "service"; id: string }
383 | { kind: "volume"; id: string }
384 | { kind: "bucket"; id: string }
385 | undefined => {
386 if (member == null) return undefined;
387 if (typeof member.serviceId === "string" && member.serviceId.length > 0) {
388 return { kind: "service", id: member.serviceId };
389 }
390 if (typeof member.bucketId === "string" && member.bucketId.length > 0) {
391 return { kind: "bucket", id: member.bucketId };
392 }
393 if (typeof member.volumeId === "string" && member.volumeId.length > 0) {
394 return { kind: "volume", id: member.volumeId };
395 }
396 return undefined;
397 };
398
399 const membersOf = (resources: readonly GroupMember[] | undefined) => {
400 const serviceIds: string[] = [];
401 const volumeIds: string[] = [];
402 const bucketIds: string[] = [];
403 for (const resource of resources ?? []) {
404 const classified = classifyMember(resource);
405 if (classified === undefined) continue;
406 if (classified.kind === "service") serviceIds.push(classified.id);
407 else if (classified.kind === "volume") volumeIds.push(classified.id);
408 else bucketIds.push(classified.id);
409 }
410 return {
411 serviceIds: uniqueSorted(serviceIds),
412 volumeIds: uniqueSorted(volumeIds),
413 bucketIds: uniqueSorted(bucketIds),
414 };
415 };
416
417 const parseRecord = <T>(value: unknown): Record<string, T | null> | undefined =>
418 value !== null && typeof value === "object" && !Array.isArray(value)
419 ? (value as Record<string, T | null>)
420 : undefined;
421
422 const parseEnvironmentConfig = (value: unknown): EnvironmentConfigShape => {
423 if (value === null || typeof value !== "object" || Array.isArray(value)) {
424 return {};
425 }
426 const rec = value as { groups?: unknown; services?: unknown; buckets?: unknown };
427 return {
428 groups: parseRecord<GroupConfig>(rec.groups),
429 services: parseRecord<ServiceConfig>(rec.services),
430 buckets: parseRecord<BucketConfig>(rec.buckets),
431 };
432 };
433
434 /**
435 * Railway stores canvas grouping as `{ [resourceId]: groupId }`
436 * (`environment.canvasGroupRefs[volume.id]` in railway/iac).
437 */
438 const parseCanvasGroupRefs = (value: unknown): Record<string, string> => {
439 if (value === null || typeof value !== "object" || Array.isArray(value)) {
440 return {};
441 }
442 const out: Record<string, string> = {};
443 for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
444 if (typeof item === "string" && item.length > 0) {
445 out[key] = item;
446 continue;
447 }
448 if (item !== null && typeof item === "object" && !Array.isArray(item)) {
449 const rec = item as { groupId?: unknown };
450 if (typeof rec.groupId === "string" && rec.groupId.length > 0) {
451 out[key] = rec.groupId;
452 }
453 }
454 }
455 return out;
456 };
457
458 const idsForGroup = (refs: Record<string, string>, groupId: string): string[] => {
459 const ids: string[] = [];
460 for (const [resourceId, assigned] of Object.entries(refs)) {
461 if (assigned === groupId) ids.push(resourceId);
462 }
463 return uniqueSorted(ids);
464 };
465
466 const groupRow = (config: EnvironmentConfigShape, groupId: string): GroupConfig | undefined => {
467 const row = config.groups?.[groupId];
468 if (row === undefined || row === null || row.isDeleted === true) {
469 return undefined;
470 }
471 return row;
472 };
473
474 const servicesForGroup = (config: EnvironmentConfigShape, groupId: string): string[] => {
475 const services = config.services;
476 if (services === undefined || services === null) return [];
477 const ids: string[] = [];
478 for (const [serviceId, row] of Object.entries(services)) {
479 if (row === null || row.isDeleted === true) continue;
480 if (row.groupId === groupId) ids.push(serviceId);
481 }
482 return uniqueSorted(ids);
483 };
484
485 const bucketsForGroup = (config: EnvironmentConfigShape, groupId: string): string[] => {
486 const buckets = config.buckets;
487 if (buckets === undefined || buckets === null) return [];
488 const ids: string[] = [];
489 for (const [bucketId, row] of Object.entries(buckets)) {
490 if (row === null || row.isDeleted === true) continue;
491 if (row.groupId === groupId) ids.push(bucketId);
492 }
493 return uniqueSorted(ids);
494 };
495
496 const liveServicesForGroup = (
497 services: readonly ProjectResponseServicesEdgesItemNode[],
498 groupId: string,
499 ): string[] =>
500 uniqueSorted(
501 services
502 .filter((service) => service.deletedAt == null && service.groupId === groupId)
503 .map((service) => service.id),
504 );
505
506 const liveBucketsForGroup = (
507 buckets: readonly ProjectResponseBucketsEdgesItemNode[],
508 groupId: string,
509 ): string[] =>
510 uniqueSorted(buckets.filter((bucket) => bucket.groupId === groupId).map((bucket) => bucket.id));
511
512 const optionalString = (value: string | null | undefined) =>
513 value !== null && value !== undefined && value.length > 0 ? value : undefined;
514
515 const volumeIdsOf = (env: EnvironmentResponse | undefined): string[] => {
516 if (env === undefined) return [];
517 const ids: string[] = [];
518 for (const node of env.volumeInstances) {
519 if (node.deletedAt != null || node.state === "DELETED") continue;
520 ids.push(node.volumeId, node.volume.id, node.id);
521 }
522 return uniqueSorted(ids);
523 };
524
525 const toAttrs = (
526 group: CloudGroup,
527 extra: { projectId: string; environmentId: string },
528 ): Group["Attributes"] => ({
529 groupId: group.groupId,
530 projectId: extra.projectId,
531 environmentId: extra.environmentId,
532 name: group.name,
533 color: group.color,
534 icon: group.icon,
535 collapsed: group.collapsed,
536 serviceIds: group.serviceIds,
537 volumeIds: group.volumeIds,
538 bucketIds: group.bucketIds,
539 });
540
541 const resolveName = (id: string, name: string | undefined, existing?: string) =>
542 Effect.gen(function* () {
543 if (name !== undefined && name.trim().length > 0) return name.trim();
544 if (existing !== undefined && existing.length > 0) return existing;
545 return yield* createRailwayName(id);
546 });
547
548 const getProject = (projectId: string) =>
549 Effect.gen(function* () {
550 const project = yield* readProjectDeletedAt(projectId);
551 const services = yield* fetchProjectServices(projectId, serviceSelection);
552 const buckets = yield* fetchProjectBuckets(projectId, bucketSelection);
553 const groups = yield* fetchProjectGroups(projectId, groupSelection);
554 return { deletedAt: project.deletedAt, services, buckets, groups } satisfies ProjectResponse;
555 }).pipe(
556 Effect.map((project) => (project.deletedAt != null ? undefined : project)),
557 Effect.catchTag("RailwayNotFound", () =>
558 Effect.succeed(undefined as ProjectResponse | undefined),
559 ),
560 );
561
562 const getEnvironment = (environmentId: string, projectId: string) =>
563 Effect.gen(function* () {
564 const environment = yield* readEnvironment(environmentId, projectId);
565 const volumes = yield* environmentVolumes(environmentId, projectId, volumeSelection);
566 return { ...environment, volumeInstances: volumes } satisfies EnvironmentResponse;
567 }).pipe(Effect.catchTag("RailwayNotFound", () => Effect.undefined));
568
569 const _getEnvironmentConfig = (environmentId: string, projectId: string) =>
570 getEnvironment(environmentId, projectId).pipe(
571 Effect.map((env) =>
572 env === undefined ? ({} as EnvironmentConfigShape) : parseEnvironmentConfig(env.config),
573 ),
574 );
575
576 const _listEnvironmentIds = (project: { projectId: string; environmentId: string }) =>
577 Query.items(
578 Railway.environments({ projectId: project.projectId, first: 50 }).pipe(
579 Query.map((env) => ({ id: env.id, deletedAt: env.deletedAt })),
580 ),
581 ).pipe(
582 Stream.filter((env) => env.deletedAt == null),
583 Stream.map((env) => env.id),
584 Stream.runCollect,
585 Effect.map((ids) => {
586 const set = new Set(Array.from(ids));
587 if (project.environmentId.length > 0) {
588 set.add(project.environmentId);
589 }
590 return Array.from(set);
591 }),
592 Effect.catchTag("RailwayNotFound", () =>
593 Effect.succeed(project.environmentId.length > 0 ? [project.environmentId] : []),
594 ),
595 );
596
597 const commitPatch = (input: {
598 environmentId: string;
599 commitMessage: string;
600 patch: Record<string, unknown>;
601 }) =>
602 withEnvironmentConfigLock(
603 input.environmentId,
604 environmentPatchCommit({
605 environmentId: input.environmentId,
606 commitMessage: input.commitMessage,
607 patch: input.patch,
608 }),
609 ).pipe(
610 Effect.catchTag(["RailwayValidationError", "RailwayInternalError"], () => Effect.succeed("")),
611 );
612
613 const previewCanvas = (environmentId: string) =>
614 canvasViewMergePreview(environmentId, environmentId).pipe(
615 Effect.catchTag(
616 ["RailwayNotFound", "RailwayValidationError", "RailwayInternalError"],
617 () => Effect.undefined,
618 ),
619 );
620
621 const mergeCanvas = (sourceEnvironmentId: string, targetEnvironmentId: string) =>
622 canvasViewMerge(sourceEnvironmentId, targetEnvironmentId).pipe(
623 Effect.catchTag(["RailwayNotFound", "RailwayValidationError", "RailwayInternalError"], () =>
624 Effect.succeed(false),
625 ),
626 );
627
628 const projectGroups = (project: ProjectResponse | undefined) => project?.groups ?? [];
629
630 const projectServices = (project: ProjectResponse | undefined) => project?.services ?? [];
631
632 const projectBuckets = (project: ProjectResponse | undefined) => project?.buckets ?? [];
633
634 const matchProjectGroup = (
635 groups: readonly ProjectResponseGroupsEdgesItemNode[],
636 match: { groupId?: string; name?: string },
637 ) => {
638 if (match.groupId !== undefined && match.groupId.length > 0) {
639 const byId = groups.find((group) => group.id === match.groupId);
640 if (byId !== undefined) return byId;
641 }
642 if (match.name !== undefined && match.name.length > 0) {
643 return groups.find((group) => group.name === match.name);
644 }
645 return undefined;
646 };
647
648 const matchConfigGroup = (
649 config: EnvironmentConfigShape,
650 match: { groupId?: string; name?: string },
651 ): { groupId: string; row: GroupConfig } | undefined => {
652 const groups = config.groups;
653 if (groups === undefined || groups === null) return undefined;
654 if (match.groupId !== undefined && match.groupId.length > 0) {
655 const row = groupRow(config, match.groupId);
656 if (row !== undefined) return { groupId: match.groupId, row };
657 }
658 if (match.name !== undefined && match.name.length > 0) {
659 for (const [groupId, row] of Object.entries(groups)) {
660 if (row === null || row.isDeleted === true) continue;
661 if (row.name === match.name) return { groupId, row };
662 }
663 }
664 return undefined;
665 };
666
667 const observe = Effect.fn(function* (input: {
668 projectId: string;
669 environmentId: string;
670 groupId?: string;
671 name?: string;
672 volumeIds?: readonly string[];
673 }) {
674 const env = yield* getEnvironment(input.environmentId, input.projectId);
675 if (env === undefined || env.deletedAt != null) return undefined;
676 const config = parseEnvironmentConfig(env.config);
677 const project = yield* getProject(input.projectId);
678 const fromConfig = matchConfigGroup(config, input);
679 const fromProject = matchProjectGroup(projectGroups(project), input);
680 const groupId = fromConfig?.groupId ?? fromProject?.id ?? input.groupId;
681 if (groupId === undefined || groupId.length === 0) return undefined;
682
683 const row = fromConfig?.row;
684 const canvasRefs = parseCanvasGroupRefs(env.canvasGroupRefs);
685 const fromCanvas = idsForGroup(canvasRefs, groupId);
686 const knownServices = projectServices(project);
687 const knownBuckets = projectBuckets(project);
688 const knownVolumeIds = new Set([...volumeIdsOf(env), ...(input.volumeIds ?? [])]);
689 const knownServiceIds = new Set(knownServices.map((service) => service.id));
690 const knownBucketIds = new Set(knownBuckets.map((bucket) => bucket.id));
691
692 const serviceIds = uniqueSorted([
693 ...servicesForGroup(config, groupId),
694 ...liveServicesForGroup(knownServices, groupId),
695 ...fromCanvas.filter((id) => knownServiceIds.has(id)),
696 ]);
697 const bucketIds = uniqueSorted([
698 ...bucketsForGroup(config, groupId),
699 ...liveBucketsForGroup(knownBuckets, groupId),
700 ...fromCanvas.filter((id) => knownBucketIds.has(id)),
701 ]);
702 const volumeIds = uniqueSorted([
703 ...(input.volumeIds ?? []).filter((id) => canvasRefs[id] === groupId),
704 ...fromCanvas.filter(
705 (id) => knownVolumeIds.has(id) || (!knownServiceIds.has(id) && !knownBucketIds.has(id)),
706 ),
707 ]);
708
709 const name = optionalString(row?.name ?? fromProject?.name) ?? input.name ?? "";
710 if (fromConfig === undefined && fromProject === undefined) {
711 if (serviceIds.length === 0 && bucketIds.length === 0 && volumeIds.length === 0) {
712 return undefined;
713 }
714 }
715
716 return {
717 groupId,
718 name,
719 color: optionalString(row?.color ?? fromProject?.color),
720 icon: optionalString(row?.icon ?? fromProject?.icon),
721 collapsed: (row?.isCollapsed ?? fromProject?.isCollapsed) === true,
722 serviceIds,
723 volumeIds,
724 bucketIds,
725 } satisfies CloudGroup;
726 });
727
728 const waitUntilPresent = (input: {
729 projectId: string;
730 environmentId: string;
731 groupId: string;
732 name: string;
733 volumeIds?: readonly string[];
734 }) =>
735 observe({
736 projectId: input.projectId,
737 environmentId: input.environmentId,
738 groupId: input.groupId,
739 name: input.name,
740 volumeIds: input.volumeIds,
741 }).pipe(
742 Effect.flatMap((group) => {
743 if (group === undefined) {
744 return Effect.fail(new GroupPending({ groupId: input.groupId, state: "creating" }));
745 }
746 return Effect.succeed(group);
747 }),
748 Effect.retry({
749 while: (e) => e._tag === "Railway.GroupPending",
750 times: 4,
751 schedule: Schedule.spaced("1 second"),
752 }),
753 Effect.catchTag("Railway.GroupPending", () =>
754 observe({
755 projectId: input.projectId,
756 environmentId: input.environmentId,
757 groupId: input.groupId,
758 name: input.name,
759 volumeIds: input.volumeIds,
760 }),
761 ),
762 );
763
764 const waitUntilGone = (input: {
765 projectId: string;
766 environmentId: string;
767 groupId: string;
768 name: string;
769 }) =>
770 waitUntilDeleted(
771 "Group",
772 input.groupId,
773 observe({
774 projectId: input.projectId,
775 environmentId: input.environmentId,
776 groupId: input.groupId,
777 name: input.name,
778 }).pipe(Effect.map((group) => group === undefined)),
779 4,
780 );
781
782 const groupPatch = (input: {
783 groupId: string;
784 name: string;
785 color?: string;
786 icon?: string;
787 collapsed: boolean;
788 create: boolean;
789 remove?: boolean;
790 }): Record<string, GroupConfig> => ({
791 [input.groupId]: input.remove
792 ? { isDeleted: true }
793 : {
794 name: input.name,
795 ...(input.color !== undefined ? { color: input.color } : {}),
796 ...(input.icon !== undefined ? { icon: input.icon } : {}),
797 isCollapsed: input.collapsed,
798 ...(input.create ? { isCreated: true } : {}),
799 },
800 });
801
802 const servicePatch = (
803 assignments: ReadonlyArray<{ serviceId: string; groupId: string | null }>,
804 ): Record<string, { groupId: string | null }> => {
805 const out: Record<string, { groupId: string | null }> = {};
806 for (const row of assignments) {
807 out[row.serviceId] = { groupId: row.groupId };
808 }
809 return out;
810 };
811
812 const bucketPatch = (
813 assignments: ReadonlyArray<{ bucketId: string; groupId: string | null }>,
814 ): Record<string, { groupId: string | null }> => {
815 const out: Record<string, { groupId: string | null }> = {};
816 for (const row of assignments) {
817 out[row.bucketId] = { groupId: row.groupId };
818 }
819 return out;
820 };
821
822 const membershipPatch = (input: {
823 groupId: string;
824 name: string;
825 color?: string;
826 icon?: string;
827 collapsed: boolean;
828 create: boolean;
829 remove?: boolean;
830 services?: ReadonlyArray<{ serviceId: string; groupId: string | null }>;
831 buckets?: ReadonlyArray<{ bucketId: string; groupId: string | null }>;
832 }): Record<string, unknown> => {
833 const patch: Record<string, unknown> = { groups: groupPatch(input) };
834 if (input.services !== undefined && input.services.length > 0) {
835 patch.services = servicePatch(input.services);
836 }
837 if (input.buckets !== undefined && input.buckets.length > 0) {
838 patch.buckets = bucketPatch(input.buckets);
839 }
840 return patch;
841 };
842
843 const fallbackGroup = (input: {
844 groupId: string;
845 name: string;
846 color?: string;
847 icon?: string;
848 collapsed: boolean;
849 serviceIds: readonly string[];
850 volumeIds: readonly string[];
851 bucketIds: readonly string[];
852 }): CloudGroup => ({
853 groupId: input.groupId,
854 name: input.name,
855 color: input.color,
856 icon: input.icon,
857 collapsed: input.collapsed,
858 serviceIds: uniqueSorted(input.serviceIds),
859 volumeIds: uniqueSorted(input.volumeIds),
860 bucketIds: uniqueSorted(input.bucketIds),
861 });
862
863 export const GroupProvider = () =>
864 Provider.succeed(Group, {
865 stables: ["groupId", "projectId", "environmentId"],
866 nuke: { dependsOn: ["Railway.Project"] },
867
868 diff: Effect.fn(function* ({ news, output }) {
869 if (news === undefined || !isResolved(news)) return undefined;
870 if (output === undefined) return undefined;
871 const nextProject = projectIdOf(news.project);
872 const projectChanged = nextProject !== undefined && nextProject !== output.projectId;
873 const nextEnv = environmentIdOf(news.environment);
874 const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId;
875 if (projectChanged || environmentChanged) {
876 return { action: "replace" as const };
877 }
878 return undefined;
879 }),
880
881 read: Effect.fn(function* ({ id, olds, output }) {
882 const projectId =
883 output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined);
884 const environmentId =
885 output?.environmentId ??
886 (olds !== undefined
887 ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project))
888 : undefined);
889 if (projectId === undefined || environmentId === undefined) {
890 return undefined;
891 }
892 const name = yield* resolveName(id, olds?.name, output?.name);
893 const desired = membersOf((olds?.resources as readonly GroupMember[] | undefined) ?? []);
894 const found = yield* observe({
895 projectId,
896 environmentId,
897 groupId: output?.groupId,
898 name,
899 volumeIds: output?.volumeIds ?? desired.volumeIds,
900 });
901 if (found === undefined) return undefined;
902 const attrs = toAttrs(found, { projectId, environmentId });
903 if (output !== undefined) return attrs;
904 return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs);
905 }),
906
907 list: Effect.fn(function* () {
908 const projects = yield* ownedProjects();
909 const rows = yield* Effect.forEach(projects, (project) =>
910 fetchProjectGroups(project.projectId, groupSelection).pipe(
911 Effect.map((live) =>
912 live.flatMap((group) => {
913 const name = group.name ?? "";
914 if (!matchesAlchemyPhysicalName(name)) return [];
915 return [
916 toAttrs(
917 {
918 groupId: group.id,
919 name,
920 color: group.color ?? undefined,
921 icon: group.icon ?? undefined,
922 collapsed: group.isCollapsed === true,
923 serviceIds: [] as string[],
924 volumeIds: [] as string[],
925 bucketIds: [] as string[],
926 },
927 { projectId: project.projectId, environmentId: project.environmentId },
928 ),
929 ];
930 }),
931 ),
932 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as Group["Attributes"][])),
933 ),
934 );
935 const seen = new Set<string>();
936 const unique: Group["Attributes"][] = [];
937 for (const row of rows.flat()) {
938 const key = `${row.groupId}:${row.environmentId}`;
939 if (seen.has(key)) continue;
940 seen.add(key);
941 unique.push(row);
942 }
943 return unique;
944 }),
945
946 reconcile: Effect.fn(function* ({ id, news, output }) {
947 const props = news ?? ({} as GroupProps);
948 const projectId = projectIdOf(props.project) ?? output?.projectId;
949 if (projectId === undefined) {
950 return yield* new GroupProjectRequired({
951 message: "Group requires a resolved Railway.Project",
952 });
953 }
954 const environmentId =
955 environmentIdOf(props.environment) ??
956 environmentIdOf(props.project) ??
957 output?.environmentId;
958 if (environmentId === undefined) {
959 return yield* new GroupEnvironmentRequired({
960 message:
961 "Group requires a Railway environment (pass environment or a Project with environmentId)",
962 });
963 }
964 const name = yield* resolveName(id, props.name, output?.name);
965 const desired = membersOf(props.resources as readonly GroupMember[]);
966 const collapsed = props.collapsed ?? output?.collapsed ?? false;
967
968 let current = yield* observe({
969 projectId,
970 environmentId,
971 groupId: output?.groupId,
972 name,
973 volumeIds: desired.volumeIds,
974 });
975
976 // Railway IaC keys new groups by name (`isCreated: true`) and stamps
977 // `service.groupId = name`. After apply, Railway remaps the key to a
978 // UUID — observe-by-name picks that up.
979 const groupId = current?.groupId ?? output?.groupId ?? name;
980
981 if (current === undefined) {
982 yield* commitPatch({
983 environmentId,
984 commitMessage: `Alchemy: create group ${name}`,
985 patch: membershipPatch({
986 groupId,
987 name,
988 color: props.color,
989 icon: props.icon,
990 collapsed,
991 create: true,
992 services: desired.serviceIds.map((serviceId) => ({ serviceId, groupId })),
993 }),
994 });
995 if (desired.bucketIds.length > 0) {
996 yield* commitPatch({
997 environmentId,
998 commitMessage: `Alchemy: assign buckets to group ${name}`,
999 patch: {
1000 buckets: bucketPatch(desired.bucketIds.map((bucketId) => ({ bucketId, groupId }))),
1001 },
1002 });
1003 }
1004 current =
1005 (yield* waitUntilPresent({
1006 projectId,
1007 environmentId,
1008 groupId,
1009 name,
1010 volumeIds: desired.volumeIds,
1011 })) ?? undefined;
1012 }
1013
1014 if (current !== undefined) {
1015 const nameChanged = current.name !== name;
1016 const colorChanged = props.color !== undefined && props.color !== current.color;
1017 const iconChanged = props.icon !== undefined && props.icon !== current.icon;
1018 const collapsedChanged = props.collapsed !== undefined && collapsed !== current.collapsed;
1019 const servicesChanged = !sameIds(current.serviceIds, desired.serviceIds);
1020 const bucketsChanged = !sameIds(current.bucketIds, desired.bucketIds);
1021 if (
1022 nameChanged ||
1023 colorChanged ||
1024 iconChanged ||
1025 collapsedChanged ||
1026 servicesChanged ||
1027 bucketsChanged
1028 ) {
1029 const services = [
1030 ...desired.serviceIds
1031 .filter((serviceId) => !current!.serviceIds.includes(serviceId))
1032 .map((serviceId) => ({ serviceId, groupId: current!.groupId })),
1033 ...current.serviceIds
1034 .filter((serviceId) => !desired.serviceIds.includes(serviceId))
1035 .map((serviceId) => ({ serviceId, groupId: null })),
1036 ];
1037 const buckets = [
1038 ...desired.bucketIds
1039 .filter((bucketId) => !current!.bucketIds.includes(bucketId))
1040 .map((bucketId) => ({ bucketId, groupId: current!.groupId })),
1041 ...current.bucketIds
1042 .filter((bucketId) => !desired.bucketIds.includes(bucketId))
1043 .map((bucketId) => ({ bucketId, groupId: null })),
1044 ];
1045 yield* commitPatch({
1046 environmentId,
1047 commitMessage: `Alchemy: update group ${name}`,
1048 patch: membershipPatch({
1049 groupId: current.groupId,
1050 name,
1051 color: props.color ?? current.color,
1052 icon: props.icon ?? current.icon,
1053 collapsed,
1054 create: false,
1055 services,
1056 buckets,
1057 }),
1058 });
1059 current =
1060 (yield* observe({
1061 projectId,
1062 environmentId,
1063 groupId: current.groupId,
1064 name,
1065 volumeIds: desired.volumeIds,
1066 })) ?? current;
1067 }
1068 }
1069
1070 const preview = yield* previewCanvas(environmentId);
1071 if (preview !== undefined && preview.mutations.length > 0) {
1072 yield* mergeCanvas(environmentId, environmentId);
1073 }
1074
1075 const observed = yield* observe({
1076 projectId,
1077 environmentId,
1078 groupId: current?.groupId ?? groupId,
1079 name,
1080 volumeIds: desired.volumeIds,
1081 });
1082
1083 const resolved = observed ?? current;
1084 return toAttrs(
1085 fallbackGroup({
1086 groupId: resolved?.groupId ?? groupId,
1087 name: resolved?.name || name,
1088 color: props.color ?? resolved?.color,
1089 icon: props.icon ?? resolved?.icon,
1090 collapsed: resolved?.collapsed ?? collapsed,
1091 serviceIds:
1092 resolved !== undefined && resolved.serviceIds.length > 0
1093 ? resolved.serviceIds
1094 : desired.serviceIds,
1095 volumeIds: uniqueSorted([...(resolved?.volumeIds ?? []), ...desired.volumeIds]),
1096 bucketIds: uniqueSorted([...(resolved?.bucketIds ?? []), ...desired.bucketIds]),
1097 }),
1098 { projectId, environmentId },
1099 );
1100 }),
1101
1102 delete: Effect.fn(function* ({ output }) {
1103 const groupId = output.groupId;
1104 const environmentId = output.environmentId;
1105 const projectId = output.projectId;
1106 if (groupId.length === 0 || environmentId.length === 0) return;
1107 const current = yield* observe({
1108 projectId,
1109 environmentId,
1110 groupId,
1111 name: output.name,
1112 volumeIds: output.volumeIds,
1113 });
1114 if (current === undefined) return;
1115 yield* commitPatch({
1116 environmentId,
1117 commitMessage: `Alchemy: delete group ${output.name}`,
1118 patch: membershipPatch({
1119 groupId,
1120 name: output.name,
1121 collapsed: false,
1122 create: false,
1123 remove: true,
1124 services: current.serviceIds.map((serviceId) => ({ serviceId, groupId: null })),
1125 buckets: current.bucketIds.map((bucketId) => ({ bucketId, groupId: null })),
1126 }),
1127 }).pipe(Effect.catchTag("RailwayNotFound", () => Effect.succeed("")));
1128 if (projectId.length > 0) {
1129 yield* waitUntilGone({ projectId, environmentId, groupId, name: output.name });
1130 }
1131 }),
1132 });