sailfork / t3code-github / .repos/ alchemy-effect/ packages/ kubernetes/ src/ internal/ helm.ts

import { unwrapRedacted } from "alchemy/Util/data";
import { collectRedactedSecrets, redactJson } from "alchemy/Util/Redaction";
/**
 * Internal Helm rendering for `Kubernetes.HelmChart`.
 *
 * Renders a chart to plain Kubernetes objects with the local `helm` CLI
 * (`helm template` — pure local templating, no cluster connection, no
 * in-cluster release records), so the rendered objects flow through the same
 * server-side-apply machinery as `Kubernetes.Manifest` and the workload platforms.
 * Mirrors the `Docker` service's local-CLI dependency: the `helm` binary
 * must be installed on the deploying machine (`HELM_BIN` overrides the
 * binary path).
 */
import * as Config from "effect/Config";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as Stream from "effect/Stream";
import * as YAML from "yaml";
import type { KubernetesObjectDefinition } from "../Objects.ts";

/** A Helm invocation or render failure (bad chart ref, template error, …). */
export class HelmError extends Data.TaggedError("HelmError")<{
  readonly message: string;
}> {}

const HelmBin = Config.String("HELM_BIN").pipe(Effect.orElseSucceed(() => "helm"));

export interface RenderHelmChartOptions {
  /**
   * Chart reference: a repository chart name (with `repo`), an
   * `oci://` reference, or a local chart directory path.
   */
  chart: string;
  /** Classic chart repository URL (`--repo`). */
  repo?: string | undefined;
  /** Chart version (`--version`). */
  version?: string | undefined;
  /** Release name the chart's templates render with (`.Release.Name`). */
  releaseName: string;
  /** Namespace the chart renders into (`.Release.Namespace`). */
  namespace: string;
  /** Values passed to the chart (written to a temp values file). */
  values?: Record<string, unknown> | undefined;
  /**
   * Render objects from the chart's `crds/` directory too
   * (`--include-crds`).
   * @default true
   */
  includeCrds?: boolean | undefined;
}

/**
 * Render a chart with `helm template --no-hooks` and parse the
 * multi-document YAML output into object definitions. Every rendered object
 * must carry `apiVersion`, `kind`, and `metadata.name` (server-side apply
 * needs a name; `generateName`-only objects are rejected with a clear
 * error). Helm lifecycle hooks are excluded from the result (see
 * {@link isHelmHook}).
 */
export const renderHelmChart = Effect.fn(function* (options: RenderHelmChartOptions) {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
  const bin = yield* HelmBin;
  const secrets = yield* Effect.sync(() =>
    options.values === undefined ? [] : collectRedactedSecrets(options.values),
  );

  // The values file holds unwrapped credentials. Close this scope when the
  // render finishes, including on helm or parse failure, so the file is removed.
  return yield* Effect.scoped(
    Effect.gen(function* () {
      const args = [
        "template",
        options.releaseName,
        options.chart,
        "--namespace",
        options.namespace,
        // Helm lifecycle hooks (`helm.sh/hook`) only make sense under Helm's own
        // release events; HelmChart server-side applies the render and does not
        // implement hook timing/weights/delete policies, so a hook (e.g. a
        // pre-delete uninstall Job) must never enter the managed-object graph.
        "--no-hooks",
      ];
      if (options.repo !== undefined) {
        args.push("--repo", options.repo);
      }
      if (options.version !== undefined) {
        args.push("--version", options.version);
      }
      if (options.includeCrds ?? true) {
        args.push("--include-crds");
      }
      if (options.values !== undefined && Object.keys(options.values).length > 0) {
        // JSON is valid YAML, so the literal values object round-trips through
        // a temp values file without a YAML serializer.
        const dir = yield* fs.makeTempDirectoryScoped({
          prefix: "alchemy-helm-",
        });
        const valuesFile = path.join(dir, "values.json");
        // JSON.stringify(Redacted) emits the display placeholder. Unwrap at the
        // values file; the chart props stay wrapped for plan and state.
        const valuesJson = yield* Effect.sync(() => JSON.stringify(unwrapRedacted(options.values)));
        yield* fs.writeFileString(valuesFile, valuesJson);
        args.push("--values", valuesFile);
      }

      const result = yield* ChildProcess.make(bin, args, {
        stdin: "ignore",
        stdout: "pipe",
        stderr: "pipe",
        detached: false,
        extendEnv: true,
      }).pipe(
        (command) => spawner.spawn(command),
        Effect.flatMap((child) =>
          Effect.all(
            {
              exitCode: child.exitCode,
              stdout: child.stdout.pipe(Stream.decodeText, Stream.mkString),
              stderr: child.stderr.pipe(Stream.decodeText, Stream.mkString),
            },
            { concurrency: "unbounded" },
          ),
        ),
        // Scope the child to this render so it isn't tied to (and killed by)
        // an enclosing scope that closes before helm exits.
        Effect.scoped,
        // A spawn failure (almost always ENOENT) means the helm CLI itself is
        // missing — a machine-setup problem, not a resource error.
        Effect.catchCause((cause) =>
          Effect.die(
            new Error(
              `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.`,
            ),
          ),
        ),
      );

      if (result.exitCode !== 0) {
        const detail =
          `helm ${args.join(" ")} exited with code ${String(result.exitCode)}: ` +
          result.stderr.trim();
        return yield* Effect.failSync(
          () => new HelmError({ message: redactJson(detail, secrets) }),
        );
      }

      return yield* parseRenderedManifests(options.chart, result.stdout, secrets);
    }),
  );
});

