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

main
ts 245 lines 10 KB
Raw
1 import { unwrapRedacted } from "alchemy/Util/data";
2 import { collectRedactedSecrets, redactJson } from "alchemy/Util/Redaction";
3 /**
4 * Internal Helm rendering for `Kubernetes.HelmChart`.
5 *
6 * Renders a chart to plain Kubernetes objects with the local `helm` CLI
7 * (`helm template` — pure local templating, no cluster connection, no
8 * in-cluster release records), so the rendered objects flow through the same
9 * server-side-apply machinery as `Kubernetes.Manifest` and the workload platforms.
10 * Mirrors the `Docker` service's local-CLI dependency: the `helm` binary
11 * must be installed on the deploying machine (`HELM_BIN` overrides the
12 * binary path).
13 */
14 import * as Config from "effect/Config";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import * as FileSystem from "effect/FileSystem";
18 import * as Path from "effect/Path";
19 import * as ChildProcess from "effect/process/ChildProcess";
20 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21 import * as Stream from "effect/Stream";
22 import * as YAML from "yaml";
23 import type { KubernetesObjectDefinition } from "../Objects.ts";
24
25 /** A Helm invocation or render failure (bad chart ref, template error, …). */
26 export class HelmError extends Data.TaggedError("HelmError")<{
27 readonly message: string;
28 }> {}
29
30 const HelmBin = Config.String("HELM_BIN").pipe(Effect.orElseSucceed(() => "helm"));
31
32 export interface RenderHelmChartOptions {
33 /**
34 * Chart reference: a repository chart name (with `repo`), an
35 * `oci://` reference, or a local chart directory path.
36 */
37 chart: string;
38 /** Classic chart repository URL (`--repo`). */
39 repo?: string | undefined;
40 /** Chart version (`--version`). */
41 version?: string | undefined;
42 /** Release name the chart's templates render with (`.Release.Name`). */
43 releaseName: string;
44 /** Namespace the chart renders into (`.Release.Namespace`). */
45 namespace: string;
46 /** Values passed to the chart (written to a temp values file). */
47 values?: Record<string, unknown> | undefined;
48 /**
49 * Render objects from the chart's `crds/` directory too
50 * (`--include-crds`).
51 * @default true
52 */
53 includeCrds?: boolean | undefined;
54 }
55
56 /**
57 * Render a chart with `helm template --no-hooks` and parse the
58 * multi-document YAML output into object definitions. Every rendered object
59 * must carry `apiVersion`, `kind`, and `metadata.name` (server-side apply
60 * needs a name; `generateName`-only objects are rejected with a clear
61 * error). Helm lifecycle hooks are excluded from the result (see
62 * {@link isHelmHook}).
63 */
64 export const renderHelmChart = Effect.fn(function* (options: RenderHelmChartOptions) {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
68 const bin = yield* HelmBin;
69 const secrets = yield* Effect.sync(() =>
70 options.values === undefined ? [] : collectRedactedSecrets(options.values),
71 );
72
73 // The values file holds unwrapped credentials. Close this scope when the
74 // render finishes, including on helm or parse failure, so the file is removed.
75 return yield* Effect.scoped(
76 Effect.gen(function* () {
77 const args = [
78 "template",
79 options.releaseName,
80 options.chart,
81 "--namespace",
82 options.namespace,
83 // Helm lifecycle hooks (`helm.sh/hook`) only make sense under Helm's own
84 // release events; HelmChart server-side applies the render and does not
85 // implement hook timing/weights/delete policies, so a hook (e.g. a
86 // pre-delete uninstall Job) must never enter the managed-object graph.
87 "--no-hooks",
88 ];
89 if (options.repo !== undefined) {
90 args.push("--repo", options.repo);
91 }
92 if (options.version !== undefined) {
93 args.push("--version", options.version);
94 }
95 if (options.includeCrds ?? true) {
96 args.push("--include-crds");
97 }
98 if (options.values !== undefined && Object.keys(options.values).length > 0) {
99 // JSON is valid YAML, so the literal values object round-trips through
100 // a temp values file without a YAML serializer.
101 const dir = yield* fs.makeTempDirectoryScoped({
102 prefix: "alchemy-helm-",
103 });
104 const valuesFile = path.join(dir, "values.json");
105 // JSON.stringify(Redacted) emits the display placeholder. Unwrap at the
106 // values file; the chart props stay wrapped for plan and state.
107 const valuesJson = yield* Effect.sync(() => JSON.stringify(unwrapRedacted(options.values)));
108 yield* fs.writeFileString(valuesFile, valuesJson);
109 args.push("--values", valuesFile);
110 }
111
112 const result = yield* ChildProcess.make(bin, args, {
113 stdin: "ignore",
114 stdout: "pipe",
115 stderr: "pipe",
116 detached: false,
117 extendEnv: true,
118 }).pipe(
119 (command) => spawner.spawn(command),
120 Effect.flatMap((child) =>
121 Effect.all(
122 {
123 exitCode: child.exitCode,
124 stdout: child.stdout.pipe(Stream.decodeText, Stream.mkString),
125 stderr: child.stderr.pipe(Stream.decodeText, Stream.mkString),
126 },
127 { concurrency: "unbounded" },
128 ),
129 ),
130 // Scope the child to this render so it isn't tied to (and killed by)
131 // an enclosing scope that closes before helm exits.
132 Effect.scoped,
133 // A spawn failure (almost always ENOENT) means the helm CLI itself is
134 // missing — a machine-setup problem, not a resource error.
135 Effect.catchCause((cause) =>
136 Effect.die(
137 new Error(
138 `Failed to run '${bin}': ${String(cause)}. Kubernetes.HelmChart renders charts with the local helm CLI; if it isn't installed, install it (https://helm.sh/docs/intro/install/) or point HELM_BIN at the binary.`,
139 ),
140 ),
141 ),
142 );
143
144 if (result.exitCode !== 0) {
145 const detail =
146 `helm ${args.join(" ")} exited with code ${String(result.exitCode)}: ` +
147 result.stderr.trim();
148 return yield* Effect.failSync(
149 () => new HelmError({ message: redactJson(detail, secrets) }),
150 );
151 }
152
153 return yield* parseRenderedManifests(options.chart, result.stdout, secrets);
154 }),
155 );
156 });
157
158 /**
159 * Whether a rendered object is a Helm lifecycle hook (`helm.sh/hook`
160 * annotation). Hooks are executed by Helm at release events (pre-install,
161 * pre-delete, test, …); HelmChart has no release and no hook lifecycle, so
162 * they are filtered out rather than applied as ordinary objects.
163 */
164 export const isHelmHook = (object: KubernetesObjectDefinition): boolean =>
165 typeof object.metadata.annotations?.["helm.sh/hook"] === "string";
166
167 const causeText = (cause: unknown): string =>
168 cause instanceof Error ? cause.message : String(cause);
169
170 /**
171 * Parse `helm template` output (multi-document YAML) into definitions.
172 * Hook-annotated objects are dropped — `renderHelmChart` already passes
173 * `--no-hooks`, but the parser enforces the invariant independently of the
174 * helm CLI's behavior.
175 *
176 * `secrets` scrubs credentials out of parser and validation diagnostics.
177 * Parsed objects stay plain; callers pass the same list to the request
178 * scrubber.
179 */
180 export const parseRenderedManifests = (
181 chart: string,
182 rendered: string,
183 secrets: readonly string[] = [],
184 ): Effect.Effect<Array<KubernetesObjectDefinition>, HelmError> =>
185 Effect.try({
186 try: () => parseRenderedManifestsSync(chart, rendered, secrets),
187 catch: (cause) =>
188 cause instanceof HelmError
189 ? cause
190 : new HelmError({
191 message: redactJson(
192 `Failed to parse rendered manifests from chart '${chart}': ${causeText(cause)}`,
193 secrets,
194 ),
195 }),
196 });
197
198 const parseRenderedManifestsSync = (
199 chart: string,
200 rendered: string,
201 secrets: readonly string[],
202 ): Array<KubernetesObjectDefinition> => {
203 const fail = (message: string): never => {
204 throw new HelmError({ message: redactJson(message, secrets) });
205 };
206 // Helm 4 writes OCI pull metadata to stdout before the rendered YAML.
207 // Strip only that exact leading preamble; chart output remains subject to
208 // the same strict Kubernetes object validation below.
209 const manifests = chart.startsWith("oci://")
210 ? rendered.replace(/^Pulled: [^\r\n]+\r?\nDigest: [^\r\n]+\r?\n(?=---(?:\r?\n|$))/, "")
211 : rendered;
212 const documents = YAML.parseAllDocuments(manifests);
213 const objects: Array<KubernetesObjectDefinition> = [];
214 for (const document of documents) {
215 // parseAllDocuments records syntax errors on the document instead of
216 // throwing. toJS() can still throw (unresolved aliases, alias cycles).
217 if (document.errors.length > 0) {
218 const detail = document.errors.map((error) => error.message).join("\n");
219 fail(`Failed to parse rendered manifests from chart '${chart}': ${detail}`);
220 }
221 const value: unknown = document.toJS();
222 // helm renders empty documents for templates that produce no output
223 // (conditionals, whitespace) — skip them.
224 if (value === null || value === undefined) continue;
225 if (typeof value !== "object" || Array.isArray(value)) {
226 fail(`Chart '${chart}' rendered a non-object YAML document: ${JSON.stringify(value)}`);
227 }
228 const object = value as Partial<KubernetesObjectDefinition>;
229 if (typeof object.apiVersion !== "string" || typeof object.kind !== "string") {
230 // Scrub the full JSON before truncating so a secret that crosses the
231 // 200-character boundary is removed entirely.
232 const snippet = redactJson(JSON.stringify(value), secrets).slice(0, 200);
233 fail(`Chart '${chart}' rendered an object without apiVersion/kind: ${snippet}`);
234 }
235 if (typeof object.metadata?.name !== "string") {
236 fail(
237 `Chart '${chart}' rendered a ${object.apiVersion}/${object.kind} without metadata.name — server-side apply requires a concrete name (generateName is not supported)`,
238 );
239 }
240 const definition = object as KubernetesObjectDefinition;
241 if (isHelmHook(definition)) continue;
242 objects.push(definition);
243 }
244 return objects;
245 };