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

main
ts 588 lines 19.1 KB
Raw
1 import * as clouddeploy from "@distilled.cloud/gcp/clouddeploy_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 expandParent,
14 fieldMask,
15 fingerprint,
16 gkeClusterName,
17 listAtLocation,
18 listLabeledPages,
19 membershipName,
20 normalizeLocation,
21 parentOf,
22 parseName,
23 replaceOnIdentity,
24 ResourceNotResolved,
25 runLocationName,
26 sameBool,
27 sameText,
28 stringMap,
29 toPhysicalId,
30 userLabels,
31 waitForOperation,
32 waitUntilExists,
33 waitUntilGone,
34 } from "./internal.ts";
35
36 export type GkeCluster = {
37 /**
38 * GKE cluster resource name
39 * `projects/{project}/locations/{location}/clusters/{cluster}` or the
40 * cluster id.
41 */
42 cluster?: string;
43 /**
44 * Access the cluster using the DNS endpoint. Cannot be combined with
45 * `internalIp`.
46 */
47 dnsEndpoint?: boolean;
48 /**
49 * Access a private cluster using the private control-plane IP.
50 */
51 internalIp?: boolean;
52 /**
53 * Optional HTTP proxy URL for the Kubernetes API server.
54 */
55 proxyUrl?: string;
56 };
57
58 export type AnthosCluster = {
59 /**
60 * GKE Hub membership
61 * `projects/{project}/locations/{location}/memberships/{membership}`
62 * or the membership id.
63 */
64 membership?: string;
65 };
66
67 export type CloudRunLocation = {
68 /**
69 * Cloud Run location
70 * `projects/{project}/locations/{location}` or a location id.
71 */
72 location?: string;
73 };
74
75 export type CustomTarget = {
76 /**
77 * Custom target type resource name
78 * `projects/{project}/locations/{location}/customTargetTypes/{customTargetType}`
79 * or the type id.
80 */
81 customTargetType?: string;
82 };
83
84 export type MultiTarget = {
85 /** Child target ids. */
86 targetIds?: string[];
87 };
88
89 export type DefaultPool = {
90 /** Cloud Storage location for execution outputs. */
91 artifactStorage?: string;
92 /** Service account used for execution. */
93 serviceAccount?: string;
94 };
95
96 export type PrivatePool = {
97 /**
98 * Cloud Build worker pool
99 * `projects/{project}/locations/{location}/workerPools/{pool}`.
100 */
101 workerPool?: string;
102 /** Cloud Storage location for execution outputs. */
103 artifactStorage?: string;
104 /** Service account used for execution. */
105 serviceAccount?: string;
106 };
107
108 export type ExecutionConfig = {
109 /**
110 * Usages this configuration applies to (`RENDER`, `DEPLOY`, `VERIFY`,
111 * `PREDEPLOY`, `POSTDEPLOY`, `ANALYSIS`).
112 */
113 usages?: Array<clouddeploy.ExecutionConfigUsagesItemEnum | (string & {})>;
114 /** Cloud Build execution timeout (10m–24h, seconds format). */
115 executionTimeout?: string;
116 /** Default Cloud Build pool. */
117 defaultPool?: DefaultPool;
118 /**
119 * Worker pool resource name. If omitted, the default Cloud Build pool
120 * is used.
121 */
122 workerPool?: string;
123 /** Cloud Storage location for execution outputs. */
124 artifactStorage?: string;
125 /** Private Cloud Build pool. */
126 privatePool?: PrivatePool;
127 /** Extra logging when running builds. */
128 verbose?: boolean;
129 /** Service account used for execution. */
130 serviceAccount?: string;
131 };
132
133 export type TargetProps = {
134 /**
135 * Target id (the `{target}` segment of
136 * `projects/{project}/locations/{location}/targets/{target}`). If
137 * omitted, a unique RFC1035 name is generated from the stack, stage,
138 * and logical id. Immutable — changing it replaces the target.
139 */
140 targetId?: string;
141 /**
142 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
143 * replaces the target. `US-CENTRAL1` is accepted and normalized to
144 * `us-central1`.
145 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
146 */
147 location?: string;
148 /**
149 * GKE cluster destination. Mutually exclusive with `run`,
150 * `anthosCluster`, `customTarget`, and `multiTarget`.
151 */
152 gke?: GkeCluster;
153 /**
154 * Cloud Run destination. Mutually exclusive with the other destination
155 * fields.
156 */
157 run?: CloudRunLocation;
158 /**
159 * Anthos / GKE Hub membership destination. Mutually exclusive with the
160 * other destination fields.
161 */
162 anthosCluster?: AnthosCluster;
163 /**
164 * Custom target destination. Mutually exclusive with the other
165 * destination fields.
166 */
167 customTarget?: CustomTarget;
168 /**
169 * Multi-target grouping child targets. Mutually exclusive with the
170 * other destination fields.
171 */
172 multiTarget?: MultiTarget;
173 /**
174 * Whether rollouts to this target require approval.
175 * @default false
176 */
177 requireApproval?: boolean;
178 /**
179 * Execution environments for render/deploy (and optional verify).
180 */
181 executionConfigs?: ExecutionConfig[];
182 /**
183 * Deploy parameters for this target.
184 */
185 deployParameters?: Record<string, string>;
186 /**
187 * Associated entities keyed by entity id (Gateway API canary, …).
188 */
189 associatedEntities?: clouddeploy.AssociatedEntitiesMap;
190 /**
191 * Human-readable description. Max length 255 characters.
192 */
193 description?: string;
194 /**
195 * User annotations (not used by Cloud Deploy).
196 */
197 annotations?: Record<string, string>;
198 /**
199 * User labels. Alchemy ownership labels are merged in automatically.
200 */
201 labels?: Record<string, string>;
202 };
203
204 export type Target = Resource<
205 "GCP.CloudDeploy.Target",
206 TargetProps,
207 {
208 /** Full resource name. */
209 name: string;
210 /** Target id (last path segment). */
211 targetId: string;
212 /** Project id. */
213 project: string;
214 /** Location id. */
215 location: string;
216 /** GKE destination, if configured. */
217 gke: GkeCluster | undefined;
218 /** Cloud Run destination, if configured. */
219 run: CloudRunLocation | undefined;
220 /** Anthos destination, if configured. */
221 anthosCluster: AnthosCluster | undefined;
222 /** Custom target destination, if configured. */
223 customTarget: CustomTarget | undefined;
224 /** Multi-target grouping, if configured. */
225 multiTarget: MultiTarget | undefined;
226 /** Whether rollouts require approval. */
227 requireApproval: boolean;
228 /** Execution environment configurations. */
229 executionConfigs: ExecutionConfig[] | undefined;
230 /** Deploy parameters. */
231 deployParameters: Record<string, string>;
232 /** Associated entities. */
233 associatedEntities: clouddeploy.AssociatedEntitiesMap | undefined;
234 /** Human-readable description. */
235 description: string | undefined;
236 /** User annotations. */
237 annotations: Record<string, string>;
238 /** User labels (Alchemy ownership labels stripped). */
239 labels: Record<string, string>;
240 /** Server-generated resource uid. */
241 uid: string | undefined;
242 /** RFC3339 creation timestamp. */
243 createTime: string | undefined;
244 /** RFC3339 last-update timestamp. */
245 updateTime: string | undefined;
246 /** Server-computed etag. */
247 etag: string | undefined;
248 },
249 never,
250 Providers
251 >;
252
253 /**
254 * A Cloud Deploy target — a location a Skaffold configuration can be
255 * deployed to (GKE, Cloud Run, Anthos, a custom target type, or a
256 * multi-target).
257 *
258 * Changing `targetId` or `location` replaces the target. Destination,
259 * approval, execution configs, description, labels, and annotations
260 * update in place.
261 *
262 * ### Creating a Target
263 * **Example:** Cloud Run
264 * ```typescript
265 * const target = yield* GCP.CloudDeploy.Target("Prod", {
266 * run: { location: "projects/my-project/locations/us-central1" },
267 * });
268 * ```
269 *
270 * **Example:** GKE cluster
271 * ```typescript
272 * const target = yield* GCP.CloudDeploy.Target("Prod", {
273 * gke: {
274 * cluster: "projects/my-project/locations/us-central1/clusters/app",
275 * },
276 * requireApproval: true,
277 * labels: { env: "prod" },
278 * });
279 * ```
280 *
281 * ### Updating a Target
282 * Re-declare the same logical id with changed props; the engine keeps the
283 * physical resource and updates it in place.
284 *
285 * **Example:** Description and labels
286 * ```typescript
287 * const target = yield* GCP.CloudDeploy.Target("Prod", {
288 * run: { location: "projects/my-project/locations/us-central1" },
289 * description: "prod run target v2",
290 * labels: { env: "prod", team: "platform" },
291 * });
292 * ```
293 *
294 * @resource
295 * @category CloudDeploy
296 */
297 export const Target = Resource<Target>("GCP.CloudDeploy.Target");
298
299 const resourceName = (project: string, location: string, targetId: string) =>
300 `projects/${project}/locations/${location}/targets/${targetId}`;
301
302 const desiredDestination = (news: TargetProps, project: string, location: string) => {
303 const gke =
304 news.gke === undefined
305 ? undefined
306 : {
307 ...news.gke,
308 cluster:
309 news.gke.cluster === undefined
310 ? undefined
311 : gkeClusterName(news.gke.cluster, project, location),
312 };
313 const run =
314 news.run === undefined
315 ? undefined
316 : {
317 location:
318 news.run.location === undefined
319 ? undefined
320 : runLocationName(news.run.location, project, location),
321 };
322 const anthosCluster =
323 news.anthosCluster === undefined
324 ? undefined
325 : {
326 membership:
327 news.anthosCluster.membership === undefined
328 ? undefined
329 : membershipName(news.anthosCluster.membership, project, location),
330 };
331 const customTarget =
332 news.customTarget === undefined
333 ? undefined
334 : {
335 customTargetType:
336 news.customTarget.customTargetType === undefined
337 ? undefined
338 : expandParent(
339 news.customTarget.customTargetType,
340 project,
341 location,
342 "customTargetTypes",
343 ),
344 };
345 return {
346 gke,
347 run,
348 anthosCluster,
349 customTarget,
350 multiTarget: news.multiTarget,
351 };
352 };
353
354 const toGke = (value: clouddeploy.GkeCluster | undefined): GkeCluster | undefined =>
355 value === undefined
356 ? undefined
357 : {
358 cluster: value.cluster,
359 dnsEndpoint: value.dnsEndpoint,
360 internalIp: value.internalIp,
361 proxyUrl: value.proxyUrl,
362 };
363
364 const toRun = (value: clouddeploy.CloudRunLocation | undefined): CloudRunLocation | undefined =>
365 value === undefined ? undefined : { location: value.location };
366
367 const toAnthos = (value: clouddeploy.AnthosCluster | undefined): AnthosCluster | undefined =>
368 value === undefined ? undefined : { membership: value.membership };
369
370 const toCustom = (value: clouddeploy.CustomTarget | undefined): CustomTarget | undefined =>
371 value === undefined ? undefined : { customTargetType: value.customTargetType };
372
373 const toMulti = (value: clouddeploy.MultiTarget | undefined): MultiTarget | undefined =>
374 value === undefined ? undefined : { targetIds: value.targetIds };
375
376 const toExecutionConfigs = (
377 value: clouddeploy.ExecutionConfigList | undefined,
378 ): ExecutionConfig[] | undefined =>
379 value === undefined
380 ? undefined
381 : value.map((config) => ({
382 usages: config.usages,
383 executionTimeout: config.executionTimeout,
384 defaultPool: config.defaultPool,
385 workerPool: config.workerPool,
386 artifactStorage: config.artifactStorage,
387 privatePool: config.privatePool,
388 verbose: config.verbose,
389 serviceAccount: config.serviceAccount,
390 }));
391
392 const toAttrs = (item: clouddeploy.Target, project: string) => {
393 const name = item.name ?? "";
394 const parsed = parseName(name, "targets");
395 return {
396 name,
397 targetId: item.targetId ?? parsed.id,
398 project: parsed.project || project,
399 location: parsed.location,
400 gke: toGke(item.gke),
401 run: toRun(item.run),
402 anthosCluster: toAnthos(item.anthosCluster),
403 customTarget: toCustom(item.customTarget),
404 multiTarget: toMulti(item.multiTarget),
405 requireApproval: item.requireApproval === true,
406 executionConfigs: toExecutionConfigs(item.executionConfigs),
407 deployParameters: stringMap(item.deployParameters),
408 associatedEntities: item.associatedEntities,
409 description: item.description,
410 annotations: stringMap(item.annotations),
411 labels: userLabels(item.labels),
412 uid: item.uid,
413 createTime: item.createTime,
414 updateTime: item.updateTime,
415 etag: item.etag,
416 };
417 };
418
419 const getByName = (name: string) =>
420 clouddeploy
421 .getProjectsLocationsTargets({ name })
422 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
423
424 const listOwned = (project: string, region: string) =>
425 listAtLocation(project, region, (parent) =>
426 listLabeledPages(
427 clouddeploy.listProjectsLocationsTargets.pages({
428 parent,
429 pageSize: 1000,
430 }),
431 (page) => page.targets,
432 (item) => item.labels,
433 ),
434 );
435
436 export const TargetProvider = () =>
437 Provider.succeed(Target, {
438 stables: ["name", "targetId", "project", "location", "uid", "createTime"],
439
440 diff: Effect.fn(function* ({ news, olds, output }) {
441 if (!isResolved(news)) return undefined;
442 const env = yield* GcpEnvironment.current;
443 return replaceOnIdentity({
444 previousId: olds?.targetId ?? output?.targetId,
445 nextId: news.targetId ?? olds?.targetId ?? output?.targetId,
446 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
447 nextLocation: normalizeLocation(
448 news.location ?? olds?.location ?? output?.location ?? env.region,
449 ),
450 });
451 }),
452
453 read: Effect.fn(function* ({ id, olds, output }) {
454 const env = yield* GcpEnvironment.current;
455 const targetId = yield* toPhysicalId(id, olds?.targetId, output?.targetId, "target");
456 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
457 const name = output?.name ?? resourceName(env.project, location, targetId);
458 const existing = yield* getByName(name);
459 if (existing === undefined) return undefined;
460 const attrs = toAttrs(existing, env.project);
461 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
462 }),
463
464 list: () =>
465 Effect.gen(function* () {
466 const env = yield* GcpEnvironment.current;
467 const items = yield* listOwned(env.project, env.region);
468 return items.map((item) => toAttrs(item, env.project));
469 }),
470
471 reconcile: Effect.fn(function* ({ id, news, output }) {
472 const env = yield* GcpEnvironment.current;
473 const targetId = yield* toPhysicalId(id, news.targetId, output?.targetId, "target");
474 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
475 const name = resourceName(env.project, location, targetId);
476 const desiredLabels = {
477 ...toLabels(news.labels),
478 ...(yield* createInternalLabels(id)),
479 };
480 const desiredAnnotations = news.annotations ?? {};
481 const desiredParameters = news.deployParameters ?? {};
482 const desiredApproval = news.requireApproval === true;
483 const destination = desiredDestination(news, env.project, location);
484
485 let current = yield* getByName(output?.name ?? name);
486
487 if (current === undefined) {
488 const created = yield* clouddeploy
489 .createProjectsLocationsTargets({
490 parent: parentOf(env.project, location),
491 targetId,
492 body: {
493 description: news.description,
494 requireApproval: desiredApproval,
495 gke: destination.gke,
496 run: destination.run,
497 anthosCluster: destination.anthosCluster,
498 customTarget: destination.customTarget,
499 multiTarget: destination.multiTarget,
500 executionConfigs: news.executionConfigs,
501 deployParameters: desiredParameters,
502 associatedEntities: news.associatedEntities,
503 annotations: desiredAnnotations,
504 labels: desiredLabels,
505 },
506 })
507 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
508 if (created !== undefined) {
509 yield* waitForOperation(created);
510 }
511 current = yield* waitUntilExists(getByName(name), name);
512 }
513
514 if (current === undefined) {
515 return yield* new ResourceNotResolved({ resourceName: name });
516 }
517
518 const observedLabels = tagRecord(current.labels);
519 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
520 const mask = fieldMask([
521 (upsert.length > 0 || removed.length > 0) && "labels",
522 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
523 "annotations",
524 !sameText(current.description, news.description) && "description",
525 !sameBool(current.requireApproval, desiredApproval) && "requireApproval",
526 fingerprint(toGke(current.gke)) !== fingerprint(destination.gke) && "gke",
527 fingerprint(toRun(current.run)) !== fingerprint(destination.run) && "run",
528 fingerprint(toAnthos(current.anthosCluster)) !== fingerprint(destination.anthosCluster) &&
529 "anthosCluster",
530 fingerprint(toCustom(current.customTarget)) !== fingerprint(destination.customTarget) &&
531 "customTarget",
532 fingerprint(toMulti(current.multiTarget)) !== fingerprint(destination.multiTarget) &&
533 "multiTarget",
534 fingerprint(toExecutionConfigs(current.executionConfigs)) !==
535 fingerprint(news.executionConfigs) && "executionConfigs",
536 fingerprint(stringMap(current.deployParameters)) !== fingerprint(desiredParameters) &&
537 "deployParameters",
538 fingerprint(current.associatedEntities) !== fingerprint(news.associatedEntities) &&
539 "associatedEntities",
540 ]);
541
542 if (mask.length > 0) {
543 const operation = yield* clouddeploy.patchProjectsLocationsTargets({
544 name: current.name ?? name,
545 updateMask: mask,
546 body: {
547 etag: current.etag,
548 description: news.description,
549 requireApproval: desiredApproval,
550 gke: destination.gke,
551 run: destination.run,
552 anthosCluster: destination.anthosCluster,
553 customTarget: destination.customTarget,
554 multiTarget: destination.multiTarget,
555 executionConfigs: news.executionConfigs,
556 deployParameters: desiredParameters,
557 associatedEntities: news.associatedEntities,
558 annotations: desiredAnnotations,
559 labels: desiredLabels,
560 },
561 });
562 yield* waitForOperation(operation);
563 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
564 }
565
566 return toAttrs(current, env.project);
567 }),
568
569 delete: Effect.fn(function* ({ output }) {
570 const operation = yield* clouddeploy
571 .deleteProjectsLocationsTargets({
572 name: output.name,
573 allowMissing: true,
574 })
575 .pipe(
576 Effect.retry({
577 while: (error) => error._tag === "Conflict",
578 times: 8,
579 schedule: Schedule.spaced("2 seconds"),
580 }),
581 Effect.catchTag("NotFound", () => Effect.undefined),
582 );
583 if (operation !== undefined) {
584 yield* waitForOperation(operation, { notFoundOk: true });
585 }
586 yield* waitUntilGone(getByName(output.name), output.name);
587 }),
588 });