@specific.dev/spectest 0.90.3 → 0.91.1

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 (46) hide show
  1. package/dist/android-step.js +2 -2
  2. package/dist/components/expo.d.ts +2 -0
  3. package/dist/components/index.d.ts +1 -1
  4. package/dist/components/k3s-trust.d.ts +57 -0
  5. package/dist/components/k3s-trust.js +125 -0
  6. package/dist/components/k3s.d.ts +17 -5
  7. package/dist/components/k3s.js +126 -53
  8. package/dist/daemon.js +71 -28
  9. package/dist/harness/component-images.d.ts +34 -0
  10. package/dist/harness/component-images.js +69 -0
  11. package/dist/harness/concurrency.d.ts +2 -0
  12. package/dist/harness/concurrency.js +9 -0
  13. package/dist/harness/k3s-image-loader.d.ts +3 -0
  14. package/dist/harness/k3s-image-loader.js +152 -0
  15. package/dist/harness/k3s-prepull.d.ts +8 -0
  16. package/dist/harness/k3s-prepull.js +35 -0
  17. package/dist/harness/sticky-consumer.d.ts +3 -3
  18. package/dist/harness/sticky-consumer.js +19 -4
  19. package/dist/harness/sticky-kubernetes.d.ts +15 -0
  20. package/dist/harness/sticky-kubernetes.js +163 -0
  21. package/dist/harness/sticky-paths.d.ts +5 -0
  22. package/dist/harness/sticky-paths.js +18 -0
  23. package/dist/index.d.ts +32 -2
  24. package/dist/index.js +25 -2
  25. package/package.json +1 -1
  26. package/src/android-step.test.ts +3 -3
  27. package/src/android-step.ts +2 -2
  28. package/src/android.test.ts +3 -3
  29. package/src/components/index.ts +1 -0
  30. package/src/components/k3s-concurrency.test.ts +60 -0
  31. package/src/components/k3s-trust.test.ts +81 -0
  32. package/src/components/k3s-trust.ts +135 -0
  33. package/src/components/k3s.ts +131 -51
  34. package/src/daemon.ts +72 -27
  35. package/src/harness/component-images.test.ts +44 -0
  36. package/src/harness/component-images.ts +79 -0
  37. package/src/harness/concurrency.ts +8 -0
  38. package/src/harness/k3s-image-loader.ts +131 -0
  39. package/src/harness/k3s-prepull.test.ts +57 -0
  40. package/src/harness/k3s-prepull.ts +33 -0
  41. package/src/harness/sticky-consumer.test.ts +28 -0
  42. package/src/harness/sticky-consumer.ts +14 -3
  43. package/src/harness/sticky-kubernetes.test.ts +88 -0
  44. package/src/harness/sticky-kubernetes.ts +165 -0
  45. package/src/harness/sticky-paths.ts +18 -0
  46. package/src/index.ts +48 -3
