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

main
ts 495 lines 17.6 KB
Raw
1 import * as workstations from "@distilled.cloud/gcp/workstations_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 { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 fieldMask,
14 fingerprint,
15 listAtLocation,
16 listLabeledPages,
17 networkName,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 sameText,
24 stringMap,
25 subnetworkName,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 } from "./internal.ts";
32
33 export type DomainConfig = {
34 /**
35 * Domain used by Workstations for HTTP ingress. Immutable.
36 */
37 domain?: string;
38 };
39
40 export type GatewayConfig = {
41 /**
42 * Whether HTTP/2 is enabled for this workstation cluster.
43 * @default false
44 */
45 http2Enabled?: boolean;
46 };
47
48 export type PrivateClusterConfig = {
49 /**
50 * Whether the Workstations endpoint is private. Immutable.
51 * @default false
52 */
53 enablePrivateEndpoint?: boolean;
54 /**
55 * Additional projects allowed to attach to the cluster's service
56 * attachment. The cluster project and VPC host project are allowed by
57 * default.
58 */
59 allowedProjects?: string[];
60 };
61
62 export type WorkstationClusterProps = {
63 /**
64 * Cluster id (the `{workstationCluster}` segment of
65 * `projects/{project}/locations/{location}/workstationClusters/{workstationCluster}`).
66 * If omitted, a unique RFC1035 name is generated from the stack, stage,
67 * and logical id. Immutable — changing it replaces the cluster.
68 */
69 workstationClusterId?: string;
70 /**
71 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
72 * replaces the cluster. `US-CENTRAL1` is accepted and normalized to
73 * `us-central1`.
74 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
75 */
76 location?: string;
77 /**
78 * VPC network. Full name
79 * `projects/{project}/global/networks/{network}` or a network id.
80 * Immutable — changing it replaces the cluster.
81 * @default "default"
82 */
83 network?: string;
84 /**
85 * Subnetwork. Full name
86 * `projects/{project}/regions/{region}/subnetworks/{subnetwork}` or a
87 * subnetwork id (combined with `location`). Immutable — changing it
88 * replaces the cluster.
89 * @default "default"
90 */
91 subnetwork?: string;
92 /**
93 * Human-readable display name.
94 */
95 displayName?: string;
96 /**
97 * User labels. Alchemy ownership labels are merged in automatically
98 * and propagated to the underlying Compute Engine resources.
99 */
100 labels?: Record<string, string>;
101 /**
102 * Client-specified annotations.
103 */
104 annotations?: Record<string, string>;
105 /**
106 * Resource Manager tags bound at create time. Immutable.
107 */
108 tags?: Record<string, string>;
109 /**
110 * Launch URL for unstarted workstations in this cluster.
111 */
112 workstationLaunchUrl?: string;
113 /**
114 * Redirect URL for unauthorized requests received by workstation VMs.
115 */
116 workstationAuthorizationUrl?: string;
117 /**
118 * Configuration options for a custom domain. Immutable.
119 */
120 domainConfig?: DomainConfig;
121 /**
122 * Cluster HTTP gateway options.
123 */
124 gatewayConfig?: GatewayConfig;
125 /**
126 * Private cluster configuration. `enablePrivateEndpoint` is immutable.
127 */
128 privateClusterConfig?: PrivateClusterConfig;
129 };
130
131 export type WorkstationCluster = Resource<
132 "GCP.Workstations.WorkstationCluster",
133 WorkstationClusterProps,
134 {
135 /** Full resource name. */
136 name: string;
137 /** Cluster id (last path segment). */
138 workstationClusterId: string;
139 /** Project id. */
140 project: string;
141 /** Location id. */
142 location: string;
143 /** VPC network name. */
144 network: string | undefined;
145 /** Subnetwork name. */
146 subnetwork: string | undefined;
147 /** Human-readable display name. */
148 displayName: string | undefined;
149 /** User labels (Alchemy ownership labels stripped). */
150 labels: Record<string, string>;
151 /** Client-specified annotations. */
152 annotations: Record<string, string>;
153 /** Launch URL for unstarted workstations. */
154 workstationLaunchUrl: string | undefined;
155 /** Redirect URL for unauthorized workstation requests. */
156 workstationAuthorizationUrl: string | undefined;
157 /** Custom domain configuration. */
158 domainConfig: DomainConfig | undefined;
159 /** HTTP gateway configuration. */
160 gatewayConfig: GatewayConfig | undefined;
161 /** Private cluster configuration. */
162 privateClusterConfig: PrivateClusterConfig | undefined;
163 /** Private IP of the cluster control plane. */
164 controlPlaneIp: string | undefined;
165 /** Whether the cluster is currently reconciling. */
166 reconciling: boolean;
167 /** Whether the cluster is in degraded mode. */
168 degraded: boolean;
169 /** Server-generated resource uid. */
170 uid: string | undefined;
171 /** RFC3339 creation timestamp. */
172 createTime: string | undefined;
173 /** RFC3339 last-update timestamp. */
174 updateTime: string | undefined;
175 },
176 never,
177 Providers
178 >;
179
180 /**
181 * A Cloud Workstations cluster — a regional group of workstations
182 * attached to a VPC network.
183 *
184 * Changing `workstationClusterId`, `location`, `network`, `subnetwork`,
185 * `domainConfig`, `tags`, or `privateClusterConfig.enablePrivateEndpoint`
186 * replaces the cluster. Display name, labels, annotations, launch URLs,
187 * gateway config, and `allowedProjects` update in place.
188 *
189 * ### Creating a Cluster
190 * **Example:** Generated name on the default VPC
191 * ```typescript
192 * const cluster = yield* GCP.Workstations.WorkstationCluster("Dev", {});
193 * ```
194 *
195 * **Example:** Explicit id, network, and labels
196 * ```typescript
197 * const cluster = yield* GCP.Workstations.WorkstationCluster("Dev", {
198 * workstationClusterId: "app-dev",
199 * location: "us-central1",
200 * network: "default",
201 * subnetwork: "default",
202 * displayName: "app-dev workstations",
203 * labels: { env: "prod" },
204 * });
205 * ```
206 *
207 * ### Updating a Cluster
208 * **Example:** Display name and labels
209 * ```typescript
210 * // Same logical id, changed props: the engine updates it in place.
211 * const cluster = yield* GCP.Workstations.WorkstationCluster("Dev", {
212 * displayName: "app-dev workstations v2",
213 * labels: { env: "prod", team: "platform" },
214 * });
215 * ```
216 *
217 * @resource
218 * @category Workstations
219 */
220 export const WorkstationCluster = Resource<WorkstationCluster>(
221 "GCP.Workstations.WorkstationCluster",
222 );
223
224 const resourceName = (project: string, location: string, workstationClusterId: string) =>
225 `projects/${project}/locations/${location}/workstationClusters/${workstationClusterId}`;
226
227 const toDomain = (
228 config: workstations.DomainConfig | DomainConfig | undefined,
229 ): DomainConfig | undefined => (config === undefined ? undefined : { domain: config.domain });
230
231 const toGateway = (
232 config: workstations.GatewayConfig | GatewayConfig | undefined,
233 ): GatewayConfig | undefined =>
234 config === undefined ? undefined : { http2Enabled: config.http2Enabled };
235
236 const toPrivate = (
237 config: workstations.PrivateClusterConfig | PrivateClusterConfig | undefined,
238 ): PrivateClusterConfig | undefined =>
239 config === undefined
240 ? undefined
241 : {
242 enablePrivateEndpoint: config.enablePrivateEndpoint,
243 allowedProjects: config.allowedProjects,
244 };
245
246 const toAttrs = (item: workstations.WorkstationCluster, project: string, region: string) => {
247 const name = item.name ?? "";
248 const parsed = parseName(name, "workstationClusters", region);
249 return {
250 name,
251 workstationClusterId: parsed.id,
252 project: parsed.project || project,
253 location: parsed.location,
254 network: item.network,
255 subnetwork: item.subnetwork,
256 displayName: item.displayName,
257 labels: userLabels(item.labels),
258 annotations: stringMap(item.annotations) ?? {},
259 workstationLaunchUrl: item.workstationLaunchUrl,
260 workstationAuthorizationUrl: item.workstationAuthorizationUrl,
261 domainConfig: toDomain(item.domainConfig),
262 gatewayConfig: toGateway(item.gatewayConfig),
263 privateClusterConfig: toPrivate(item.privateClusterConfig),
264 controlPlaneIp: item.controlPlaneIp,
265 reconciling: item.reconciling === true,
266 degraded: item.degraded === true,
267 uid: item.uid,
268 createTime: item.createTime,
269 updateTime: item.updateTime,
270 };
271 };
272
273 const getByName = (name: string) =>
274 workstations
275 .getProjectsLocationsWorkstationClusters({ name })
276 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
277
278 const listOwned = (project: string, region: string) =>
279 listAtLocation(project, region, (parent) =>
280 listLabeledPages(
281 workstations.listProjectsLocationsWorkstationClusters.pages({
282 parent,
283 pageSize: 1000,
284 }),
285 (page) => page.workstationClusters,
286 (item) => item.labels,
287 ),
288 );
289
290 export const WorkstationClusterProvider = () =>
291 Provider.succeed(WorkstationCluster, {
292 stables: ["name", "workstationClusterId", "project", "location", "uid", "createTime"],
293
294 diff: Effect.fn(function* ({ news, olds, output }) {
295 if (!isResolved(news)) return undefined;
296 const env = yield* GcpEnvironment.current;
297 const previousNetwork = olds?.network ?? output?.network;
298 const previousSubnetwork = olds?.subnetwork ?? output?.subnetwork;
299 const previousPrivate = olds?.privateClusterConfig ?? output?.privateClusterConfig;
300 const previousDomain = olds?.domainConfig ?? output?.domainConfig;
301 const previousTags = olds?.tags;
302 return replaceOnIdentity({
303 previousId: olds?.workstationClusterId ?? output?.workstationClusterId,
304 nextId:
305 news.workstationClusterId ?? olds?.workstationClusterId ?? output?.workstationClusterId,
306 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
307 nextLocation: normalizeLocation(
308 news.location ?? olds?.location ?? output?.location,
309 env.region,
310 ),
311 extra:
312 (previousNetwork !== undefined &&
313 news.network !== undefined &&
314 !sameText(previousNetwork, news.network) &&
315 !previousNetwork.endsWith(`/${news.network}`)) ||
316 (previousSubnetwork !== undefined &&
317 news.subnetwork !== undefined &&
318 !sameText(previousSubnetwork, news.subnetwork) &&
319 !previousSubnetwork.endsWith(`/${news.subnetwork}`)) ||
320 (previousPrivate?.enablePrivateEndpoint !== undefined &&
321 news.privateClusterConfig?.enablePrivateEndpoint !== undefined &&
322 previousPrivate.enablePrivateEndpoint !==
323 news.privateClusterConfig.enablePrivateEndpoint) ||
324 (previousDomain?.domain !== undefined &&
325 news.domainConfig?.domain !== undefined &&
326 previousDomain.domain !== news.domainConfig.domain) ||
327 (previousTags !== undefined &&
328 news.tags !== undefined &&
329 fingerprint(previousTags) !== fingerprint(news.tags)),
330 });
331 }),
332
333 read: Effect.fn(function* ({ id, olds, output }) {
334 const env = yield* GcpEnvironment.current;
335 const workstationClusterId = yield* toPhysicalId(
336 id,
337 olds?.workstationClusterId,
338 output?.workstationClusterId,
339 "cluster",
340 );
341 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
342 const name = output?.name ?? resourceName(env.project, location, workstationClusterId);
343 const existing = yield* getByName(name);
344 if (existing === undefined) return undefined;
345 const attrs = toAttrs(existing, env.project, env.region);
346 // A resource we recorded is ours even while GCP hides its labels
347 // (clusters report none while `reconciling`), so destroy can still
348 // clean it up.
349 if (output !== undefined && output.name === existing.name) return attrs;
350 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
351 }),
352
353 list: () =>
354 Effect.gen(function* () {
355 const env = yield* GcpEnvironment.current;
356 const items = yield* listOwned(env.project, env.region);
357 return items.map((item) => toAttrs(item, env.project, env.region));
358 }),
359
360 reconcile: Effect.fn(function* ({ id, news, output }) {
361 const env = yield* GcpEnvironment.current;
362 const workstationClusterId = yield* toPhysicalId(
363 id,
364 news.workstationClusterId,
365 output?.workstationClusterId,
366 "cluster",
367 );
368 const location = normalizeLocation(news.location ?? output?.location, env.region);
369 const name = resourceName(env.project, location, workstationClusterId);
370 const network = networkName(news.network, env.project);
371 const subnetwork = subnetworkName(news.subnetwork, env.project, location);
372 const desiredLabels = {
373 ...toLabels(news.labels),
374 ...(yield* createInternalLabels(id)),
375 };
376 const desiredAnnotations = stringMap(news.annotations);
377
378 let current = yield* getByName(output?.name ?? name);
379
380 if (current === undefined) {
381 const created = yield* workstations
382 .createProjectsLocationsWorkstationClusters({
383 parent: parentOf(env.project, location),
384 workstationClusterId,
385 body: {
386 network,
387 subnetwork,
388 displayName: news.displayName,
389 labels: desiredLabels,
390 annotations: desiredAnnotations,
391 tags: stringMap(news.tags),
392 workstationLaunchUrl: news.workstationLaunchUrl,
393 workstationAuthorizationUrl: news.workstationAuthorizationUrl,
394 domainConfig: news.domainConfig,
395 gatewayConfig: news.gatewayConfig,
396 privateClusterConfig: news.privateClusterConfig,
397 },
398 })
399 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
400 if (created !== undefined) {
401 // ALREADY_EXISTS (6): a concurrent create won the race.
402 yield* waitForOperation(created).pipe(
403 Effect.catchTag("GCP.OperationFailed", (error) =>
404 error.code === 6 ? Effect.void : Effect.fail(error),
405 ),
406 );
407 }
408 current = yield* waitUntilExists(getByName(name), name);
409 }
410
411 if (current === undefined) {
412 return yield* new ResourceNotResolved({ resourceName: name });
413 }
414
415 const observedLabels = tagRecord(current.labels);
416 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
417 const observedPrivate = toPrivate(current.privateClusterConfig);
418 const mask = fieldMask([
419 (upsert.length > 0 || removed.length > 0) && "labels",
420 !sameText(current.displayName, news.displayName) && "displayName",
421 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
422 "annotations",
423 // Both URLs default server-side; only converge them when set.
424 news.workstationLaunchUrl !== undefined &&
425 !sameText(current.workstationLaunchUrl, news.workstationLaunchUrl) &&
426 "workstationLaunchUrl",
427 news.workstationAuthorizationUrl !== undefined &&
428 !sameText(current.workstationAuthorizationUrl, news.workstationAuthorizationUrl) &&
429 "workstationAuthorizationUrl",
430 news.gatewayConfig !== undefined &&
431 fingerprint(toGateway(current.gatewayConfig)) !==
432 fingerprint(toGateway(news.gatewayConfig)) &&
433 "gatewayConfig",
434 fingerprint(observedPrivate?.allowedProjects) !==
435 fingerprint(news.privateClusterConfig?.allowedProjects) &&
436 "privateClusterConfig.allowedProjects",
437 ]);
438
439 if (mask.length > 0) {
440 const operation = yield* workstations
441 .patchProjectsLocationsWorkstationClusters({
442 name: current.name ?? name,
443 updateMask: mask,
444 body: {
445 etag: current.etag,
446 labels: desiredLabels,
447 displayName: news.displayName,
448 annotations: desiredAnnotations,
449 workstationLaunchUrl: news.workstationLaunchUrl,
450 workstationAuthorizationUrl: news.workstationAuthorizationUrl,
451 gatewayConfig: news.gatewayConfig,
452 privateClusterConfig: {
453 allowedProjects: news.privateClusterConfig?.allowedProjects,
454 },
455 },
456 })
457 .pipe(
458 Effect.retry({
459 while: (error) => error._tag === "Conflict",
460 times: 8,
461 schedule: Schedule.spaced("2 seconds"),
462 }),
463 );
464 yield* waitForOperation(operation);
465 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
466 }
467
468 return toAttrs(current, env.project, env.region);
469 }),
470
471 delete: Effect.fn(function* ({ output }) {
472 const operation = yield* workstations
473 .deleteProjectsLocationsWorkstationClusters({
474 name: output.name,
475 force: true,
476 })
477 .pipe(
478 Effect.retry({
479 while: (error) => error._tag === "Conflict",
480 times: 8,
481 schedule: Schedule.spaced("2 seconds"),
482 }),
483 Effect.catchTag("NotFound", () => Effect.undefined),
484 );
485 if (operation !== undefined) {
486 // NOT_FOUND (5): already gone.
487 yield* waitForOperation(operation).pipe(
488 Effect.catchTag("GCP.OperationFailed", (error) =>
489 error.code === 5 ? Effect.void : Effect.fail(error),
490 ),
491 );
492 }
493 yield* waitUntilGone(getByName(output.name), output.name);
494 }),
495 });