@olivervea/pipelines 2.0.0-beta.2 → 2.0.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +125 -62
  2. package/manifest.schema.json +208 -11
  3. package/package.json +6 -4
  4. package/src/assets.d.ts +2 -2
  5. package/src/build/build.ts +121 -51
  6. package/src/build/cli.ts +29 -22
  7. package/src/build/elf.ts +8 -7
  8. package/src/build/hashes.ts +82 -20
  9. package/src/build/project.ts +95 -28
  10. package/src/builder/pipeline.ts +344 -88
  11. package/src/builder/refs.ts +15 -5
  12. package/src/core/brands.ts +7 -5
  13. package/src/core/config-refs.ts +103 -0
  14. package/src/core/config.ts +224 -0
  15. package/src/core/external.ts +86 -0
  16. package/src/core/handlers.ts +61 -15
  17. package/src/core/models.ts +32 -15
  18. package/src/core/origin.ts +23 -0
  19. package/src/core/secrets.ts +2 -2
  20. package/src/core/steps.ts +89 -38
  21. package/src/core/types.ts +5 -1
  22. package/src/core/webhooks.ts +21 -7
  23. package/src/ctx/files.ts +111 -40
  24. package/src/ctx/index.ts +84 -31
  25. package/src/ctx/sh.ts +105 -44
  26. package/src/ctx/types.ts +12 -4
  27. package/src/describe/describe.ts +701 -133
  28. package/src/describe/manifest-schema.ts +258 -61
  29. package/src/describe/mapper-source.ts +249 -104
  30. package/src/describe/record.ts +67 -37
  31. package/src/dev/cli.ts +72 -35
  32. package/src/harness/env.ts +45 -25
  33. package/src/harness/execute.ts +58 -29
  34. package/src/harness/index.ts +22 -9
  35. package/src/harness/main.ts +239 -78
  36. package/src/harness/result.ts +38 -22
  37. package/src/harness/validate.ts +77 -15
  38. package/src/index.ts +124 -11
  39. package/src/library/checks.ts +28 -0
  40. package/src/library/compose-deploy.ts +113 -0
  41. package/src/library/github-source.ts +100 -47
  42. package/src/library/helm-deploy-ssh.ts +452 -108
  43. package/src/library/helm-deploy.ts +449 -0
  44. package/src/library/http-health.ts +7 -5
  45. package/src/library/image-build.ts +499 -105
  46. package/src/library/index.ts +48 -12
  47. package/src/library/models.ts +33 -9
  48. package/src/library/ssh.ts +67 -0
  49. package/src/testing/index.ts +74 -36
  50. package/src/util/canonical.ts +7 -4
  51. package/src/util/handler-hash.ts +17 -7
  52. package/src/util/hash.ts +5 -5
  53. package/src/util/tar.ts +86 -36
  54. package/src/library/script.ts +0 -85
@@ -1,151 +1,495 @@
1
- // steps.helmDeployOverSsh — import a built image into a k3s host's containerd and helm-upgrade a
2
- // release there, over SSH; optionally verify an HTTP health endpoint afterwards.
1
+ // steps.helmDeployOverSsh — get built images onto a k3s host and helm-upgrade a release there, over
2
+ // SSH; optionally verify an HTTP health endpoint afterwards.
3
3
  //
4
4
  // Ported from v1's olve-lib.sh (olve_ssh_host, olve_image_import, olve_helm_deploy) and
5
5
  // deploy-beta.sh (rollout wait + health loop); the footguns are kept as comments below.
