@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, 04:45 UTC

main
ts 373 lines 14.3 KB
Raw
1 import type { InlineDockerfile } from "@alchemy.run/docker/Dockerfile";
2 import type { DockerfileBuild } from "@alchemy.run/docker/ImageSource";
3 import type * as Bundle from "alchemy/Bundle/Bundle";
4 import type { ResourceBinding } from "alchemy/Resource";
5 import type { ResourceContext } from "alchemy/ResourceContext";
6 import type { Stack } from "alchemy/Stack";
7 import type { Stage } from "alchemy/Stage";
8 /**
9 * The extension seam between the cluster-agnostic `Kubernetes.*` workloads
10 * and the platform a cluster runs on.
11 *
12 * A {@link ClusterAdapterService} is registered under a keyed Context tag —
13 * `Kubernetes.ClusterAdapter/<auth kind>` — and resolved dynamically from
14 * the ambient provider context by {@link findClusterAdapter}, mirroring how
15 * resource providers are resolved by type. `Kubernetes.providers()` ships
16 * the built-in adapters (`kubeconfig`, `token`, `client-cert`, `exec`);
17 * cloud provider layers contribute theirs (`AWS.providers()` registers
18 * `aws-eks`).
19 *
20 * An adapter owns everything platform-specific:
21 *
22 * - **connect** (required) — resolve the API server endpoint/CA and mint
23 * per-request auth headers.
24 * - **identity** (optional) — provision workload identity for a namespace +
25 * service account and translate host bindings into cloud credentials
26 * (EKS Pod Identity, GKE Workload Identity Federation).
27 * - **registry** (optional) — build/mirror container images into a managed
28 * registry the cluster can pull from (ECR on EKS, Artifact Registry on GKE).
29 * - **bootstrap** (optional) — platform-specific generated container
30 * entries for Effect-native workloads (e.g. wiring the AWS credential
31 * chain for Pod Identity).
32 * - **loadBalancerDefaults** (optional) — platform defaults for
33 * `LoadBalancer` Services (EKS Auto Mode's `loadBalancerClass` +
34 * internet-facing scheme).
35 */
36 import * as Context from "effect/Context";
37 import * as Data from "effect/Data";
38 import * as Effect from "effect/Effect";
39 import * as Option from "effect/Option";
40 import type { Connection } from "./Connection.ts";
41
42 /**
43 * Per-resource engine services ambient inside every provider lifecycle
44 * operation. Adapter methods run inside the workload providers' lifecycle
45 * ops, so they may require these (physical-name generation needs the
46 * resource's ResourceContext + Stack + Stage) — everything else an adapter
47 * needs is captured at its layer build.
48 */
49 export type AdapterLifecycleServices = ResourceContext | Stack | Stage;
50
51 /**
52 * The target cluster no longer exists (definitively — e.g. the managed
53 * control plane is deleted or deleting). Distinct from transient
54 * unreachability: `read`/`delete` treat this as "everything in-cluster is
55 * already gone".
56 */
57 export class ClusterNotFoundError extends Data.TaggedError("Kubernetes.ClusterNotFoundError")<{
58 message: string;
59 }> {}
60
61 /**
62 * A resolved transport to a cluster's API server. `headers` is an Effect
63 * so short-lived tokens (EKS SigV4 presigns, exec plugin credentials) are
64 * minted per request.
65 */
66 export interface ClusterTransport {
67 /** The API server endpoint URL. */
68 endpoint: string;
69 /** Base64-encoded PEM certificate authority bundle. */
70 certificateAuthorityData?: string;
71 /** Skip TLS verification (self-signed local clusters). */
72 insecureSkipTlsVerify?: boolean;
73 /** Mint the auth headers for one request. */
74 headers: Effect.Effect<Record<string, string>, Error>;
75 /** PEM client certificate credentials for mutual TLS. */
76 clientCert?: { certificate: string; key: string };
77 }
78
79 /**
80 * Workload identity state persisted on a workload's attributes, keyed by
81 * adapter kind. Cloud providers extend it via module augmentation — AWS
82 * registers:
83 *
84 * ```ts
85 * declare module "@alchemy.run/kubernetes/ClusterAdapter" {
86 * interface IdentityStateRegistry {
87 * "aws-pod-identity": {
88 * roleArn: string;
89 * roleName: string;
90 * associationArn: string;
91 * associationId: string;
92 * };
93 * }
94 * }
95 * ```
96 */
97 export interface IdentityStateRegistry {}
98
99 /** The discriminated identity-state union across all registered adapters. */
100 export type IdentityState = {
101 [K in keyof IdentityStateRegistry]: {
102 readonly kind: K;
103 } & IdentityStateRegistry[K];
104 }[keyof IdentityStateRegistry];
105
106 /**
107 * Image-registry state persisted on a workload's attributes, keyed by
108 * adapter kind (AWS registers `"aws-ecr"` with the repository name/URI).
109 * The built-in `"registry"` entry records images pushed to a connection's
110 * {@link Connection.registry}.
111 */
112 export interface RegistryStateRegistry {
113 registry: {
114 /** The registry `server` the image was pushed to. */
115 server: string;
116 /** The repository the image was pushed to (`<server>/<name>`). */
117 repository: string;
118 };
119 }
120
121 /** The discriminated registry-state union across all registered adapters. */
122 export type RegistryState = {
123 [K in keyof RegistryStateRegistry]: {
124 readonly kind: K;
125 } & RegistryStateRegistry[K];
126 }[keyof RegistryStateRegistry];
127
128 /**
129 * Cloud-specific workload identity options, extended via module
130 * augmentation (AWS adds `managedPolicyArns`, GCP `gcpServiceAccount`).
131 */
132 export interface WorkloadIdentityOptions {}
133
134 /**
135 * The binding contract of `Kubernetes.Deployment` / `Kubernetes.Job`
136 * hosts. The core contract is environment variables; cloud providers
137 * augment it with their credential-grant channels (AWS adds
138 * `policyStatements`, GCP adds `iam`), which the matching {@link ClusterAdapterService}'s
139 * identity adapter materializes at deploy time.
140 */
141 export interface WorkloadBindingContract {
142 env?: Record<string, any>;
143 }
144
145 /**
146 * Ambient runtime services the workload platforms assume inside the
147 * deployed container, keyed by contributor and extended via module
148 * augmentation — AWS registers its credential-chain services so inline
149 * impls can use AWS bindings without providing them:
150 *
151 * ```ts
152 * declare module "@alchemy.run/kubernetes/ClusterAdapter" {
153 * interface WorkloadServicesRegistry {
154 * aws: Credentials | Region | AWSEnvironment;
155 * }
156 * }
157 * ```
158 */
159 export interface WorkloadServicesRegistry {}
160
161 /** The union of all registered ambient workload services. */
162 export type WorkloadServices = WorkloadServicesRegistry[keyof WorkloadServicesRegistry];
163
164 /**
165 * The image-source shape shared by every workload: exactly one of `main`
166 * (bundle an inline Effect program), `context`/`dockerfile` (build the
167 * user's Dockerfile), or `image` (a pre-built registry reference).
168 * Structurally mirrors the AWS container platforms' source props.
169 */
170 export interface WorkloadImageSource {
171 main?: string;
172 handler?: string;
173 /**
174 * Bundler configuration for `main`, or Docker build args and secrets for
175 * a `context`/`dockerfile` build. Unused bundled code is tree-shaken.
176 * `effect`, alchemy, and `@distilled.cloud` are marked pure so unused
177 * parts prune more aggressively. List extra packages with
178 * `pure.packages`, or disable with `pure: false`.
179 */
180 build?: Bundle.BundleConfig & DockerfileBuild;
181 context?: string;
182 dockerfile?: string | InlineDockerfile;
183 image?: string;
184 }
185
186 export interface WorkloadIdentityReconcileOptions {
187 /** Logical resource id. */
188 id: string;
189 /** The resolved cluster connection. */
190 connection: Connection;
191 /** The namespace the workload runs in. */
192 namespace: string;
193 /** The service account name the workload's pods run as. */
194 serviceAccount: string;
195 /** Host bindings attached to the workload. */
196 bindings: ResourceBinding<WorkloadBindingContract>[];
197 /** Cloud-specific identity options from the workload's `identity` prop. */
198 options: WorkloadIdentityOptions | undefined;
199 /**
200 * Previously persisted identity state, if any — untyped hints because
201 * legacy pre-rename rows carry the old flat attribute shape; adapters
202 * narrow structurally and re-observe cloud state as the authority.
203 */
204 state: Record<string, unknown> | undefined;
205 /** Internal + user tags for identity-owned cloud resources. */
206 tags: Record<string, string>;
207 }
208
209 export interface WorkloadIdentityResult {
210 /** Extra container environment collected from bindings. */
211 env: Record<string, any>;
212 /** Annotations to stamp on the workload's ServiceAccount object. */
213 serviceAccountAnnotations?: Record<string, string>;
214 /** Serializable state persisted on the workload's attributes. */
215 // oxlint-disable-next-line typescript/no-redundant-type-constituents -- registry type is `never` until cloud packages augment it
216 state: IdentityState | undefined;
217 }
218
219 export interface WorkloadIdentityDeleteOptions {
220 /** The persisted cluster connection (may reference a gone cluster). */
221 connection: Connection | undefined;
222 /**
223 * The persisted identity state. Untyped because legacy pre-rename rows
224 * carry the old flat attribute shape — adapters narrow structurally.
225 */
226 state: Record<string, unknown> | undefined;
227 }
228
229 export interface ImageRegistryResolveOptions {
230 /** Logical resource id — keys generated repository names. */
231 id: string;
232 /** The image-source props bag. */
233 source: WorkloadImageSource;
234 /** Target image platform (`linux/amd64` / `linux/arm64`). */
235 platform: string;
236 /** Port the generated Dockerfile exposes (`main` sources only). */
237 port?: number;
238 /** True when `main` bundles as-is (no Effect bootstrap entry). */
239 isExternal?: boolean;
240 /** The generated-entry bootstrap wrapped around `main`. */
241 bootstrap: (importPath: string) => string;
242 /** Tags for registry-owned cloud resources. */
243 tags: Record<string, string>;
244 /**
245 * Previously persisted registry state, if any — untyped hints because
246 * legacy pre-rename rows carry the old flat attribute shape; adapters
247 * narrow structurally.
248 */
249 state: Record<string, unknown> | undefined;
250 /** Plan-status session for build/push progress notes. */
251 session: { note: (message: string) => Effect.Effect<void> };
252 }
253
254 export interface ImageRegistryResult {
255 /** Full image reference the pod spec should run. */
256 imageUri: string;
257 /** Content hash identifying the image. */
258 codeHash: string;
259 /** Serializable state persisted on the workload's attributes. */
260 state: RegistryState | undefined;
261 }
262
263 export interface ImageRegistryHashOptions {
264 source: WorkloadImageSource;
265 platform: string;
266 port?: number;
267 isExternal?: boolean;
268 bootstrap: (importPath: string) => string;
269 }
270
271 export interface ImageRegistryDeleteOptions {
272 /**
273 * The persisted registry state. Untyped because legacy pre-rename rows
274 * carry the old flat attribute shape — adapters narrow structurally.
275 */
276 state: Record<string, unknown> | undefined;
277 }
278
279 export interface ClusterAdapterService {
280 readonly kind: "Kubernetes.ClusterAdapter";
281 /**
282 * Resolve the transport for a connection: discover the endpoint/CA when
283 * the connection doesn't carry them, and return a per-request auth
284 * header mint. Fails with {@link ClusterNotFoundError} when the cluster
285 * definitively no longer exists.
286 */
287 readonly connect: (
288 connection: Connection,
289 ) => Effect.Effect<ClusterTransport, ClusterNotFoundError | Error>;
290 /** Workload identity provisioning (Pod Identity on EKS, Workload Identity Federation on GKE). */
291 readonly identity?: {
292 readonly reconcile: (
293 options: WorkloadIdentityReconcileOptions,
294 ) => Effect.Effect<WorkloadIdentityResult, any, AdapterLifecycleServices>;
295 readonly delete: (
296 options: WorkloadIdentityDeleteOptions,
297 ) => Effect.Effect<void, any, AdapterLifecycleServices>;
298 };
299 /** Managed container-image registry (ECR on EKS, Artifact Registry on GKE). */
300 readonly registry?: {
301 readonly resolve: (
302 options: ImageRegistryResolveOptions,
303 ) => Effect.Effect<ImageRegistryResult, any, AdapterLifecycleServices>;
304 /** Plan-time content hash used by `diff` to surface source drift. */
305 readonly hash: (
306 options: ImageRegistryHashOptions,
307 ) => Effect.Effect<string | undefined, any, AdapterLifecycleServices>;
308 readonly delete: (
309 options: ImageRegistryDeleteOptions,
310 ) => Effect.Effect<void, any, AdapterLifecycleServices>;
311 };
312 /**
313 * Platform-specific generated container entries for Effect-native
314 * workloads. Defaults to the platform-neutral bootstraps when omitted.
315 */
316 readonly bootstrap?: {
317 readonly server?: (handler: string) => (importPath: string) => string;
318 readonly job?: (handler: string) => (importPath: string) => string;
319 };
320 /**
321 * Platform defaults applied to a `LoadBalancer` Service (EKS Auto Mode
322 * sets `loadBalancerClass: eks.amazonaws.com/nlb` and defaults the
323 * scheme to internet-facing). User `serviceAnnotations` always win.
324 */
325 readonly loadBalancerDefaults?: (options: { connection: Connection }) => Effect.Effect<
326 {
327 loadBalancerClass?: string | undefined;
328 annotations?: Record<string, string>;
329 },
330 any,
331 AdapterLifecycleServices
332 >;
333 }
334
335 const adapterKey = (authKind: string) => `Kubernetes.ClusterAdapter/${authKind}`;
336
337 /**
338 * The keyed Context tag for an adapter. Same auth kind → same tag, so a
339 * layer built with `ClusterAdapter("aws-eks")` is found by any dynamic
340 * lookup for that kind.
341 */
342 export const ClusterAdapter = (
343 authKind: string,
344 ): Context.Service<ClusterAdapterService, ClusterAdapterService> =>
345 Context.Service<ClusterAdapterService, ClusterAdapterService>()(adapterKey(authKind)) as any;
346
347 /**
348 * Resolve the {@link ClusterAdapterService} for a connection's auth kind
349 * from the ambient context (the stack's composed provider layers). Dies
350 * with setup guidance when no adapter is registered — that means the
351 * provider layer contributing it (e.g. `AWS.providers()` for `aws-eks`)
352 * is missing from the stack.
353 */
354 export const findClusterAdapter = (authKind: string): Effect.Effect<ClusterAdapterService> =>
355 Effect.serviceOption(ClusterAdapter(authKind)).pipe(
356 Effect.flatMap(
357 Option.match({
358 onSome: (adapter) => Effect.succeed(adapter),
359 onNone: () =>
360 Effect.die(
361 new Error(
362 `No Kubernetes cluster adapter is registered for auth kind ` +
363 `'${authKind}'. Add the provider layer that contributes it ` +
364 `to the stack's providers — e.g. 'aws-eks' ships with ` +
365 "`AWS.providers()`; the built-in kinds (kubeconfig, token, " +
366 "client-cert, exec) ship with `Kubernetes.providers()`. " +
367 "Compose multiple provider layers with " +
368 "`Layer.mergeAll(AWS.providers(), Kubernetes.providers())`.",
369 ),
370 ),
371 }),
372 ),
373 );