The best way to control Claude Code, Codex and more from any computer or phone

main
ts 193 lines 6.47 KB
Raw
1 import { Unowned } from "alchemy/AdoptPolicy";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, hasAlchemyTags, stripInternalTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import * as Equal from "effect/Equal";
8 import { Docker, dockerContextName, dockerPhysicalName } from "./Docker.ts";
9 import type { Providers } from "./Providers.ts";
10
11 export interface VolumeLabel {
12 /** Label name. */
13 name: string;
14 /** Label value. */
15 value: string;
16 }
17
18 export interface VolumeProps {
19 /**
20 * Docker volume name.
21 *
22 * @default Generated from stack, stage, logical id, and instance id.
23 */
24 name?: string;
25 /** Volume driver. @default "local" */
26 driver?: string;
27 /** Driver-specific options. */
28 driverOpts?: Record<string, string>;
29 /** Custom metadata labels. */
30 labels?: Record<string, string>;
31 /** Docker context name or context resource. */
32 context?: Docker.ContextRef;
33 }
34
35 export interface Volume extends Resource<
36 "Docker.Volume",
37 VolumeProps,
38 {
39 /** Docker volume name. */
40 id: string;
41 /** Docker volume name. */
42 name: string;
43 /** Volume driver. */
44 driver: string;
45 /** Driver-specific options reported by Docker. */
46 driverOpts: Record<string, string>;
47 /** Labels reported by Docker. */
48 labels: Record<string, string>;
49 /** Host mountpoint path. */
50 mountpoint?: string;
51 /** Creation timestamp in milliseconds since epoch. */
52 createdAt: number;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * A Docker volume managed through the active Docker context.
60 *
61 * Pre-existing same-name volumes are treated as foreign until the engine is
62 * allowed to adopt them with `--adopt` or `adopt(true)`.
63 *
64 *
65 * ### Creating Volumes
66 * **Example:** Basic volume
67 * ```typescript
68 * const data = yield* Docker.Volume("data", {
69 * name: "app-data",
70 * });
71 * ```
72 *
73 * **Example:** PostgreSQL data volume
74 * ```typescript
75 * const data = yield* Docker.Volume("postgres-data");
76 * ```
77 *
78 * **Example:** Driver options and labels
79 * ```typescript
80 * const data = yield* Docker.Volume("db-data", {
81 * driver: "local",
82 * driverOpts: {
83 * type: "nfs",
84 * o: "addr=10.0.0.1,rw",
85 * device: ":/path/to/dir",
86 * },
87 * labels: {
88 * "com.example.usage": "database",
89 * },
90 * });
91 * ```
92 *
93 * ### Docker Context
94 * **Example:** Create a volume in a named Docker context
95 * ```typescript
96 * const data = yield* Docker.Volume("data", {
97 * name: "app-data",
98 * context: "remote-build",
99 * });
100 * ```
101 *
102 * @resource
103 * @product Volume
104 */
105 export const Volume = Resource<Volume>("Docker.Volume");
106
107 export const VolumeProvider = () =>
108 Provider.effect(
109 Volume,
110 Effect.gen(function* () {
111 const docker = yield* Docker;
112
113 return Volume.Provider.of({
114 list: () => Effect.succeed([]),
115 read: Effect.fn(function* ({ id, instanceId, olds, output }) {
116 const context = dockerContextName(olds?.context);
117 const name = yield* dockerPhysicalName(id, olds, instanceId);
118 const info = yield* docker.volume
119 .inspect(name, context)
120 .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined));
121 if (!info) return undefined;
122 const attrs = toVolumeAttributes(info);
123 if (output) return attrs;
124 // Without prior state, only adopt a volume that carries our branding;
125 // anything else is foreign and gated behind `--adopt`.
126 const owned = yield* hasAlchemyTags(id, info.Labels ?? undefined);
127 return owned ? attrs : Unowned(attrs);
128 }),
129 diff: Effect.fn(function* ({ id, instanceId, output, news, olds }) {
130 if (!isResolved(news)) return undefined;
131 if (dockerContextName(olds?.context) !== dockerContextName(news?.context)) {
132 return { action: "replace" as const, deleteFirst: true };
133 }
134 const args = yield* makeVolumeArgs(id, news, instanceId);
135 // Auto-generated names are engine-owned: the deployed name stays
136 // authoritative even if the generator would name this id differently
137 // today. Only an explicit user-provided name can force a replace.
138 const desiredName = news?.name ?? output?.name ?? args.name;
139 if (
140 output?.name !== desiredName ||
141 output?.driver !== args.driver ||
142 !Equal.equals(output?.driverOpts ?? {}, args.opt ?? {}) ||
143 // Compare only user labels; internal `alchemy::*` branding lives on
144 // the observed volume but must not drive replacement.
145 !Equal.equals(stripInternalTags(output?.labels), args.label ?? {})
146 ) {
147 return { action: "replace" as const, deleteFirst: true };
148 }
149 }),
150 reconcile: Effect.fn(function* ({ id, instanceId, news, output }) {
151 const context = dockerContextName(news?.context);
152 const args = yield* makeVolumeArgs(id, news, instanceId);
153 // Prefer the deployed name: regenerating would target a different
154 // volume if the generator's output for this id ever drifts.
155 const name = news?.name ?? output?.name ?? args.name;
156 const internalTags = yield* createInternalTags(id);
157 const result = yield* docker.volume.create({
158 ...args,
159 name,
160 label: { ...internalTags, ...args.label },
161 context,
162 });
163 return toVolumeAttributes(yield* docker.volume.inspect(result.stdout, context));
164 }),
165 delete: Effect.fn(({ olds, output }) =>
166 docker.volume
167 .remove(output.name, dockerContextName(olds?.context))
168 .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.void)),
169 ),
170 });
171 }),
172 );
173
174 // Every prop is optional, so `Docker.Volume("data")` arrives with no props.
175 const makeVolumeArgs = (id: string, props: VolumeProps | undefined, instanceId: string) =>
176 dockerPhysicalName(id, props, instanceId).pipe(
177 Effect.map((name): Parameters<Docker["Service"]["volume"]["create"]>[0] => ({
178 name,
179 driver: props?.driver ?? "local",
180 opt: props?.driverOpts,
181 label: props?.labels,
182 })),
183 );
184
185 export const toVolumeAttributes = (info: Docker.Volume): Volume["Attributes"] => ({
186 id: info.Name,
187 name: info.Name,
188 driver: info.Driver,
189 driverOpts: info.Options ?? {},
190 labels: info.Labels ?? {},
191 mountpoint: info.Mountpoint,
192 createdAt: Date.parse(info.CreatedAt) || Date.now(),
193 });