@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 745 lines 27 KB
Raw
1 import {
2 ClusterAdapter,
3 ClusterNotFoundError,
4 type AdapterLifecycleServices,
5 type ClusterAdapterService,
6 type ClusterTransport,
7 type ImageRegistryDeleteOptions,
8 type ImageRegistryResolveOptions,
9 type ImageRegistryResult,
10 type WorkloadBindingContract,
11 type WorkloadIdentityReconcileOptions,
12 } from "@alchemy.run/kubernetes/ClusterAdapter";
13 import type { Connection } from "@alchemy.run/kubernetes/Connection";
14 /**
15 * The `gcp-gke` {@link ClusterAdapter}: everything platform-specific about
16 * running `Kubernetes.*` workloads on Google Kubernetes Engine.
17 *
18 * - **connect** — Google OAuth bearer tokens against the cluster endpoint,
19 * re-getting the cluster when the connection doesn't carry endpoint/CA.
20 * - **identity** — GKE Workload Identity Federation: every `iam` grant a
21 * GCP binding attaches to the workload is granted directly to the
22 * Kubernetes ServiceAccount's principal
23 * (`principal://iam.googleapis.com/projects/{number}/locations/global/workloadIdentityPools/{project}.svc.id.goog/subject/ns/{namespace}/sa/{ksa}`)
24 * — no Google service account involved. Applied grants are recorded in
25 * the identity state; grants no binding asks for any more are revoked on
26 * the next reconcile, and all of them on delete. With
27 * `identity.gcpServiceAccount`, the KSA is instead annotated with
28 * `iam.gke.io/gcp-service-account`, granted
29 * `roles/iam.workloadIdentityUser` on that GSA, and the binding grants
30 * go to the GSA. The cluster's `workloadIdentityConfig.workloadPool` is
31 * enabled by `GCP.Container.Cluster` (Autopilot enables it by default).
32 * - **registry** — a per-workload Artifact Registry Docker repository;
33 * `main` programs are bundled, `context` Dockerfiles built, and `image`
34 * refs mirrored into it.
35 * - **bootstrap** — generated container entries wiring the GCP credential
36 * chain so Workload Identity's GCE metadata server resolves inside the
37 * pod.
38 * - **loadBalancerDefaults** — GKE backend-service based L4
39 * (`cloud.google.com/l4-rbs`).
40 *
41 * Registered by `GCP.providers()`; resolved dynamically by the
42 * `Kubernetes.*` providers via the connection's `auth.kind`.
43 */
44 import * as container from "@distilled.cloud/gcp/container_v1";
45 import { Credentials } from "@distilled.cloud/gcp/Credentials";
46 import { createPhysicalName } from "alchemy/PhysicalName";
47 import type { ResourceBinding } from "alchemy/Resource";
48 import { Self } from "alchemy/Self";
49 import * as Data from "effect/Data";
50 import * as Effect from "effect/Effect";
51 import * as FileSystem from "effect/FileSystem";
52 import type { HttpClient } from "effect/http/HttpClient";
53 import * as Layer from "effect/Layer";
54 import * as Path from "effect/Path";
55 import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
56 import * as Redacted from "effect/Redacted";
57 import { makeImageSource, type ImageSourceLike } from "../ArtifactRegistry/ImageSource.ts";
58 import { GcpEnvironment } from "../Environment.ts";
59 import {
60 projectNumber,
61 revokeHostIam,
62 syncHostIam,
63 type AppliedIamGrant,
64 type GcpIamGrant,
65 } from "../Host.ts";
66 import { revokeIamMembership, updateIamMembership } from "../IamPolicy.ts";
67
68 export class KubernetesAdapterNotReady extends Data.TaggedError("KubernetesAdapterNotReady")<{
69 readonly message: string;
70 readonly cause?: unknown;
71 }> {}
72
73 export class KubernetesAdapterOperationFailed extends Data.TaggedError(
74 "KubernetesAdapterOperationFailed",
75 )<{
76 readonly message: string;
77 readonly cause?: unknown;
78 }> {}
79
80 declare module "@alchemy.run/kubernetes/Connection" {
81 interface AuthRegistry {
82 /**
83 * Authenticate against a GKE cluster with Google OAuth bearer tokens
84 * minted from the ambient GCP credentials. Contributed by
85 * `GCP.providers()` — `GCP.Container.Cluster` attributes expose a
86 * ready-made `connection` carrying this descriptor.
87 */
88 "gcp-gke": {
89 /** GKE cluster id (the `{cluster}` path segment). */
90 clusterId: string;
91 /** Zone or region (`us-central1-a`, `us-central1`, …). */
92 location: string;
93 /**
94 * GCP project id.
95 * @default the ambient GCP project
96 */
97 project?: string;
98 };
99 }
100 }
101
102 declare module "@alchemy.run/kubernetes/ClusterAdapter" {
103 interface IdentityStateRegistry {
104 /**
105 * GKE Workload Identity Federation: binding grants are applied to the
106 * Kubernetes ServiceAccount's principal (or to the GSA supplied via
107 * `identity.gcpServiceAccount`).
108 */
109 "gcp-workload-identity": {
110 /** Workload Identity pool (`{project}.svc.id.goog`). */
111 workloadPool: string;
112 /** Project the grants and workload pool belong to. */
113 project?: string;
114 /**
115 * The IAM member binding grants were applied to — the KSA's
116 * `principal://…` identifier, or `serviceAccount:{gsa}`.
117 */
118 member?: string;
119 /** Grants applied to `member`, revoked once no binding asks for them. */
120 iamGrants?: AppliedIamGrant[];
121 /** Existing GSA email stamped on the KSA annotation, if any. */
122 gcpServiceAccount?: string;
123 /**
124 * The KSA principal granted `roles/iam.workloadIdentityUser` on
125 * `gcpServiceAccount`, if any.
126 */
127 impersonator?: string;
128 };
129 }
130 interface RegistryStateRegistry {
131 /** The per-workload Artifact Registry repository holding the image. */
132 "gcp-artifact-registry": {
133 /** Artifact Registry repository id. */
134 repositoryName: string;
135 /** Docker image prefix (`{loc}-docker.pkg.dev/{project}/{repo}/app`). */
136 repositoryUri: string;
137 /** Full resource name `projects/.../repositories/{repository}`. */
138 name: string;
139 /** Artifact Registry location (`us-central1`, …). */
140 location: string;
141 };
142 }
143 interface WorkloadIdentityOptions {
144 /**
145 * Existing Google service-account email the workload runs as (GKE
146 * only). Alchemy annotates the Kubernetes ServiceAccount with
147 * `iam.gke.io/gcp-service-account`, grants the KSA principal
148 * `roles/iam.workloadIdentityUser` on the GSA, and lands binding
149 * grants on the GSA. Omit it (the default) to grant bindings directly
150 * to the KSA's Workload Identity Federation principal.
151 */
152 gcpServiceAccount?: string;
153 }
154 interface WorkloadBindingContract {
155 /**
156 * IAM grants landed on the workload's Workload Identity principal (GKE
157 * only) — the same host-binding channel as `GCP.Run.Service` and
158 * `GCP.Function`.
159 */
160 iam?: GcpIamGrant[];
161 }
162 interface WorkloadServicesRegistry {
163 /** GCP credential-chain services ambient inside GKE workload pods. */
164 gcp: Credentials | GcpEnvironment;
165 }
166 }
167
168 /** Services the adapter's methods close over at layer build. */
169 type GkeAdapterDeps =
170 | Credentials
171 | GcpEnvironment
172 | HttpClient
173 | FileSystem.FileSystem
174 | Path.Path
175 // Hashing an unbundled Node image resolves installed packages.
176 | ChildProcessSpawner;
177
178 const GSA_ANNOTATION = "iam.gke.io/gcp-service-account";
179
180 /** Zone `us-central1-a` → region `us-central1`; regions pass through. */
181 export const regionOfLocation = (location: string) => {
182 const parts = location.split("-");
183 const last = parts[parts.length - 1] ?? "";
184 if (parts.length >= 3 && last.length === 1) {
185 return parts.slice(0, -1).join("-");
186 }
187 return location;
188 };
189
190 export const apiServerEndpoint = (endpoint: string | undefined) => {
191 if (endpoint === undefined || endpoint.length === 0) return undefined;
192 return endpoint.startsWith("https://") || endpoint.startsWith("http://")
193 ? endpoint
194 : `https://${endpoint}`;
195 };
196
197 export const workloadPoolOf = (project: string) => `${project}.svc.id.goog`;
198
199 /**
200 * The Workload Identity Federation principal of a Kubernetes
201 * ServiceAccount — the IAM member GKE pods running as that KSA
202 * authenticate as. Every cluster in the project shares the pool, so the
203 * same `namespace`/`serviceAccount` pair is one identity project-wide.
204 */
205 export const workloadIdentityPrincipal = (options: {
206 projectNumber: string;
207 project: string;
208 namespace: string;
209 serviceAccount: string;
210 }) =>
211 `principal://iam.googleapis.com/projects/${options.projectNumber}` +
212 `/locations/global/workloadIdentityPools/${workloadPoolOf(options.project)}` +
213 `/subject/ns/${options.namespace}/sa/${options.serviceAccount}`;
214
215 const WORKLOAD_IDENTITY_USER = "roles/iam.workloadIdentityUser";
216
217 const gsaResourceName = (email: string) => `projects/-/serviceAccounts/${email}`;
218
219 /** Binding channels a GKE workload can materialize. */
220 const GKE_BINDING_KEYS = new Set(["env", "iam"]);
221
222 /** Narrow persisted identity state (possibly a legacy shape). */
223 const identityStateOf = (state: Record<string, unknown> | undefined) => ({
224 member: typeof state?.member === "string" ? state.member : undefined,
225 iamGrants: Array.isArray(state?.iamGrants) ? (state.iamGrants as AppliedIamGrant[]) : [],
226 gcpServiceAccount:
227 typeof state?.gcpServiceAccount === "string" ? state.gcpServiceAccount : undefined,
228 impersonator: typeof state?.impersonator === "string" ? state.impersonator : undefined,
229 });
230
231 /**
232 * Build a {@link ClusterTransport} for a GKE cluster from known
233 * endpoint/CA. Captures the ambient GCP credentials so the per-request
234 * token mint is self-contained — used by the adapter and by the
235 * `GCP.Container.Cluster` provider's kubernetes-object binding channel.
236 */
237 export const makeGkeTransport = Effect.fn(function* (options: {
238 endpoint: string;
239 certificateAuthorityData: string;
240 }) {
241 const context = yield* Effect.context<Credentials>();
242 return {
243 endpoint: options.endpoint,
244 certificateAuthorityData: options.certificateAuthorityData,
245 headers: Effect.gen(function* () {
246 const creds = yield* yield* Credentials;
247 return {
248 Authorization: `Bearer ${Redacted.value(creds.accessToken)}`,
249 };
250 }).pipe(Effect.provideContext(context)),
251 } satisfies ClusterTransport;
252 });
253
254 /**
255 * The `Kubernetes.Connection` of a GKE cluster — stamped on
256 * `GCP.Container.Cluster` attributes so the cluster resource can be passed
257 * directly as any `Kubernetes.*` workload's `cluster`.
258 */
259 export const gkeConnectionOf = (options: {
260 clusterId: string;
261 location: string;
262 project?: string | undefined;
263 endpoint?: string | undefined;
264 certificateAuthorityData?: string | undefined;
265 }): Connection => ({
266 endpoint: apiServerEndpoint(options.endpoint) ?? options.endpoint,
267 certificateAuthorityData: options.certificateAuthorityData,
268 auth: {
269 kind: "gcp-gke",
270 clusterId: options.clusterId,
271 location: options.location,
272 project: options.project,
273 },
274 });
275
276 const narrowGkeAuth = (connection: Connection) =>
277 connection.auth.kind === "gcp-gke"
278 ? Effect.succeed(connection.auth)
279 : Effect.die(new Error(`gcp-gke adapter received auth kind '${connection.auth.kind}'`));
280
281 const clusterResourceName = (project: string, location: string, clusterId: string) =>
282 `projects/${project}/locations/${location}/clusters/${clusterId}`;
283
284 const createRepositoryName = (id: string) =>
285 createPhysicalName({
286 id: `${id}-repo`,
287 maxLength: 63,
288 lowercase: true,
289 });
290
291 /**
292 * Generated container entry for an Effect-native GKE server: resolves the
293 * program's registered runners and serves the returned `{ fetch }` handler
294 * on `PORT`. Credentials use the GCP chain so Workload Identity's GCE
295 * metadata server resolves inside the pod.
296 */
297 export const makeGkeServerBootstrap =
298 (handler: string) =>
299 (importPath: string): string =>
300 `
301 import { BunServices } from "@effect/platform-bun";
302 import { BunHttpServer } from "alchemy/Http";
303 import { Stack } from "alchemy/Stack";
304 import { makeEntrypointLayer, reifyBoundConfigProvider } from "alchemy/Runtime";
305 import { provideProcessTelemetry } from "alchemy/Telemetry";
306 import * as Context from "effect/Context";
307 import * as Config from "effect/Config";
308 import * as ConfigProvider from "effect/ConfigProvider";
309 import * as Effect from "effect/Effect";
310 import * as FetchHttpClient from "effect/http/FetchHttpClient";
311 import * as Layer from "effect/Layer";
312 import * as Logger from "effect/Logger";
313 import { fromChain, fromCredentials } from "@alchemy.run/gcp";
314
315 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
316
317 const tag = Context.Service("${Self.key}");
318 const layer = makeEntrypointLayer(tag, entrypoint);
319
320 const platform = Layer.mergeAll(
321 BunServices.layer,
322 FetchHttpClient.layer,
323 Logger.layer([Logger.consolePretty()]),
324 );
325
326 const program = tag.pipe(
327 Effect.flatMap((host) =>
328 host.RuntimeContext.exports.pipe(
329 Effect.flatMap((exports) => exports.program),
330 provideProcessTelemetry(host.RuntimeContext),
331 ),
332 ),
333 Effect.provide(
334 layer.pipe(Layer.provideMerge(Layer.effect(
335 Stack,
336 Effect.all([
337 Config.String("ALCHEMY_STACK_NAME"),
338 Config.String("ALCHEMY_STAGE")
339 ]).pipe(
340 Effect.map(([name, stage]) => ({
341 name,
342 stage,
343 bindings: {},
344 resources: {}
345 }))
346 )
347 )),
348 Layer.provideMerge(fromCredentials()),
349 Layer.provideMerge(fromChain()),
350 Layer.provideMerge(BunHttpServer()),
351 Layer.provideMerge(platform),
352 Layer.provideMerge(
353 Layer.succeed(
354 ConfigProvider.ConfigProvider,
355 reifyBoundConfigProvider(ConfigProvider.fromEnv(), process.env)
356 )
357 ),
358 )
359 ),
360 Effect.scoped
361 );
362
363 console.log(\`GKE Deployment bootstrap starting on port \${process.env.PORT ?? 3000}...\`);
364 await Effect.runPromise(program).catch((err) => {
365 console.error("GKE Deployment bootstrap failed:", err);
366 process.exit(1);
367 });
368 `;
369
370 /**
371 * Generated container entry for an Effect-native GKE Job: resolves the
372 * program's `run` effect, executes it to completion, and exits. Credentials
373 * use the GCP chain so Workload Identity's GCE metadata server resolves
374 * inside the pod.
375 */
376 export const makeGkeJobBootstrap =
377 (handler: string) =>
378 (importPath: string): string =>
379 `
380 import { BunServices } from "@effect/platform-bun";
381 import { Stack } from "alchemy/Stack";
382 import { makeEntrypointLayer, reifyBoundConfigProvider } from "alchemy/Runtime";
383 import { provideProcessTelemetry } from "alchemy/Telemetry";
384 import * as Context from "effect/Context";
385 import * as Config from "effect/Config";
386 import * as ConfigProvider from "effect/ConfigProvider";
387 import * as Effect from "effect/Effect";
388 import * as FetchHttpClient from "effect/http/FetchHttpClient";
389 import * as Layer from "effect/Layer";
390 import * as Logger from "effect/Logger";
391 import { fromChain, fromCredentials } from "@alchemy.run/gcp";
392
393 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
394
395 const tag = Context.Service("${Self.key}");
396 const layer = makeEntrypointLayer(tag, entrypoint);
397
398 const platform = Layer.mergeAll(
399 BunServices.layer,
400 FetchHttpClient.layer,
401 Logger.layer([Logger.consolePretty()]),
402 );
403
404 const program = tag.pipe(
405 Effect.flatMap((host) =>
406 host.RuntimeContext.exports.pipe(
407 Effect.flatMap((exports) => exports.program),
408 provideProcessTelemetry(host.RuntimeContext),
409 ),
410 ),
411 Effect.provide(
412 layer.pipe(Layer.provideMerge(Layer.effect(
413 Stack,
414 Effect.all([
415 Config.String("ALCHEMY_STACK_NAME"),
416 Config.String("ALCHEMY_STAGE")
417 ]).pipe(
418 Effect.map(([name, stage]) => ({
419 name,
420 stage,
421 bindings: {},
422 resources: {}
423 }))
424 )
425 )),
426 Layer.provideMerge(fromCredentials()),
427 Layer.provideMerge(fromChain()),
428 Layer.provideMerge(platform),
429 Layer.provideMerge(
430 Layer.succeed(
431 ConfigProvider.ConfigProvider,
432 reifyBoundConfigProvider(ConfigProvider.fromEnv(), process.env)
433 )
434 ),
435 )
436 ),
437 Effect.scoped
438 );
439
440 console.log("GKE Job bootstrap starting...");
441 await Effect.runPromise(program).catch((err) => {
442 console.error("GKE Job bootstrap failed:", err);
443 process.exit(1);
444 });
445 process.exit(0);
446 `;
447
448 /**
449 * The `gcp-gke` cluster adapter layer. Provided (merged) by
450 * `GCP.providers()` so the `Kubernetes.*` workload providers can resolve
451 * it from the stack context.
452 */
453 export const GkeKubernetesAdapter = () =>
454 Layer.effect(
455 ClusterAdapter("gcp-gke"),
456 Effect.gen(function* () {
457 const imageSource = yield* makeImageSource;
458 const context = yield* Effect.context<GkeAdapterDeps>();
459
460 const withGcp = <A, E, R>(self: Effect.Effect<A, E, R>) =>
461 Effect.provideContext(self, context);
462
463 const getLiveCluster = Effect.fn(function* (auth: {
464 clusterId: string;
465 location: string;
466 project?: string | undefined;
467 }) {
468 const cluster = yield* Effect.gen(function* () {
469 const env = yield* GcpEnvironment.current;
470 const project = auth.project ?? env.project;
471 const name = clusterResourceName(project, auth.location, auth.clusterId);
472 return yield* container
473 .getProjectsLocationsClusters({ name })
474 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
475 }).pipe(withGcp);
476 // STOPPING still serves the API until the endpoint is gone. A missing
477 // CA with that endpoint is not "gone": connect fails and destroy retries
478 // instead of skipping Service deletion.
479 const apiGone = cluster?.status === "STOPPING" && !apiServerEndpoint(cluster.endpoint);
480 if (!cluster || apiGone) {
481 return yield* new ClusterNotFoundError({
482 message: `GKE cluster '${auth.clusterId}' no longer exists`,
483 });
484 }
485 return cluster;
486 });
487
488 const connect: ClusterAdapterService["connect"] = (connection) =>
489 Effect.gen(function* () {
490 const auth = yield* narrowGkeAuth(connection);
491 // Always read the cluster. A persisted endpoint does not prove it
492 // still exists, and delete uses ClusterNotFoundError to skip
493 // in-cluster objects and still remove workload-identity bindings.
494 const cluster = yield* getLiveCluster(auth);
495 const endpoint = apiServerEndpoint(cluster.endpoint);
496 const certificateAuthorityData = cluster.masterAuth?.clusterCaCertificate;
497 if (!endpoint || !certificateAuthorityData) {
498 return yield* new KubernetesAdapterNotReady({
499 message:
500 `GKE cluster '${auth.clusterId}' has no endpoint or ` +
501 "certificate authority data yet (still creating?)",
502 });
503 }
504 return yield* makeGkeTransport({
505 endpoint,
506 certificateAuthorityData,
507 });
508 }).pipe(
509 withGcp,
510 Effect.mapError((error): ClusterNotFoundError | Error =>
511 error instanceof ClusterNotFoundError || error instanceof Error
512 ? error
513 : new KubernetesAdapterOperationFailed({ message: String(error) }),
514 ),
515 );
516
517 const identityReconcile = Effect.fn(function* (options: WorkloadIdentityReconcileOptions) {
518 const auth = yield* narrowGkeAuth(options.connection);
519 const bindings = options.bindings.filter(
520 (
521 binding: ResourceBinding<WorkloadBindingContract> & {
522 action?: string;
523 },
524 ) => binding.action !== "delete",
525 );
526 const unsupported = [
527 ...new Set(
528 bindings.flatMap((binding) =>
529 Object.entries(binding.data ?? {})
530 .filter(([key, value]) => value !== undefined && !GKE_BINDING_KEYS.has(key))
531 .map(([key]) => key),
532 ),
533 ),
534 ];
535 if (unsupported.length > 0) {
536 return yield* Effect.die(
537 new Error(
538 `'${options.id}': bindings carry ${unsupported.join(", ")}, ` +
539 "which GKE workloads cannot materialize (only env and " +
540 "GCP `iam` grants).",
541 ),
542 );
543 }
544 return yield* Effect.gen(function* () {
545 const env = yield* GcpEnvironment.current;
546 const project = auth.project ?? env.project;
547 const workloadPool = workloadPoolOf(project);
548 const principal = workloadIdentityPrincipal({
549 projectNumber: yield* projectNumber(project),
550 project,
551 namespace: options.namespace,
552 serviceAccount: options.serviceAccount,
553 });
554 const gcpServiceAccount = options.options?.gcpServiceAccount;
555 const member = gcpServiceAccount ? `serviceAccount:${gcpServiceAccount}` : principal;
556 const previous = identityStateOf(options.state);
557
558 // Let the KSA impersonate the user-supplied GSA.
559 if (gcpServiceAccount) {
560 yield* updateIamMembership({
561 kind: "iam.serviceAccount",
562 name: gsaResourceName(gcpServiceAccount),
563 member: principal,
564 add: [WORKLOAD_IDENTITY_USER],
565 });
566 }
567 if (
568 previous.gcpServiceAccount !== undefined &&
569 previous.impersonator !== undefined &&
570 (previous.gcpServiceAccount !== gcpServiceAccount ||
571 previous.impersonator !== principal)
572 ) {
573 yield* revokeIamMembership({
574 kind: "iam.serviceAccount",
575 name: gsaResourceName(previous.gcpServiceAccount),
576 member: previous.impersonator,
577 roles: [WORKLOAD_IDENTITY_USER],
578 });
579 }
580
581 // A renamed KSA / namespace or a GSA switch is a new member: its
582 // predecessor loses everything it was granted.
583 const sameMember = previous.member === member;
584 if (previous.member !== undefined && !sameMember) {
585 yield* revokeHostIam({
586 serviceAccount: previous.member,
587 grants: previous.iamGrants,
588 });
589 }
590 const { grants } = yield* syncHostIam({
591 project,
592 serviceAccount: member,
593 // The principal is shared by every cluster in the project, so
594 // only grants this workload recorded are ever revoked.
595 managed: false,
596 bindings,
597 previous: sameMember ? previous.iamGrants : undefined,
598 });
599
600 return {
601 env: {
602 GOOGLE_PROJECT_ID: project,
603 GOOGLE_CLOUD_PROJECT: project,
604 },
605 serviceAccountAnnotations: gcpServiceAccount
606 ? { [GSA_ANNOTATION]: gcpServiceAccount }
607 : undefined,
608 state: {
609 kind: "gcp-workload-identity" as const,
610 workloadPool,
611 project,
612 member,
613 iamGrants: grants,
614 gcpServiceAccount,
615 impersonator: gcpServiceAccount ? principal : undefined,
616 },
617 };
618 }).pipe(withGcp);
619 });
620
621 const identityDelete = Effect.fn(function* (options: {
622 connection: Connection | undefined;
623 state: Record<string, unknown> | undefined;
624 }) {
625 // Grants live on project / resource IAM policies, not on the
626 // cluster, so they are revoked even when the cluster is gone. The
627 // KSA itself dies with the workload's objects.
628 const state = identityStateOf(options.state);
629 yield* Effect.gen(function* () {
630 if (state.member !== undefined) {
631 yield* revokeHostIam({
632 serviceAccount: state.member,
633 grants: state.iamGrants,
634 });
635 }
636 if (state.gcpServiceAccount !== undefined && state.impersonator !== undefined) {
637 yield* revokeIamMembership({
638 kind: "iam.serviceAccount",
639 name: gsaResourceName(state.gcpServiceAccount),
640 member: state.impersonator,
641 roles: [WORKLOAD_IDENTITY_USER],
642 });
643 }
644 }).pipe(withGcp);
645 });
646
647 const registryResolve = (
648 options: ImageRegistryResolveOptions,
649 ): Effect.Effect<ImageRegistryResult, any, AdapterLifecycleServices> =>
650 Effect.gen(function* () {
651 const state = options.state;
652 const env = yield* GcpEnvironment.current;
653 const location = typeof state?.location === "string" ? state.location : env.region;
654 const repositoryName =
655 typeof state?.repositoryName === "string"
656 ? state.repositoryName
657 : yield* createRepositoryName(options.id);
658 const repositoryUri =
659 typeof state?.repositoryUri === "string" && state.repositoryName === repositoryName
660 ? state.repositoryUri
661 : undefined;
662 const resolved = yield* imageSource.resolve({
663 id: options.id,
664 source: options.source as ImageSourceLike,
665 repositoryName,
666 repositoryUri,
667 location,
668 tags: options.tags,
669 platform: options.platform,
670 port: options.port,
671 isExternal: options.isExternal,
672 bootstrap: options.bootstrap,
673 session: options.session,
674 });
675 return {
676 imageUri: resolved.imageUri,
677 codeHash: resolved.codeHash,
678 state: {
679 kind: "gcp-artifact-registry" as const,
680 repositoryName: resolved.repositoryName,
681 repositoryUri: resolved.repositoryUri,
682 location,
683 name:
684 typeof state?.name === "string" && state.repositoryName === repositoryName
685 ? state.name
686 : imageSource.resourceName(env.project, location, resolved.repositoryName),
687 },
688 } satisfies ImageRegistryResult;
689 }).pipe(withGcp) as Effect.Effect<ImageRegistryResult, any, AdapterLifecycleServices>;
690
691 const registryHash = Effect.fn(function* (options: {
692 source: ImageSourceLike;
693 platform: string;
694 port?: number | undefined;
695 isExternal?: boolean | undefined;
696 bootstrap: (importPath: string) => string;
697 }) {
698 return yield* imageSource
699 .hash({
700 source: options.source,
701 platform: options.platform,
702 port: options.port,
703 isExternal: options.isExternal,
704 bootstrap: options.bootstrap,
705 })
706 .pipe(withGcp);
707 });
708
709 const registryDelete = (
710 options: ImageRegistryDeleteOptions,
711 ): Effect.Effect<void, any, AdapterLifecycleServices> =>
712 Effect.gen(function* () {
713 if (typeof options.state?.name !== "string") return;
714 yield* imageSource.destroyRepository(options.state.name);
715 }).pipe(withGcp) as Effect.Effect<void, any, AdapterLifecycleServices>;
716
717 const loadBalancerDefaults = Effect.fn(function* (_options: { connection: Connection }) {
718 return {
719 loadBalancerClass: undefined,
720 annotations: {
721 "cloud.google.com/l4-rbs": "enabled",
722 },
723 };
724 });
725
726 return {
727 kind: "Kubernetes.ClusterAdapter" as const,
728 connect,
729 identity: {
730 reconcile: identityReconcile,
731 delete: identityDelete,
732 },
733 registry: {
734 resolve: registryResolve,
735 hash: registryHash,
736 delete: registryDelete,
737 },
738 bootstrap: {
739 server: makeGkeServerBootstrap,
740 job: makeGkeJobBootstrap,
741 },
742 loadBalancerDefaults,
743 } satisfies ClusterAdapterService;
744 }),
745 );