@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 301 lines 10.8 KB
Raw
1 import { isResolved } from "alchemy/Diff";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import { isPlainObject } from "alchemy/Util/data";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import {
8 applyObject,
9 connectCluster,
10 deleteObject,
11 ifClusterExists,
12 readObject,
13 } from "./Client.ts";
14 import { toConnection, type ClusterLike, type Connection } from "./Connection.ts";
15 import { driftMask, hashDriftSelection } from "./internal/declared.ts";
16 import { connectionIdentity, connectionOfOutput, tryConnectionOf } from "./internal/workload.ts";
17 import type { KubernetesObjectDefinition, KubernetesObjectRef } from "./Objects.ts";
18 import type { Providers } from "./Providers.ts";
19
20 export class ManifestInvalidProps extends Data.TaggedError("ManifestInvalidProps")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 /**
26 * A literal Kubernetes object: `apiVersion` + `kind` + `metadata`, with the
27 * rest of the object's fields (`spec`, `data`, …) carried as-is. Any kind is
28 * accepted — built-in objects and CRDs alike; the API server validates the
29 * shape on apply.
30 */
31 export interface KubernetesManifest {
32 apiVersion: string;
33 kind: string;
34 metadata?: {
35 name?: string;
36 namespace?: string;
37 labels?: Record<string, string>;
38 annotations?: Record<string, string>;
39 [key: string]: unknown;
40 };
41 [key: string]: unknown;
42 }
43
44 export interface ManifestProps {
45 /**
46 * Target cluster the manifest is applied onto. Pass a managed cluster
47 * resource (e.g. `AWS.EKS.Cluster`), a `Kubernetes.KubeConfig(...)`, or
48 * a raw `Kubernetes.Connection`.
49 */
50 cluster: ClusterLike;
51 /**
52 * The Kubernetes object to apply (server-side apply, field manager
53 * `alchemy`) — a literal object with `apiVersion`, `kind`, `metadata`, and
54 * the kind's own fields. Arbitrary CRDs are supported via API discovery.
55 */
56 manifest: KubernetesManifest;
57 }
58
59 export interface Manifest extends Resource<
60 "Kubernetes.Manifest",
61 ManifestProps,
62 {
63 /** The connection of the cluster the object is applied to. */
64 connection: Connection;
65 /** The Kubernetes API version of the applied object. */
66 apiVersion: string;
67 /** The Kubernetes kind of the applied object. */
68 kind: string;
69 /** The name of the applied object. */
70 name: string;
71 /** The namespace of the applied object (`undefined` for cluster-scoped kinds). */
72 namespace: string | undefined;
73 /** Reference to the applied Kubernetes object. */
74 ref: KubernetesObjectRef;
75 /** The server-assigned UID of the applied object, when returned. */
76 uid: string | undefined;
77 /**
78 * Fingerprint of the declared fields last applied. `read` compares a GET
79 * projected through {@link driftMask} to this.
80 */
81 baselineHash?: string;
82 /**
83 * Declared-field mask from the last apply. Older state omits it and is
84 * compared with the same selection against the stored manifest.
85 */
86 driftMask?: unknown;
87 /**
88 * Set by `read` when the live object diverges. Reconcile does not persist
89 * it; the extra field is what `alchemy drift` compares.
90 */
91 observedHash?: string;
92 },
93 {},
94 Providers
95 > {}
96
97 /**
98 * Applies a raw Kubernetes manifest onto any cluster via server-side
99 * apply.
100 *
101 * Any literal object is accepted — built-in kinds and custom resources
102 * alike; unknown kinds are resolved through the Kubernetes API discovery
103 * endpoint, so CRDs work without any registration. The target `cluster`
104 * can be a managed cluster resource (e.g. `AWS.EKS.Cluster`) or any
105 * cluster your kubeconfig can reach (`Kubernetes.KubeConfig(...)`).
106 * ### Applying Manifests
107 * **Example:** StatefulSet
108 * ```typescript
109 * const sts = yield* Kubernetes.Manifest("Cache", {
110 * cluster,
111 * manifest: {
112 * apiVersion: "apps/v1",
113 * kind: "StatefulSet",
114 * metadata: { name: "cache", namespace: "apps" },
115 * spec: {
116 * serviceName: "cache",
117 * replicas: 3,
118 * selector: { matchLabels: { app: "cache" } },
119 * template: {
120 * metadata: { labels: { app: "cache" } },
121 * spec: { containers: [{ name: "redis", image: "redis:7" }] },
122 * },
123 * },
124 * },
125 * });
126 * ```
127 *
128 * **Example:** Custom resource (CRD)
129 * ```typescript
130 * const widget = yield* Kubernetes.Manifest("Widget", {
131 * cluster,
132 * manifest: {
133 * apiVersion: "acme.io/v1",
134 * kind: "Widget",
135 * metadata: { name: "w", namespace: "default" },
136 * spec: { size: 3 },
137 * },
138 * });
139 * ```
140 *
141 * ### Namespaces
142 * **Example:** Create a Namespace
143 * ```typescript
144 * const ns = yield* Kubernetes.Manifest("AppsNamespace", {
145 * cluster,
146 * manifest: {
147 * apiVersion: "v1",
148 * kind: "Namespace",
149 * metadata: { name: "apps" },
150 * },
151 * });
152 * ```
153 *
154 * ### Any Cluster
155 * **Example:** Apply onto a kubeconfig context
156 * ```typescript
157 * const local = Kubernetes.KubeConfig({ context: "kind-dev" });
158 *
159 * const config = yield* Kubernetes.Manifest("AppConfig", {
160 * cluster: local,
161 * manifest: {
162 * apiVersion: "v1",
163 * kind: "ConfigMap",
164 * metadata: { name: "app-config", namespace: "default" },
165 * data: { LOG_LEVEL: "info" },
166 * },
167 * });
168 * ```
169 *
170 * @resource
171 * @product Manifest
172 */
173 export const Manifest = Resource<Manifest>("Kubernetes.Manifest", {
174 aliases: ["AWS.EKS.Manifest"],
175 });
176
177 const toObjectDefinition = (
178 manifest: KubernetesManifest,
179 ): Effect.Effect<KubernetesObjectDefinition, Error> => {
180 const name = manifest.metadata?.name;
181 if (!name) {
182 return Effect.fail(
183 new ManifestInvalidProps({
184 message: `Kubernetes.Manifest requires manifest.metadata.name (got ${manifest.apiVersion}/${manifest.kind})`,
185 }),
186 );
187 }
188 return Effect.succeed(manifest as KubernetesObjectDefinition);
189 };
190
191 export const ManifestProvider = () =>
192 Provider.effect(
193 Manifest,
194 Effect.gen(function* () {
195 return {
196 stables: ["connection", "apiVersion", "kind", "name", "namespace"],
197 // In-cluster objects have no cloud-side enumeration that attributes
198 // them to alchemy; refresh happens per-instance through `read`.
199 list: () => Effect.succeed([] as Manifest["Attributes"][]),
200 diff: Effect.fn(function* ({ olds = {} as ManifestProps, news }) {
201 if (!isResolved(news)) return;
202 const oldManifest = olds.manifest as KubernetesManifest | undefined;
203 const newManifest = news.manifest as KubernetesManifest;
204 const oldCluster = connectionIdentity(tryConnectionOf(olds.cluster));
205 const newCluster = connectionIdentity(tryConnectionOf(news.cluster));
206 // Object identity (cluster, group/version/kind, name, namespace) is
207 // immutable — changing any of it is a replacement.
208 if (
209 oldManifest &&
210 ((oldCluster !== undefined && newCluster !== undefined && oldCluster !== newCluster) ||
211 oldManifest.apiVersion !== newManifest.apiVersion ||
212 oldManifest.kind !== newManifest.kind ||
213 oldManifest.metadata?.name !== newManifest.metadata?.name ||
214 oldManifest.metadata?.namespace !== newManifest.metadata?.namespace)
215 ) {
216 return { action: "replace" } as const;
217 }
218 }),
219 read: Effect.fn(function* ({ output, olds }) {
220 if (!output) return undefined;
221 const connection = connectionOfOutput(output);
222 if (!connection) return undefined;
223 // ClusterNotFound fails the drift row. undefined means this object is gone.
224 const transport = yield* connectCluster(connection);
225 const observed = yield* readObject({
226 transport,
227 object: output.ref,
228 }).pipe(Effect.catchTag("KubernetesNotFound", () => Effect.undefined));
229 if (!observed) return undefined;
230 const uid = (observed as { metadata?: { uid?: string } }).metadata?.uid;
231 const attrs = { ...output, uid };
232 const manifest = olds?.manifest;
233 // A stored mask is the apply-time selection. Older rows have the
234 // manifest and no mask; they use that same selection, not the
235 // previous whole-object hash.
236 const desired =
237 output.driftMask === undefined && manifest !== undefined
238 ? yield* toObjectDefinition(manifest)
239 : undefined;
240 const mask = output.driftMask ?? (desired === undefined ? undefined : driftMask(desired));
241 if (mask === undefined) return attrs;
242 const liveHash = yield* hashDriftSelection(mask, observed);
243 const baseline =
244 output.driftMask !== undefined && output.baselineHash !== undefined
245 ? output.baselineHash
246 : desired === undefined
247 ? undefined
248 : yield* hashDriftSelection(mask, desired);
249 if (baseline !== undefined && liveHash !== baseline) {
250 return { ...attrs, observedHash: liveHash };
251 }
252 return attrs;
253 }),
254 reconcile: Effect.fn(function* ({ news, output, session }) {
255 const connection = toConnection(news.cluster);
256 const transport = yield* connectCluster(connection);
257 const object = yield* toObjectDefinition(news.manifest);
258 const ref: KubernetesObjectRef = {
259 apiVersion: object.apiVersion,
260 kind: object.kind,
261 name: object.metadata.name,
262 namespace: object.metadata.namespace,
263 };
264
265 // Server-side apply is a true upsert: create-if-missing and
266 // converge-if-present in one call, `force: true` so alchemy owns
267 // the fields it manages regardless of prior managers.
268 const applied = yield* applyObject({ transport, object });
269 const witnessed = isPlainObject(applied) ? applied : undefined;
270 const baselineHash = yield* hashDriftSelection(object, witnessed ?? object);
271
272 yield* session.note(
273 `Applied ${ref.apiVersion}/${ref.kind} ${ref.namespace ? `${ref.namespace}/` : ""}${ref.name}`,
274 );
275
276 const uid = (applied as { metadata?: { uid?: string } })?.metadata?.uid ?? output?.uid;
277
278 return {
279 connection,
280 apiVersion: ref.apiVersion,
281 kind: ref.kind,
282 name: ref.name,
283 namespace: ref.namespace,
284 ref,
285 uid,
286 baselineHash,
287 driftMask: driftMask(object, witnessed),
288 };
289 }),
290 delete: Effect.fn(function* ({ output }) {
291 const connection = connectionOfOutput(output);
292 if (!connection) return;
293 const transport = yield* ifClusterExists(connectCluster(connection));
294 if (!transport) return;
295 // 404 (including a removed CRD's discovery 404) is already success.
296 // 403/5xx must surface: the object is still there.
297 yield* deleteObject({ transport, object: output.ref });
298 }),
299 };
300 }),
301 );