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

main
ts 365 lines 11.5 KB
Raw
1 import * as vmwareengine from "@distilled.cloud/gcp/vmwareengine_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 VmwareengineNotResolved,
12 changedFields,
13 collectPages,
14 createInternalLabels,
15 encodeOwnership,
16 hasAlchemyLabels,
17 hasOwnershipMarker,
18 listAcrossLocations,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 parseOwnership,
23 replaceOnIdentity,
24 rfc1035,
25 sameJson,
26 toPhysicalId,
27 waitForOperation,
28 waitUntilGone,
29 waitUntilPresent,
30 waitUntilReady,
31 } from "./internal.ts";
32
33 const COLLECTION = "datastores";
34
35 export type GoogleFileService = {
36 /** NetApp Volume resource name. */
37 netappVolume?: string;
38 /** Filestore instance resource name. */
39 filestoreInstance?: string;
40 };
41
42 export type ThirdPartyFileService = {
43 /** NFS server IP addresses or DNS names. */
44 servers?: string[];
45 /** VPC used for NFS access. */
46 network?: string;
47 /** Mount folder name. */
48 fileShare?: string;
49 };
50
51 export type NfsDatastore = {
52 /** Google-managed file service (NetApp or Filestore). */
53 googleFileService?: GoogleFileService;
54 /** GCVE-managed file service. */
55 googleVmwareFileService?: Record<string, never>;
56 /** Third-party NFS file service. */
57 thirdPartyFileService?: ThirdPartyFileService;
58 };
59
60 export type DatastoreProps = {
61 /**
62 * Datastore id (the `{datastore}` segment of
63 * `projects/{project}/locations/{location}/datastores/{datastore}`).
64 * If omitted, a unique RFC1035 name is generated. Immutable — changing
65 * it replaces the datastore.
66 */
67 datastoreId?: string;
68 /**
69 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
70 * replaces the datastore. `US-CENTRAL1` is accepted and normalized.
71 * @default the stack's GCP region (`GCP.Region`, else the profile
72 * region, else `us-central1`)
73 */
74 location?: string;
75 /**
76 * NFS backend. Required. Choose Google Filestore/NetApp, a GCVE file
77 * service, or a third-party NFS server.
78 */
79 nfsDatastore: NfsDatastore;
80 /**
81 * Human-readable description. Datastores have no labels field, so
82 * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it
83 * from attributes.
84 */
85 description?: string;
86 };
87
88 export type Datastore = Resource<
89 "GCP.VMwareEngine.Datastore",
90 DatastoreProps,
91 {
92 /** Full resource name. */
93 name: string;
94 /** Datastore id (last path segment). */
95 datastoreId: string;
96 /** Project id. */
97 project: string;
98 /** Location id. */
99 location: string;
100 /** NFS backend currently configured. */
101 nfsDatastore: NfsDatastore | undefined;
102 /** Clusters the datastore is attached to. */
103 clusters: string[];
104 /** User description with the Alchemy ownership prefix stripped. */
105 description: string | undefined;
106 /** Server-reported state. */
107 state: string | undefined;
108 /** Server etag. */
109 etag: string | undefined;
110 /** System-generated unique identifier. */
111 uid: string | undefined;
112 /** RFC3339 creation timestamp. */
113 createTime: string | undefined;
114 /** RFC3339 last-update timestamp. */
115 updateTime: string | undefined;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A Google Cloud VMware Engine NFS datastore.
123 *
124 * Datastores have no labels field, so Alchemy stamps ownership into the
125 * description for `list` / nuke. Changing `datastoreId`, `location`, or
126 * the NFS backend identity replaces the datastore. Description updates
127 * in place.
128 *
129 * ### Creating a Datastore
130 * **Example:** Filestore-backed NFS datastore
131 * ```typescript
132 * const datastore = yield* GCP.VMwareEngine.Datastore("Nfs", {
133 * nfsDatastore: {
134 * googleFileService: {
135 * filestoreInstance:
136 * "projects/my-project/locations/us-central1-a/instances/share",
137 * },
138 * },
139 * description: "app nfs datastore",
140 * });
141 * ```
142 *
143 * **Example:** Third-party NFS
144 * ```typescript
145 * const datastore = yield* GCP.VMwareEngine.Datastore("VendorNfs", {
146 * nfsDatastore: {
147 * thirdPartyFileService: {
148 * servers: ["10.1.2.3"],
149 * network: "projects/my-project/global/networks/default",
150 * fileShare: "vol1",
151 * },
152 * },
153 * });
154 * ```
155 *
156 * @resource
157 * @category VMwareEngine
158 */
159 export const Datastore = Resource<Datastore>("GCP.VMwareEngine.Datastore");
160
161 const resourceName = (project: string, location: string, datastoreId: string) =>
162 `${parentOf(project, location)}/${COLLECTION}/${datastoreId}`;
163
164 const nfsOf = (
165 value: vmwareengine.NfsDatastore | NfsDatastore | undefined,
166 ): NfsDatastore | undefined => {
167 if (value === undefined) return undefined;
168 return {
169 googleFileService:
170 value.googleFileService === undefined
171 ? undefined
172 : {
173 netappVolume: value.googleFileService.netappVolume,
174 filestoreInstance: value.googleFileService.filestoreInstance,
175 },
176 googleVmwareFileService: value.googleVmwareFileService === undefined ? undefined : {},
177 thirdPartyFileService:
178 value.thirdPartyFileService === undefined
179 ? undefined
180 : {
181 servers: value.thirdPartyFileService.servers,
182 network: value.thirdPartyFileService.network,
183 fileShare: value.thirdPartyFileService.fileShare,
184 },
185 };
186 };
187
188 const toAttrs = (item: vmwareengine.Datastore, project: string, region: string) => {
189 const name = item.name ?? "";
190 const parsed = parseName(name, COLLECTION, region);
191 const ownership = parseOwnership(item.description);
192 return {
193 name,
194 datastoreId: parsed.id,
195 project: parsed.project || project,
196 location: parsed.location,
197 nfsDatastore: nfsOf(item.nfsDatastore),
198 clusters: item.clusters ?? [],
199 description: ownership.text,
200 state: item.state,
201 etag: item.etag,
202 uid: item.uid,
203 createTime: item.createTime,
204 updateTime: item.updateTime,
205 };
206 };
207
208 const getByName = (name: string) =>
209 vmwareengine
210 .getProjectsLocationsDatastores({ name })
211 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
212
213 export const DatastoreProvider = () =>
214 Provider.succeed(Datastore, {
215 stables: ["name", "datastoreId", "project", "location", "uid", "createTime"],
216
217 diff: Effect.fn(function* ({ news, olds, output }) {
218 if (!isResolved(news)) return undefined;
219 const env = yield* GcpEnvironment.current;
220 return replaceOnIdentity({
221 previousId: olds?.datastoreId ?? output?.datastoreId,
222 nextId: news.datastoreId
223 ? rfc1035(news.datastoreId, "datastore")
224 : (olds?.datastoreId ?? output?.datastoreId),
225 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
226 nextLocation: normalizeLocation(
227 news.location ?? olds?.location ?? output?.location,
228 env.region,
229 ),
230 extra: !sameJson(news.nfsDatastore, olds?.nfsDatastore),
231 });
232 }),
233
234 read: Effect.fn(function* ({ id, olds, output }) {
235 const env = yield* GcpEnvironment.current;
236 const datastoreId = yield* toPhysicalId(
237 id,
238 olds?.datastoreId,
239 output?.datastoreId,
240 "datastore",
241 );
242 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
243 const name = output?.name ?? resourceName(env.project, location, datastoreId);
244 const existing = yield* getByName(name);
245 if (existing === undefined) return undefined;
246 const attrs = toAttrs(existing, env.project, env.region);
247 const { labels } = parseOwnership(existing.description);
248 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
249 }),
250
251 list: () =>
252 Effect.gen(function* () {
253 const env = yield* GcpEnvironment.current;
254 const items = yield* listAcrossLocations(env.project, env.region, (parent) =>
255 collectPages(
256 vmwareengine.listProjectsLocationsDatastores.pages({
257 parent,
258 pageSize: 1000,
259 }),
260 (page) => page.datastores,
261 ),
262 );
263 return items
264 .filter((item) => hasOwnershipMarker(item.description))
265 .map((item) => toAttrs(item, env.project, env.region));
266 }),
267
268 reconcile: Effect.fn(function* ({ id, news, output }) {
269 const env = yield* GcpEnvironment.current;
270 const datastoreId = yield* toPhysicalId(
271 id,
272 news.datastoreId,
273 output?.datastoreId,
274 "datastore",
275 );
276 const location = normalizeLocation(news.location ?? output?.location, env.region);
277 const name = resourceName(env.project, location, datastoreId);
278 const ownership = yield* createInternalLabels(id);
279 const desiredDescription = encodeOwnership(ownership, news.description);
280
281 let current = yield* getByName(output?.name ?? name);
282
283 if (current === undefined) {
284 const created = yield* vmwareengine
285 .createProjectsLocationsDatastores({
286 parent: parentOf(env.project, location),
287 datastoreId,
288 body: {
289 nfsDatastore: news.nfsDatastore,
290 description: desiredDescription,
291 },
292 })
293 .pipe(
294 Effect.retry({
295 while: (error) => error._tag === "Conflict",
296 times: 5,
297 schedule: Schedule.spaced("2 seconds"),
298 }),
299 Effect.catchTag("Conflict", () => Effect.undefined),
300 );
301 if (created !== undefined) {
302 yield* waitForOperation(created);
303 }
304 current = yield* waitUntilPresent(getByName(name), name);
305 }
306
307 if (current === undefined) {
308 return yield* new VmwareengineNotResolved({ resourceName: name });
309 }
310
311 current = yield* waitUntilReady(
312 getByName(current.name ?? name),
313 current.name ?? name,
314 (item) => item.state,
315 );
316
317 const descriptionChanged = (current.description ?? "") !== desiredDescription;
318 const nfsChanged = !sameJson(nfsOf(current.nfsDatastore), nfsOf(news.nfsDatastore));
319 const updateMask = changedFields([
320 ["description", descriptionChanged],
321 ["nfsDatastore", nfsChanged],
322 ]);
323
324 if (updateMask.length > 0) {
325 const operation = yield* vmwareengine.patchProjectsLocationsDatastores({
326 name: current.name ?? name,
327 updateMask: updateMask.join(","),
328 body: {
329 name: current.name ?? name,
330 description: desiredDescription,
331 nfsDatastore: news.nfsDatastore,
332 etag: current.etag,
333 },
334 });
335 yield* waitForOperation(operation);
336 current = yield* waitUntilReady(
337 getByName(current.name ?? name),
338 current.name ?? name,
339 (item) => item.state,
340 );
341 }
342
343 return toAttrs(current, env.project, env.region);
344 }),
345
346 delete: Effect.fn(function* ({ output }) {
347 const operation = yield* vmwareengine
348 .deleteProjectsLocationsDatastores({
349 name: output.name,
350 etag: output.etag,
351 })
352 .pipe(
353 Effect.retry({
354 while: (error) => error._tag === "Conflict",
355 times: 8,
356 schedule: Schedule.spaced("2 seconds"),
357 }),
358 Effect.catchTag("NotFound", () => Effect.undefined),
359 );
360 if (operation !== undefined) {
361 yield* waitForOperation(operation, { notFoundOk: true });
362 }
363 yield* waitUntilGone(getByName(output.name), output.name);
364 }),
365 });