@@ -0,0 +1,44 @@
1
+ import { expect, test } from "bun:test";
2
+ import { canonicalImageReference, componentBuildTasks, kubernetesImages } from "./component-images";
3
+ import { validateServiceImage, type BuildImage } from "../index";
4
+
5
+ test("services and Kubernetes share all Dockerfile build options without a type discriminator", () => {
6
+ const image: BuildImage & { reference: string } = {
7
+ reference: "k8s.internal:5000/runtime:spectest", content: "FROM scratch AS test",
8
+ target: "test", context: ".", exclude: ["fixtures"], buildArgs: { MODE: "test" },
9
+ };
10
+ expect(validateServiceImage("app", { ...image, context: undefined })).toEqual({ ...image, context: undefined, type: "dockerfile" });
11
+ expect(validateServiceImage("redis", "redis:7.4")).toEqual({ type: "registry", reference: "redis:7.4" });
12
+ const parsed = kubernetesImages(["redis:7.4", image]);
13
+ expect(parsed.pulls).toEqual(["redis:7.4"]);
14
+ expect(parsed.builds).toEqual([{ reference: image.reference, image }]);
15
+ const tasks = componentBuildTasks([{ name: "cluster", image: "k3s:latest", imageBuilds: parsed.builds }]);
16
+ expect(tasks[0].image).toBe(image);
17
+ expect(tasks[0].owner).toBe("cluster");
18
+ expect(tasks[0].name).toMatch(/^spectest-image-[a-f0-9]+$/);
19
+ });
20
+
21
+ test("image identity validates references and rejects conflicting definitions", () => {
22
+ expect(canonicalImageReference("redis:7.4")).toBe("docker.io/library/redis:7.4");
23
+ expect(canonicalImageReference("docker.io/redis:7.4")).toBe("docker.io/library/redis:7.4");
24
+ expect(canonicalImageReference("company/api")).toBe("docker.io/company/api:latest");
25
+ expect(canonicalImageReference("localhost:5000/api")).toBe("localhost:5000/api:latest");
26
+ expect(kubernetesImages(["redis:7.4", "redis:7.4"]).pulls).toHaveLength(1);
27
+ for (const value of ["", "--help", "https://example.com/api", "has space", "bad:tag:extra"]) {
28
+ expect(() => kubernetesImages([value])).toThrow();
29
+ }
30
+ expect(() => kubernetesImages([{ content: "FROM scratch" } as never])).toThrow("reference");
31
+ expect(() => kubernetesImages([{ type: "registry", reference: "redis:7" } as never])).toThrow();
32
+ expect(() => kubernetesImages([{ reference: `api@sha256:${"a".repeat(64)}`, content: "FROM scratch" }])).toThrow("digest");
33
+ expect(() => kubernetesImages(["api:1", { reference: "docker.io/library/api:1", content: "FROM scratch" }])).toThrow("conflicting");
34
+ });
35
+
36
+ test("build task identity survives list reordering but is scoped to the owning cluster", () => {
37
+ const a = { reference: "app:1", image: { content: "FROM scratch" } };
38
+ const b = { reference: "app:2", image: { content: "FROM scratch" } };
39
+ const tasks = (name: string, imageBuilds: typeof a[]) => componentBuildTasks([{ name, image: "k3s:1", imageBuilds }]);
40
+ expect(tasks("cluster", [a, b])[0].name).toBe(tasks("cluster", [b, a])[1].name);
41
+ expect(tasks("cluster", [a])[0].name).not.toBe(tasks("other", [a])[0].name);
42
+ expect(() => validateServiceImage("app", { content: "FROM scratch", buildArgs: { "bad-key": "x" } })).toThrow("ARG");
43
+ expect(() => validateServiceImage("app", { content: "FROM scratch", exclude: [1] as never })).toThrow("exclude");
44
+ });
@@ -0,0 +1,79 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { BuildImage, ComponentImageBuild, ServiceConfig } from "../index.js";
3
+
4
+ export type KubernetesImage = string | (BuildImage & { reference: string });
5
+
6
+ /** containerd/CRI use fully qualified names, including the default tag. */
7
+ export function canonicalImageReference(reference: string): string {
8
+ if (typeof reference !== "string" || !reference || reference.startsWith("-") || /[\s\x00]/.test(reference)) {
9
+ throw new Error("image reference must be a non-empty image name without whitespace");
10
+ }
11
+ const slash = reference.indexOf("/");
12
+ const first = slash < 0 ? "" : reference.slice(0, slash);
13
+ let result = slash < 0 ? `docker.io/library/${reference}`
14
+ : first.includes(".") || first.includes(":") || first === "localhost" ? reference : `docker.io/${reference}`;
15
+ if (result.startsWith("index.docker.io/")) result = result.replace("index.docker.io/", "docker.io/");
16
+ if (result.startsWith("docker.io/") && !result.slice(10).includes("/")) result = `docker.io/library/${result.slice(10)}`;
17
+ const [name, digest] = result.split("@");
18
+ const tagAt = name.lastIndexOf(":") > name.lastIndexOf("/") ? name.lastIndexOf(":") : -1;
19
+ const repository = tagAt < 0 ? name : name.slice(0, tagAt);
20
+ if (!/^[a-z0-9.-]+(?::[0-9]+)?\/[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*)*$/.test(repository)
21
+ || (tagAt >= 0 && !/^[\w][\w.-]{0,127}$/.test(name.slice(tagAt + 1)))
22
+ || (result.includes("@") && (!digest || !/^sha256:[a-f0-9]{64}$/.test(digest) || result.split("@").length !== 2))) {
23
+ throw new Error(`invalid image reference: ${reference}`);
24
+ }
25
+ if (tagAt < 0 && !digest) result += ":latest";
26
+ return result;
27
+ }
28
+
29
+ export function kubernetesImages(images: readonly KubernetesImage[]): { pulls: string[]; builds: ComponentImageBuild[] } {
30
+ if (!Array.isArray(images)) throw new Error("k3s(): images must be an array of registry references or Dockerfile builds");
31
+ const pulls: string[] = [];
32
+ const builds: ComponentImageBuild[] = [];
33
+ const seen = new Map<string, string>();
34
+ for (const image of images) {
35
+ if (typeof image !== "string" && (!image || typeof image !== "object" || "type" in image || !image.reference)) {
36
+ throw new Error("k3s(): images expects registry strings or Dockerfile builds with a reference");
37
+ }
38
+ const reference = canonicalImageReference(typeof image === "string" ? image : image.reference);
39
+ if (typeof image !== "string" && reference.includes("@")) throw new Error("k3s(): a build reference must be an image name/tag, not a digest");
40
+ const identity = JSON.stringify(image);
41
+ const previous = seen.get(reference);
42
+ if (previous !== undefined) {
43
+ if (previous !== identity) throw new Error(`k3s(): conflicting images for ${reference}`);
44
+ continue;
45
+ }
46
+ seen.set(reference, identity);
47
+ if (typeof image === "string") pulls.push(image);
48
+ else builds.push({ reference, image });
49
+ }
50
+ return { pulls, builds };
51
+ }
52
+
53
+ /** Stable internal task names, separate from the service graph. */
54
+ export function componentBuildTasks<T extends ServiceConfig & { name: string }>(services: readonly T[]) {
55
+ return services.flatMap(svc => (svc.imageBuilds ?? []).map(build => ({
56
+ name: `spectest-image-${createHash("sha256").update(`${svc.name}\0${build.reference}`).digest("hex")}`,
57
+ owner: svc.name,
58
+ reference: build.reference,
59
+ image: build.image,
60
+ })));
61
+ }
62
+
63
+ /** Private handoff to a component's setup hook. Builds stay generic; the
64
+ * component decides how its runtime consumes them and establishes trust. */
65
+ export const COMPONENT_RUNTIME = Symbol.for("spectest.component-runtime");
66
+ export interface PreparedComponentImage {
67
+ source: string;
68
+ reference: string;
69
+ /** A component can load each result as soon as its own build finishes. */
70
+ ready?: Promise<void>;
71
+ }
72
+ export interface ComponentRuntime {
73
+ images: readonly PreparedComponentImage[];
74
+ gateway: string;
75
+ caBundle: string | null;
76
+ }
77
+ export function componentRuntime(context: object): ComponentRuntime | undefined {
78
+ return (context as { [COMPONENT_RUNTIME]?: ComponentRuntime })[COMPONENT_RUNTIME];
79
+ }
@@ -0,0 +1,8 @@
1
+ /** Wait for every writer to stop before reporting a failure to setup/cleanup. */
2
+ export async function waitForAll(work: readonly Promise<unknown>[]): Promise<void> {
3
+ const results = await Promise.allSettled(work);
4
+ const failures = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
5
+ if (failures.length === 1) throw failures[0];
6
+ if (failures.length > 1) throw new AggregateError(failures,
7
+ `Concurrent environment preparation failed: ${failures.map(error => error instanceof Error ? error.message : String(error)).join("; ")}`);
8
+ }
@@ -0,0 +1,131 @@
1
+ /** A short-lived, read-only OCI endpoint over the host containerd content store.
2
+ * k3s fetches only missing blobs and unpacks only missing snapshots. No Docker
3
+ * archive, staging registry, or second persistent copy of application blobs. */
4
+ import { execFile, spawn } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import { createServer } from "node:http";
7
+ import { promisify } from "node:util";
8
+ import type { SpectestContext } from "../index.js";
9
+ import { canonicalImageReference, type PreparedComponentImage } from "./component-images.js";
10
+ import { waitForK3sRuntime } from "./k3s-prepull.js";
11
+ import { waitForAll } from "./concurrency.js";
12
+
13
+ interface Descriptor { digest: string; size: number; mediaType: string; platform?: { os: string; architecture: string } }
14
+ interface Manifest { schemaVersion: number; mediaType: string; config: Descriptor; layers: Descriptor[]; annotations?: Record<string, string> }
15
+ const digest = (bytes: Uint8Array) => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
16
+ const descriptor = (bytes: Uint8Array, mediaType: string): Descriptor => ({ digest: digest(bytes), size: bytes.length, mediaType });
17
+ const run = promisify(execFile);
18
+ const HOST_CTR = ["--address", "/run/containerd/containerd.sock", "--namespace", "moby"];
19
+
20
+ async function hostContent(id: string): Promise<Buffer> {
21
+ if (!/^sha256:[a-f0-9]{64}$/.test(id)) throw new Error(`invalid content digest ${id}`);
22
+ const result = await run("ctr", [...HOST_CTR, "content", "get", id], { encoding: "buffer", maxBuffer: 16 * 1024 * 1024, timeout: 30_000 });
23
+ if (digest(result.stdout) !== id) throw new Error(`corrupt image metadata ${id}`);
24
+ return result.stdout;
25
+ }
26
+
27
+ /** Preserve the original index/manifest bytes and all application descriptors. */
28
+ async function hostImage(source: string) {
29
+ const name = canonicalImageReference(source);
30
+ const { stdout } = await run("ctr", [...HOST_CTR, "images", "ls", `name==${name}`], { timeout: 30_000 });
31
+ const found = stdout.split("\n").map(line => line.trim().split(/\s+/)).find(row => row[0] === name)?.[2];
32
+ if (!found) throw new Error(`built image ${name} is missing from the VM container store`);
33
+ const metadata = new Map<string, Buffer>();
34
+ const allowed = new Map<string, Descriptor>();
35
+ let configDigest: string | undefined;
36
+ async function visit(id: string, selected: boolean, depth = 0): Promise<Descriptor> {
37
+ if (depth > 4) throw new Error(`built image ${name} has a recursive manifest index`);
38
+ const bytes = await hostContent(id);
39
+ const obj = JSON.parse(bytes.toString());
40
+ const desc = descriptor(bytes, obj.mediaType);
41
+ metadata.set(id, bytes);
42
+ allowed.set(id, desc);
43
+ if (obj.config && Array.isArray(obj.layers)) {
44
+ const manifest = obj as Manifest;
45
+ for (const blob of [manifest.config, ...manifest.layers]) allowed.set(blob.digest, blob);
46
+ if (selected) configDigest = manifest.config.digest;
47
+ } else if (Array.isArray(obj.manifests)) {
48
+ for (const entry of obj.manifests as Descriptor[]) {
49
+ const matches = !entry.platform || (entry.platform.os === "linux" && entry.platform.architecture === (process.arch === "arm64" ? "arm64" : "amd64"));
50
+ await visit(entry.digest, selected && matches, depth + 1);
51
+ }
52
+ } else throw new Error(`built image ${name} has invalid image metadata`);
53
+ return desc;
54
+ }
55
+ const target = await visit(found, true);
56
+ if (!configDigest) throw new Error(`built image ${name} has no image for this VM's platform`);
57
+ return { target, metadata, allowed, configDigest };
58
+ }
59
+
60
+ export async function loadK3sBuildImages(
61
+ service: string, images: readonly PreparedComponentImage[],
62
+ gateway: string, exec: SpectestContext["exec"],
63
+ ): Promise<void> {
64
+ if (!images.length) return;
65
+ await waitForK3sRuntime(service, exec);
66
+ const checked = async (args: string[], timeoutMs = 30_000) => {
67
+ const result = await exec(service, args, { timeoutMs });
68
+ if (result.exitCode !== 0) throw new Error(`k3s(${service}): image load failed: ${result.stderr || result.stdout}`);
69
+ return result.stdout;
70
+ };
71
+ const config = await checked(["cat", "/var/lib/rancher/k3s/agent/etc/containerd/config.toml"]);
72
+ const snapshotter = config.match(/^\s*snapshotter\s*=\s*['"]([^'"]+)['"]/m)?.[1];
73
+ if (!snapshotter) throw new Error(`k3s(${service}): cannot determine kubelet's snapshotter`);
74
+ const ctr = ["ctr", "--address", "/run/k3s/containerd/containerd.sock", "--namespace", "k8s.io"];
75
+ const help = await checked([...ctr, "images", "pull", "--help"]);
76
+ const local = help.includes("--local") ? ["--local"] : [];
77
+ await waitForAll(images.map(async image => {
78
+ await image.ready;
79
+ const reference = canonicalImageReference(image.reference);
80
+ const { target, metadata: blobs, allowed, configDigest } = await hostImage(image.source);
81
+ const streams = new Set<ReturnType<typeof spawn>>();
82
+ let transferred = 0;
83
+ const server = createServer((req, res) => {
84
+ const pathname = new URL(req.url ?? "/", "http://local").pathname;
85
+ const match = pathname.match(/^\/v2\/.+\/(manifests|blobs)\/([^/]+)$/);
86
+ if (!["GET", "HEAD"].includes(req.method ?? "") || !match) { res.writeHead(404).end(); return; }
87
+ const id = match[1] === "manifests" && !match[2].startsWith("sha256:") ? target.digest : match[2];
88
+ const desc = allowed.get(id);
89
+ if (!desc) { res.writeHead(404).end(); return; }
90
+ res.writeHead(200, { "Content-Type": desc.mediaType, "Content-Length": desc.size, "Docker-Content-Digest": id });
91
+ if (req.method === "HEAD") { res.end(); return; }
92
+ transferred += desc.size;
93
+ const bytes = blobs.get(id);
94
+ if (bytes) { res.end(bytes); return; }
95
+ const proc = spawn("ctr", [...HOST_CTR, "content", "get", id], { stdio: ["ignore", "pipe", "ignore"] });
96
+ streams.add(proc);
97
+ proc.stdout!.pipe(res);
98
+ proc.on("error", err => res.destroy(err));
99
+ proc.on("exit", code => { streams.delete(proc); if (code !== 0) res.destroy(new Error(`content read failed: ${id}`)); });
100
+ res.on("close", () => { if (proc.exitCode === null) proc.kill(); });
101
+ });
102
+ const directory = `/run/spectest-image-load-${createHash("sha256").update(reference).digest("hex").slice(0, 16)}`;
103
+ try {
104
+ await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(0, gateway, resolve); });
105
+ const port = (server.address() as { port: number }).port;
106
+ // A private hosts directory scopes this override to this single ctr call;
107
+ // it cannot change the cluster's configured registries or pull policy.
108
+ const hosts = `server = "http://${gateway}:${port}"\n`;
109
+ await checked(["sh", "-c", 'mkdir -p "$1/_default"; printf "%s" "$2" > "$1/_default/hosts.toml"', "sh", directory, hosts]);
110
+ await checked([...ctr, "images", "pull", ...local, "--hosts-dir", directory,
111
+ "--snapshotter", snapshotter, "--label", "io.cri-containerd.image=managed", reference], 600_000);
112
+ const repo = reference.slice(0, reference.lastIndexOf(":"));
113
+ await checked([...ctr, "images", "tag", "--force", reference, `${repo}@${target.digest}`]);
114
+ // CRI learns about ctr image updates asynchronously. Confirm the current
115
+ // build's config, not merely that an older tag already exists.
116
+ const deadline = Date.now() + 30_000;
117
+ for (;;) {
118
+ const result = await exec(service, ["crictl", "--runtime-endpoint", "unix:///run/k3s/containerd/containerd.sock", "inspecti", reference], { timeoutMs: 5_000 });
119
+ if (result.exitCode === 0 && JSON.parse(result.stdout).status?.id === configDigest) break;
120
+ if (Date.now() >= deadline) throw new Error(`k3s(${service}): current build is not visible to kubelet: ${reference}`);
121
+ await new Promise(resolve => setTimeout(resolve, 100));
122
+ }
123
+ console.log(`[k3s-images] ${service}: ${reference} @ ${target.digest}, transferred ${transferred} bytes`);
124
+ } finally {
125
+ for (const proc of streams) proc.kill();
126
+ server.closeAllConnections();
127
+ await new Promise<void>(resolve => server.close(() => resolve()));
128
+ await exec(service, ["rm", "-rf", directory], { timeoutMs: 5_000 }).catch(() => undefined);
129
+ }
130
+ }));
131
+ }
@@ -0,0 +1,57 @@
1
+ import { expect, test } from "bun:test";
2
+ import type { SpectestContext } from "../index.js";
3
+ import { prePullK3sImages } from "./k3s-prepull";
4
+
5
+ const cri = ["crictl", "--runtime-endpoint", "unix:///run/k3s/containerd/containerd.sock"];
6
+ const digest = `registry.test/app@sha256:${"a".repeat(64)}`;
7
+ const mockExec = (fn: (args: string[]) => Promise<{ exitCode: number; stdout?: string; stderr?: string }>) =>
8
+ (async (_name: string, args: string[]) => ({ stdout: "", stderr: "", ...await fn(args) })) as SpectestContext["exec"];
9
+
10
+ test("pre-pulls reuse immutable cached images, but resolve tags on every fresh setup", async () => {
11
+ const calls: string[][] = [];
12
+ await prePullK3sImages("cluster", [digest, "registry.test/app:latest"], mockExec(async args => {
13
+ calls.push(args); return { exitCode: 0 };
14
+ }));
15
+ expect(calls).toEqual([[...cri, "info"], [...cri, "inspecti", digest], [...cri, "pull", "registry.test/app:latest"]]);
16
+ calls.length = 0;
17
+ await prePullK3sImages("cluster", [digest], mockExec(async args => {
18
+ calls.push(args); return { exitCode: args[3] === "inspecti" ? 1 : 0 };
19
+ }));
20
+ expect(calls.at(-1)).toEqual([...cri, "pull", digest]);
21
+ });
22
+
23
+ test("failed pre-pulls fail setup after all concurrent pulls finish", async () => {
24
+ let active = 0, peak = 0, finished = 0;
25
+ const work = prePullK3sImages("cluster", ["a:1", "b:1", "c:1"], mockExec(async args => {
26
+ if (args.at(-1) === "info") return { exitCode: 0 };
27
+ peak = Math.max(peak, ++active);
28
+ await Bun.sleep(args.at(-1) === "a:1" ? 1 : 20);
29
+ --active; ++finished;
30
+ return { exitCode: args.at(-1) === "a:1" ? 1 : 0, stderr: "registry unavailable" };
31
+ }));
32
+ await expect(work).rejects.toThrow("pre-pull failed for a:1: registry unavailable");
33
+ expect(active).toBe(0);
34
+ expect(peak).toBe(3);
35
+ expect(finished).toBe(3);
36
+ });
37
+
38
+ test("pre-pulls wait for the runtime even when the API server is already ready", async () => {
39
+ const calls: string[] = [];
40
+ let ready = false;
41
+ await prePullK3sImages("cluster", ["app:1"], mockExec(async args => {
42
+ calls.push(args[3]!);
43
+ if (args[3] === "info" && !ready) { ready = true; return { exitCode: 1, stderr: "connection refused" }; }
44
+ return { exitCode: 0 };
45
+ }));
46
+ expect(calls).toEqual(["info", "info", "pull"]);
47
+ });
48
+
49
+ test("simultaneous pull failures retain every failing image in the setup error", async () => {
50
+ const error = await prePullK3sImages("cluster", ["a:1", "b:1"], mockExec(async args => ({
51
+ exitCode: args[3] === "pull" ? 1 : 0, stderr: "unavailable",
52
+ }))).catch(error => error);
53
+ expect(error).toBeInstanceOf(AggregateError);
54
+ expect(error.errors).toHaveLength(2);
55
+ expect(error.message).toContain("pre-pull failed for a:1");
56
+ expect(error.message).toContain("pre-pull failed for b:1");
57
+ });
@@ -0,0 +1,33 @@
1
+ import type { SpectestContext } from "../index.js";
2
+ import { waitForAll } from "./concurrency.js";
3
+
4
+ /** CRI PullImage waits for unpacking and uses k3s's registry configuration.
5
+ * Always resolve tags on a fresh setup. Immutable digests can be used offline.
6
+ * Submit every image concurrently; containerd manages downloads and unpacking.
7
+ * Drain all pulls on failure so none outlive the setup hook.
8
+ */
9
+ export async function prePullK3sImages(name: string, images: readonly string[], exec: SpectestContext["exec"]): Promise<void> {
10
+ if (!images.length) return;
11
+ await waitForK3sRuntime(name, exec);
12
+ const cri = ["crictl", "--runtime-endpoint", "unix:///run/k3s/containerd/containerd.sock"];
13
+ await waitForAll(images.map(async image => {
14
+ if (/@sha256:[a-f0-9]{64}$/.test(image)) {
15
+ const existing = await exec(name, [...cri, "inspecti", image], { timeoutMs: 30_000 });
16
+ if (existing.exitCode === 0) return;
17
+ }
18
+ const result = await exec(name, [...cri, "pull", image], { timeoutMs: 600_000 });
19
+ if (result.exitCode !== 0) throw new Error(`k3s(${name}): pre-pull failed for ${image}: ${result.stderr || result.stdout}`);
20
+ }));
21
+ }
22
+
23
+ export async function waitForK3sRuntime(name: string, exec: SpectestContext["exec"]): Promise<void> {
24
+ const cri = ["crictl", "--runtime-endpoint", "unix:///run/k3s/containerd/containerd.sock"];
25
+ // /readyz belongs to the API server and can precede the node runtime.
26
+ const deadline = Date.now() + 60_000;
27
+ for (;;) {
28
+ const result = await exec(name, [...cri, "info"], { timeoutMs: 5_000 });
29
+ if (result.exitCode === 0) break;
30
+ if (Date.now() >= deadline) throw new Error(`k3s(${name}): containerd did not become ready for pre-pulls: ${result.stderr || result.stdout}`);
31
+ await new Promise(resolve => setTimeout(resolve, 250));
32
+ }
33
+ }
@@ -43,3 +43,31 @@ test("healthy cache keeps recent images and a cache that cannot shrink is not pu
43
43
  await expect(collectStickyCache(config, run, async () => ({ totalBytes: 256 * GiB, freeBytes: 5 * GiB })))
44
44
  .rejects.toThrow("cannot meet filesystem retention target");
45
45
  });
