@leitwerk-dev/worker-runners 0.3.1 → 0.4.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 (60) hide show
  1. package/dist/{chunk-YDYI3BD2.js → chunk-FEIZN5GL.js} +53 -9
  2. package/dist/chunk-FEIZN5GL.js.map +1 -0
  3. package/dist/{chunk-ZGFD76I6.js → chunk-GF3H4C3J.js} +1 -1
  4. package/dist/chunk-GF3H4C3J.js.map +1 -0
  5. package/dist/{chunk-V7TTFLGE.js → chunk-GMZOYHQD.js} +414 -82
  6. package/dist/chunk-GMZOYHQD.js.map +1 -0
  7. package/dist/{chunk-ISH4647R.js → chunk-LZOVBKHR.js} +89 -89
  8. package/dist/chunk-LZOVBKHR.js.map +1 -0
  9. package/dist/index.js +15 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/{kubernetes-api-client-CEe7pHC4.d.ts → kubernetes-api-client-BMWAgyfW.d.ts} +192 -103
  12. package/dist/kubernetes-api-client.d.ts +3 -0
  13. package/dist/kubernetes-api-client.d.ts.map +1 -1
  14. package/dist/kubernetes-client-public.js +2 -2
  15. package/dist/kubernetes-http-client.d.ts.map +1 -1
  16. package/dist/kubernetes-http-client.js +2 -2
  17. package/dist/kubernetes-image-preload-api.d.ts +69 -0
  18. package/dist/kubernetes-image-preload-api.d.ts.map +1 -0
  19. package/dist/kubernetes-image-preload.d.ts +48 -0
  20. package/dist/kubernetes-image-preload.d.ts.map +1 -0
  21. package/dist/kubernetes-manifests.d.ts +10 -1
  22. package/dist/kubernetes-manifests.d.ts.map +1 -1
  23. package/dist/kubernetes-preparation-api.d.ts +26 -0
  24. package/dist/kubernetes-preparation-api.d.ts.map +1 -0
  25. package/dist/kubernetes-preparation.d.ts +21 -0
  26. package/dist/kubernetes-preparation.d.ts.map +1 -0
  27. package/dist/kubernetes-public.js +3 -3
  28. package/dist/kubernetes-volume-pool-api.d.ts +17 -14
  29. package/dist/kubernetes-volume-pool-api.d.ts.map +1 -1
  30. package/dist/kubernetes-volume-pool.d.ts +5 -5
  31. package/dist/kubernetes-volume-pool.d.ts.map +1 -1
  32. package/dist/kubernetes-volume-retirement.d.ts +20 -0
  33. package/dist/kubernetes-volume-retirement.d.ts.map +1 -0
  34. package/dist/kubernetes-worker-runner.d.ts +13 -3
  35. package/dist/kubernetes-worker-runner.d.ts.map +1 -1
  36. package/dist/kubernetes-worker-runner.js +3 -3
  37. package/dist/process-volume-retention.d.ts +4 -0
  38. package/dist/process-volume-retention.d.ts.map +1 -1
  39. package/dist/types-public.js +1 -1
  40. package/dist/types.d.ts +11 -1
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/types.js +1 -1
  43. package/package.json +5 -5
  44. package/src/kubernetes-api-client.ts +3 -0
  45. package/src/kubernetes-http-client.ts +4 -0
  46. package/src/kubernetes-image-preload-api.ts +96 -0
  47. package/src/kubernetes-image-preload.ts +278 -0
  48. package/src/kubernetes-manifests.ts +75 -11
  49. package/src/kubernetes-preparation-api.ts +77 -0
  50. package/src/kubernetes-preparation.ts +100 -0
  51. package/src/kubernetes-volume-pool-api.ts +45 -105
  52. package/src/kubernetes-volume-pool.ts +28 -58
  53. package/src/kubernetes-volume-retirement.ts +139 -0
  54. package/src/kubernetes-worker-runner.ts +78 -28
  55. package/src/process-volume-retention.ts +27 -4
  56. package/src/types.ts +15 -1
  57. package/dist/chunk-ISH4647R.js.map +0 -1
  58. package/dist/chunk-V7TTFLGE.js.map +0 -1
  59. package/dist/chunk-YDYI3BD2.js.map +0 -1
  60. package/dist/chunk-ZGFD76I6.js.map +0 -1