6
- import { chmodSync, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
7
- import { join } from "node:path";
8
- import type { Ctx } from "../ctx/types.ts";
9
- import type { FileRef } from "../core/models.ts";
10
- import type { Secret } from "../core/secrets.ts";
11
- import { makeStep, type LibraryStep, type LiteralName, type Step } from "../core/steps.ts";
12
- import { httpHealthCheck } from "./http-health.ts";
13
- import { BuiltImage, HelmRelease, Source } from "./models.ts";
6
+ import { existsSync, readFileSync, statSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import type { Ctx } from '../ctx/types.ts';
9
+ import type { FileRef } from '../core/models.ts';
10
+ import type { Secret } from '../core/secrets.ts';
11
+ import type { Configurable } from '../core/config.ts';
12
+ import { resolveConfigRefs } from '../core/config-refs.ts';
13
+ import { implement, type Implementation } from '../core/handlers.ts';
14
+ import { step, type LiteralName, type Step } from '../core/steps.ts';
15
+ import type { Simplify } from '../core/types.ts';
16
+ import { httpHealthCheck, type HttpHealthCheckOptions } from './http-health.ts';
17
+ import { BuiltImage, HelmRelease, PushedImage, Source } from './models.ts';
18
+ import { shq, sshSession } from './ssh.ts';
19
+ import {
20
+ helmDeployOverSshTarget,
21
+ type HelmDeploySshTargetDef,
22
+ type HelmTargetDeployInput,
23
+ } from './helm-deploy.ts';
14
24
 
15
25
  /** Alpine: `apk add openssh-client` at run time gives ssh/scp (the health check runs in the harness). */
16
- export const HELM_DEPLOY_IMAGE = "alpine:3.22";
26
+ export const HELM_DEPLOY_IMAGE = 'alpine:3.22';
17
27
 
18
28
  /**
19
29
  * Footgun: import via the k3s containerd socket, NOT the default one — kubelet only sees images in
20
30
  * the k3s instance's `k8s.io` namespace (otherwise pods fail with ErrImageNeverPull).
21
31
  */
22
- export const K3S_IMAGE_IMPORT = "sudo nerdctl --address /run/k3s/containerd/containerd.sock --namespace k8s.io load";
32
+ export const K3S_IMAGE_IMPORT =
33
+ 'sudo nerdctl --address /run/k3s/containerd/containerd.sock --namespace k8s.io load';
34
+ /** Registry images are pulled the same way before the rollout, so the rollout doesn't wait on the pull. */
35
+ export const K3S_IMAGE_PULL =
36
+ 'sudo nerdctl --address /run/k3s/containerd/containerd.sock --namespace k8s.io pull -q';
23
37
 
24
- const ROLLOUT_TIMEOUT = "120s";
38
+ export const DEFAULT_ROLLOUT_TIMEOUT_SECONDS = 120;
25
39
 
26
- const input = { source: Source, image: BuiltImage };
27
- export type HelmDeployOverSshInput = typeof input;
40
+ type DefaultImages = { readonly image: 'image' };
41
+ type ImageModel<R extends boolean> = R extends true
42
+ ? typeof PushedImage
43
+ : typeof BuiltImage;
44
+ export type HelmDeployOverSshInput<
45
+ Im extends Record<string, string> = DefaultImages,
46
+ R extends boolean = false,
47
+ Rf extends Record<string, string> = {},
48
+ > = Simplify<
49
+ { readonly source: typeof Source } & { readonly [K in keyof Im]: ImageModel<R> } & {
50
+ readonly [K in keyof Rf]: typeof PushedImage;
51
+ }
52
+ >;
28
53
 
29
- export interface HelmDeployOverSshDef<N extends string, K extends string> {
54
+ export interface HelmDeployOverSshDef<
55
+ N extends string,
56
+ K extends string,
57
+ Im extends Record<string, string> = DefaultImages,
58
+ R extends boolean = false,
59
+ Rf extends Record<string, string> = {},
60
+ > {
30
61
  name: LiteralName<N>;
31
62
  /** What the step does, shown in the UI. Required; may be empty. */
32
63
  description: string;
33
64
  /** SSH target, `user@host`. The user needs passwordless sudo for nerdctl, and helm/kubectl with a kubeconfig. */
34
- host: string;
65
+ host: Configurable<string>;
35
66
  /** Private key for `host`. */
36
67
  sshKey: Secret<K>;
37
- /** Helm release name; the chart's Deployment is expected to be named the same (rollout wait). */
38
- release: string;
39
- namespace: string;
68
+ /** Helm release name. */
69
+ release: Configurable<string>;
70
+ namespace: Configurable<string>;
40
71
  /** Chart directory inside the source tree, e.g. `helm`. */
41
72
  chart: string;
42
73
  /** Values files, relative to the chart directory (`-f`, in order). */
43
- values?: readonly string[];
74
+ values?: Configurable<readonly string[]>;
44
75
  /**
45
- * Chart-specific `--set` flags (e.g. `{ "slo.enabled": "false" }`). The image flags are added by
46
- * the step and always win: `image.repository`, `image.tag`, `image.pullPolicy=Never`.
76
+ * Chart-specific `--set` flags (e.g. `{ "ingress.enabled": "false" }`). The image flags are added by
77
+ * the step and always win: `<prefix>.repository`, `<prefix>.tag`, `<prefix>.pullPolicy`.
47
78
  */
48
- set?: Readonly<Record<string, string>>;
49
- /** After the rollout, GET this URL until it returns 2xx, 5 × 5 s (`httpHealthCheck`), or fail the step. */
50
- healthUrl?: string;
79
+ set?: Configurable<Readonly<Record<string, string>>>;
80
+ /**
81
+ * The images to deploy: step input key → the chart's values prefix for that image. Each input is a
82
+ * `BuiltImage` (or `PushedImage` with `fromRegistry`). Default `{ image: "image" }`; several images
83
+ * need a mapper, e.g. `{ server: "image", web: "web.image" }`. `{}` deploys the chart alone.
84
+ */
85
+ images?: Im & { readonly source?: never };
86
+ /**
87
+ * The images are `PushedImage`s from a registry (`imageBuild` with `push`): pulled on the host
88
+ * first, then `pullPolicy=IfNotPresent`. Default: `BuiltImage` tarballs, imported on the host, then
89
+ * `pullPolicy=Never`.
90
+ */
91
+ fromRegistry?: R &
92
+ (boolean extends R
93
+ ? '❌ fromRegistry must be a literal true or false (use `as const` on a shared config object)'
94
+ : unknown);
95
+ /**
96
+ * Registry images the chart only references (not run by the release's own pods, e.g. an image the
97
+ * app starts Jobs with): step input key → values prefix. Each input is a `PushedImage`; the step sets
98
+ * `<prefix>.repository`, `<prefix>.tag` and `<prefix>.digest` and does not pull it on the host. Works
99
+ * next to tarball `images`.
100
+ */
101
+ imageRefs?: Rf & { readonly source?: never };
102
+ /** Rollouts to wait for, in order: `deploy/<name>` for a bare name. Default: the release name, or none without images or with helm's wait. */
103
+ deployments?: readonly string[];
104
+ /** Per rollout (`kubectl rollout status --timeout`), or for helm's own wait. Default 120. */
105
+ rolloutTimeoutSeconds?: number;
106
+ /**
107
+ * Pull the dependencies `Chart.yaml` lists (`charts/` is usually not committed) into the chart on the
108
+ * host before installing: `helm pull <name> --repo <repository> --version <version>`, or the `oci://`
109
+ * reference. Default false.
110
+ */
111
+ dependencies?: boolean;
112
+ /** `helm upgrade --wait`: helm waits for all of the release's resources to be ready. Default false. */
113
+ helmWait?: boolean;
114
+ /** `helm upgrade --atomic`: wait like `helmWait`, and roll back when the upgrade fails. Default false. */
115
+ atomic?: boolean;
116
+ /** After the rollouts, GET this URL until it returns 2xx (`httpHealthCheck`: 5 × 5 s unless given), or fail the step. */
117
+ healthUrl?:
118
+ | Configurable<string>
119
+ | ({ url: Configurable<string> } & Pick<
120
+ HttpHealthCheckOptions,
121
+ 'attempts' | 'delaySeconds'
122
+ >);
51
123
  timeoutSeconds?: number;
52
124
  }
53
125
 
54
- const SAFE = /^[A-Za-z0-9_\/.:=@%+,-]+$/;
55
- /** POSIX shell quoting (safe words are left bare, so logs stay readable). */
56
- export function shq(s: string): string {
57
- return SAFE.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
126
+ export interface HelmImageFlags {
127
+ prefix: string;
128
+ repository: string;
129
+ tag: string;
130
+ pullPolicy: 'Never' | 'IfNotPresent';
131
+ /** Pins the image: `<prefix>.digest` (the chart renders `repository:tag@digest`). */
132
+ digest?: string;
58
133
  }
59
134
 
60
- /** Remote `helm upgrade --install`, run from inside the copied chart directory. */
61
- export function helmUpgradeCommand(o: {
62
- remoteChart: string;
63
- release: string;
64
- namespace: string;
65
- values: readonly string[];
66
- set: Readonly<Record<string, string>>;
135
+ /** A registry image the chart only references (`imageRefs`). */
136
+ export interface HelmImageRefFlags {
137
+ prefix: string;
67
138
  repository: string;
68
139
  tag: string;
69
- }): string {
140
+ digest: string;
141
+ }
142
+
143
+ export interface HelmFlagOptions {
144
+ values: readonly string[];
145
+ set: Readonly<Record<string, string>>;
146
+ images: readonly HelmImageFlags[];
147
+ imageRefs?: readonly HelmImageRefFlags[];
148
+ }
149
+
150
+ /** `helm upgrade` flags: values files, `--set`, then the image flags (which win). */
151
+ export function helmFlags(o: HelmFlagOptions): string[] {
70
152
  // Chart-relative values paths (`-f values-beta.yaml`) resolve because helm runs from inside the
71
- // copied chart dir. Extra flags come before the image flags, so the image overrides win. The image
72
- // is local to the node (imported above), never pulled: pullPolicy=Never.
153
+ // copied chart dir. Extra flags come before the image flags, so the image overrides win.
154
+ // --set-string: a tag like `2026.10` or `1e5` would otherwise be parsed as a number.
73
155
  const flags = [
74
- ...o.values.flatMap((v) => ["-f", v]),
75
- ...Object.entries(o.set).flatMap(([k, v]) => ["--set", `${k}=${v}`]),
76
- "--set", `image.repository=${o.repository}`,
77
- "--set", `image.tag=${o.tag}`,
78
- "--set", "image.pullPolicy=Never",
156
+ ...o.values.flatMap((v) => ['-f', v]),
157
+ ...Object.entries(o.set).flatMap(([k, v]) => ['--set', `${k}=${v}`]),
158
+ ...o.images.flatMap((i) => [
159
+ '--set',
160
+ `${i.prefix}.repository=${i.repository}`,
161
+ '--set',
162
+ `${i.prefix}.tag=${i.tag}`,
163
+ '--set',
164
+ `${i.prefix}.pullPolicy=${i.pullPolicy}`,
165
+ ...(i.digest ? ['--set-string', `${i.prefix}.digest=${i.digest}`] : []),
166
+ ]),
167
+ ...(o.imageRefs ?? []).flatMap((i) => [
168
+ '--set-string',
169
+ `${i.prefix}.repository=${i.repository}`,
170
+ '--set-string',
171
+ `${i.prefix}.tag=${i.tag}`,
172
+ '--set-string',
173
+ `${i.prefix}.digest=${i.digest}`,
174
+ ]),
79
175
  ];
176
+ return flags;
177
+ }
178
+
179
+ /** Remote `helm upgrade --install`, run from inside the copied chart directory. */
180
+ export function helmUpgradeCommand(
181
+ o: HelmFlagOptions & {
182
+ remoteChart: string;
183
+ release: string;
184
+ namespace: string;
185
+ wait?: HelmWait;
186
+ },
187
+ ): string {
188
+ const flags = helmFlags(o);
189
+ const wait = o.wait
190
+ ? [o.wait.atomic ? '--atomic' : '--wait', `--timeout=${o.wait.timeoutSeconds}s`]
191
+ : [];
80
192
  return [
81
193
  `cd ${shq(o.remoteChart)}`,
82
- ["helm", "upgrade", "--install", o.release, ".", "-n", o.namespace, ...flags].map(shq).join(" "),
194
+ ['helm', 'upgrade', '--install', o.release, '.', '-n', o.namespace, ...flags, ...wait]
195
+ .map(shq)
196
+ .join(' '),
83
197
  `cd / && rm -rf ${shq(o.remoteChart)}`,
84
- ].join(" && ");
198
+ ].join(' && ');
199
+ }
200
+
201
+ /** helm's own wait (`--wait`, or `--atomic` to roll back on failure). */
202
+ export interface HelmWait {
203
+ atomic: boolean;
204
+ timeoutSeconds: number;
205
+ }
206
+
207
+ /** A dependency from `Chart.yaml`. */
208
+ export interface ChartDependency {
209
+ name: string;
210
+ version: string;
211
+ repository: string;
212
+ }
213
+
214
+ /** The dependencies `<chartDir>/Chart.yaml` lists, checked to be pullable (an http(s) or oci repository). */
215
+ export function chartDependencies(chartDir: string): ChartDependency[] {
216
+ const chart = Bun.YAML.parse(readFileSync(join(chartDir, 'Chart.yaml'), 'utf8')) as {
217
+ dependencies?: Partial<ChartDependency>[];
218
+ } | null;
219
+ return (chart?.dependencies ?? []).map((d) => {
220
+ if (
221
+ !d.name ||
222
+ !d.version ||
223
+ !d.repository ||
224
+ !/^(https?|oci):\/\//.test(d.repository)
225
+ )
226
+ throw new Error(
227
+ `chart dependency ${JSON.stringify(d)}: needs a name, a version and an http(s) or oci repository`,
228
+ );
229
+ return { name: d.name, version: d.version, repository: d.repository };
230
+ });
231
+ }
232
+
233
+ /** The remote `helm pull` of a dependency into `<remoteChart>/charts`. */
234
+ export function helmPullCommand(dep: ChartDependency, remoteChart: string): string {
235
+ const ref = dep.repository.startsWith('oci://')
236
+ ? [`${dep.repository.replace(/\/+$/, '')}/${dep.name}`]
237
+ : [dep.name, '--repo', dep.repository];
238
+ return [
239
+ 'helm',
240
+ 'pull',
241
+ ...ref,
242
+ '--version',
243
+ dep.version,
244
+ '--destination',
245
+ `${remoteChart}/charts`,
246
+ ]
247
+ .map(shq)
248
+ .join(' ');
249
+ }
250
+
251
+ /** One image to get onto the host before the upgrade. */
252
+ export interface HostImage {
253
+ repository: string;
254
+ tag: string;
255
+ digest?: string;
256
+ /** An image tarball to stream in; without one the image is pulled from its registry. */
257
+ tar?: string;
85
258
  }
86
259
 
87
260
  /**
88
- * Deploys `image` with the Helm chart at `<source>/<chart>` on a k3s host over SSH:
89
- * stream the image tar into the host's k3s containerd, copy the chart, `helm upgrade --install`,
90
- * wait for `deploy/<release>` to roll out, then (with `healthUrl`) poll the health endpoint.
261
+ * Over SSH: get each image into the host's k3s containerd, copy the chart (with any generated values
262
+ * files in it), `helm upgrade --install`, then wait for each rollout.
91
263
  */
92
- export function helmDeployOverSsh<const N extends string, const K extends string>(
93
- def: HelmDeployOverSshDef<N, K>,
94
- ): Step<N, HelmDeployOverSshInput, typeof HelmRelease, K> & LibraryStep {
95
- const values = def.values ?? [];
96
- const set = def.set ?? {};
97
- return makeStep(
98
- "helmDeployOverSsh",
99
- { name: def.name, description: def.description, image: HELM_DEPLOY_IMAGE, input, output: HelmRelease, secrets: [def.sshKey], timeoutSeconds: def.timeoutSeconds },
100
- {
101
- manifestConfig: () => ({
102
- host: def.host,
103
- sshKey: def.sshKey.name,
104
- release: def.release,
105
- namespace: def.namespace,
106
- chart: def.chart,
107
- values: [...values],
108
- set: { ...set },
109
- ...(def.healthUrl ? { healthUrl: def.healthUrl } : {}),
110
- }),
111
- async run(
112
- { source, image }: { source: { tree: FileRef }; image: { repository: string; tag: string; tar: FileRef } },
113
- ctx: Ctx,
114
- ) {
115
- const tree = await ctx.files.fetch(source.tree);
116
- const chartDir = join(tree, def.chart);
117
- if (!existsSync(chartDir) || !statSync(chartDir).isDirectory()) throw new Error(`chart directory '${def.chart}' not found in the source tree`);
118
- const imageTar = await ctx.files.fetch(image.tar);
119
-
120
- // SSH setup. The key file needs a trailing newline (OpenSSH rejects the key otherwise) and
121
- // mode 600. The host key is not verified (as in v1): the host is reached over the tailnet.
122
- await ctx.exec(["apk", "add", "--no-cache", "openssh-client"]);
123
- const sshDir = join(ctx.tmpDir, "ssh");
124
- mkdirSync(sshDir, { recursive: true, mode: 0o700 });
125
- const keyFile = join(sshDir, "id");
126
- const key = ctx.secrets[def.sshKey.name]!;
127
- writeFileSync(keyFile, key.endsWith("\n") ? key : key + "\n", { mode: 0o600 });
128
- chmodSync(keyFile, 0o600);
129
- const opts = ["-i", keyFile, "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "LogLevel=ERROR", "-o", "BatchMode=yes"];
130
- const ssh = (remote: string) => ctx.exec(["ssh", ...opts, def.host, remote]);
131
-
132
- const ref = `${image.repository}:${image.tag}`;
133
- ctx.log("importing image", { image: ref, host: def.host });
134
- // Streamed over ssh's stdin (ctx.exec has none, hence the shell redirect).
135
- await ctx.sh(["ssh", ...opts, def.host, K3S_IMAGE_IMPORT].map(shq).join(" ") + ` < ${shq(imageTar)}`);
136
-
137
- const remoteChart = `/tmp/${def.release}-helm-${def.namespace}`;
138
- ctx.log("helm upgrade", { release: def.release, namespace: def.namespace, image: ref });
139
- await ssh(`rm -rf ${shq(remoteChart)}`);
140
- await ctx.exec(["scp", ...opts, "-r", chartDir, `${def.host}:${remoteChart}`]);
141
- await ssh(helmUpgradeCommand({ remoteChart, release: def.release, namespace: def.namespace, values, set, repository: image.repository, tag: image.tag }));
142
-
143
- ctx.log("waiting for rollout", { deployment: def.release });
144
- await ssh(`kubectl -n ${shq(def.namespace)} rollout status ${shq(`deploy/${def.release}`)} --timeout=${ROLLOUT_TIMEOUT}`);
145
-
146
- if (def.healthUrl) await httpHealthCheck(ctx, def.healthUrl);
147
- return { release: def.release, namespace: def.namespace, image: ref };
148
- },
264
+ export async function deployOverSsh(
265
+ ctx: Ctx,
266
+ o: {
267
+ host: string;
268
+ key: string;
269
+ chartDir: string;
270
+ release: string;
271
+ namespace: string;
272
+ hostImages: readonly HostImage[];
273
+ flags: HelmFlagOptions;
274
+ deployments: readonly string[];
275
+ rolloutTimeoutSeconds: number;
276
+ dependencies?: readonly ChartDependency[];
277
+ wait?: HelmWait;
278
+ },
279
+ ): Promise<void> {
280
+ const ssh = await sshSession(ctx, { host: o.host, key: o.key });
281
+ for (const image of o.hostImages) {
282
+ if (image.tar) {
283
+ ctx.log('importing image', {
284
+ image: `${image.repository}:${image.tag}`,
285
+ host: o.host,
286
+ });
287
+ // Streamed over ssh's stdin (ctx.exec has none, hence the shell redirect).
288
+ await ctx.sh(`${ssh.shell(K3S_IMAGE_IMPORT)} < ${shq(image.tar)}`);
289
+ } else {
290
+ const ref = image.digest
291
+ ? `${image.repository}@${image.digest}`
292
+ : `${image.repository}:${image.tag}`;
293
+ ctx.log('pulling image', { image: ref, host: o.host });
294
+ await ssh.run(`${K3S_IMAGE_PULL} ${shq(ref)}`);
295
+ }
296
+ }
297
+ const remoteChart = `/tmp/${o.release}-helm-${o.namespace}`;
298
+ ctx.log('helm upgrade', { release: o.release, namespace: o.namespace, host: o.host });
299
+ await ssh.run(`rm -rf ${shq(remoteChart)}`);
300
+ await ssh.copy(o.chartDir, remoteChart);
301
+ if (o.dependencies?.length) await ssh.run(`mkdir -p ${shq(`${remoteChart}/charts`)}`);
302
+ for (const dep of o.dependencies ?? []) {
303
+ ctx.log('pulling chart dependency', {
304
+ chart: `${dep.name}@${dep.version}`,
305
+ repository: dep.repository,
306
+ });
307
+ await ssh.run(helmPullCommand(dep, remoteChart));
308
+ }
309
+ await ssh.run(
310
+ helmUpgradeCommand({
311
+ ...o.flags,
312
+ remoteChart,
313
+ release: o.release,
314
+ namespace: o.namespace,
315
+ ...(o.wait ? { wait: o.wait } : {}),
316
+ }),
317
+ );
318
+ for (const d of o.deployments) {
319
+ const target = d.includes('/') ? d : `deploy/${d}`;
320
+ ctx.log('waiting for rollout', { deployment: target });
321
+ await ssh.run(
322
+ `kubectl -n ${shq(o.namespace)} rollout status ${shq(target)} --timeout=${o.rolloutTimeoutSeconds}s`,
323
+ );
324
+ }
325
+ }
326
+
327
+ /** The chart directory inside a fetched source tree, or an error naming it. */
328
+ export function chartDirectory(tree: string, chart: string): string {
329
+ const dir = join(tree, chart);
330
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
331
+ throw new Error(`chart directory '${chart}' not found in the source tree`);
332
+ return dir;
333
+ }
334
+
335
+ /**
336
+ * Deploys images with the Helm chart at `<source>/<chart>` on a k3s host over SSH: get each image
337
+ * into the host's k3s containerd (stream a tarball in, or pull from the registry), copy the chart,
338
+ * `helm upgrade --install`, wait for each rollout, then (with `healthUrl`) poll the health endpoint.
339
+ */
340
+ export function helmDeployOverSsh<
341
+ const N extends string,
342
+ const K extends string,
343
+ const Im extends Record<string, string> = DefaultImages,
344
+ const Rf extends Record<string, string> = {},
345
+ >(
346
+ def: HelmDeploySshTargetDef<N, K, Im, Rf>,
347
+ ): Implementation<Step<N, HelmTargetDeployInput<Im, Rf>, typeof HelmRelease, K>>;
348
+ export function helmDeployOverSsh<
349
+ const N extends string,
350
+ const K extends string,
351
+ const Im extends Record<string, string> = DefaultImages,
352
+ const R extends boolean = false,
353
+ const Rf extends Record<string, string> = {},
354
+ >(
355
+ def: HelmDeployOverSshDef<N, K, Im, R, Rf>,
356
+ ): Implementation<Step<N, HelmDeployOverSshInput<Im, R, Rf>, typeof HelmRelease, K>>;
357
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
358
+ export function helmDeployOverSsh(def: any): any {
359
+ return 'target' in def ? helmDeployOverSshTarget(def) : helmDeployOverSshLiteral(def);
360
+ }
361
+
362
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
363
+ function helmDeployOverSshLiteral(
364
+ def: HelmDeployOverSshDef<string, string, any, boolean, any>,
365
+ ): Implementation {
366
+ const images: Record<string, string> = def.images ?? { image: 'image' };
367
+ const imageEntries = Object.entries(images);
368
+ const fromRegistry = def.fromRegistry === true;
369
+ const rolloutTimeout = def.rolloutTimeoutSeconds ?? DEFAULT_ROLLOUT_TIMEOUT_SECONDS;
370
+ const wait: HelmWait | undefined =
371
+ def.atomic || def.helmWait
372
+ ? { atomic: def.atomic === true, timeoutSeconds: rolloutTimeout }
373
+ : undefined;
374
+ if ('source' in images)
375
+ throw new Error(`helmDeployOverSsh '${def.name}': 'source' can't be an image input`);
376
+ if (def.deployments?.length === 0)
377
+ throw new Error(`helmDeployOverSsh '${def.name}': deployments must not be empty`);
378
+ const imageRefs: Record<string, string> = def.imageRefs ?? {};
379
+ const refEntries = Object.entries(imageRefs);
380
+ if ('source' in imageRefs)
381
+ throw new Error(`helmDeployOverSsh '${def.name}': 'source' can't be an image input`);
382
+ for (const [key] of refEntries)
383
+ if (key in images)
384
+ throw new Error(
385
+ `helmDeployOverSsh '${def.name}': '${key}' is both in images and imageRefs`,
386
+ );
387
+ const imageModel = fromRegistry ? PushedImage : BuiltImage;
388
+ const input = {
389
+ source: Source,
390
+ ...Object.fromEntries(imageEntries.map(([key]) => [key, imageModel])),
391
+ ...Object.fromEntries(refEntries.map(([key]) => [key, PushedImage])),
392
+ };
393
+ const isDefaultImages = imageEntries.length === 1 && images.image === 'image';
394
+ const configurable = {
395
+ host: def.host,
396
+ release: def.release,
397
+ namespace: def.namespace,
398
+ values: def.values ?? [],
399
+ set: def.set ?? {},
400
+ healthUrl: def.healthUrl,
401
+ };
402
+
403
+ const contract = step({
404
+ name: def.name,
405
+ description: def.description,
406
+ kind: 'helmDeployOverSsh',
407
+ image: HELM_DEPLOY_IMAGE,
408
+ input,
409
+ output: HelmRelease,
410
+ secrets: [def.sshKey],
411
+ timeoutSeconds: def.timeoutSeconds,
412
+ settings: {
413
+ host: def.host,
414
+ sshKey: def.sshKey.name,
415
+ release: def.release,
416
+ namespace: def.namespace,
417
+ chart: def.chart,
418
+ values: configurable.values,
419
+ set: configurable.set,
420
+ ...(isDefaultImages ? {} : { images: { ...images } }),
421
+ ...(fromRegistry ? { fromRegistry: true } : {}),
422
+ ...(refEntries.length > 0 ? { imageRefs: { ...imageRefs } } : {}),
423
+ ...(def.deployments ? { deployments: [...def.deployments] } : {}),
424
+ ...(def.rolloutTimeoutSeconds !== undefined
425
+ ? { rolloutTimeoutSeconds: def.rolloutTimeoutSeconds }
426
+ : {}),
427
+ ...(def.dependencies ? { dependencies: true } : {}),
428
+ ...(def.atomic ? { atomic: true } : def.helmWait ? { helmWait: true } : {}),
429
+ ...(def.healthUrl !== undefined ? { healthUrl: def.healthUrl } : {}),
149
430
  },
150
- ) as never;
431
+ });
432
+ return implement(contract, async (stepInput, ctx: Ctx) => {
433
+ const input = stepInput as unknown as Record<
434
+ string,
435
+ { repository: string; tag: string; digest: string; tar?: FileRef }
436
+ > & { source: { tree: FileRef } };
437
+ const d = resolveConfigRefs(configurable, ctx.config ?? {}) as {
438
+ host: string;
439
+ release: string;
440
+ namespace: string;
441
+ values: string[];
442
+ set: Record<string, string>;
443
+ healthUrl?:
444
+ | string
445
+ | ({ url: string } & Pick<HttpHealthCheckOptions, 'attempts' | 'delaySeconds'>);
446
+ };
447
+ const chartDir = chartDirectory(await ctx.files.fetch(input.source.tree), def.chart);
448
+ const hostImages: HostImage[] = [];
449
+ const flags: HelmImageFlags[] = [];
450
+ for (const [key, prefix] of imageEntries) {
451
+ const image = input[key]!;
452
+ hostImages.push({
453
+ repository: image.repository,
454
+ tag: image.tag,
455
+ ...(fromRegistry ? {} : { tar: await ctx.files.fetch(image.tar!) }),
456
+ });
457
+ flags.push({
458
+ prefix,
459
+ repository: image.repository,
460
+ tag: image.tag,
461
+ pullPolicy: fromRegistry ? 'IfNotPresent' : 'Never',
462
+ });
463
+ }
464
+ const refs: HelmImageRefFlags[] = refEntries.map(([key, prefix]) => ({
465
+ prefix,
466
+ repository: input[key]!.repository,
467
+ tag: input[key]!.tag,
468
+ digest: input[key]!.digest,
469
+ }));
470
+ await deployOverSsh(ctx, {
471
+ host: d.host,
472
+ key: ctx.secrets[def.sshKey.name]!,
473
+ chartDir,
474
+ release: d.release,
475
+ namespace: d.namespace,
476
+ hostImages,
477
+ flags: { values: d.values, set: d.set, images: flags, imageRefs: refs },
478
+ deployments: def.deployments ?? (imageEntries.length && !wait ? [d.release] : []),
479
+ rolloutTimeoutSeconds: rolloutTimeout,
480
+ ...(def.dependencies ? { dependencies: chartDependencies(chartDir) } : {}),
481
+ ...(wait ? { wait } : {}),
482
+ });
483
+ const health = typeof d.healthUrl === 'string' ? { url: d.healthUrl } : d.healthUrl;
484
+ if (health)
485
+ await httpHealthCheck(ctx, health.url, {
486
+ attempts: health.attempts,
487
+ delaySeconds: health.delaySeconds,
488
+ });
489
+ return {
490
+ release: d.release,
491
+ namespace: d.namespace,
492
+ ...(flags[0] ? { image: `${flags[0].repository}:${flags[0].tag}` } : {}),
493
+ };
494
+ }) as never;
151
495
  }