46
+
47
+ test("nested Kubernetes stores share the filesystem budget and are pruned before recent Docker images", async () => {
48
+ let used = 100 * GiB;
49
+ const calls: string[][] = [];
50
+ let evictions = 0;
51
+ const run = async (command: string, args: string[]) => { calls.push([command, ...args]); return ""; };
52
+ await collectStickyCache(config, run, async () => ({ totalBytes: 256 * GiB, freeBytes: 256 * GiB - used }), {
53
+ protectedImages: new Set(), close: async () => {},
54
+ pruneOldest: async () => { used -= 40 * GiB; evictions++; return true; },
55
+ });
56
+ expect(evictions).toBe(1);
57
+ expect(calls.some(c => c[0] === "docker" && c[1] === "image" && c[2] === "ls")).toBe(false);
58
+ });
59
+
60
+ test("GC does not remove an image while it supplies the Kubernetes maintenance daemon", async () => {
61
+ const removed: string[] = [];
62
+ const run = async (command: string, args: string[]) => {
63
+ if (command === "docker" && args[1] === "ls") return "runtime\nold";
64
+ if (command === "docker" && args[1] === "inspect") return JSON.stringify([
65
+ { Id: "runtime", Created: "2020" }, { Id: "old", Created: "2021" }]);
66
+ if (command === "docker" && args[1] === "rm") removed.push(args.at(-1)!);
67
+ return "";
68
+ };
69
+ await collectStickyCache(config, run, async () => ({ totalBytes: 256 * GiB, freeBytes: (removed.length ? 220 : 150) * GiB }), {
70
+ protectedImages: new Set(["runtime"]), close: async () => {}, pruneOldest: async () => false,
71
+ });
72
+ expect(removed).toEqual(["old"]);
73
+ });
@@ -1,10 +1,13 @@
1
- /** Docker/BuildKit policy for the generic sticky disk. No host publication API. */
1
+ /** Docker, BuildKit and nested Kubernetes policy for the generic sticky disk. */
2
2
  import { execFile } from "node:child_process";