/**
 * Whether a rendered object is a Helm lifecycle hook (`helm.sh/hook`
 * annotation). Hooks are executed by Helm at release events (pre-install,
 * pre-delete, test, …); HelmChart has no release and no hook lifecycle, so
 * they are filtered out rather than applied as ordinary objects.
 */
export const isHelmHook = (object: KubernetesObjectDefinition): boolean =>
  typeof object.metadata.annotations?.["helm.sh/hook"] === "string";

const causeText = (cause: unknown): string =>
  cause instanceof Error ? cause.message : String(cause);

/**
 * Parse `helm template` output (multi-document YAML) into definitions.
 * Hook-annotated objects are dropped — `renderHelmChart` already passes
 * `--no-hooks`, but the parser enforces the invariant independently of the
 * helm CLI's behavior.
 *
 * `secrets` scrubs credentials out of parser and validation diagnostics.
 * Parsed objects stay plain; callers pass the same list to the request
 * scrubber.
 */
export const parseRenderedManifests = (
  chart: string,
  rendered: string,
  secrets: readonly string[] = [],
): Effect.Effect<Array<KubernetesObjectDefinition>, HelmError> =>
  Effect.try({
    try: () => parseRenderedManifestsSync(chart, rendered, secrets),
    catch: (cause) =>
      cause instanceof HelmError
        ? cause
        : new HelmError({
            message: redactJson(
              `Failed to parse rendered manifests from chart '${chart}': ${causeText(cause)}`,
              secrets,
            ),
          }),
  });

const parseRenderedManifestsSync = (
  chart: string,
  rendered: string,
  secrets: readonly string[],
): Array<KubernetesObjectDefinition> => {
  const fail = (message: string): never => {
    throw new HelmError({ message: redactJson(message, secrets) });
  };
  // Helm 4 writes OCI pull metadata to stdout before the rendered YAML.
  // Strip only that exact leading preamble; chart output remains subject to
  // the same strict Kubernetes object validation below.
  const manifests = chart.startsWith("oci://")
    ? rendered.replace(/^Pulled: [^\r\n]+\r?\nDigest: [^\r\n]+\r?\n(?=---(?:\r?\n|$))/, "")
    : rendered;
  const documents = YAML.parseAllDocuments(manifests);
  const objects: Array<KubernetesObjectDefinition> = [];
  for (const document of documents) {
    // parseAllDocuments records syntax errors on the document instead of
    // throwing. toJS() can still throw (unresolved aliases, alias cycles).
    if (document.errors.length > 0) {
      const detail = document.errors.map((error) => error.message).join("\n");
      fail(`Failed to parse rendered manifests from chart '${chart}': ${detail}`);
    }
    const value: unknown = document.toJS();
    // helm renders empty documents for templates that produce no output
    // (conditionals, whitespace) — skip them.
    if (value === null || value === undefined) continue;
    if (typeof value !== "object" || Array.isArray(value)) {
      fail(`Chart '${chart}' rendered a non-object YAML document: ${JSON.stringify(value)}`);
    }
    const object = value as Partial<KubernetesObjectDefinition>;
    if (typeof object.apiVersion !== "string" || typeof object.kind !== "string") {
      // Scrub the full JSON before truncating so a secret that crosses the
      // 200-character boundary is removed entirely.
      const snippet = redactJson(JSON.stringify(value), secrets).slice(0, 200);
      fail(`Chart '${chart}' rendered an object without apiVersion/kind: ${snippet}`);
    }
    if (typeof object.metadata?.name !== "string") {
      fail(
        `Chart '${chart}' rendered a ${object.apiVersion}/${object.kind} without metadata.name — server-side apply requires a concrete name (generateName is not supported)`,
      );
    }
    const definition = object as KubernetesObjectDefinition;
    if (isHelmHook(definition)) continue;
    objects.push(definition);
  }
  return objects;
};