@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 418 lines 13.6 KB
Raw
1 import * as gkeonprem from "@distilled.cloud/gcp/gkeonprem_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 ResourceNotResolved,
14 VMWARE_NAME_LENGTH,
15 collectPages,
16 createInternalLabels,
17 desiredAnnotations,
18 differs,
19 encodeOwnership,
20 expandParent,
21 fieldMask,
22 isOwned,
23 listAtLocation,
24 listAtNested,
25 listChildrenOf,
26 normalizeLocation,
27 parseName,
28 parseOwnership,
29 replaceOnIdentity,
30 rfc1035,
31 sameText,
32 textState,
33 toPhysicalId,
34 userLabels,
35 waitForOperation,
36 waitUntilExists,
37 waitUntilGone,
38 } from "./internal.ts";
39 import type { VmwareNodeConfig, VmwareNodePoolAutoscalingConfig } from "./types.ts";
40
41 const COLLECTION = "vmwareNodePools";
42 const PARENT_COLLECTION = "vmwareClusters";
43
44 export type VmwareClustersVmwareNodePoolProps = {
45 /**
46 * Parent VMware user cluster. Full name
47 * `projects/{project}/locations/{location}/vmwareClusters/{cluster}`
48 * or the cluster id (combined with `location`). Immutable — changing
49 * it replaces the node pool.
50 */
51 vmwareCluster: string;
52 /**
53 * Region used when `vmwareCluster` is a bare id.
54 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
55 */
56 location?: string;
57 /**
58 * Node pool id (the `{vmwareNodePool}` segment). If omitted, a unique
59 * RFC1123 name is generated. Max 40 characters. Immutable — changing
60 * it replaces the pool.
61 */
62 vmwareNodePoolId?: string;
63 /**
64 * Node configuration (image type, replicas, CPU, memory).
65 */
66 config: VmwareNodeConfig;
67 /**
68 * Display name. Node pools have no GCP labels field, so Alchemy stamps
69 * ownership into annotations and a `[alchemy …]` displayName prefix
70 * and strips both from attributes.
71 */
72 displayName?: string;
73 /**
74 * Anthos version for the node pool. Defaults to the user cluster version.
75 */
76 onPremVersion?: string;
77 /**
78 * Node pool autoscaling bounds.
79 */
80 nodePoolAutoscaling?: VmwareNodePoolAutoscalingConfig;
81 /**
82 * Kubernetes-style annotations. Alchemy ownership keys are merged in.
83 */
84 annotations?: Record<string, string>;
85 /**
86 * User labels stored as annotations (keys sanitized like GCP labels).
87 * Alchemy ownership labels are merged in automatically.
88 */
89 labels?: Record<string, string>;
90 };
91
92 export type VmwareClustersVmwareNodePool = Resource<
93 "GCP.GKEOnPrem.VmwareClustersVmwareNodePool",
94 VmwareClustersVmwareNodePoolProps,
95 {
96 /** Full resource name. */
97 name: string;
98 /** Node pool id (last path segment). */
99 vmwareNodePoolId: string;
100 /** Parent cluster resource name. */
101 vmwareCluster: string;
102 /** Project id. */
103 project: string;
104 /** Location id. */
105 location: string;
106 /** Node configuration. */
107 config: gkeonprem.VmwareNodeConfig | undefined;
108 /** User display name with the Alchemy ownership prefix stripped. */
109 displayName: string | undefined;
110 /** Anthos version. */
111 onPremVersion: string | undefined;
112 /** Autoscaling bounds. */
113 nodePoolAutoscaling: gkeonprem.VmwareNodePoolAutoscalingConfig | undefined;
114 /** User annotations (Alchemy ownership keys stripped). */
115 annotations: Record<string, string>;
116 /** User labels (Alchemy ownership keys stripped). */
117 labels: Record<string, string>;
118 /** Server-reported state. */
119 state: string | undefined;
120 /** Server-generated resource uid. */
121 uid: string | undefined;
122 /** Whether a change is in flight. */
123 reconciling: boolean | undefined;
124 /** Controller error message. */
125 errorMessage: string | undefined;
126 /** RFC3339 creation timestamp. */
127 createTime: string | undefined;
128 /** RFC3339 last-update timestamp. */
129 updateTime: string | undefined;
130 /** RFC3339 deletion timestamp. */
131 deleteTime: string | undefined;
132 /** Server etag. */
133 etag: string | undefined;
134 },
135 never,
136 Providers
137 >;
138
139 /**
140 * A worker node pool on an Anthos on VMware user cluster.
141 *
142 * Node pools have no GCP labels field, so Alchemy stamps ownership into
143 * annotations and a `[alchemy …]` displayName prefix for `list` / nuke.
144 * Pool id, location, and parent cluster are identity — changing them
145 * replaces the pool. Config, display name, version, and autoscaling
146 * update in place.
147 *
148 * ### Creating a VMware Node Pool
149 * **Example:** Ubuntu worker pool
150 * ```typescript
151 * const pool = yield* GCP.GKEOnPrem.VmwareClustersVmwareNodePool("Workers", {
152 * vmwareCluster: cluster.name,
153 * config: {
154 * imageType: "ubuntu_containerd",
155 * replicas: "3",
156 * cpus: "4",
157 * memoryMb: "8192",
158 * },
159 * displayName: "app workers",
160 * });
161 * ```
162 *
163 * ### Updating a VMware Node Pool
164 * Re-declare the same logical id with changed props; the engine keeps the
165 * physical resource and updates it in place.
166 *
167 * **Example:** Scale replicas
168 * ```typescript
169 * const pool = yield* GCP.GKEOnPrem.VmwareClustersVmwareNodePool("Workers", {
170 * vmwareCluster: cluster.name,
171 * config: {
172 * imageType: "ubuntu_containerd",
173 * replicas: "5",
174 * cpus: "4",
175 * memoryMb: "8192",
176 * },
177 * displayName: "app workers v2",
178 * });
179 * ```
180 *
181 * @resource
182 * @category GKEOnPrem
183 */
184 export const VmwareClustersVmwareNodePool = Resource<VmwareClustersVmwareNodePool>(
185 "GCP.GKEOnPrem.VmwareClustersVmwareNodePool",
186 );
187
188 const resourceName = (cluster: string, vmwareNodePoolId: string) =>
189 `${cluster}/${COLLECTION}/${vmwareNodePoolId}`;
190
191 const toAttrs = (item: gkeonprem.VmwareNodePool, project: string, region: string) => {
192 const name = item.name ?? "";
193 const parsed = parseName(name, COLLECTION, region);
194 const ownership = parseOwnership(item.displayName);
195 const annotations = userLabels(item.annotations);
196 return {
197 name,
198 vmwareNodePoolId: parsed.id,
199 vmwareCluster: parsed.parent,
200 project: parsed.project || project,
201 location: parsed.location,
202 config: item.config,
203 displayName: ownership.text,
204 onPremVersion: item.onPremVersion,
205 nodePoolAutoscaling: item.nodePoolAutoscaling,
206 annotations,
207 labels: annotations,
208 state: textState(item.state),
209 uid: item.uid,
210 reconciling: item.reconciling,
211 errorMessage: item.status?.errorMessage,
212 createTime: item.createTime,
213 updateTime: item.updateTime,
214 deleteTime: item.deleteTime,
215 etag: item.etag,
216 };
217 };
218
219 const getByName = (name: string) =>
220 gkeonprem
221 .getProjectsLocationsVmwareClustersVmwareNodePools({
222 name,
223 view: "FULL",
224 })
225 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
226
227 const listChildren = (parent: string) =>
228 collectPages(
229 gkeonprem.listProjectsLocationsVmwareClustersVmwareNodePools.pages({
230 parent,
231 pageSize: 1000,
232 view: "FULL",
233 }),
234 (page): readonly gkeonprem.VmwareNodePool[] | undefined => page.vmwareNodePools,
235 );
236
237 const listOwned = (project: string, region: string) =>
238 listAtNested(project, region, `${PARENT_COLLECTION}/-`, listChildren).pipe(
239 Effect.flatMap((items) =>
240 items.length > 0
241 ? Effect.succeed(items)
242 : listChildrenOf(
243 listAtLocation(project, region, (parent) =>
244 collectPages(
245 gkeonprem.listProjectsLocationsVmwareClusters.pages({
246 parent,
247 pageSize: 1000,
248 view: "BASIC",
249 }),
250 (page): readonly gkeonprem.VmwareCluster[] | undefined => page.vmwareClusters,
251 ),
252 ),
253 (cluster: gkeonprem.VmwareCluster) => cluster.name,
254 listChildren,
255 ),
256 ),
257 Effect.map((items) =>
258 items.filter((item: gkeonprem.VmwareNodePool) => isOwned(item.annotations, item.displayName)),
259 ),
260 );
261
262 export const VmwareClustersVmwareNodePoolProvider = () =>
263 Provider.succeed(VmwareClustersVmwareNodePool, {
264 stables: [
265 "name",
266 "vmwareNodePoolId",
267 "vmwareCluster",
268 "project",
269 "location",
270 "uid",
271 "createTime",
272 ],
273
274 diff: Effect.fn(function* ({ news, olds, output }) {
275 if (!isResolved(news)) return undefined;
276 const env = yield* GcpEnvironment.current;
277 return replaceOnIdentity({
278 previousId: olds?.vmwareNodePoolId ?? output?.vmwareNodePoolId,
279 nextId: news.vmwareNodePoolId
280 ? rfc1035(news.vmwareNodePoolId, "vmwarenodepool", VMWARE_NAME_LENGTH)
281 : (olds?.vmwareNodePoolId ?? output?.vmwareNodePoolId),
282 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
283 nextLocation: normalizeLocation(
284 news.location ?? olds?.location ?? output?.location,
285 env.region,
286 ),
287 previousParent: olds?.vmwareCluster ?? output?.vmwareCluster,
288 nextParent: news.vmwareCluster,
289 });
290 }),
291
292 read: Effect.fn(function* ({ id, olds, output }) {
293 const env = yield* GcpEnvironment.current;
294 const vmwareNodePoolId = yield* toPhysicalId(
295 id,
296 olds?.vmwareNodePoolId,
297 output?.vmwareNodePoolId,
298 "vmwarenodepool",
299 VMWARE_NAME_LENGTH,
300 );
301 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
302 const cluster = expandParent(
303 olds?.vmwareCluster ?? output?.vmwareCluster ?? "",
304 env.project,
305 location,
306 PARENT_COLLECTION,
307 );
308 const name = output?.name ?? resourceName(cluster, vmwareNodePoolId);
309 const existing = yield* getByName(name);
310 if (existing === undefined) return undefined;
311 const attrs = toAttrs(existing, env.project, env.region);
312 const fromName = parseOwnership(existing.displayName).labels;
313 const owned =
314 (yield* hasAlchemyLabels(id, tagRecord(existing.annotations))) ||
315 (yield* hasAlchemyLabels(id, fromName));
316 return owned ? attrs : Unowned(attrs);
317 }),
318
319 list: () =>
320 Effect.gen(function* () {
321 const env = yield* GcpEnvironment.current;
322 const items = yield* listOwned(env.project, env.region);
323 return items.map((item: gkeonprem.VmwareNodePool) =>
324 toAttrs(item, env.project, env.region),
325 );
326 }),
327
328 reconcile: Effect.fn(function* ({ id, news, output }) {
329 const env = yield* GcpEnvironment.current;
330 const vmwareNodePoolId = yield* toPhysicalId(
331 id,
332 news.vmwareNodePoolId,
333 output?.vmwareNodePoolId,
334 "vmwarenodepool",
335 VMWARE_NAME_LENGTH,
336 );
337 const location = normalizeLocation(news.location ?? output?.location, env.region);
338 const cluster = expandParent(news.vmwareCluster, env.project, location, PARENT_COLLECTION);
339 const name = resourceName(cluster, vmwareNodePoolId);
340 const ownership = yield* createInternalLabels(id);
341 const annotations = desiredAnnotations(ownership, news.labels, news.annotations);
342 const displayName = encodeOwnership(ownership, news.displayName);
343 const body: gkeonprem.VmwareNodePool = {
344 config: news.config,
345 displayName,
346 onPremVersion: news.onPremVersion,
347 nodePoolAutoscaling: news.nodePoolAutoscaling,
348 annotations,
349 };
350
351 let current = yield* getByName(output?.name ?? name);
352
353 if (current === undefined) {
354 const created = yield* gkeonprem
355 .createProjectsLocationsVmwareClustersVmwareNodePools({
356 parent: cluster,
357 vmwareNodePoolId,
358 body,
359 })
360 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
361 if (created !== undefined) {
362 yield* waitForOperation(created);
363 }
364 current = yield* waitUntilExists(getByName(name), name);
365 }
366
367 if (current === undefined) {
368 return yield* new ResourceNotResolved({ resourceName: name });
369 }
370
371 const mask = fieldMask([
372 differs(current.annotations, annotations) && "annotations",
373 !sameText(parseOwnership(current.displayName).text, news.displayName) && "displayName",
374 differs(current.config, news.config) && "config",
375 differs(current.onPremVersion, news.onPremVersion) && "onPremVersion",
376 differs(current.nodePoolAutoscaling, news.nodePoolAutoscaling) && "nodePoolAutoscaling",
377 ]);
378
379 if (mask.length > 0) {
380 const operation = yield* gkeonprem.patchProjectsLocationsVmwareClustersVmwareNodePools({
381 name: current.name ?? name,
382 updateMask: mask,
383 body: {
384 ...body,
385 etag: current.etag,
386 },
387 });
388 yield* waitForOperation(operation);
389 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
390 }
391
392 if (current === undefined) {
393 return yield* new ResourceNotResolved({ resourceName: name });
394 }
395 return toAttrs(current, env.project, env.region);
396 }),
397
398 delete: Effect.fn(function* ({ output }) {
399 const operation = yield* gkeonprem
400 .deleteProjectsLocationsVmwareClustersVmwareNodePools({
401 name: output.name,
402 allowMissing: true,
403 etag: output.etag,
404 })
405 .pipe(
406 Effect.retry({
407 while: (error) => error._tag === "Conflict",
408 times: 8,
409 schedule: Schedule.spaced("2 seconds"),
410 }),
411 Effect.catchTag("NotFound", () => Effect.undefined),
412 );
413 if (operation !== undefined) {
414 yield* waitForOperation(operation, { notFoundOk: true });
415 }
416 yield* waitUntilGone(getByName(output.name), output.name);
417 }),
418 });