3
3
  import { mkdir, readFile, statfs, writeFile } from "node:fs/promises";
4
4
 
5
+ import { STICKY_RUNTIME } from "./sticky-paths.js";
6
+ import { openKubernetesCacheMaintenance, type KubernetesCacheMaintenance } from "./sticky-kubernetes.js";
7
+
5
8
  export const STICKY_CAPABILITY = "sticky-disks-v1";
6
9
  export const STICKY_COMPATIBILITY = "docker29-ctr21-buildkit032-overlayfs-256g-v2";
7
- export const STICKY_RUNTIME = "/run/spectest-sticky";
10
+ export { STICKY_RUNTIME } from "./sticky-paths.js";
8
11
  export interface StickyConsumerConfig {
9
12
  path: string;
10
13
  capacityBytes: number;
@@ -115,6 +118,7 @@ export async function collectStickyCache(
115
118
  const fs = await statfs(config.path);
116
119
  return { freeBytes: fs.bavail * fs.bsize, totalBytes: fs.blocks * fs.bsize };
117
120
  },
121
+ kubernetes?: KubernetesCacheMaintenance,
118
122
  ): Promise<void> {
119
123
  validateStickyConfig(config);
120
124
  const buildctl = ["--addr", "tcp://127.0.0.1:1234", "prune"];
@@ -133,6 +137,10 @@ export async function collectStickyCache(
133
137
  };
134
138
  await pruneBuildkit();
135
139
  if (withinTarget(fs)) return;
140
+ while (await kubernetes?.pruneOldest()) {
141
+ fs = await usage();
142
+ if (withinTarget(fs)) return;
143
+ }
136
144
  // Pressure can be entirely in recent Docker images. Drop oldest images
137
145
  // first, even within the age window, until the whole filesystem fits.
138
146
  const ids = [...new Set((await run("docker", ["image", "ls", "-aq", "--no-trunc"])).split(/\s+/).filter(Boolean))];
@@ -140,6 +148,7 @@ export async function collectStickyCache(
140
148
  ? JSON.parse(await run("docker", ["image", "inspect", ...ids])) : [];
141
149
  images.sort((a, b) => a.Created.localeCompare(b.Created) || a.Id.localeCompare(b.Id));
142
150
  for (const image of images) {
151
+ if (kubernetes?.protectedImages.has(image.Id)) continue;
143
152
  await run("docker", ["image", "rm", "-f", image.Id], 120_000);
144
153
  await pruneBuildkit();
145
154
  if (withinTarget(fs)) return;
@@ -158,7 +167,9 @@ export async function prepareStickyConsumer(artifact = false): Promise<{ prepare
158
167
  if (containers.length) await exec("docker", ["rm", "-f", ...containers]);
159
168
  const volumes = (await exec("docker", ["volume", "ls", "-q"])).split(/\s+/).filter(Boolean);
160
169
  if (volumes.length) await exec("docker", ["volume", "rm", ...volumes]);
161
- await collectStickyCache(config);
170
+ const kubernetes = await openKubernetesCacheMaintenance(exec);
171
+ try { await collectStickyCache(config, exec, undefined, kubernetes); }
172
+ finally { await kubernetes.close(); }
162
173
  }
163
174
  const units = ["spectest-sticky-buildkit", "spectest-sticky-docker", "spectest-sticky-containerd"];
164
175
  for (const unit of units) {
@@ -0,0 +1,88 @@
1
+ import { afterEach, expect, test } from "bun:test";
2
+ import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { openKubernetesCacheMaintenance, stickyKubernetesDirectory, type CacheCommand } from "./sticky-kubernetes";
6
+ import { isOnStickyDisk, stickyDiskPathSync, STICKY_ROOT } from "./sticky-paths";
7
+
8
+ const roots: string[] = [];
9
+ afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
10
+ async function temporary() { const root = await mkdtemp(join(tmpdir(), "sticky-k8s-test-")); roots.push(root); return root; }
11
+ const image = `sha256:${"a".repeat(64)}`;
12
+ async function store(root: string, service: string, age = 0) {
13
+ const dir = `${root}/${service}/0123456789abcdef`;
14
+ await mkdir(dir, { recursive: true });
15
+ await writeFile(`${dir}/store.json`, JSON.stringify({ schema: 1, image, updatedAt: Date.now() - age }));
16
+ return dir;
17
+ }
18
+ function runner(calls: string[][]): CacheCommand {
19
+ return async (program, args) => {
20
+ calls.push([program, ...args]);
21
+ if (program === "docker" && args[0] === "inspect") return JSON.stringify({ ExitCode: 0, OOMKilled: false });
22
+ return "";
23
+ };
24
+ }
25
+
26
+ test("sticky volume preservation requires an active manifest and a path inside the mount", async () => {
27
+ const manifest = `${await temporary()}/consumer.json`;
28
+ expect(stickyDiskPathSync(manifest)).toBeNull();
29
+ await writeFile(manifest, JSON.stringify({ path: STICKY_ROOT }));
30
+ expect(stickyDiskPathSync(manifest)).toBe(STICKY_ROOT);
31
+ expect(isOnStickyDisk(`${STICKY_ROOT}/kubernetes/cluster`, STICKY_ROOT)).toBe(true);
32
+ for (const path of [`${STICKY_ROOT}-other/store`, `${STICKY_ROOT}/../other`, "/workspace/data"]) {
33
+ expect(isOnStickyDisk(path, STICKY_ROOT)).toBe(false);
34
+ }
35
+ expect(isOnStickyDisk(`${STICKY_ROOT}/kubernetes/cluster`, null)).toBe(false);
36
+ await writeFile(manifest, JSON.stringify({ path: "/" }));
37
+ expect(stickyDiskPathSync(manifest)).toBeNull();
38
+ });
39
+
40
+ test("Kubernetes stores are isolated by service and k3s version", () => {
41
+ const original = stickyKubernetesDirectory("cluster", "v1.33.5-k3s1");
42
+ expect(stickyKubernetesDirectory("cluster", "v1.32.1-k3s1")).not.toBe(original);
43
+ expect(stickyKubernetesDirectory("second", "v1.33.5-k3s1")).not.toBe(original);
44
+ });
45
+
46
+ test("maintenance prunes oldest stores and releases runtime-image protection only after the last writer stops", async () => {
47
+ const root = await temporary();
48
+ const old = await store(root, "old", 1000);
49
+ const recent = await store(root, "recent");
50
+ const calls: string[][] = [];
51
+ const cache = await openKubernetesCacheMaintenance(runner(calls), root);
52
+ expect(cache.protectedImages.has(image)).toBe(true);
53
+ expect(await cache.pruneOldest()).toBe(true);
54
+ expect(calls).toContainEqual(["rm", "-rf", old]);
55
+ expect(cache.protectedImages.has(image)).toBe(true);
56
+ expect(await cache.pruneOldest()).toBe(true);
57
+ expect(calls).toContainEqual(["rm", "-rf", recent]);
58
+ expect(cache.protectedImages.size).toBe(0);
59
+ expect(await cache.pruneOldest()).toBe(false);
60
+ await cache.close();
61
+ expect(calls.filter(c => c[0] === "docker" && c[1] === "stop")).toHaveLength(2);
62
+ });
63
+
64
+ test("failed maintenance startup closes every started store and refuses publication", async () => {
65
+ const root = await temporary();
66
+ await store(root, "first"); await store(root, "second");
67
+ const calls: string[][] = [];
68
+ const run = runner(calls);
69
+ let checks = 0;
70
+ await expect(openKubernetesCacheMaintenance(async (program, args, timeout) => {
71
+ const result = await run(program, args, timeout);
72
+ if (args[0] === "exec" && ++checks === 2) throw new Error("containerd cannot open store");
73
+ return result;
74
+ }, root)).rejects.toThrow("Kubernetes cache preparation failed");
75
+ expect(calls.filter(c => c[0] === "docker" && c[1] === "stop")).toHaveLength(2);
76
+ });
77
+
78
+ test("unclean nested containerd shutdown rejects sealing instead of publishing its store", async () => {
79
+ const root = await temporary(); await store(root, "cluster");
80
+ const calls: string[][] = [];
81
+ const run = runner(calls);
82
+ const cache = await openKubernetesCacheMaintenance(async (program, args, timeout) => {
83
+ const result = await run(program, args, timeout);
84
+ return args[0] === "inspect" ? JSON.stringify({ ExitCode: 137, OOMKilled: false }) : result;
85
+ }, root);
86
+ await expect(cache.close()).rejects.toThrow("Kubernetes cache shutdown failed");
87
+ expect(calls.some(c => c[0] === "rm")).toBe(false);
88
+ });