@@ -0,0 +1,278 @@
1
+ import { createHash } from "node:crypto";
2
+ import type {
3
+ ImagePreloadApi,
4
+ ImagePreparationPod,
5
+ PreparationNode,
6
+ } from "./kubernetes-image-preload-api.js";
7
+ import { buildPreparationPodSpec, createPreparationController } from "./kubernetes-preparation.js";
8
+
9
+ export const IMAGE_PRELOAD_LABEL = "leitwerk.dev/image-preload";
10
+ const NODE_UID = "leitwerk.dev/preparation-node-uid";
11
+ const NODE_NAME = "leitwerk.dev/preparation-node-name";
12
+ const IMAGE = "leitwerk.dev/preparation-image";
13
+ const INTERVAL = 30_000;
14
+ const hash = (value: string) => createHash("sha256").update(value).digest("hex");
15
+
16
+ /** @internal */
17
+ export interface ImagePreparationEvent {
18
+ /** @internal */
19
+ component: "image-preparation";
20
+ /** @internal */
21
+ outcome: "succeeded" | "failed";
22
+ /** @internal */
23
+ node?: string;
24
+ /** @internal */
25
+ nodeUid?: string;
26
+ /** @internal */
27
+ image?: string;
28
+ /** @internal */
29
+ pod?: string;
30
+ /** @internal */
31
+ reason?: string;
32
+ }
33
+
34
+ /** @internal */
35
+ export function immutableWorkerImage(image: string): string {
36
+ const match = /^([a-zA-Z0-9][a-zA-Z0-9._:/-]*)@(sha256:[0-9a-f]{64})$/.exec(image);
37
+ if (!match) throw new Error("Image preloading requires digest-qualified worker images");
38
+ return `${match[1].replace(/:[^/:]+$/, "")}@${match[2]}`;
39
+ }
40
+
41
+ /** @internal */
42
+ export function eligiblePreparationNode(
43
+ node: PreparationNode,
44
+ selector: Record<string, string>,
45
+ tolerations: unknown[],
46
+ ): boolean {
47
+ if (!node.metadata.uid || node.metadata.deletionTimestamp || node.spec?.unschedulable)
48
+ return false;
49
+ if (
50
+ !node.status?.conditions?.some(
51
+ (condition) => condition.type === "Ready" && condition.status === "True",
52
+ )
53
+ )
54
+ return false;
55
+ if (!Object.entries(selector).every(([key, value]) => node.metadata.labels?.[key] === value))
56
+ return false;
57
+ return (node.spec?.taints ?? []).every((taint) => {
58
+ if (!["NoSchedule", "NoExecute"].includes(taint.effect)) return true;
59
+ return tolerations.some((value) => {
60
+ if (!value || typeof value !== "object") return false;
61
+ const tolerance = value as Record<string, unknown>;
62
+ if (tolerance.effect && tolerance.effect !== taint.effect) return false;
63
+ if (tolerance.operator === "Exists") return !tolerance.key || tolerance.key === taint.key;
64
+ return (
65
+ (!tolerance.operator || tolerance.operator === "Equal") &&
66
+ tolerance.key === taint.key &&
67
+ (tolerance.value ?? "") === (taint.value ?? "")
68
+ );
69
+ });
70
+ });
71
+ }
72
+
73
+ /** @internal */
74
+ export function createKubernetesImagePreload(options: {
75
+ /** @internal */
76
+ api: ImagePreloadApi;
77
+ /** @internal */
78
+ namespace: string;
79
+ /** @internal */
80
+ images: string[];
81
+ /** @internal */
82
+ imagePullSecrets?: string[];
83
+ /** @internal */
84
+ nodeSelector?: Record<string, string>;
85
+ /** Other worker placements to prepare, deduplicated by node and image. @internal */
86
+ additionalNodeSelectors?: Record<string, string>[];
87
+ /** @internal */
88
+ tolerations?: unknown[];
89
+ /** @internal */
90
+ onEvent?: (event: ImagePreparationEvent) => void;
91
+ }) {
92
+ const { api, namespace } = options;
93
+ const nodeSelectors = [options.nodeSelector ?? {}, ...(options.additionalNodeSelectors ?? [])];
94
+ const selectorForNode = (node: PreparationNode) =>
95
+ nodeSelectors.find((selector) =>
96
+ eligiblePreparationNode(node, selector, options.tolerations ?? []),
97
+ );
98
+ const images = [...new Set(options.images.map(immutableWorkerImage))];
99
+ const preloadId = hash(namespace).slice(0, 16);
100
+ const selector = `${IMAGE_PRELOAD_LABEL}=${preloadId}`;
101
+ const labels = {
102
+ "leitwerk.dev/managed-by": "leitwerk",
103
+ "leitwerk.dev/component": "image-preparation",
104
+ [IMAGE_PRELOAD_LABEL]: preloadId,
105
+ };
106
+ const podName = (uid: string, image: string) =>
107
+ `lw-image-${hash(`${uid}/${image}`).slice(0, 40)}`;
108
+ const reported = new Map<string, string>();
109
+ const failedSince = new Map<string, number>();
110
+
111
+ function owned(pod: ImagePreparationPod) {
112
+ const annotations = pod.metadata.annotations ?? {};
113
+ const uid = annotations[NODE_UID];
114
+ const name = annotations[NODE_NAME];
115
+ const image = annotations[IMAGE];
116
+ const containers = pod.spec.containers as
117
+ | Array<{
118
+ /** @internal */ image?: string /** @internal */;
119
+ command?: string[];
120
+ }>
121
+ | undefined;
122
+ return (
123
+ pod.metadata.namespace === namespace &&
124
+ !!pod.metadata.uid &&
125
+ !!uid &&
126
+ !!name &&
127
+ !!image &&
128
+ Object.entries(labels).every(([key, value]) => pod.metadata.labels?.[key] === value) &&
129
+ pod.metadata.name === podName(uid, image) &&
130
+ pod.metadata.ownerReferences?.some(
131
+ (owner) =>
132
+ owner.apiVersion === "v1" &&
133
+ owner.kind === "Node" &&
134
+ owner.name === name &&
135
+ owner.uid === uid,
136
+ ) &&
137
+ pod.spec.nodeName === name &&
138
+ pod.spec.automountServiceAccountToken === false &&
139
+ containers?.length === 1 &&
140
+ containers[0].image === image &&
141
+ JSON.stringify(containers[0].command) === JSON.stringify(["node", "-e", "process.exit(0)"])
142
+ );
143
+ }
144
+ function report(
145
+ pod: ImagePreparationPod,
146
+ outcome: ImagePreparationEvent["outcome"],
147
+ reason?: string,
148
+ ) {
149
+ const uid = pod.metadata.uid ?? pod.metadata.name;
150
+ const state = `${outcome}/${reason ?? ""}`;
151
+ if (reported.get(uid) === state) return;
152
+ reported.set(uid, state);
153
+ options.onEvent?.({
154
+ component: "image-preparation",
155
+ outcome,
156
+ reason,
157
+ pod: pod.metadata.name,
158
+ node: pod.metadata.annotations?.[NODE_NAME],
159
+ nodeUid: pod.metadata.annotations?.[NODE_UID],
160
+ image: pod.metadata.annotations?.[IMAGE],
161
+ });
162
+ }
163
+ function manifest(
164
+ node: PreparationNode,
165
+ image: string,
166
+ nodeSelector: Record<string, string>,
167
+ ): ImagePreparationPod {
168
+ const uid = node.metadata.uid ?? "";
169
+ return {
170
+ apiVersion: "v1",
171
+ kind: "Pod",
172
+ metadata: {
173
+ name: podName(uid, image),
174
+ namespace,
175
+ labels,
176
+ annotations: { [NODE_UID]: uid, [NODE_NAME]: node.metadata.name, [IMAGE]: image },
177
+ ownerReferences: [{ apiVersion: "v1", kind: "Node", name: node.metadata.name, uid }],
178
+ },
179
+ spec: {
180
+ ...buildPreparationPodSpec({
181
+ ...options,
182
+ image,
183
+ imagePullPolicy: "IfNotPresent",
184
+ nodeSelector: { ...nodeSelector },
185
+ }),
186
+ nodeName: node.metadata.name,
187
+ securityContext: {
188
+ runAsNonRoot: true,
189
+ runAsUser: 1000,
190
+ runAsGroup: 1000,
191
+ seccompProfile: { type: "RuntimeDefault" },
192
+ },
193
+ },
194
+ };
195
+ }
196
+ /** @internal */
197
+ async function reconcile(signal: AbortSignal) {
198
+ const nodes = await api.listNodes(signal);
199
+ const desired = new Map<string, ImagePreparationPod>();
200
+ for (const node of nodes) {
201
+ const nodeSelector = selectorForNode(node);
202
+ if (!nodeSelector) continue;
203
+ for (const image of images) {
204
+ const pod = manifest(node, image, nodeSelector);
205
+ desired.set(pod.metadata.name, pod);
206
+ }
207
+ }
208
+ const pods = await api.listPods(namespace, selector, signal);
209
+ for (const pod of pods) {
210
+ if (desired.has(pod.metadata.name) || !owned(pod) || pod.metadata.deletionTimestamp) continue;
211
+ try {
212
+ await api.deletePod(namespace, pod, signal);
213
+ } catch {
214
+ if (!signal.aborted) report(pod, "failed", "cleanup_failed");
215
+ }
216
+ }
217
+ const liveUids = new Set(pods.map((pod) => pod.metadata.uid ?? ""));
218
+ for (const uid of reported.keys())
219
+ if (!liveUids.has(uid)) {
220
+ reported.delete(uid);
221
+ failedSince.delete(uid);
222
+ }
223
+ for (const expected of desired.values()) {
224
+ try {
225
+ const pod =
226
+ pods.find((value) => value.metadata.name === expected.metadata.name) ??
227
+ (await api.getPod(namespace, expected.metadata.name, signal));
228
+ if (!pod) {
229
+ await api.createPod(namespace, expected, signal);
230
+ continue;
231
+ }
232
+ if (!owned(pod)) {
233
+ report(expected, "failed", "ownership_mismatch");
234
+ continue;
235
+ }
236
+ if (pod.metadata.deletionTimestamp) continue;
237
+ if (pod.status?.phase === "Succeeded") {
238
+ report(pod, "succeeded");
239
+ continue;
240
+ }
241
+ if (pod.status?.phase === "Failed") {
242
+ report(pod, "failed", "pod_failed");
243
+ const uid = pod.metadata.uid ?? "";
244
+ const finished = Date.parse(
245
+ pod.status.containerStatuses?.[0]?.state?.terminated?.finishedAt ?? "",
246
+ );
247
+ const since = failedSince.get(uid) ?? (Number.isFinite(finished) ? finished : Date.now());
248
+ failedSince.set(uid, since);
249
+ if (Date.now() - since >= INTERVAL) {
250
+ await api.deletePod(namespace, pod, signal);
251
+ await api.createPod(namespace, expected, signal);
252
+ }
253
+ continue;
254
+ }
255
+ const reason = pod.status?.containerStatuses?.[0]?.state?.waiting?.reason;
256
+ if (
257
+ reason === "ErrImagePull" ||
258
+ reason === "ImagePullBackOff" ||
259
+ reason === "InvalidImageName"
260
+ )
261
+ report(pod, "failed", reason);
262
+ } catch {
263
+ if (!signal.aborted) report(expected, "failed", "api_error");
264
+ }
265
+ }
266
+ }
267
+ return {
268
+ /** @internal */
269
+ reconcile,
270
+ ...createPreparationController(reconcile, INTERVAL, () =>
271
+ options.onEvent?.({
272
+ component: "image-preparation",
273
+ outcome: "failed",
274
+ reason: "discovery_failed",
275
+ }),
276
+ ),
277
+ };
278
+ }
@@ -52,12 +52,14 @@ export interface KubernetesWorkerServerCaConfigMapSpec {
52
52
 
53
53
  /** @internal */
54
54
  export interface KubernetesDockerPodSpecOptions {
55
+ /** Docker-only keys override the global Pod selector. @internal */
56
+ nodeSelector?: Record<string, string>;
55
57
  /** @internal */
56
58
  runtimeClassName: string;
57
59
  /** @internal */
58
60
  hostUsers?: boolean;
59
61
  /** @internal */
60
- gvisor?: boolean;
62
+ isolation?: "gvisor" | "virtual-machine";
61
63
  /** @internal */
62
64
  network?: DockerNetworkConfig;
63
65
  }
@@ -147,6 +149,13 @@ export interface KubernetesDockerConfigJsonSecretManifest extends NamespacedMani
147
149
 
148
150
  /** @internal */
149
151
  export interface KubernetesPodEventSummary {
152
+ /** @internal */
153
+ series?: {
154
+ /** @internal */
155
+ count?: number;
156
+ /** @internal */
157
+ lastObservedTime?: string;
158
+ };
150
159
  /** @internal */
151
160
  objectUid?: string;
152
161
  /** @internal */
@@ -598,25 +607,37 @@ export function buildKubernetesWorkerPodManifest(
598
607
  });
599
608
  const containerResources = resources(input);
600
609
  const ca = options.serverCaConfigMap;
610
+ const dockerEnv = { ...input.env };
611
+ delete dockerEnv.LEITWERK_DOCKER_GVISOR;
612
+ delete dockerEnv.LEITWERK_DOCKER_ISOLATION;
601
613
  const trustedDockerEnv = input.docker
602
614
  ? {
603
- ...input.env,
615
+ ...dockerEnv,
604
616
  DOCKER_HOST: "unix:///var/run/docker.sock",
605
617
  LEITWERK_PRIVATE_DOCKER: "1",
606
- ...(options.docker?.gvisor ? { LEITWERK_DOCKER_GVISOR: "1" } : {}),
618
+ ...(options.docker?.isolation === "gvisor" ? { LEITWERK_DOCKER_GVISOR: "1" } : {}),
619
+ ...(options.docker?.isolation === "virtual-machine"
620
+ ? { LEITWERK_DOCKER_ISOLATION: "virtual-machine" }
621
+ : {}),
607
622
  LEITWERK_PROCESS_VOLUME_MOUNT_PATH: volume.mountPath,
608
623
  ...(options.docker?.network
609
624
  ? { LEITWERK_DOCKER_NETWORK: JSON.stringify(options.docker.network) }
610
625
  : {}),
611
626
  }
612
- : input.env;
627
+ : dockerEnv;
613
628
  const container: KubernetesPodManifest["spec"]["containers"][number] = {
614
629
  name: "worker",
615
- ...(input.docker && options.docker?.gvisor
630
+ ...(input.docker && options.docker?.isolation
616
631
  ? {
617
632
  securityContext: {
618
633
  privileged: false as const,
619
- capabilities: { add: ["SYS_ADMIN", "NET_ADMIN"] },
634
+ // Docker opens nonroot child namespace handles within the VM guest.
635
+ capabilities: {
636
+ add:
637
+ options.docker?.isolation === "virtual-machine"
638
+ ? ["SYS_ADMIN", "NET_ADMIN", "SYS_PTRACE"]
639
+ : ["SYS_ADMIN", "NET_ADMIN"],
640
+ },
620
641
  },
621
642
  }
622
643
  : {}),
@@ -634,7 +655,13 @@ export function buildKubernetesWorkerPodManifest(
634
655
  input.docker && options.docker
635
656
  ? {
636
657
  runtimeClassName: options.docker.runtimeClassName,
637
- ...(options.docker.gvisor ? {} : { hostUsers: options.docker.hostUsers }),
658
+ ...(options.docker.nodeSelector
659
+ ? { nodeSelector: { ...options.nodeSelector, ...options.docker.nodeSelector } }
660
+ : {}),
661
+ ...(options.docker.isolation ? {} : { hostUsers: options.docker.hostUsers }),
662
+ ...(options.docker.isolation === "virtual-machine"
663
+ ? { automountServiceAccountToken: false }
664
+ : {}),
638
665
  }
639
666
  : {},
640
667
  );
@@ -667,7 +694,8 @@ function formatPodEvent(
667
694
  const pieces: string[] = [];
668
695
  if (event.type?.trim()) pieces.push(event.type.trim());
669
696
  if (event.reason?.trim()) pieces.push(event.reason.trim());
670
- if (event.count !== undefined && event.count > 1) pieces.push(`x${event.count}`);
697
+ const count = event.series?.count ?? event.count;
698
+ if (count !== undefined && count > 1) pieces.push(`x${count}`);
671
699
  const prefix = pieces.join(" ");
672
700
  const message = event.message?.trim();
673
701
  if (!prefix && !message) return null;
@@ -677,15 +705,51 @@ function formatPodEvent(
677
705
  );
678
706
  }
679
707
 
708
+ function podEventTimestamp(event: KubernetesPodEventSummary): number {
709
+ for (const value of [
710
+ event.series?.lastObservedTime,
711
+ event.lastTimestamp,
712
+ event.eventTime,
713
+ event.firstTimestamp,
714
+ ]) {
715
+ if (!value) continue;
716
+ const timestamp = Date.parse(value);
717
+ if (Number.isFinite(timestamp)) return timestamp;
718
+ }
719
+ return Number.NEGATIVE_INFINITY;
720
+ }
721
+
680
722
  /** @internal */
681
723
  export function formatKubernetesPodDiagnostics(
682
724
  events: readonly KubernetesPodEventSummary[] | undefined,
683
725
  limit = 3,
684
726
  sensitiveValues: readonly string[] = [],
685
727
  ): string | undefined {
686
- const formatted = (events ?? [])
687
- .map((event) => formatPodEvent(event, sensitiveValues))
688
- .filter((entry): entry is string => entry !== null)
728
+ const candidates = (events ?? []).map((event) => ({
729
+ formatted: formatPodEvent(event, sensitiveValues),
730
+ timestamp: podEventTimestamp(event),
731
+ warning: event.type?.trim() === "Warning",
732
+ identity: redactKubernetesDiagnostic(
733
+ JSON.stringify([event.type?.trim(), event.reason?.trim(), event.message?.trim()]),
734
+ sensitiveValues,
735
+ ),
736
+ }));
737
+ // API list order is not chronological. Keep recent phase context, using warnings only for ties.
738
+ candidates.sort((left, right) => {
739
+ if (left.timestamp !== right.timestamp) return left.timestamp > right.timestamp ? -1 : 1;
740
+ if (left.warning !== right.warning) return left.warning ? -1 : 1;
741
+ const leftText = left.formatted ?? "";
742
+ const rightText = right.formatted ?? "";
743
+ return leftText < rightText ? -1 : leftText > rightText ? 1 : 0;
744
+ });
745
+ const seen = new Set<string>();
746
+ const formatted = candidates
747
+ .filter((candidate) => {
748
+ if (candidate.formatted === null || seen.has(candidate.identity)) return false;
749
+ seen.add(candidate.identity);
750
+ return true;
751
+ })
752
+ .map((candidate) => candidate.formatted)
689
753
  .slice(0, limit);
690
754
  return formatted.length > 0
691
755
  ? boundedDiagnostic(`Kubernetes events: ${formatted.join(" | ")}`, sensitiveValues)
@@ -0,0 +1,77 @@
1
+ /** @internal */
2
+ export type PreparationRequest = <T>(input: {
3
+ /** @internal */ method: string;
4
+ /** @internal */ path: string;
5
+ /** @internal */ body?: unknown;
6
+ /** @internal */ contentType?: string;
7
+ /** @internal */ ok?: readonly number[];
8
+ /** @internal */ signal?: AbortSignal;
9
+ }) => Promise<{
10
+ /** @internal */ status: number;
11
+ /** @internal */ body: T | null;
12
+ }>;
13
+
14
+ /** Bounded transport for the server-owned preparation resources. @internal */
15
+ export function createPreparationApi(transport: PreparationRequest, component: string) {
16
+ const request: PreparationRequest = <T>(input: Parameters<PreparationRequest>[0]) =>
17
+ transport<T>({
18
+ ...input,
19
+ signal: input.signal
20
+ ? AbortSignal.any([input.signal, AbortSignal.timeout(10_000)])
21
+ : undefined,
22
+ });
23
+ return {
24
+ /** @internal */
25
+ request,
26
+ /** @internal */
27
+ async list<T>(path: string, selector: string, signal: AbortSignal): Promise<T[]> {
28
+ const items: T[] = [];
29
+ let cursor = "";
30
+ do {
31
+ const query = new URLSearchParams({ labelSelector: selector, limit: "100" });
32
+ if (cursor) query.set("continue", cursor);
33
+ const response = await request<{
34
+ /** @internal */ items: T[];
35
+ /** @internal */ metadata?: {
36
+ /** @internal */ continue?: string;
37
+ };
38
+ }>({ method: "GET", path: `${path}?${query}`, signal });
39
+ if (!response.body) throw new Error(`Missing ${component} list response`);
40
+ items.push(...response.body.items);
41
+ cursor = response.body.metadata?.continue ?? "";
42
+ } while (cursor);
43
+ return items;
44
+ },
45
+ /** @internal */
46
+ async get<T>(path: string, signal: AbortSignal): Promise<T | null> {
47
+ const response = await request<T>({ method: "GET", path, ok: [200, 404], signal });
48
+ return response.status === 404 ? null : response.body;
49
+ },
50
+ /** @internal */
51
+ async create(path: string, body: unknown, signal: AbortSignal): Promise<void> {
52
+ await request({ method: "POST", path, body, ok: [201, 409], signal });
53
+ },
54
+ /** @internal */
55
+ async delete(
56
+ path: string,
57
+ uid: string | undefined,
58
+ signal: AbortSignal,
59
+ identity: string,
60
+ gracePeriodSeconds?: number,
61
+ ): Promise<void> {
62
+ if (!uid) throw new Error(`${identity} identity is missing`);
63
+ await request({
64
+ method: "DELETE",
65
+ path,
66
+ body: {
67
+ apiVersion: "v1",
68
+ kind: "DeleteOptions",
69
+ preconditions: { uid },
70
+ ...(gracePeriodSeconds === undefined ? {} : { gracePeriodSeconds }),
71
+ },
72
+ ok: [200, 202, 404],
73
+ signal,
74
+ });
75
+ },
76
+ };
77
+ }
@@ -0,0 +1,100 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import type { VolumePoolOptions } from "./kubernetes-volume-pool.js";
3
+ import type { PoolObject } from "./kubernetes-volume-pool-api.js";
4
+
5
+ /** Shared inert preparation workload; callers supply ownership and placement constraints. @internal */
6
+ export function buildPreparationPodSpec(
7
+ options: Pick<
8
+ VolumePoolOptions,
9
+ "image" | "imagePullPolicy" | "imagePullSecrets" | "nodeSelector" | "tolerations"
10
+ >,
11
+ volumeMounts?: unknown[],
12
+ ): PoolObject["spec"] {
13
+ return {
14
+ restartPolicy: "Never",
15
+ serviceAccountName: "default",
16
+ automountServiceAccountToken: false,
17
+ nodeSelector: options.nodeSelector ?? {},
18
+ tolerations: options.tolerations ?? [],
19
+ imagePullSecrets: (options.imagePullSecrets ?? []).map((name) => ({ name })),
20
+ containers: [
21
+ {
22
+ name: "prepare",
23
+ image: options.image,
24
+ imagePullPolicy: options.imagePullPolicy ?? "IfNotPresent",
25
+ command: ["node", "-e", "process.exit(0)"],
26
+ resources: {
27
+ requests: { cpu: "1m", memory: "32Mi" },
28
+ limits: { cpu: "100m", memory: "64Mi" },
29
+ },
30
+ securityContext: {
31
+ allowPrivilegeEscalation: false,
32
+ readOnlyRootFilesystem: true,
33
+ capabilities: { drop: ["ALL"] },
34
+ },
35
+ ...(volumeMounts ? { volumeMounts } : {}),
36
+ },
37
+ ],
38
+ };
39
+ }
40
+
41
+ /** @internal */
42
+ export interface PreparationController {
43
+ /** @internal */
44
+ start(): void;
45
+ /** @internal */
46
+ stop(): Promise<void>;
47
+ }
48
+
49
+ /** One non-overlapping loop; stopping cancels and joins its current work. @internal */
50
+ export function createPreparationController(
51
+ reconcile: (signal: AbortSignal) => Promise<void>,
52
+ intervalMs: number,
53
+ onError?: (error?: unknown) => void,
54
+ errorIntervalMs = intervalMs,
55
+ ): PreparationController {
56
+ let controller: AbortController | undefined;
57
+ let running: Promise<void> | undefined;
58
+ return {
59
+ start() {
60
+ if (controller) return;
61
+ controller = new AbortController();
62
+ const { signal } = controller;
63
+ running = (async () => {
64
+ while (!signal.aborted) {
65
+ let interval = intervalMs;
66
+ try {
67
+ await reconcile(signal);
68
+ } catch (error) {
69
+ interval = errorIntervalMs;
70
+ if (!signal.aborted) onError?.(error);
71
+ }
72
+ try {
73
+ await delay(interval, undefined, { signal });
74
+ } catch {
75
+ break;
76
+ }
77
+ }
78
+ })();
79
+ },
80
+ async stop() {
81
+ controller?.abort();
82
+ await running;
83
+ controller = undefined;
84
+ },
85
+ };
86
+ }
87
+
88
+ /** Controllers own separate asynchronous reconciliation loops. @internal */
89
+ export function createKubernetesPreparation(controllers: PreparationController[]) {
90
+ return {
91
+ /** @internal */
92
+ start() {
93
+ for (const controller of controllers) controller.start();
94
+ },
95
+ /** @internal */
96
+ async stop() {
97
+ await Promise.allSettled(controllers.map((controller) => controller.stop()));
98
+ },
99
+ };
100
+ }