@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 819 lines 28.1 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import {
3 Railway,
4 type VolumeCreateInput,
5 type VolumeInstance,
6 type VolumeState,
7 } from "@distilled.cloud/railway";
8 import { Unowned } from "alchemy/AdoptPolicy";
9 import { isResolved } from "alchemy/Diff";
10 import * as Provider from "alchemy/Provider";
11 import { Resource } from "alchemy/Resource";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Schedule from "effect/Schedule";
15 import * as Semaphore from "effect/Semaphore";
16 import * as Stream from "effect/Stream";
17 import { environmentVolumes, waitUntilDeleted } from "./GraphQL.ts";
18 import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts";
19 import { MultipleVolumes } from "./MountVolume.ts";
20 import { ownedProjects, type Project } from "./Project.ts";
21 import type { Providers } from "./Providers.ts";
22
23 const volumeFields = <E>(instance: Query<VolumeInstance, E>) => ({
24 id: instance.id,
25 volumeId: instance.volumeId,
26 environmentId: instance.environmentId,
27 serviceId: instance.serviceId,
28 deletedAt: instance.deletedAt,
29 isPendingDeletion: instance.isPendingDeletion,
30 state: instance.state,
31 mountPath: instance.mountPath,
32 volume: {
33 id: instance.volume.id,
34 name: instance.volume.name,
35 projectId: instance.volume.projectId,
36 },
37 region: instance.region,
38 sizeMB: instance.sizeMB,
39 createdAt: instance.createdAt,
40 });
41 type CloudInstance = UnwrapPlan<ReturnType<typeof volumeFields>>;
42
43 /**
44 * A resource-valued prop: the resource itself, or an Effect that produces
45 * it (so `yield* Project(...)` and `Project(...)` both type-check).
46 */
47 type Ref<T> = T | Effect.Effect<T, never, Providers>;
48
49 /**
50 * Environment identity a Volume is deployed into. Accepts a
51 * `Railway.Project` (its primary environment), a `Railway.Environment`,
52 * or an `{ environmentId }` stub.
53 */
54 export type VolumeEnvironment = { readonly environmentId: string };
55
56 /**
57 * Service identity a Volume can attach to at create time. Accepts a
58 * `Railway.Service` or a `{ serviceId }` stub. Subsequent attach is
59 * `MountVolume` — omit `service` to leave the volume disconnected.
60 */
61 export type VolumeService = { readonly serviceId: string };
62
63 export interface VolumeProps {
64 /**
65 * Parent Railway Project. Changing it replaces the Volume.
66 */
67 project: Ref<Project>;
68 /**
69 * Environment to deploy the volume instance into. Accepts a
70 * `Railway.Project` (primary environment), a `Railway.Environment`, or
71 * `{ environmentId }`. Defaults to the project's primary environment.
72 * Changing it replaces the Volume.
73 */
74 environment?: Ref<VolumeEnvironment>;
75 /**
76 * Path in the container to mount the volume. Updates in place via
77 * `volumeInstanceUpdate`.
78 */
79 mountPath: string;
80 /**
81 * Region for the volume instance (`us-west2`, `us-east4`, …). If
82 * omitted, Railway picks the default. Changing it replaces the Volume.
83 */
84 region?: string;
85 /**
86 * Service to attach the volume to. If omitted, the volume is
87 * disconnected — attach later with MountVolume. Accepts a
88 * `Railway.Service` or `{ serviceId }`. Updating it attaches or moves
89 * the volume in place.
90 */
91 service?: Ref<VolumeService>;
92 /**
93 * Requested provisioned size in megabytes (Railway IaC parity).
94 *
95 * The public GraphQL `VolumeCreateInput` has no `size`/`sizeMB` field,
96 * and `VolumeInstanceUpdateInput` cannot grow a volume — growing is
97 * Pro-dashboard-only. Alchemy records this prop and reports the cloud
98 * plan default on the observed `sizeMB` attribute. Changing it does
99 * not call an API.
100 */
101 sizeMB?: number;
102 }
103
104 export type Volume = Resource<
105 "Railway.Volume",
106 VolumeProps,
107 {
108 /** Railway volume id. */
109 volumeId: string;
110 /** Volume instance id in the target environment. */
111 volumeInstanceId: string;
112 /** Physical volume name (unique per project). */
113 name: string;
114 /** Parent Railway project id. */
115 projectId: string;
116 /** Environment the instance is deployed in. */
117 environmentId: string;
118 /** Mount path in the container. */
119 mountPath: string;
120 /** Region the instance lives in, if Railway reported one. */
121 region: string | undefined;
122 /** Attached service id, if any. */
123 serviceId: string | undefined;
124 /** Observed instance state (`READY`, `UPDATING`, …). */
125 state: VolumeState | undefined;
126 /**
127 * Observed provisioned size in MB. Railway picks this from the
128 * workspace plan; the public create/update APIs cannot set it.
129 */
130 sizeMB: number;
131 /** RFC3339 creation timestamp. */
132 createdAt: string;
133 },
134 never,
135 Providers
136 >;
137
138 const resolveVolumeProps = (
139 props: VolumeProps | Effect.Effect<VolumeProps, never, Providers>,
140 ): Effect.Effect<VolumeProps, never, Providers> =>
141 Effect.gen(function* () {
142 const resolved = Effect.isEffect(props) ? yield* props : props;
143 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
144 const project = Effect.isEffect(resolved.project)
145 ? yield* resolved.project as Effect.Effect<Project, never, Providers>
146 : resolved.project;
147 const environment =
148 resolved.environment === undefined
149 ? undefined
150 : Effect.isEffect(resolved.environment)
151 ? yield* resolved.environment as Effect.Effect<VolumeEnvironment, never, Providers>
152 : resolved.environment;
153 const service =
154 resolved.service === undefined
155 ? undefined
156 : Effect.isEffect(resolved.service)
157 ? yield* resolved.service as Effect.Effect<VolumeService, never, Providers>
158 : resolved.service;
159 return { ...resolved, project, environment, service };
160 });
161
162 const VolumeResource = Resource<Volume>("Railway.Volume");
163
164 /**
165 * A Railway.Volume is block disk in a Project. Create it disconnected
166 * (no `service`) and attach later with `MountVolume`, or pass `service`
167 * to attach at create time.
168 *
169 * Railway has no labels. Ownership is stamped into the volume name via
170 * `createPhysicalName`. `mountPath` updates in place. Changing `project`,
171 * `environment`, or `region` replaces the Volume.
172 *
173 * @see https://docs.railway.com/guides/volumes
174 * @see https://docs.railway.com/integrations/api/manage-volumes
175 *
176 * ### Create a Volume
177 * Pass a Project and a mount path. Alchemy generates a unique name.
178 * The volume is disconnected until you attach a Service.
179 *
180 * **Example:** Disconnected volume
181 * ```typescript
182 * const site = yield* Railway.Project("Site");
183 * const data = yield* Railway.Volume("Data", {
184 * project: site,
185 * mountPath: "/data",
186 * });
187 * ```
188 *
189 * :::caution[Changing `project` replaces the Volume]
190 * The Volume is created in the new Project. The old Volume is deleted.
191 * :::
192 *
193 * ### Mount path
194 * `mountPath` is the path in the container. Updating it is in place.
195 *
196 * **Example:** Update the mount path
197 * ```typescript
198 * const data = yield* Railway.Volume("Data", {
199 * project: site,
200 * mountPath: "/app/data",
201 * });
202 * ```
203 *
204 * ### Environment
205 * Defaults to the Project's primary environment. Pass a
206 * `Railway.Environment` (or `{ environmentId }`) to target another one.
207 *
208 * **Example:** Extra environment
209 * ```typescript
210 * const staging = yield* Railway.Environment("Staging", { project: site });
211 * const data = yield* Railway.Volume("StagingData", {
212 * project: site,
213 * environment: staging,
214 * mountPath: "/data",
215 * });
216 * ```
217 *
218 * :::caution[Changing `environment` replaces the Volume]
219 * The Volume is created in the new environment. The old Volume is deleted.
220 * :::
221 *
222 * ### Region
223 * Omit `region` to use Railway's default. Changing it replaces the Volume.
224 *
225 * **Example:** Pin a region
226 * ```typescript
227 * const data = yield* Railway.Volume("Data", {
228 * project: site,
229 * mountPath: "/data",
230 * region: "us-west2",
231 * });
232 * ```
233 *
234 * :::caution[Changing `region` replaces the Volume]
235 * Volumes cannot move region. A new Volume is created, then the old one
236 * is deleted.
237 * :::
238 *
239 * ### Size
240 * `sizeMB` on attributes is the observed plan default. Railway's public
241 * `VolumeCreateInput` has no size field; growing is Pro-dashboard-only.
242 * Passing `sizeMB` on props is IaC-parity documentation — it is not
243 * applied.
244 *
245 * **Example:** Observed size
246 * ```typescript
247 * const data = yield* Railway.Volume("Data", {
248 * project: site,
249 * mountPath: "/data",
250 * });
251 * // data.sizeMB is the plan default (e.g. 5120 on Hobby)
252 * ```
253 *
254 * ### Attach to a Service
255 * Pass `service` to attach at create time. Omit it and attach later with
256 * `MountVolume`. One volume per service.
257 *
258 * **Example:** Create-time attach
259 * ```typescript
260 * const api = yield* Railway.Service("Api", {
261 * project: site,
262 * image: "hashicorp/http-echo",
263 * });
264 * const data = yield* Railway.Volume("Data", {
265 * project: site,
266 * mountPath: "/data",
267 * service: api,
268 * });
269 * ```
270 *
271 * :::caution[One volume per service]
272 * A second volume on the same Service fails with
273 * `Railway.MultipleVolumes`. Railway does not give each replica its
274 * own disk.
275 * :::
276 *
277 * ### Backups
278 * Snapshot a mounted volume with {@link VolumeBackup}. Railway only
279 * backups attached volumes. Restore is destructive — see
280 * `restoreVolumeBackup`.
281 *
282 * **Example:** Manual snapshot
283 * ```typescript
284 * const snap = yield* Railway.VolumeBackup("Nightly", { volume: data });
285 * ```
286 *
287 * ### Module-scope declarations
288 * Declare the Project once. Pass it into every child. Resource-valued
289 * props accept the resource or an Effect producing it.
290 *
291 * **Example:** Module-scope Volume
292 * ```typescript
293 * // src/data.ts
294 * import * as Railway from "@alchemy.run/railway";
295 *
296 * export const Site = Railway.Project("Site");
297 * export const Data = Railway.Volume("Data", {
298 * project: Site,
299 * mountPath: "/data",
300 * });
301 * ```
302 *
303 * @resource
304 * @product Volume
305 */
306 export const Volume: typeof VolumeResource = Object.assign(
307 (id: string, props: VolumeProps | Effect.Effect<VolumeProps, never, Providers>) =>
308 VolumeResource(id, resolveVolumeProps(props)),
309 VolumeResource,
310 );
311
312 export class VolumeNotCreated extends Data.TaggedError("Railway.VolumeNotCreated")<{
313 resourceName: string;
314 projectId: string;
315 }> {}
316
317 export class VolumeProjectRequired extends Data.TaggedError("Railway.VolumeProjectRequired")<{
318 message: string;
319 }> {}
320
321 export class VolumeEnvironmentRequired extends Data.TaggedError(
322 "Railway.VolumeEnvironmentRequired",
323 )<{ message: string }> {}
324
325 class VolumePending extends Data.TaggedError("Railway.VolumePending")<{
326 volumeId: string;
327 state: string;
328 }> {}
329
330 const projectIdOf = (value: unknown): string | undefined => {
331 if (value === null || typeof value !== "object") return undefined;
332 const rec = value as { projectId?: unknown };
333 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
334 };
335
336 const environmentIdOf = (value: unknown): string | undefined => {
337 if (value === null || typeof value !== "object") return undefined;
338 const rec = value as { environmentId?: unknown };
339 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
340 ? rec.environmentId
341 : undefined;
342 };
343
344 const serviceIdOf = (value: unknown): string | undefined => {
345 if (value === null || typeof value !== "object") return undefined;
346 const rec = value as { serviceId?: unknown };
347 return typeof rec.serviceId === "string" && rec.serviceId.length > 0 ? rec.serviceId : undefined;
348 };
349
350 const goneState = (state: VolumeState | null | undefined) =>
351 state === "DELETED" || state === "DELETING";
352
353 const transientState = (state: VolumeState | null | undefined) =>
354 state === "UPDATING" ||
355 state === "MIGRATING" ||
356 state === "MIGRATION_PENDING" ||
357 state === "RESTORING";
358
359 const isDeletedAt = (value: string | null | undefined) =>
360 typeof value === "string" && value.length > 0;
361
362 const isGone = (instance: CloudInstance | undefined) =>
363 instance === undefined || isDeletedAt(instance.deletedAt) || goneState(instance.state);
364
365 const toAttrs = (instance: CloudInstance, fallback?: { name?: string }): Volume["Attributes"] => ({
366 volumeId: instance.volumeId || instance.volume.id,
367 volumeInstanceId: instance.id,
368 name: instance.volume.name || fallback?.name || "",
369 projectId: instance.volume.projectId,
370 environmentId: instance.environmentId,
371 mountPath: instance.mountPath,
372 region: instance.region ?? undefined,
373 serviceId: instance.serviceId ?? undefined,
374 state: instance.state ?? undefined,
375 sizeMB: instance.sizeMB,
376 createdAt: instance.createdAt,
377 });
378
379 const resolveName = (id: string, existing?: string) =>
380 Effect.gen(function* () {
381 if (existing !== undefined) return existing;
382 return yield* createRailwayName(id);
383 });
384
385 const readVolumeInstance = Query.fn((id: string) => volumeFields(Railway.volumeInstance({ id })));
386
387 const getByInstanceId = (volumeInstanceId: string) =>
388 readVolumeInstance(volumeInstanceId).pipe(
389 Effect.map((instance): CloudInstance | undefined => (isGone(instance) ? undefined : instance)),
390 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
391 );
392
393 const listVolumeInstances = (environmentId: string, projectId: string) =>
394 environmentVolumes(environmentId, projectId, volumeFields).pipe(
395 Effect.map((instances) => instances.filter((node) => !isGone(node))),
396 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudInstance[])),
397 );
398
399 /** Volumes currently attached to a service instance. Used by Service reconcile. */
400 export const listServiceVolumes = (environmentId: string, projectId: string, serviceId: string) =>
401 listVolumeInstances(environmentId, projectId).pipe(
402 Effect.map((rows) => rows.filter((row) => (row.serviceId ?? undefined) === serviceId)),
403 );
404
405 const findInEnvironment = (
406 environmentId: string,
407 projectId: string,
408 match: (instance: CloudInstance) => boolean,
409 ) =>
410 listVolumeInstances(environmentId, projectId).pipe(
411 Effect.map((instances) => instances.find(match)),
412 );
413
414 const volumeInstanceUpdate = Query.fn((args: Parameters<typeof Railway.volumeInstanceUpdate>[0]) =>
415 Railway.volumeInstanceUpdate(args),
416 );
417
418 const volumeAttachSlots = new Map<string, Semaphore.Semaphore>();
419
420 const withVolumeAttachLock = <A, E, R>(
421 serviceId: string | undefined,
422 effect: Effect.Effect<A, E, R>,
423 ): Effect.Effect<A, E, R> => {
424 if (serviceId === undefined) return effect;
425 let slot = volumeAttachSlots.get(serviceId);
426 if (slot === undefined) {
427 slot = Semaphore.makeUnsafe(1);
428 volumeAttachSlots.set(serviceId, slot);
429 }
430 return Semaphore.withPermits(slot, 1)(effect);
431 };
432
433 const assertAttachTarget = Effect.fn(function* (input: {
434 name: string;
435 environmentId: string;
436 projectId: string;
437 serviceId: string;
438 volumeId?: string;
439 }) {
440 const others = (yield* listVolumeInstances(input.environmentId, input.projectId)).filter(
441 (row) => {
442 if ((row.serviceId ?? undefined) !== input.serviceId) return false;
443 if (input.volumeId !== undefined && row.volumeId === input.volumeId) {
444 return false;
445 }
446 return true;
447 },
448 );
449 if (others.length > 0) {
450 return yield* new MultipleVolumes({
451 resourceName: input.name,
452 paths: others.map((row) => row.mountPath),
453 volumeIds: others.map((row) => row.volumeId),
454 });
455 }
456 });
457
458 const liveEnvironments = (projectId: string) =>
459 Query.items(
460 Railway.environments({ projectId, first: 50 }).pipe(
461 Query.map((env) => ({ id: env.id, deletedAt: env.deletedAt })),
462 ),
463 );
464
465 const _listEnvironmentIds = (project: { projectId: string; environmentId: string }) =>
466 liveEnvironments(project.projectId).pipe(
467 Stream.filter((env) => env.deletedAt == null),
468 Stream.map((env) => env.id),
469 Stream.runCollect,
470 Effect.map((ids) => {
471 const set = new Set(Array.from(ids));
472 if (project.environmentId.length > 0) {
473 set.add(project.environmentId);
474 }
475 return Array.from(set);
476 }),
477 Effect.catchTag("RailwayNotFound", () =>
478 Effect.succeed(project.environmentId.length > 0 ? [project.environmentId] : []),
479 ),
480 );
481
482 const waitUntilSynced = (
483 volumeInstanceId: string,
484 volumeId: string,
485 desired: { mountPath?: string; serviceId?: string },
486 ) =>
487 getByInstanceId(volumeInstanceId).pipe(
488 Effect.flatMap((instance) => {
489 const mountPending =
490 desired.mountPath !== undefined && instance?.mountPath !== desired.mountPath;
491 const servicePending =
492 desired.serviceId !== undefined && (instance?.serviceId ?? undefined) !== desired.serviceId;
493 if (
494 instance === undefined ||
495 transientState(instance.state) ||
496 mountPending ||
497 servicePending
498 ) {
499 return Effect.fail(new VolumePending({ volumeId, state: instance?.state ?? "creating" }));
500 }
501 return Effect.succeed(instance);
502 }),
503 Effect.retry({
504 while: (e) => e._tag === "Railway.VolumePending",
505 times: 10,
506 schedule: Schedule.spaced("3 seconds"),
507 }),
508 Effect.catchTag("Railway.VolumePending", () => getByInstanceId(volumeInstanceId)),
509 );
510
511 const waitForInstance = (environmentId: string, projectId: string, volumeId: string) =>
512 findInEnvironment(environmentId, projectId, (instance) => instance.volumeId === volumeId).pipe(
513 Effect.flatMap((instance) => {
514 if (instance === undefined || transientState(instance.state)) {
515 return Effect.fail(new VolumePending({ volumeId, state: instance?.state ?? "creating" }));
516 }
517 return Effect.succeed(instance);
518 }),
519 Effect.retry({
520 while: (e) => e._tag === "Railway.VolumePending",
521 times: 10,
522 schedule: Schedule.spaced("3 seconds"),
523 }),
524 Effect.catchTag("Railway.VolumePending", () =>
525 findInEnvironment(environmentId, projectId, (instance) => instance.volumeId === volumeId),
526 ),
527 );
528
529 /**
530 * Attach a volume instance to a service and wait until Railway reports
531 * the mount path and service id. Used by Service/Function reconcile
532 * (`MountVolume`); uploading a build before the attach is READY is
533 * how `railway up` deploys land FAILED.
534 */
535 export const attachVolumeToService = Effect.fn(function* (input: {
536 environmentId: string;
537 projectId: string;
538 serviceId: string;
539 volumeId: string;
540 mountPath: string;
541 }) {
542 if (input.volumeId.length === 0) return;
543 const observed = yield* findInEnvironment(
544 input.environmentId,
545 input.projectId,
546 (instance) => instance.volumeId === input.volumeId,
547 );
548 const already =
549 observed !== undefined &&
550 (observed.serviceId ?? undefined) === input.serviceId &&
551 observed.mountPath === input.mountPath &&
552 !transientState(observed.state);
553 if (!already) {
554 yield* volumeInstanceUpdate({
555 volumeId: input.volumeId,
556 environmentId: input.environmentId,
557 input: { serviceId: input.serviceId, mountPath: input.mountPath },
558 }).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
559 }
560 const instance =
561 observed ?? (yield* waitForInstance(input.environmentId, input.projectId, input.volumeId));
562 if (instance === undefined) return;
563 yield* waitUntilSynced(instance.id, input.volumeId, {
564 mountPath: input.mountPath,
565 serviceId: input.serviceId,
566 });
567 });
568
569 const waitUntilGone = (input: {
570 volumeInstanceId?: string;
571 volumeId: string;
572 environmentId: string;
573 projectId: string;
574 }) => {
575 const check =
576 input.volumeInstanceId !== undefined && input.volumeInstanceId.length > 0
577 ? getByInstanceId(input.volumeInstanceId).pipe(
578 Effect.map((instance) => instance === undefined),
579 )
580 : findInEnvironment(
581 input.environmentId,
582 input.projectId,
583 (instance) => instance.volumeId === input.volumeId,
584 ).pipe(Effect.map((instance) => instance === undefined));
585 return waitUntilDeleted("Volume", input.volumeId, check);
586 };
587
588 const stampName = Query.fn((volumeId: string, name: string) => ({
589 id: Railway.volumeUpdate({ volumeId, input: { name } }).id,
590 }));
591
592 const volumeCreate = Query.fn((input: VolumeCreateInput) => {
593 const volume = Railway.volumeCreate({ input });
594 return { id: volume.id, name: volume.name };
595 });
596
597 const volumeDelete = Query.fn((volumeId: string) => Railway.volumeDelete({ volumeId }));
598
599 export const VolumeProvider = () =>
600 Provider.succeed(Volume, {
601 stables: ["volumeId", "volumeInstanceId", "projectId", "environmentId", "createdAt"],
602 nuke: { dependsOn: ["Railway.Project"] },
603
604 diff: Effect.fn(function* ({ news, output }) {
605 if (news === undefined || !isResolved(news)) return undefined;
606 if (output === undefined) return undefined;
607 const nextProject = projectIdOf(news.project);
608 const projectChanged = nextProject !== undefined && nextProject !== output.projectId;
609 const nextEnv = environmentIdOf(news.environment);
610 const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId;
611 const regionChanged = news.region !== undefined && news.region !== output.region;
612 if (projectChanged || environmentChanged || regionChanged) {
613 return { action: "replace" as const };
614 }
615 return undefined;
616 }),
617
618 read: Effect.fn(function* ({ id, olds, output }) {
619 const projectId =
620 output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined);
621 const environmentId =
622 output?.environmentId ??
623 (olds !== undefined
624 ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project))
625 : undefined);
626 const name = yield* resolveName(id, output?.name);
627
628 const byInstance =
629 output?.volumeInstanceId !== undefined && output.volumeInstanceId.length > 0
630 ? yield* getByInstanceId(output.volumeInstanceId)
631 : undefined;
632 const found =
633 byInstance ??
634 (projectId !== undefined && environmentId !== undefined
635 ? ((output?.volumeId !== undefined
636 ? yield* findInEnvironment(
637 environmentId,
638 projectId,
639 (instance) => instance.volumeId === output.volumeId,
640 )
641 : undefined) ??
642 (yield* findInEnvironment(
643 environmentId,
644 projectId,
645 (instance) => instance.volume.name === name,
646 )))
647 : undefined);
648 if (found === undefined) return undefined;
649 const attrs = toAttrs(found, { name });
650 if (output !== undefined) return attrs;
651 return matchesAlchemyPhysicalName(found.volume.name) ? attrs : Unowned(attrs);
652 }),
653
654 list: Effect.fn(function* () {
655 const projects = yield* ownedProjects();
656 const rows = yield* Effect.forEach(projects, (project) =>
657 liveEnvironments(project.projectId).pipe(
658 Stream.filter((env) => env.deletedAt == null),
659 Stream.runCollect,
660 Effect.flatMap((environments) =>
661 Effect.forEach(environments, (env) => listVolumeInstances(env.id, project.projectId)),
662 ),
663 Effect.map((rows) =>
664 rows
665 .flat()
666 .filter((instance) => matchesAlchemyPhysicalName(instance.volume.name))
667 .map((instance) => toAttrs(instance)),
668 ),
669 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as Volume["Attributes"][])),
670 ),
671 );
672 const seen = new Set<string>();
673 const unique: Volume["Attributes"][] = [];
674 for (const row of rows.flat()) {
675 if (seen.has(row.volumeId)) continue;
676 seen.add(row.volumeId);
677 unique.push(row);
678 }
679 return unique;
680 }),
681
682 reconcile: Effect.fn(function* ({ id, news, output }) {
683 const props = news ?? ({} as VolumeProps);
684 const projectId = projectIdOf(props.project) ?? output?.projectId;
685 if (projectId === undefined) {
686 return yield* new VolumeProjectRequired({
687 message: "Volume requires a resolved Railway.Project",
688 });
689 }
690 const environmentId =
691 environmentIdOf(props.environment) ??
692 environmentIdOf(props.project) ??
693 output?.environmentId;
694 if (environmentId === undefined) {
695 return yield* new VolumeEnvironmentRequired({
696 message:
697 "Volume requires a Railway environment (pass environment or a Project with environmentId)",
698 });
699 }
700 const name = yield* resolveName(id, output?.name);
701 const desiredServiceId = props.service !== undefined ? serviceIdOf(props.service) : undefined;
702
703 let current: CloudInstance | undefined =
704 output?.volumeInstanceId !== undefined && output.volumeInstanceId.length > 0
705 ? yield* getByInstanceId(output.volumeInstanceId)
706 : undefined;
707 if (current === undefined && output?.volumeId !== undefined) {
708 current = yield* findInEnvironment(
709 environmentId,
710 projectId,
711 (instance) => instance.volumeId === output.volumeId,
712 );
713 }
714 if (current === undefined) {
715 current = yield* findInEnvironment(
716 environmentId,
717 projectId,
718 (instance) => instance.volume.name === name,
719 );
720 }
721
722 current = yield* withVolumeAttachLock(
723 desiredServiceId,
724 Effect.gen(function* () {
725 if (desiredServiceId !== undefined) {
726 yield* assertAttachTarget({
727 name,
728 environmentId,
729 projectId,
730 serviceId: desiredServiceId,
731 volumeId: current?.volumeId,
732 });
733 }
734
735 if (current === undefined) {
736 const created = yield* volumeCreate({
737 projectId,
738 environmentId,
739 mountPath: props.mountPath,
740 ...(props.region !== undefined ? { region: props.region } : {}),
741 ...(desiredServiceId !== undefined ? { serviceId: desiredServiceId } : {}),
742 }).pipe(
743 Effect.catchTag("RailwayInternalError", (error) =>
744 desiredServiceId === undefined
745 ? Effect.fail(error)
746 : assertAttachTarget({
747 name,
748 environmentId,
749 projectId,
750 serviceId: desiredServiceId,
751 volumeId: current?.volumeId,
752 }).pipe(Effect.flatMap(() => Effect.fail(error))),
753 ),
754 );
755 if (created.name !== name) {
756 yield* stampName(created.id, name);
757 }
758 current = yield* waitForInstance(environmentId, projectId, created.id);
759 }
760
761 if (current === undefined || isGone(current)) {
762 return yield* new VolumeNotCreated({ resourceName: name, projectId });
763 }
764
765 if (current.volume.name !== name) {
766 yield* stampName(current.volumeId, name);
767 current =
768 (yield* getByInstanceId(current.id)) ??
769 (yield* findInEnvironment(
770 environmentId,
771 projectId,
772 (instance) => instance.volumeId === current!.volumeId,
773 )) ??
774 current;
775 }
776
777 const mountChanged = current.mountPath !== props.mountPath;
778 const observedServiceId = current.serviceId ?? undefined;
779 const serviceChanged =
780 desiredServiceId !== undefined && desiredServiceId !== observedServiceId;
781 if (mountChanged || serviceChanged) {
782 yield* volumeInstanceUpdate({
783 volumeId: current.volumeId,
784 environmentId,
785 input: {
786 ...(mountChanged ? { mountPath: props.mountPath } : {}),
787 ...(serviceChanged ? { serviceId: desiredServiceId } : {}),
788 },
789 });
790 current =
791 (yield* waitUntilSynced(current.id, current.volumeId, {
792 ...(mountChanged ? { mountPath: props.mountPath } : {}),
793 ...(serviceChanged ? { serviceId: desiredServiceId } : {}),
794 })) ?? current;
795 }
796
797 return current;
798 }),
799 );
800
801 if (current === undefined || isGone(current)) {
802 return yield* new VolumeNotCreated({ resourceName: name, projectId });
803 }
804
805 return toAttrs(current, { name });
806 }),
807
808 delete: Effect.fn(function* ({ output }) {
809 const volumeId = output.volumeId;
810 if (volumeId.length === 0) return;
811 yield* volumeDelete(volumeId).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
812 yield* waitUntilGone({
813 volumeInstanceId: output.volumeInstanceId,
814 volumeId,
815 environmentId: output.environmentId,
816 projectId: output.projectId,
817 });
818 }),
819 });