@leitwerk-dev/worker-runners 0.4.2 → 0.4.4
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.
- package/dist/{chunk-GMZOYHQD.js → chunk-NUZMI6HJ.js} +21 -29
- package/dist/chunk-NUZMI6HJ.js.map +1 -0
- package/dist/index.js +10 -10
- package/dist/index.js.map +1 -1
- package/dist/kubernetes-public.js +1 -1
- package/dist/kubernetes-worker-runner.d.ts.map +1 -1
- package/dist/kubernetes-worker-runner.js +1 -1
- package/dist/process-volume-retention.d.ts +1 -9
- package/dist/process-volume-retention.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/kubernetes-worker-runner.ts +26 -27
- package/src/process-volume-retention.ts +21 -26
- package/dist/chunk-GMZOYHQD.js.map +0 -1
|
@@ -833,6 +833,22 @@ function createKubernetesWorkerRunner(options) {
|
|
|
833
833
|
const delay2 = options.delay ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
834
834
|
const podDisappearanceTimeoutMs = options.podDisappearanceTimeoutMs ?? 3e4;
|
|
835
835
|
const podDisappearancePollIntervalMs = options.podDisappearancePollIntervalMs ?? 250;
|
|
836
|
+
async function releaseVolume(instanceId, retirement = {}) {
|
|
837
|
+
const name = kubernetesProcessPvcName(instanceId, options.volume.namePrefix);
|
|
838
|
+
const namespace = namespaceForProcess(instanceId);
|
|
839
|
+
if (client.volumePool)
|
|
840
|
+
return retireKubernetesProcessVolume({
|
|
841
|
+
api: client.volumePool,
|
|
842
|
+
namespace,
|
|
843
|
+
name,
|
|
844
|
+
instanceId,
|
|
845
|
+
signal: AbortSignal.timeout(3e4),
|
|
846
|
+
...retirement
|
|
847
|
+
});
|
|
848
|
+
if (retirement.reclaimBackingStorage)
|
|
849
|
+
throw new Error("Backing-storage reclamation requires Kubernetes volume inspection");
|
|
850
|
+
await client.deletePersistentVolumeClaim(name, namespace);
|
|
851
|
+
}
|
|
836
852
|
const samplers = /* @__PURE__ */ new Map();
|
|
837
853
|
const volume = {
|
|
838
854
|
async ensure(instanceId, requirements, observer) {
|
|
@@ -926,39 +942,15 @@ function createKubernetesWorkerRunner(options) {
|
|
|
926
942
|
namespace: manifest.metadata.namespace
|
|
927
943
|
});
|
|
928
944
|
},
|
|
929
|
-
|
|
930
|
-
if (client.volumePool) {
|
|
931
|
-
await retireKubernetesProcessVolume({
|
|
932
|
-
api: client.volumePool,
|
|
933
|
-
namespace: namespaceForProcess(instanceId),
|
|
934
|
-
name: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
|
|
935
|
-
instanceId,
|
|
936
|
-
signal: AbortSignal.timeout(3e4),
|
|
937
|
-
reclaimBackingStorage: releaseOptions?.reclaimBackingStorage
|
|
938
|
-
});
|
|
939
|
-
return;
|
|
940
|
-
}
|
|
941
|
-
if (releaseOptions?.reclaimBackingStorage)
|
|
942
|
-
throw new Error("Backing-storage reclamation requires Kubernetes volume inspection");
|
|
943
|
-
await client.deletePersistentVolumeClaim(
|
|
944
|
-
kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
|
|
945
|
-
namespaceForProcess(instanceId)
|
|
946
|
-
);
|
|
947
|
-
},
|
|
945
|
+
release: releaseVolume,
|
|
948
946
|
async deleteProcessResources(instanceId) {
|
|
949
947
|
samplers.get(instanceId)?.stop();
|
|
950
948
|
samplers.delete(instanceId);
|
|
951
|
-
if (client.volumePool)
|
|
952
|
-
await
|
|
953
|
-
api: client.volumePool,
|
|
954
|
-
namespace: namespaceForProcess(instanceId),
|
|
955
|
-
name: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
|
|
956
|
-
instanceId,
|
|
949
|
+
if (client.volumePool)
|
|
950
|
+
await releaseVolume(instanceId, {
|
|
957
951
|
reason: "process-deleted",
|
|
958
|
-
reclaimBackingStorage: options.reclaimOnClose ? "process-deleted" : void 0
|
|
959
|
-
signal: AbortSignal.timeout(3e4)
|
|
952
|
+
reclaimBackingStorage: options.reclaimOnClose ? "process-deleted" : void 0
|
|
960
953
|
});
|
|
961
|
-
}
|
|
962
954
|
await client.deleteNamespace(namespaceForProcess(instanceId));
|
|
963
955
|
}
|
|
964
956
|
};
|
|
@@ -1228,4 +1220,4 @@ function createKubernetesWorkerRunner(options) {
|
|
|
1228
1220
|
export {
|
|
1229
1221
|
createKubernetesWorkerRunner
|
|
1230
1222
|
};
|
|
1231
|
-
//# sourceMappingURL=chunk-
|
|
1223
|
+
//# sourceMappingURL=chunk-NUZMI6HJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/kubernetes-worker-runner.ts","../src/kubernetes-image-preload.ts","../src/kubernetes-preparation.ts","../src/kubernetes-startup-sampler.ts","../src/kubernetes-volume-pool.ts","../src/kubernetes-volume-retirement.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n\tcreateHelperProcessStateExporter,\n\texportHelperEnvironment,\n} from \"./helper-process-state-exporter.js\";\nimport type { KubernetesApiClient } from \"./kubernetes-api-client.js\";\nimport {\n\tcreateKubernetesImagePreload,\n\ttype ImagePreparationEvent,\n} from \"./kubernetes-image-preload.js\";\nimport {\n\tbuildKubernetesDockerConfigJsonSecretManifest,\n\tbuildKubernetesExportHelperPodManifest,\n\tbuildKubernetesProcessNamespaceManifest,\n\tbuildKubernetesProcessPvcManifest,\n\tbuildKubernetesServerCaConfigMapManifest,\n\tbuildKubernetesWorkerPodManifest,\n\tKUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\tKUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\tKUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\ttype KubernetesDockerPodSpecOptions,\n\ttype KubernetesPodSpecOptions,\n\ttype KubernetesProcessVolumeSpec,\n\tkubernetesExportHelperPodName,\n\tkubernetesProcessNamespaceName,\n\tkubernetesProcessPvcName,\n\tredactKubernetesDiagnostic,\n\tvolumeRefFromPvc,\n} from \"./kubernetes-manifests.js\";\nimport { createKubernetesPreparation } from \"./kubernetes-preparation.js\";\nimport { sampleKubernetesStartup, startupReceipt } from \"./kubernetes-startup-sampler.js\";\nimport { createKubernetesVolumePool } from \"./kubernetes-volume-pool.js\";\nimport { retireKubernetesProcessVolume } from \"./kubernetes-volume-retirement.js\";\nimport { UnitExitNotifier } from \"./runner-utils.js\";\nimport {\n\tSESSION_TRANSFER_HELPER_ENTRY_PATH,\n\tSESSION_TRANSFER_HELPER_MOUNT_PATH,\n} from \"./session-transfer-helper.js\";\nimport type {\n\tIsolatedStartWorkerInput,\n\tProcessStateExporter,\n\tProcessStateExportHelperRelayProvider,\n\tProcessVolume,\n\tStopWorkerOptions,\n\tWorkerRunner,\n\tWorkerUnit,\n\tWorkerUnitDescriptor,\n\tWorkerUnitRef,\n} from \"./types.js\";\nimport { WorkerStartDiagnosticError } from \"./types.js\";\nimport {\n\tmanagedExportHelperLabelSelector,\n\tmanagedProcessNamespaceLabelSelector,\n\tmanagedWorkerLabelSelector,\n\tparseWorkerUnitIdentity,\n\tWORKER_LABEL_COMPONENT,\n\tWORKER_LABEL_INSTANCE_ID,\n\tWORKER_LABEL_MANAGED_BY,\n\tWORKER_LABEL_MANAGED_BY_VALUE,\n} from \"./worker-labels.js\";\n\nconst KUBERNETES_START_DIAGNOSTIC_MAX_LENGTH = 2_048;\n\nfunction boundedKubernetesStartDiagnostic(\n\terror: unknown,\n\tsensitiveValues: readonly string[],\n): string {\n\tconst detail = error instanceof Error ? error.message : \"Kubernetes Pod admission failed\";\n\treturn redactKubernetesDiagnostic(detail, sensitiveValues).slice(\n\t\t0,\n\t\tKUBERNETES_START_DIAGNOSTIC_MAX_LENGTH,\n\t);\n}\n\n/** @internal */\nexport interface KubernetesWorkerRunnerOptions {\n\t/** Enable CSI backing reclamation for explicit process deletion. @internal */\n\treclaimOnClose?: boolean;\n\t/** @internal */\n\timagePreload?: {\n\t\t/** @internal */\n\t\timages: string[];\n\t\t/** @internal */\n\t\tonEvent?: (event: ImagePreparationEvent) => void;\n\t};\n\t/** @internal */\n\tpreProvision?: {\n\t\t/** @internal */\n\t\tcount: number;\n\t\t/** @internal */\n\t\tonError?: (error?: unknown) => void;\n\t};\n\t/** @internal */\n\tclient: KubernetesApiClient;\n\t/** Prefix used to derive one Kubernetes namespace per process instance. @internal */\n\tprocessNamespacePrefix: string;\n\t/** @internal */\n\tvolume: KubernetesProcessVolumeSpec;\n\t/** Storage and Pod wiring for process definitions that require private Docker. @internal */\n\tdocker?: KubernetesDockerPodSpecOptions & {\n\t\t/** @internal */\n\t\tprocessStorageClassName: string;\n\t};\n\t/** Maximum wait after deletion before replacement is rejected. @internal */\n\tpodDisappearanceTimeoutMs?: number;\n\t/** @internal */\n\tpodDisappearancePollIntervalMs?: number;\n\t/** Test seam for bounded disappearance polling. @internal */\n\tdelay?: (ms: number) => Promise<void>;\n\t/** Server-local CA bundle copied into each process namespace for worker TLS trust. @internal */\n\tserverCaFile?: string;\n\t/** Namespace containing operator-managed source image-pull Secrets. @internal */\n\tserverNamespace?: string;\n\t/** Docker registry Secrets copied into every process namespace. @internal */\n\timagePullSecretCopies?: Array<{\n\t\t/** @internal */\n\t\tsourceName: string;\n\t\t/** @internal */\n\t\ttargetName: string;\n\t}>;\n\t/** @internal */\n\tpod?: Omit<KubernetesPodSpecOptions, \"namespace\">;\n\t/** Stable internal URL used by PVC export helpers. @internal */\n\tserverUrl?: string;\n\t/** Trusted image containing the bundled session-transfer helper entrypoint. @internal */\n\texporterImage?: string;\n\t/** Pull policy for the trusted helper image. @internal */\n\texporterImagePullPolicy?: string;\n\t/** Server-owned relay registry used by PVC export helpers. @internal */\n\thelperRelays?: ProcessStateExportHelperRelayProvider;\n}\n\n/** @internal */\nexport function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOptions): {\n\t/** @internal */\n\trunner: WorkerRunner<IsolatedStartWorkerInput>;\n\t/** @internal */\n\tvolume: ProcessVolume;\n\t/** @internal */\n\texporter: ProcessStateExporter;\n\t/** @internal */\n\tpreparation?: ReturnType<typeof createKubernetesPreparation>;\n} {\n\tif (!options.serverUrl || !options.exporterImage || !options.helperRelays) {\n\t\tthrow new Error(\"Kubernetes transfer exporter is not configured\");\n\t}\n\tconst { client } = options;\n\tconst exporterServerUrl = options.serverUrl;\n\tconst exporterImage = options.exporterImage;\n\tconst helperRelays = options.helperRelays;\n\tconst serverCaFile = options.serverCaFile?.trim();\n\tconst serverCaConfig = serverCaFile\n\t\t? {\n\t\t\t\tserverCaConfigMap: {\n\t\t\t\t\tname: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\t\t\t\t\tkey: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\t\t\t\t\tmountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\t\t\t\t},\n\t\t\t}\n\t\t: {};\n\tconst namespaceForProcess = (instanceId: string) =>\n\t\tkubernetesProcessNamespaceName(instanceId, options.processNamespacePrefix);\n\tconst delay =\n\t\toptions.delay ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\tconst podDisappearanceTimeoutMs = options.podDisappearanceTimeoutMs ?? 30_000;\n\tconst podDisappearancePollIntervalMs = options.podDisappearancePollIntervalMs ?? 250;\n\n\tasync function releaseVolume(\n\t\tinstanceId: string,\n\t\tretirement: Pick<\n\t\t\tParameters<typeof retireKubernetesProcessVolume>[0],\n\t\t\t\"reason\" | \"reclaimBackingStorage\"\n\t\t> = {},\n\t) {\n\t\tconst name = kubernetesProcessPvcName(instanceId, options.volume.namePrefix);\n\t\tconst namespace = namespaceForProcess(instanceId);\n\t\tif (client.volumePool)\n\t\t\treturn retireKubernetesProcessVolume({\n\t\t\t\tapi: client.volumePool,\n\t\t\t\tnamespace,\n\t\t\t\tname,\n\t\t\t\tinstanceId,\n\t\t\t\tsignal: AbortSignal.timeout(30_000),\n\t\t\t\t...retirement,\n\t\t\t});\n\t\tif (retirement.reclaimBackingStorage)\n\t\t\tthrow new Error(\"Backing-storage reclamation requires Kubernetes volume inspection\");\n\t\tawait client.deletePersistentVolumeClaim(name, namespace);\n\t}\n\n\tconst samplers = new Map<string, ReturnType<typeof sampleKubernetesStartup>>();\n\tconst volume: ProcessVolume = {\n\t\tasync ensure(instanceId, requirements, observer) {\n\t\t\tconst namespaceManifest = buildKubernetesProcessNamespaceManifest({\n\t\t\t\tinstanceId,\n\t\t\t\tprocessNamespacePrefix: options.processNamespacePrefix,\n\t\t\t\t...(requirements?.docker && options.docker?.isolation\n\t\t\t\t\t? { extraLabels: { \"pod-security.kubernetes.io/enforce\": \"privileged\" } }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tif (requirements?.docker && options.docker) {\n\t\t\t\tif (!client.getPersistentVolumeClaim)\n\t\t\t\t\tthrow new Error(\"Docker requires process storage inspection\");\n\t\t\t\tconst existing = await client.getPersistentVolumeClaim(\n\t\t\t\t\tkubernetesProcessPvcName(instanceId, options.volume.namePrefix),\n\t\t\t\t\tnamespaceManifest.metadata.name,\n\t\t\t\t);\n\t\t\t\tif (existing && existing.storageClass !== options.docker.processStorageClassName) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Docker requires the configured block StorageClass; preserve and migrate the existing process volume before resuming\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait client.ensureNamespace(namespaceManifest);\n\t\t\tconst copySecrets = (options.imagePullSecretCopies ?? []).map(async (copy) => {\n\t\t\t\tconst dockerConfigJson = await client.getDockerConfigJsonSecret(\n\t\t\t\t\tcopy.sourceName,\n\t\t\t\t\toptions.serverNamespace ?? \"leitwerk-system\",\n\t\t\t\t);\n\t\t\t\tawait client.ensureDockerConfigJsonSecret(\n\t\t\t\t\tbuildKubernetesDockerConfigJsonSecretManifest({\n\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\t\t\tname: copy.targetName,\n\t\t\t\t\t\tdockerConfigJson,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t});\n\t\t\tconst workerServiceAccount = options.pod?.workerServiceAccount?.trim();\n\t\t\tconst manifest = buildKubernetesProcessPvcManifest({\n\t\t\t\tinstanceId,\n\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\tvolume: {\n\t\t\t\t\t...options.volume,\n\t\t\t\t\tsize: requirements?.size ?? options.volume.size,\n\t\t\t\t\t...(requirements?.docker && options.docker\n\t\t\t\t\t\t? { storageClassName: options.docker.processStorageClassName }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\t...copySecrets,\n\t\t\t\t...(serverCaFile\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tclient.ensureConfigMap(\n\t\t\t\t\t\t\t\tbuildKubernetesServerCaConfigMapManifest({\n\t\t\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\t\t\t\t\t\tcaPem: readFileSync(serverCaFile, \"utf8\"),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t\t...(workerServiceAccount && workerServiceAccount !== \"default\"\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tclient.ensureServiceAccount(workerServiceAccount, namespaceManifest.metadata.name, {\n\t\t\t\t\t\t\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t\t\t\t\t\t\t[WORKER_LABEL_COMPONENT]: \"worker-service-account\",\n\t\t\t\t\t\t\t\t[WORKER_LABEL_INSTANCE_ID]: instanceId,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t\t(async () => {\n\t\t\t\t\tstartupReceipt(observer, \"pvc_requested\", {\n\t\t\t\t\t\tstorageClass: manifest.spec.storageClassName,\n\t\t\t\t\t});\n\t\t\t\t\tawait client.ensurePersistentVolumeClaim(manifest);\n\t\t\t\t\tstartupReceipt(observer, \"pvc_acknowledged\", {\n\t\t\t\t\t\tstorageClass: manifest.spec.storageClassName,\n\t\t\t\t\t});\n\t\t\t\t\tif (observer?.observe) {\n\t\t\t\t\t\tsamplers.get(instanceId)?.stop();\n\t\t\t\t\t\tsamplers.set(\n\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\tsampleKubernetesStartup(\n\t\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\t\tobserver,\n\t\t\t\t\t\t\t\tmanifest.metadata.namespace,\n\t\t\t\t\t\t\t\tmanifest.metadata.name,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t]);\n\t\t\treturn volumeRefFromPvc({\n\t\t\t\tinstanceId,\n\t\t\t\tpvcName: manifest.metadata.name,\n\t\t\t\tmountPath: options.volume.mountPath,\n\t\t\t\tnamespace: manifest.metadata.namespace,\n\t\t\t});\n\t\t},\n\t\trelease: releaseVolume,\n\t\tasync deleteProcessResources(instanceId) {\n\t\t\tsamplers.get(instanceId)?.stop();\n\t\t\tsamplers.delete(instanceId);\n\t\t\tif (client.volumePool)\n\t\t\t\tawait releaseVolume(instanceId, {\n\t\t\t\t\treason: \"process-deleted\",\n\t\t\t\t\treclaimBackingStorage: options.reclaimOnClose ? \"process-deleted\" : undefined,\n\t\t\t\t});\n\t\t\tawait client.deleteNamespace(namespaceForProcess(instanceId));\n\t\t},\n\t};\n\n\tconst exitNotifier = new UnitExitNotifier();\n\tconst unsubscribers = new Map<string, () => void>();\n\tconst disappearancePromises = new Map<string, Promise<void>>();\n\n\tfunction unitKey(namespace: string, unitId: string): string {\n\t\treturn `${namespace}/${unitId}`;\n\t}\n\n\tfunction deletePodAndWait(\n\t\tname: string,\n\t\tnamespace: string,\n\t\tgracePeriodSeconds: number,\n\t): Promise<void> {\n\t\tconst key = unitKey(namespace, name);\n\t\tconst existing = disappearancePromises.get(key);\n\t\tif (existing) return existing;\n\t\tconst operation = Promise.resolve()\n\t\t\t.then(async () => {\n\t\t\t\tconst deadline = Date.now() + podDisappearanceTimeoutMs;\n\t\t\t\tconst timeoutError = new Error(\n\t\t\t\t\t`Kubernetes worker Pod ${namespace}/${name} did not disappear within ${podDisappearanceTimeoutMs}ms; replacement was not started`,\n\t\t\t\t);\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tconst { signal } = controller;\n\t\t\t\tlet rejectTimeout!: (error: Error) => void;\n\t\t\t\tconst timedOut = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\trejectTimeout = reject;\n\t\t\t\t});\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tcontroller.abort(timeoutError);\n\t\t\t\t\trejectTimeout(timeoutError);\n\t\t\t\t}, podDisappearanceTimeoutMs);\n\t\t\t\tconst waitForDisappearance = async () => {\n\t\t\t\t\tawait client.deletePod(name, namespace, { gracePeriodSeconds, signal });\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (Date.now() >= deadline) throw timeoutError;\n\t\t\t\t\t\tconst pod = await client.getPod(name, namespace, { signal });\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (Date.now() >= deadline) throw timeoutError;\n\t\t\t\t\t\tif (!pod) return;\n\t\t\t\t\t\tawait delay(\n\t\t\t\t\t\t\tMath.min(podDisappearancePollIntervalMs, Math.max(0, deadline - Date.now())),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.race([waitForDisappearance(), timedOut]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (signal.aborted) throw timeoutError;\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => disappearancePromises.delete(key));\n\t\tdisappearancePromises.set(key, operation);\n\t\treturn operation;\n\t}\n\n\tfunction watchPod(\n\t\tunitId: string,\n\t\tnamespace: string,\n\t\tsensitiveValues: readonly string[] = [],\n\t): void {\n\t\tconst key = unitKey(namespace, unitId);\n\t\tif (unsubscribers.has(key)) return;\n\t\tconst unsubscribe = client.onPodExit(\n\t\t\tunitId,\n\t\t\tnamespace,\n\t\t\t(info) => {\n\t\t\t\texitNotifier.fireExit(key, info);\n\t\t\t\tunsubscribers.get(key)?.();\n\t\t\t\tunsubscribers.delete(key);\n\t\t\t},\n\t\t\t{ sensitiveValues },\n\t\t);\n\t\tunsubscribers.set(key, unsubscribe);\n\t}\n\n\tconst runner: WorkerRunner<IsolatedStartWorkerInput> = {\n\t\tasync start(input: IsolatedStartWorkerInput, observer): Promise<WorkerUnit> {\n\t\t\tobserver?.report(\"preparing_runtime\");\n\t\t\tif (input.docker && !options.docker) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Kubernetes Docker runtime is unavailable; configure kubernetes.docker completely\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst processNamespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);\n\t\t\tconst manifest = buildKubernetesWorkerPodManifest(input, {\n\t\t\t\tnamespace: processNamespace,\n\t\t\t\t...(options.pod ?? {}),\n\t\t\t\t...(input.docker && options.docker ? { docker: options.docker } : {}),\n\t\t\t\t...serverCaConfig,\n\t\t\t});\n\t\t\tobserver?.report(\"allocating_runtime\");\n\t\t\ttry {\n\t\t\t\tstartupReceipt(observer, \"pod_requested\", {\n\t\t\t\t\timage: input.image.reference,\n\t\t\t\t\t...input.resources,\n\t\t\t\t});\n\t\t\t\tawait client.createPod(manifest);\n\t\t\t\tstartupReceipt(observer, \"pod_acknowledged\");\n\t\t\t\tsamplers.get(input.instanceId)?.attachPod({\n\t\t\t\t\tname: manifest.metadata.name,\n\t\t\t\t\tworkerId: input.workerId,\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsamplers.get(input.instanceId)?.stop();\n\t\t\t\tsamplers.delete(input.instanceId);\n\t\t\t\tthrow new WorkerStartDiagnosticError(\n\t\t\t\t\tboundedKubernetesStartDiagnostic(error, Object.values(input.env)),\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t\tobserver?.report(\"starting_runtime\");\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tworkerId: input.workerId,\n\t\t\t\tunitId: manifest.metadata.name,\n\t\t\t\tnamespace: manifest.metadata.namespace,\n\t\t\t};\n\t\t\twatchPod(ref.unitId, ref.namespace ?? processNamespace, Object.values(input.env));\n\t\t\treturn exitNotifier.wrapUnit(ref, unitKey(ref.namespace ?? processNamespace, ref.unitId), {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t\tasync stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {\n\t\t\tsamplers.get(ref.instanceId)?.stop();\n\t\t\tsamplers.delete(ref.instanceId);\n\t\t\tawait deletePodAndWait(\n\t\t\t\tref.unitId,\n\t\t\t\tref.namespace ?? namespaceForProcess(ref.instanceId),\n\t\t\t\tMath.max(0, Math.ceil(opts.graceMs / 1000)),\n\t\t\t);\n\t\t},\n\t\tasync list(): Promise<WorkerUnitDescriptor[]> {\n\t\t\tconst namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());\n\t\t\tconst descriptors: WorkerUnitDescriptor[] = [];\n\t\t\tfor (const namespace of namespaces) {\n\t\t\t\tif (!namespace.name.startsWith(options.processNamespacePrefix)) continue;\n\t\t\t\tconst pods = await client.listPods(namespace.name, managedWorkerLabelSelector());\n\t\t\t\tfor (const pod of pods) {\n\t\t\t\t\tconst identity = parseWorkerUnitIdentity(pod.labels);\n\t\t\t\t\tif (!identity) continue;\n\t\t\t\t\tdescriptors.push({\n\t\t\t\t\t\tinstanceId: identity.instanceId,\n\t\t\t\t\t\tworkerId: identity.workerId,\n\t\t\t\t\t\tunitId: pod.name,\n\t\t\t\t\t\tnamespace: pod.namespace,\n\t\t\t\t\t\tobservedState:\n\t\t\t\t\t\t\tpod.phase === \"Failed\" || pod.phase === \"Succeeded\"\n\t\t\t\t\t\t\t\t? \"terminal\"\n\t\t\t\t\t\t\t\t: pod.phase === \"Pending\"\n\t\t\t\t\t\t\t\t\t? \"pending\"\n\t\t\t\t\t\t\t\t\t: pod.phase === \"Running\"\n\t\t\t\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t\t\t\t: \"unknown\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn descriptors;\n\t\t},\n\t\tasync adopt(descriptor: WorkerUnitDescriptor, observer): Promise<WorkerUnit> {\n\t\t\tconst podNamespace = descriptor.namespace ?? namespaceForProcess(descriptor.instanceId);\n\t\t\tconst pod = await client.getPod(descriptor.unitId, podNamespace);\n\t\t\tconst identity = pod ? parseWorkerUnitIdentity(pod.labels) : null;\n\t\t\tif (\n\t\t\t\t!identity ||\n\t\t\t\tidentity.instanceId !== descriptor.instanceId ||\n\t\t\t\tidentity.workerId !== descriptor.workerId\n\t\t\t) {\n\t\t\t\tthrow new Error(`Cannot adopt worker pod ${descriptor.unitId}: labels changed`);\n\t\t\t}\n\t\t\tif (!pod || pod.phase === \"Failed\" || pod.phase === \"Succeeded\") {\n\t\t\t\tthrow new Error(`Cannot adopt worker pod ${descriptor.unitId}: not running`);\n\t\t\t}\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: descriptor.instanceId,\n\t\t\t\tworkerId: descriptor.workerId,\n\t\t\t\tunitId: descriptor.unitId,\n\t\t\t\tnamespace: podNamespace,\n\t\t\t};\n\t\t\tif (observer?.observe && pod.pvcName) {\n\t\t\t\tsamplers.get(descriptor.instanceId)?.stop();\n\t\t\t\tconst sampler = sampleKubernetesStartup(client, observer, podNamespace, pod.pvcName);\n\t\t\t\tsampler.attachPod({ name: ref.unitId, workerId: ref.workerId, instanceId: ref.instanceId });\n\t\t\t\tsamplers.set(descriptor.instanceId, sampler);\n\t\t\t}\n\t\t\twatchPod(ref.unitId, podNamespace);\n\t\t\treturn exitNotifier.wrapUnit(ref, unitKey(podNamespace, ref.unitId), {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t};\n\n\tconst exporter = createHelperProcessStateExporter({\n\t\tvolume,\n\t\thelperRelays,\n\t\tasync launch(input) {\n\t\t\tconst namespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);\n\t\t\tconst podName = kubernetesExportHelperPodName(input.instanceId, input.exportId);\n\t\t\tconst manifest = buildKubernetesExportHelperPodManifest(\n\t\t\t\t{\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\timage: exporterImage,\n\t\t\t\t\tcommand: [\"node\", SESSION_TRANSFER_HELPER_ENTRY_PATH],\n\t\t\t\t\tenv: exportHelperEnvironment({\n\t\t\t\t\t\tserverUrl: exporterServerUrl,\n\t\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\t\tcredential: input.credential,\n\t\t\t\t\t}),\n\t\t\t\t\tvolume: { ...input.volume, mountPath: SESSION_TRANSFER_HELPER_MOUNT_PATH },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tnamespace,\n\t\t\t\t\t...(options.pod ?? {}),\n\t\t\t\t\timagePullPolicy: options.exporterImagePullPolicy,\n\t\t\t\t\t...serverCaConfig,\n\t\t\t\t},\n\t\t\t);\n\t\t\tawait client.createPod(manifest);\n\t\t\tconst exit = new Promise<{ exitCode: number | null; reason?: string }>((resolve) => {\n\t\t\t\tclient.onPodExit(podName, namespace, (info) =>\n\t\t\t\t\tresolve({ exitCode: info.exitCode, reason: info.reason }),\n\t\t\t\t);\n\t\t\t});\n\t\t\treturn {\n\t\t\t\twait: () => exit,\n\t\t\t\tremove: () => client.deletePod(podName, namespace, { gracePeriodSeconds: 0 }),\n\t\t\t};\n\t\t},\n\t\tasync reconcileHelpers() {\n\t\t\tconst namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());\n\t\t\tfor (const namespace of namespaces) {\n\t\t\t\tconst helpers = await client.listPods(namespace.name, managedExportHelperLabelSelector());\n\t\t\t\tawait Promise.all(\n\t\t\t\t\thelpers.map((helper) =>\n\t\t\t\t\t\tclient.deletePod(helper.name, helper.namespace, { gracePeriodSeconds: 0 }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t});\n\n\tconst preparationPullSecrets = (options.pod?.imagePullSecrets ?? []).map(\n\t\t(name) =>\n\t\t\toptions.imagePullSecretCopies?.find((copy) => copy.targetName === name)?.sourceName ?? name,\n\t);\n\tlet volumePool: ReturnType<typeof createKubernetesVolumePool> | undefined;\n\tif (options.preProvision) {\n\t\tif (!client.volumePool || !options.volume.storageClassName || !options.serverNamespace) {\n\t\t\tthrow new Error(\"Volume pre-provisioning requires an API, namespace and StorageClass\");\n\t\t}\n\t\tvolumePool = createKubernetesVolumePool({\n\t\t\tapi: client.volumePool,\n\t\t\tnamespace: options.serverNamespace,\n\t\t\tstorageClassName: options.volume.storageClassName,\n\t\t\tsize: options.volume.size,\n\t\t\taccessModes: options.volume.accessModes,\n\t\t\t...options.preProvision,\n\t\t\timage: exporterImage,\n\t\t\timagePullPolicy: options.exporterImagePullPolicy,\n\t\t\timagePullSecrets: preparationPullSecrets,\n\t\t\tnodeSelector: options.pod?.nodeSelector,\n\t\t\ttolerations: options.pod?.tolerations,\n\t\t});\n\t}\n\tlet imagePreload: ReturnType<typeof createKubernetesImagePreload> | undefined;\n\tif (options.imagePreload) {\n\t\tif (!client.imagePreload || !options.serverNamespace)\n\t\t\tthrow new Error(\"Image preloading requires an API and server namespace\");\n\t\timagePreload = createKubernetesImagePreload({\n\t\t\tapi: client.imagePreload,\n\t\t\tnamespace: options.serverNamespace,\n\t\t\t...options.imagePreload,\n\t\t\timagePullSecrets: preparationPullSecrets,\n\t\t\tnodeSelector: options.pod?.nodeSelector,\n\t\t\tadditionalNodeSelectors: options.docker\n\t\t\t\t? [{ ...options.pod?.nodeSelector, ...options.docker.nodeSelector }]\n\t\t\t\t: undefined,\n\t\t\ttolerations: options.pod?.tolerations,\n\t\t});\n\t}\n\tconst controllers = [volumePool, imagePreload].filter((value) => value !== undefined);\n\tconst preparation = controllers.length ? createKubernetesPreparation(controllers) : undefined;\n\treturn { runner, volume, exporter, preparation };\n}\n","import { createHash } from \"node:crypto\";\nimport type {\n\tImagePreloadApi,\n\tImagePreparationPod,\n\tPreparationNode,\n} from \"./kubernetes-image-preload-api.js\";\nimport { buildPreparationPodSpec, createPreparationController } from \"./kubernetes-preparation.js\";\n\nexport const IMAGE_PRELOAD_LABEL = \"leitwerk.dev/image-preload\";\nconst NODE_UID = \"leitwerk.dev/preparation-node-uid\";\nconst NODE_NAME = \"leitwerk.dev/preparation-node-name\";\nconst IMAGE = \"leitwerk.dev/preparation-image\";\nconst INTERVAL = 30_000;\nconst hash = (value: string) => createHash(\"sha256\").update(value).digest(\"hex\");\n\n/** @internal */\nexport interface ImagePreparationEvent {\n\t/** @internal */\n\tcomponent: \"image-preparation\";\n\t/** @internal */\n\toutcome: \"succeeded\" | \"failed\";\n\t/** @internal */\n\tnode?: string;\n\t/** @internal */\n\tnodeUid?: string;\n\t/** @internal */\n\timage?: string;\n\t/** @internal */\n\tpod?: string;\n\t/** @internal */\n\treason?: string;\n}\n\n/** @internal */\nexport function immutableWorkerImage(image: string): string {\n\tconst match = /^([a-zA-Z0-9][a-zA-Z0-9._:/-]*)@(sha256:[0-9a-f]{64})$/.exec(image);\n\tif (!match) throw new Error(\"Image preloading requires digest-qualified worker images\");\n\treturn `${match[1].replace(/:[^/:]+$/, \"\")}@${match[2]}`;\n}\n\n/** @internal */\nexport function eligiblePreparationNode(\n\tnode: PreparationNode,\n\tselector: Record<string, string>,\n\ttolerations: unknown[],\n): boolean {\n\tif (!node.metadata.uid || node.metadata.deletionTimestamp || node.spec?.unschedulable)\n\t\treturn false;\n\tif (\n\t\t!node.status?.conditions?.some(\n\t\t\t(condition) => condition.type === \"Ready\" && condition.status === \"True\",\n\t\t)\n\t)\n\t\treturn false;\n\tif (!Object.entries(selector).every(([key, value]) => node.metadata.labels?.[key] === value))\n\t\treturn false;\n\treturn (node.spec?.taints ?? []).every((taint) => {\n\t\tif (![\"NoSchedule\", \"NoExecute\"].includes(taint.effect)) return true;\n\t\treturn tolerations.some((value) => {\n\t\t\tif (!value || typeof value !== \"object\") return false;\n\t\t\tconst tolerance = value as Record<string, unknown>;\n\t\t\tif (tolerance.effect && tolerance.effect !== taint.effect) return false;\n\t\t\tif (tolerance.operator === \"Exists\") return !tolerance.key || tolerance.key === taint.key;\n\t\t\treturn (\n\t\t\t\t(!tolerance.operator || tolerance.operator === \"Equal\") &&\n\t\t\t\ttolerance.key === taint.key &&\n\t\t\t\t(tolerance.value ?? \"\") === (taint.value ?? \"\")\n\t\t\t);\n\t\t});\n\t});\n}\n\n/** @internal */\nexport function createKubernetesImagePreload(options: {\n\t/** @internal */\n\tapi: ImagePreloadApi;\n\t/** @internal */\n\tnamespace: string;\n\t/** @internal */\n\timages: string[];\n\t/** @internal */\n\timagePullSecrets?: string[];\n\t/** @internal */\n\tnodeSelector?: Record<string, string>;\n\t/** Other worker placements to prepare, deduplicated by node and image. @internal */\n\tadditionalNodeSelectors?: Record<string, string>[];\n\t/** @internal */\n\ttolerations?: unknown[];\n\t/** @internal */\n\tonEvent?: (event: ImagePreparationEvent) => void;\n}) {\n\tconst { api, namespace } = options;\n\tconst nodeSelectors = [options.nodeSelector ?? {}, ...(options.additionalNodeSelectors ?? [])];\n\tconst selectorForNode = (node: PreparationNode) =>\n\t\tnodeSelectors.find((selector) =>\n\t\t\teligiblePreparationNode(node, selector, options.tolerations ?? []),\n\t\t);\n\tconst images = [...new Set(options.images.map(immutableWorkerImage))];\n\tconst preloadId = hash(namespace).slice(0, 16);\n\tconst selector = `${IMAGE_PRELOAD_LABEL}=${preloadId}`;\n\tconst labels = {\n\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t\"leitwerk.dev/component\": \"image-preparation\",\n\t\t[IMAGE_PRELOAD_LABEL]: preloadId,\n\t};\n\tconst podName = (uid: string, image: string) =>\n\t\t`lw-image-${hash(`${uid}/${image}`).slice(0, 40)}`;\n\tconst reported = new Map<string, string>();\n\tconst failedSince = new Map<string, number>();\n\n\tfunction owned(pod: ImagePreparationPod) {\n\t\tconst annotations = pod.metadata.annotations ?? {};\n\t\tconst uid = annotations[NODE_UID];\n\t\tconst name = annotations[NODE_NAME];\n\t\tconst image = annotations[IMAGE];\n\t\tconst containers = pod.spec.containers as\n\t\t\t| Array<{\n\t\t\t\t\t/** @internal */ image?: string /** @internal */;\n\t\t\t\t\tcommand?: string[];\n\t\t\t }>\n\t\t\t| undefined;\n\t\treturn (\n\t\t\tpod.metadata.namespace === namespace &&\n\t\t\t!!pod.metadata.uid &&\n\t\t\t!!uid &&\n\t\t\t!!name &&\n\t\t\t!!image &&\n\t\t\tObject.entries(labels).every(([key, value]) => pod.metadata.labels?.[key] === value) &&\n\t\t\tpod.metadata.name === podName(uid, image) &&\n\t\t\tpod.metadata.ownerReferences?.some(\n\t\t\t\t(owner) =>\n\t\t\t\t\towner.apiVersion === \"v1\" &&\n\t\t\t\t\towner.kind === \"Node\" &&\n\t\t\t\t\towner.name === name &&\n\t\t\t\t\towner.uid === uid,\n\t\t\t) &&\n\t\t\tpod.spec.nodeName === name &&\n\t\t\tpod.spec.automountServiceAccountToken === false &&\n\t\t\tcontainers?.length === 1 &&\n\t\t\tcontainers[0].image === image &&\n\t\t\tJSON.stringify(containers[0].command) === JSON.stringify([\"node\", \"-e\", \"process.exit(0)\"])\n\t\t);\n\t}\n\tfunction report(\n\t\tpod: ImagePreparationPod,\n\t\toutcome: ImagePreparationEvent[\"outcome\"],\n\t\treason?: string,\n\t) {\n\t\tconst uid = pod.metadata.uid ?? pod.metadata.name;\n\t\tconst state = `${outcome}/${reason ?? \"\"}`;\n\t\tif (reported.get(uid) === state) return;\n\t\treported.set(uid, state);\n\t\toptions.onEvent?.({\n\t\t\tcomponent: \"image-preparation\",\n\t\t\toutcome,\n\t\t\treason,\n\t\t\tpod: pod.metadata.name,\n\t\t\tnode: pod.metadata.annotations?.[NODE_NAME],\n\t\t\tnodeUid: pod.metadata.annotations?.[NODE_UID],\n\t\t\timage: pod.metadata.annotations?.[IMAGE],\n\t\t});\n\t}\n\tfunction manifest(\n\t\tnode: PreparationNode,\n\t\timage: string,\n\t\tnodeSelector: Record<string, string>,\n\t): ImagePreparationPod {\n\t\tconst uid = node.metadata.uid ?? \"\";\n\t\treturn {\n\t\t\tapiVersion: \"v1\",\n\t\t\tkind: \"Pod\",\n\t\t\tmetadata: {\n\t\t\t\tname: podName(uid, image),\n\t\t\t\tnamespace,\n\t\t\t\tlabels,\n\t\t\t\tannotations: { [NODE_UID]: uid, [NODE_NAME]: node.metadata.name, [IMAGE]: image },\n\t\t\t\townerReferences: [{ apiVersion: \"v1\", kind: \"Node\", name: node.metadata.name, uid }],\n\t\t\t},\n\t\t\tspec: {\n\t\t\t\t...buildPreparationPodSpec({\n\t\t\t\t\t...options,\n\t\t\t\t\timage,\n\t\t\t\t\timagePullPolicy: \"IfNotPresent\",\n\t\t\t\t\tnodeSelector: { ...nodeSelector },\n\t\t\t\t}),\n\t\t\t\tnodeName: node.metadata.name,\n\t\t\t\tsecurityContext: {\n\t\t\t\t\trunAsNonRoot: true,\n\t\t\t\t\trunAsUser: 1000,\n\t\t\t\t\trunAsGroup: 1000,\n\t\t\t\t\tseccompProfile: { type: \"RuntimeDefault\" },\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\t/** @internal */\n\tasync function reconcile(signal: AbortSignal) {\n\t\tconst nodes = await api.listNodes(signal);\n\t\tconst desired = new Map<string, ImagePreparationPod>();\n\t\tfor (const node of nodes) {\n\t\t\tconst nodeSelector = selectorForNode(node);\n\t\t\tif (!nodeSelector) continue;\n\t\t\tfor (const image of images) {\n\t\t\t\tconst pod = manifest(node, image, nodeSelector);\n\t\t\t\tdesired.set(pod.metadata.name, pod);\n\t\t\t}\n\t\t}\n\t\tconst pods = await api.listPods(namespace, selector, signal);\n\t\tfor (const pod of pods) {\n\t\t\tif (desired.has(pod.metadata.name) || !owned(pod) || pod.metadata.deletionTimestamp) continue;\n\t\t\ttry {\n\t\t\t\tawait api.deletePod(namespace, pod, signal);\n\t\t\t} catch {\n\t\t\t\tif (!signal.aborted) report(pod, \"failed\", \"cleanup_failed\");\n\t\t\t}\n\t\t}\n\t\tconst liveUids = new Set(pods.map((pod) => pod.metadata.uid ?? \"\"));\n\t\tfor (const uid of reported.keys())\n\t\t\tif (!liveUids.has(uid)) {\n\t\t\t\treported.delete(uid);\n\t\t\t\tfailedSince.delete(uid);\n\t\t\t}\n\t\tfor (const expected of desired.values()) {\n\t\t\ttry {\n\t\t\t\tconst pod =\n\t\t\t\t\tpods.find((value) => value.metadata.name === expected.metadata.name) ??\n\t\t\t\t\t(await api.getPod(namespace, expected.metadata.name, signal));\n\t\t\t\tif (!pod) {\n\t\t\t\t\tawait api.createPod(namespace, expected, signal);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!owned(pod)) {\n\t\t\t\t\treport(expected, \"failed\", \"ownership_mismatch\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (pod.metadata.deletionTimestamp) continue;\n\t\t\t\tif (pod.status?.phase === \"Succeeded\") {\n\t\t\t\t\treport(pod, \"succeeded\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (pod.status?.phase === \"Failed\") {\n\t\t\t\t\treport(pod, \"failed\", \"pod_failed\");\n\t\t\t\t\tconst uid = pod.metadata.uid ?? \"\";\n\t\t\t\t\tconst finished = Date.parse(\n\t\t\t\t\t\tpod.status.containerStatuses?.[0]?.state?.terminated?.finishedAt ?? \"\",\n\t\t\t\t\t);\n\t\t\t\t\tconst since = failedSince.get(uid) ?? (Number.isFinite(finished) ? finished : Date.now());\n\t\t\t\t\tfailedSince.set(uid, since);\n\t\t\t\t\tif (Date.now() - since >= INTERVAL) {\n\t\t\t\t\t\tawait api.deletePod(namespace, pod, signal);\n\t\t\t\t\t\tawait api.createPod(namespace, expected, signal);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reason = pod.status?.containerStatuses?.[0]?.state?.waiting?.reason;\n\t\t\t\tif (\n\t\t\t\t\treason === \"ErrImagePull\" ||\n\t\t\t\t\treason === \"ImagePullBackOff\" ||\n\t\t\t\t\treason === \"InvalidImageName\"\n\t\t\t\t)\n\t\t\t\t\treport(pod, \"failed\", reason);\n\t\t\t} catch {\n\t\t\t\tif (!signal.aborted) report(expected, \"failed\", \"api_error\");\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\t/** @internal */\n\t\treconcile,\n\t\t...createPreparationController(reconcile, INTERVAL, () =>\n\t\t\toptions.onEvent?.({\n\t\t\t\tcomponent: \"image-preparation\",\n\t\t\t\toutcome: \"failed\",\n\t\t\t\treason: \"discovery_failed\",\n\t\t\t}),\n\t\t),\n\t};\n}\n","import { setTimeout as delay } from \"node:timers/promises\";\nimport type { VolumePoolOptions } from \"./kubernetes-volume-pool.js\";\nimport type { PoolObject } from \"./kubernetes-volume-pool-api.js\";\n\n/** Shared inert preparation workload; callers supply ownership and placement constraints. @internal */\nexport function buildPreparationPodSpec(\n\toptions: Pick<\n\t\tVolumePoolOptions,\n\t\t\"image\" | \"imagePullPolicy\" | \"imagePullSecrets\" | \"nodeSelector\" | \"tolerations\"\n\t>,\n\tvolumeMounts?: unknown[],\n): PoolObject[\"spec\"] {\n\treturn {\n\t\trestartPolicy: \"Never\",\n\t\tserviceAccountName: \"default\",\n\t\tautomountServiceAccountToken: false,\n\t\tnodeSelector: options.nodeSelector ?? {},\n\t\ttolerations: options.tolerations ?? [],\n\t\timagePullSecrets: (options.imagePullSecrets ?? []).map((name) => ({ name })),\n\t\tcontainers: [\n\t\t\t{\n\t\t\t\tname: \"prepare\",\n\t\t\t\timage: options.image,\n\t\t\t\timagePullPolicy: options.imagePullPolicy ?? \"IfNotPresent\",\n\t\t\t\tcommand: [\"node\", \"-e\", \"process.exit(0)\"],\n\t\t\t\tresources: {\n\t\t\t\t\trequests: { cpu: \"1m\", memory: \"32Mi\" },\n\t\t\t\t\tlimits: { cpu: \"100m\", memory: \"64Mi\" },\n\t\t\t\t},\n\t\t\t\tsecurityContext: {\n\t\t\t\t\tallowPrivilegeEscalation: false,\n\t\t\t\t\treadOnlyRootFilesystem: true,\n\t\t\t\t\tcapabilities: { drop: [\"ALL\"] },\n\t\t\t\t},\n\t\t\t\t...(volumeMounts ? { volumeMounts } : {}),\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** @internal */\nexport interface PreparationController {\n\t/** @internal */\n\tstart(): void;\n\t/** @internal */\n\tstop(): Promise<void>;\n}\n\n/** One non-overlapping loop; stopping cancels and joins its current work. @internal */\nexport function createPreparationController(\n\treconcile: (signal: AbortSignal) => Promise<void>,\n\tintervalMs: number,\n\tonError?: (error?: unknown) => void,\n\terrorIntervalMs = intervalMs,\n): PreparationController {\n\tlet controller: AbortController | undefined;\n\tlet running: Promise<void> | undefined;\n\treturn {\n\t\tstart() {\n\t\t\tif (controller) return;\n\t\t\tcontroller = new AbortController();\n\t\t\tconst { signal } = controller;\n\t\t\trunning = (async () => {\n\t\t\t\twhile (!signal.aborted) {\n\t\t\t\t\tlet interval = intervalMs;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait reconcile(signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinterval = errorIntervalMs;\n\t\t\t\t\t\tif (!signal.aborted) onError?.(error);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait delay(interval, undefined, { signal });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\t\tasync stop() {\n\t\t\tcontroller?.abort();\n\t\t\tawait running;\n\t\t\tcontroller = undefined;\n\t\t},\n\t};\n}\n\n/** Controllers own separate asynchronous reconciliation loops. @internal */\nexport function createKubernetesPreparation(controllers: PreparationController[]) {\n\treturn {\n\t\t/** @internal */\n\t\tstart() {\n\t\t\tfor (const controller of controllers) controller.start();\n\t\t},\n\t\t/** @internal */\n\t\tasync stop() {\n\t\t\tawait Promise.allSettled(controllers.map((controller) => controller.stop()));\n\t\t},\n\t};\n}\n","import type { StartupMilestone, StartupObservation } from \"@leitwerk-dev/domain\";\nimport type { KubernetesApiClient } from \"./kubernetes-api-client.js\";\nimport type { WorkerStartObserver } from \"./types.js\";\nimport { parseWorkerUnitIdentity } from \"./worker-labels.js\";\nexport function startupReceipt(\n\tobserver: WorkerStartObserver | undefined,\n\tmilestone: StartupMilestone,\n\tmetadata: StartupObservation[\"metadata\"] = {},\n): void {\n\ttry {\n\t\tobserver?.observe?.({\n\t\t\tmilestone,\n\t\t\tobservedAt: new Date().toISOString(),\n\t\t\tsourceAt: null,\n\t\t\tsourceKind: \"server\",\n\t\t\tobjectUid: null,\n\t\t\tnotBefore: null,\n\t\t\tmetadata,\n\t\t});\n\t} catch {\n\t\t/* Observation cannot fail startup. */\n\t}\n}\n/** One asynchronous collection cycle per physical worker. Never awaited by lifecycle work. */\nexport function sampleKubernetesStartup(\n\tclient: KubernetesApiClient,\n\tobserver: WorkerStartObserver,\n\tnamespace: string,\n\tpvcName: string,\n) {\n\tlet pod: { name: string; workerId: string; instanceId: string } | undefined;\n\tlet podUid: string | undefined;\n\tlet pvcUid: string | undefined;\n\tlet lastUnbound: string | null = null;\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet active: AbortController | undefined;\n\tlet failures = 0;\n\tconst seen = new Set<StartupMilestone>();\n\tconst deadline = Date.now() + 120_000;\n\tconst emit = (\n\t\tmilestone: StartupMilestone,\n\t\tobjectUid: string,\n\t\tsourceAt: string | null,\n\t\tmetadata: StartupObservation[\"metadata\"],\n\t\tsourceKind: StartupObservation[\"sourceKind\"] = \"kubernetes_status\",\n\t\tnotBefore: string | null = null,\n\t) => {\n\t\tif (\n\t\t\tstopped ||\n\t\t\tseen.has(milestone) ||\n\t\t\t(sourceAt !== null && !Number.isFinite(Date.parse(sourceAt)))\n\t\t)\n\t\t\treturn;\n\t\tobserver.observe?.({\n\t\t\tmilestone,\n\t\t\tobservedAt: new Date().toISOString(),\n\t\t\tsourceAt,\n\t\t\tobjectUid,\n\t\t\tsourceKind,\n\t\t\tnotBefore,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\t...(sourceAt !== null ? { precision: sourcePrecision(sourceAt) } : {}),\n\t\t\t},\n\t\t});\n\t\tseen.add(milestone);\n\t};\n\tconst stop = () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tactive?.abort();\n\t};\n\tconst reportFailure = () => {\n\t\tif (!stopped && failures++ < 3)\n\t\t\tconsole.warn(\"Worker startup observation unavailable: Kubernetes collection failed\");\n\t};\n\tconst cycle = async () => {\n\t\tif (stopped || observer.shouldStop?.() || Date.now() >= deadline) {\n\t\t\tstop();\n\t\t\treturn;\n\t\t}\n\t\tactive = new AbortController();\n\t\tconst timeout = setTimeout(() => active?.abort(), 1500);\n\t\tconst signal = active.signal;\n\t\tconst collectPvc = async () => {\n\t\t\tif (!seen.has(\"pvc_bound\") && client.getPersistentVolumeClaim) {\n\t\t\t\tconst pvc = await client.getPersistentVolumeClaim(pvcName, namespace, { signal });\n\t\t\t\tif (pvc?.uid) {\n\t\t\t\t\tif (pvcUid && pvcUid !== pvc.uid) {\n\t\t\t\t\t\tstop();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpvcUid = pvc.uid;\n\t\t\t\t\tif (pvc.phase === \"Bound\")\n\t\t\t\t\t\temit(\n\t\t\t\t\t\t\t\"pvc_bound\",\n\t\t\t\t\t\t\tpvc.uid,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{ storageClass: pvc.storageClass, precision: \"sampling_interval\" },\n\t\t\t\t\t\t\t\"kubernetes_status\",\n\t\t\t\t\t\t\tlastUnbound,\n\t\t\t\t\t\t);\n\t\t\t\t\telse lastUnbound = new Date().toISOString();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tconst collectPod = async () => {\n\t\t\tif (pod) {\n\t\t\t\tconst summary = await client.getPod(pod.name, namespace, { signal });\n\t\t\t\tif (!summary) {\n\t\t\t\t\tstop();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst identity = parseWorkerUnitIdentity(summary.labels);\n\t\t\t\tif (\n\t\t\t\t\t!identity ||\n\t\t\t\t\tidentity.workerId !== pod.workerId ||\n\t\t\t\t\tidentity.instanceId !== pod.instanceId ||\n\t\t\t\t\t(podUid && podUid !== summary.uid)\n\t\t\t\t) {\n\t\t\t\t\tstop();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (summary.uid) {\n\t\t\t\t\tpodUid = summary.uid;\n\t\t\t\t\tconst metadata = {\n\t\t\t\t\t\tnode: summary.node,\n\t\t\t\t\t\timageId: summary.imageId,\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tpodName: pod.name,\n\t\t\t\t\t\t...summary.resources,\n\t\t\t\t\t};\n\t\t\t\t\tif (summary.createdAt) emit(\"pod_created\", podUid, summary.createdAt, metadata);\n\t\t\t\t\tif (summary.scheduledAt) emit(\"pod_scheduled\", podUid, summary.scheduledAt, metadata);\n\t\t\t\t\tif (summary.containerStartedAt)\n\t\t\t\t\t\temit(\"container_started\", podUid, summary.containerStartedAt, metadata);\n\t\t\t\t\tconst events = await client.listPodEvents(pod.name, namespace, { signal });\n\t\t\t\t\tfor (const event of events) {\n\t\t\t\t\t\tif (event.objectUid !== podUid || event.fieldPath !== \"spec.containers{worker}\")\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tconst at = event.eventTime || event.firstTimestamp;\n\t\t\t\t\t\tif (!at) continue;\n\t\t\t\t\t\tif (event.reason === \"Pulling\")\n\t\t\t\t\t\t\temit(\"image_pull_started\", podUid, at, metadata, \"kubernetes_event\");\n\t\t\t\t\t\tif (event.reason === \"Pulled\")\n\t\t\t\t\t\t\temit(\n\t\t\t\t\t\t\t\tevent.message?.includes(\"already present\") ? \"image_cached\" : \"image_pull_finished\",\n\t\t\t\t\t\t\t\tpodUid,\n\t\t\t\t\t\t\t\tat,\n\t\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t\t\t\"kubernetes_event\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (summary.phase === \"Failed\" || summary.phase === \"Succeeded\") stop();\n\t\t\t}\n\t\t};\n\t\ttry {\n\t\t\tawait Promise.all([collectPvc().catch(reportFailure), collectPod().catch(reportFailure)]);\n\t\t\tif (\n\t\t\t\tseen.has(\"container_started\") &&\n\t\t\t\tseen.has(\"pod_scheduled\") &&\n\t\t\t\tseen.has(\"pvc_bound\") &&\n\t\t\t\t(seen.has(\"image_cached\") ||\n\t\t\t\t\t(seen.has(\"image_pull_started\") && seen.has(\"image_pull_finished\")))\n\t\t\t)\n\t\t\t\tstop();\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tactive = undefined;\n\t\t\tif (!stopped) {\n\t\t\t\ttimer = setTimeout(() => void cycle(), 250);\n\t\t\t\ttimer.unref?.();\n\t\t\t}\n\t\t}\n\t};\n\ttimer = setTimeout(() => void cycle(), 0);\n\ttimer.unref?.();\n\treturn {\n\t\tstop,\n\t\tattachPod(input: NonNullable<typeof pod>) {\n\t\t\tpod = input;\n\t\t},\n\t};\n}\n\nfunction sourcePrecision(timestamp: string): \"seconds\" | \"milliseconds\" | \"microseconds\" {\n\tconst digits = /\\.(\\d+)/.exec(timestamp)?.[1].length ?? 0;\n\treturn digits === 0 ? \"seconds\" : digits <= 3 ? \"milliseconds\" : \"microseconds\";\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { buildPreparationPodSpec, createPreparationController } from \"./kubernetes-preparation.js\";\nimport type { PoolObject, VolumePoolApi } from \"./kubernetes-volume-pool-api.js\";\n\nexport const POOL_LABEL = \"leitwerk.dev/volume-pool\";\nconst CLAIM_UID = \"leitwerk.dev/preparation-claim-uid\";\nconst CLAIM_NAME = \"leitwerk.dev/preparation-claim-name\";\nconst POLICY = \"leitwerk.dev/original-reclaim-policy\";\nconst TARGET_CLASS = \"leitwerk.dev/target-storage-class\";\nconst STATE = \"leitwerk.dev/volume-pool-state\";\nconst SIZE = \"leitwerk.dev/preparation-size\";\nconst MODES = \"leitwerk.dev/preparation-access-modes\";\n\n/** @internal */\nexport interface VolumePoolOptions {\n\t/** @internal */\n\tapi: VolumePoolApi;\n\t/** @internal */\n\tnamespace: string;\n\t/** @internal */\n\tcount: number;\n\t/** @internal */\n\tstorageClassName: string;\n\t/** @internal */\n\tsize: string;\n\t/** @internal */\n\taccessModes: string[];\n\t/** @internal */\n\timage: string;\n\t/** @internal */\n\timagePullPolicy?: string;\n\t/** @internal */\n\timagePullSecrets?: string[];\n\t/** @internal */\n\tnodeSelector?: Record<string, string>;\n\t/** @internal */\n\ttolerations?: unknown[];\n\t/** @internal */\n\tonError?: (error?: unknown) => void;\n\t/** Clock seam; Kubernetes creation times survive controller restarts. @internal */\n\tnow?: () => number;\n}\n\n/** Only the staging claim's UID authorizes rebinding; process claims are never recycled. @internal */\nexport function createKubernetesVolumePool(options: VolumePoolOptions) {\n\tconst { api, namespace } = options;\n\tif (!Number.isSafeInteger(options.count) || options.count < 0)\n\t\tthrow new Error(\"Invalid volume pool count\");\n\tconst poolId = createHash(\"sha256\")\n\t\t.update(`${namespace}/${options.storageClassName}`)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 16);\n\tconst selector = `${POOL_LABEL}=${poolId}`;\n\tconst labels = {\n\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t[POOL_LABEL]: poolId,\n\t\t\"leitwerk.dev/component\": \"volume-preparation\",\n\t};\n\n\tfunction preparationPod(claim: PoolObject): PoolObject {\n\t\treturn {\n\t\t\tapiVersion: \"v1\",\n\t\t\tkind: \"Pod\",\n\t\t\tmetadata: {\n\t\t\t\tname: claim.metadata.name,\n\t\t\t\tnamespace,\n\t\t\t\tlabels,\n\t\t\t\townerReferences: [\n\t\t\t\t\t{\n\t\t\t\t\t\tapiVersion: \"v1\",\n\t\t\t\t\t\tkind: \"PersistentVolumeClaim\",\n\t\t\t\t\t\tname: claim.metadata.name,\n\t\t\t\t\t\tuid: claim.metadata.uid ?? \"\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tspec: {\n\t\t\t\t...buildPreparationPodSpec(options, [{ name: \"volume\", mountPath: \"/volume\" }]),\n\t\t\t\tactiveDeadlineSeconds: 900,\n\t\t\t\tvolumes: [{ name: \"volume\", persistentVolumeClaim: { claimName: claim.metadata.name } }],\n\t\t\t},\n\t\t};\n\t}\n\n\tasync function advanceVolume(pv: PoolObject, signal: AbortSignal): Promise<boolean> {\n\t\tconst annotations = pv.metadata.annotations ?? {};\n\t\tconst uid = annotations[CLAIM_UID];\n\t\tconst name = annotations[CLAIM_NAME];\n\t\tconst policy = annotations[POLICY];\n\t\tif (!uid || !name || ![\"Delete\", \"Retain\"].includes(policy))\n\t\t\tthrow new Error(\"Invalid prepared-volume ownership\");\n\t\tif (pv.metadata.deletionTimestamp) return false;\n\t\tconst claim = pv.spec.claimRef;\n\t\tif (claim && claim.uid !== uid) {\n\t\t\t// A process has consumed this PV, including if it was already released again.\n\t\t\tconst remainingLabels = { ...pv.metadata.labels };\n\t\t\tdelete remainingLabels[POOL_LABEL];\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: policy },\n\t\t\t\t\t{ op: \"add\", path: \"/metadata/labels\", value: remainingLabels },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tif (claim) {\n\t\t\tif (pv.spec.persistentVolumeReclaimPolicy !== \"Retain\")\n\t\t\t\tthrow new Error(\"Staging PV must be retained before release\");\n\t\t\tconst pod = await api.get(\"pods\", namespace, name, signal);\n\t\t\tif (pod) {\n\t\t\t\tif (\n\t\t\t\t\tpod.metadata.labels?.[POOL_LABEL] !== poolId ||\n\t\t\t\t\t!pod.metadata.ownerReferences?.some((owner) => owner.uid === uid)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Preparation Pod ownership mismatch\");\n\t\t\t\tawait api.delete(\"pods\", namespace, pod, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst pvc = await api.get(\"persistentvolumeclaims\", namespace, name, signal);\n\t\t\tif (pvc) {\n\t\t\t\tif (pvc.metadata.uid !== uid) throw new Error(\"Preparation PVC ownership mismatch\");\n\t\t\t\tawait api.delete(\"persistentvolumeclaims\", namespace, pvc, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (pv.status?.phase === \"Released\") {\n\t\t\t\tawait api.patchVolume(\n\t\t\t\t\tpv,\n\t\t\t\t\t[\n\t\t\t\t\t\t{ op: \"test\", path: \"/spec/claimRef/uid\", value: uid },\n\t\t\t\t\t\t{ op: \"remove\", path: \"/spec/claimRef\" },\n\t\t\t\t\t],\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\t// Never restore Delete while the old Released status remains: a provisioner could reclaim it.\n\t\tif (pv.status?.phase === \"Available\" && annotations[STATE] !== \"ready\") {\n\t\t\tconst stagingClass = await api.getStorageClass(name, signal);\n\t\t\tif (stagingClass) {\n\t\t\t\tif (stagingClass.metadata.labels?.[POOL_LABEL] !== poolId)\n\t\t\t\t\tthrow new Error(\"Staging StorageClass ownership mismatch\");\n\t\t\t\tawait api.deleteStorageClass(stagingClass, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst targetClass = annotations[TARGET_CLASS];\n\t\t\tif (!targetClass) throw new Error(\"Target StorageClass is missing\");\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: policy },\n\t\t\t\t\t{ op: \"add\", path: \"/spec/storageClassName\", value: targetClass },\n\t\t\t\t\t{ op: \"add\", path: \"/metadata/annotations\", value: { ...annotations, [STATE]: \"ready\" } },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\tannotations[STATE] !== \"ready\" ||\n\t\t\t(annotations[SIZE] === options.size &&\n\t\t\t\tannotations[MODES] === JSON.stringify(options.accessModes))\n\t\t);\n\t}\n\n\t/** @internal */\n\tasync function reconcile(signal: AbortSignal) {\n\t\tconst volumes = await api.list(\"persistentvolumes\", \"\", selector, signal);\n\t\tconst classes = await api.listStorageClasses(selector, signal);\n\t\tconst active = new Set<string>(classes.map((value) => value.metadata.name));\n\t\tfor (const pv of volumes) {\n\t\t\tif (await advanceVolume(pv, signal)) active.add(pv.metadata.annotations?.[CLAIM_NAME] ?? \"\");\n\t\t}\n\t\tconst failures: string[] = [];\n\t\tconst claims = await api.list(\"persistentvolumeclaims\", namespace, selector, signal);\n\t\tfor (const claim of claims) {\n\t\t\tactive.add(claim.metadata.name);\n\t\t\tif (!claim.metadata.uid || claim.spec.storageClassName !== claim.metadata.name)\n\t\t\t\tthrow new Error(\"Invalid staging PVC identity\");\n\t\t\tif (\n\t\t\t\tclaim.metadata.deletionTimestamp ||\n\t\t\t\tvolumes.some((pv) => pv.metadata.annotations?.[CLAIM_UID] === claim.metadata.uid)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tconst pod = await api.get(\"pods\", namespace, claim.metadata.name, signal);\n\t\t\tif (!pod) {\n\t\t\t\tawait api.create(\"pods\", namespace, preparationPod(claim), signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tpod.metadata.labels?.[POOL_LABEL] !== poolId ||\n\t\t\t\t!pod.metadata.ownerReferences?.some((owner) => owner.uid === claim.metadata.uid)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Preparation Pod ownership mismatch\");\n\t\t\tconst created = Date.parse(claim.metadata.creationTimestamp ?? \"\");\n\t\t\tconst ageSeconds = Number.isFinite(created)\n\t\t\t\t? Math.max(0, Math.floor(((options.now?.() ?? Date.now()) - created) / 1_000))\n\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\tpod.status?.phase === \"Failed\" ||\n\t\t\t\t(pod.status?.phase !== \"Succeeded\" && ageSeconds !== undefined && ageSeconds >= 900)\n\t\t\t) {\n\t\t\t\t// Keep the failed receipt and reservation across restarts. An operator retries\n\t\t\t\t// the same PVC by deleting its Pod only after fixing storage; never allocate\n\t\t\t\t// another volume to work around replica scheduling or attach failures.\n\t\t\t\tfailures.push(\n\t\t\t\t\t`${namespace}/${pod.metadata.name}: age=${ageSeconds ?? \"unknown\"}s phase=${pod.status?.phase ?? \"unknown\"} reason=${pod.status?.reason ?? pod.status?.conditions?.find((condition) => condition.status === \"False\")?.reason ?? \"inspect Pod events and CSI/Longhorn scheduling conditions\"}`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (pod.status?.phase !== \"Succeeded\" || !claim.spec.volumeName) continue;\n\t\t\tconst pv = await api.get(\"persistentvolumes\", \"\", claim.spec.volumeName, signal);\n\t\t\tif (\n\t\t\t\t!pv ||\n\t\t\t\tpv.spec.claimRef?.uid !== claim.metadata.uid ||\n\t\t\t\tpv.metadata.ownerReferences?.length ||\n\t\t\t\tpv.metadata.deletionTimestamp\n\t\t\t)\n\t\t\t\tthrow new Error(\"Cannot safely retain staging volume\");\n\t\t\tif (pv.metadata.labels?.[POOL_LABEL]) throw new Error(\"PV already belongs to a pool\");\n\t\t\tconst policy = pv.spec.persistentVolumeReclaimPolicy;\n\t\t\tif (!policy || ![\"Delete\", \"Retain\"].includes(policy))\n\t\t\t\tthrow new Error(\"Unsupported reclaim policy\");\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/metadata/labels\",\n\t\t\t\t\t\tvalue: { ...pv.metadata.labels, [POOL_LABEL]: poolId },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/metadata/annotations\",\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\t...pv.metadata.annotations,\n\t\t\t\t\t\t\t[CLAIM_UID]: claim.metadata.uid,\n\t\t\t\t\t\t\t[CLAIM_NAME]: claim.metadata.name,\n\t\t\t\t\t\t\t[POLICY]: policy,\n\t\t\t\t\t\t\t[STATE]: \"preparing\",\n\t\t\t\t\t\t\t\"leitwerk.dev/preparation-pod-uid\": pod.metadata.uid ?? \"\",\n\t\t\t\t\t\t\t\"leitwerk.dev/preparation-image\": options.image,\n\t\t\t\t\t\t\t\"leitwerk.dev/preparation-completed-at\": new Date(\n\t\t\t\t\t\t\t\toptions.now?.() ?? Date.now(),\n\t\t\t\t\t\t\t).toISOString(),\n\t\t\t\t\t\t\t[TARGET_CLASS]: options.storageClassName,\n\t\t\t\t\t\t\t[SIZE]: claim.metadata.annotations?.[SIZE],\n\t\t\t\t\t\t\t[MODES]: claim.metadata.annotations?.[MODES],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: \"Retain\" },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\tfor (const stagingClass of classes) {\n\t\t\tconst name = stagingClass.metadata.name;\n\t\t\tif (\n\t\t\t\tstagingClass.metadata.deletionTimestamp ||\n\t\t\t\tclaims.some((claim) => claim.metadata.name === name) ||\n\t\t\t\tvolumes.some((pv) => pv.metadata.annotations?.[CLAIM_NAME] === name)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tawait api.create(\n\t\t\t\t\"persistentvolumeclaims\",\n\t\t\t\tnamespace,\n\t\t\t\t{\n\t\t\t\t\tapiVersion: \"v1\",\n\t\t\t\t\tkind: \"PersistentVolumeClaim\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tlabels,\n\t\t\t\t\t\tannotations: {\n\t\t\t\t\t\t\t[SIZE]: stagingClass.metadata.annotations?.[SIZE] ?? \"\",\n\t\t\t\t\t\t\t[MODES]: stagingClass.metadata.annotations?.[MODES] ?? \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tspec: {\n\t\t\t\t\t\tstorageClassName: name,\n\t\t\t\t\t\taccessModes: JSON.parse(stagingClass.metadata.annotations?.[MODES] ?? \"null\"),\n\t\t\t\t\t\tvolumeMode: \"Filesystem\",\n\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\trequests: {\n\t\t\t\t\t\t\t\tstorage: stagingClass.metadata.annotations?.[SIZE],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\tif (active.size < options.count) {\n\t\t\tconst source = await api.getStorageClass(options.storageClassName, signal);\n\t\t\tif (!source || [\"kubernetes.io/no-provisioner\", \"manual\"].includes(source.provisioner))\n\t\t\t\tthrow new Error(\"Volume pre-provisioning requires a dynamic StorageClass\");\n\t\t\tfor (let i = active.size; i < options.count; i++) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t// A unique staging class prevents preparation PVCs from consuming the ready pool.\n\t\t\t\tawait api.createStorageClass(\n\t\t\t\t\t{\n\t\t\t\t\t\tapiVersion: \"storage.k8s.io/v1\",\n\t\t\t\t\t\tkind: \"StorageClass\",\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tname: `lw-volume-${randomUUID()}`,\n\t\t\t\t\t\t\tlabels,\n\t\t\t\t\t\t\tannotations: {\n\t\t\t\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\t\t\t\tObject.entries(source.metadata.annotations ?? {}).filter(\n\t\t\t\t\t\t\t\t\t\t([key]) =>\n\t\t\t\t\t\t\t\t\t\t\t![\n\t\t\t\t\t\t\t\t\t\t\t\t\"storageclass.kubernetes.io/is-default-class\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"storageclass.beta.kubernetes.io/is-default-class\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"kubectl.kubernetes.io/last-applied-configuration\",\n\t\t\t\t\t\t\t\t\t\t\t].includes(key),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t[SIZE]: options.size,\n\t\t\t\t\t\t\t\t[MODES]: JSON.stringify(options.accessModes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprovisioner: source.provisioner,\n\t\t\t\t\t\tparameters: source.parameters,\n\t\t\t\t\t\treclaimPolicy: source.reclaimPolicy,\n\t\t\t\t\t\tmountOptions: source.mountOptions,\n\t\t\t\t\t\tallowVolumeExpansion: source.allowVolumeExpansion,\n\t\t\t\t\t\tvolumeBindingMode: source.volumeBindingMode,\n\t\t\t\t\t\tallowedTopologies: source.allowedTopologies,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (failures.length) throw new Error(`Volume pool preparation blocked: ${failures.join(\"; \")}`);\n\t}\n\n\treturn {\n\t\t/** @internal */\n\t\tpoolId,\n\t\t/** @internal */\n\t\treconcile,\n\t\t...createPreparationController(reconcile, 2_000, options.onError, 30_000),\n\t};\n}\n","import { POOL_LABEL } from \"./kubernetes-volume-pool.js\";\nimport type { VolumePoolApi } from \"./kubernetes-volume-pool-api.js\";\nimport type { ProcessVolumeReclamation } from \"./types.js\";\n\n/** Persist ownership and any terminal disposal authorization before PVC deletion. @internal */\nexport async function retireKubernetesProcessVolume(input: {\n\t/** @internal */\n\tapi: VolumePoolApi;\n\t/** @internal */\n\tnamespace: string;\n\t/** @internal */\n\tname: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tsignal: AbortSignal;\n\t/** @internal */\n\treason?: \"retention-expired\" | \"process-deleted\";\n\t/** @internal */\n\treclaimBackingStorage?: ProcessVolumeReclamation | \"process-deleted\";\n}): Promise<void> {\n\tconst { api, namespace, name, instanceId, signal } = input;\n\tconst reclamation = input.reclaimBackingStorage;\n\tif (\n\t\ttypeof reclamation === \"object\" &&\n\t\t(![\"completed\", \"aborted\"].includes(reclamation.lifecycleStatus) ||\n\t\t\t!Number.isFinite(Date.parse(reclamation.closedAt)) ||\n\t\t\tDate.parse(reclamation.closedAt) > Date.now())\n\t)\n\t\tthrow new Error(\"Backing-storage reclamation requires a closed terminal process\");\n\tif (reclamation === \"process-deleted\" && input.reason !== \"process-deleted\")\n\t\tthrow new Error(\"Explicit storage deletion requires a process deletion request\");\n\tconst pvc = await api.get(\"persistentvolumeclaims\", namespace, name, signal);\n\tif (!pvc) return;\n\tconst labels = pvc.metadata.labels;\n\tif (\n\t\t!pvc.metadata.uid ||\n\t\tlabels?.[\"leitwerk.dev/managed-by\"] !== \"leitwerk\" ||\n\t\tlabels[\"leitwerk.dev/component\"] !== \"process-volume\" ||\n\t\tlabels[\"leitwerk.dev/instance-id\"] !== instanceId ||\n\t\tpvc.metadata.ownerReferences?.length\n\t)\n\t\tthrow new Error(\"Cannot retire a foreign or ambiguous process PVC\");\n\tif (reclamation && !pvc.spec.volumeName)\n\t\tthrow new Error(\n\t\t\t\"PVC is still provisioning; preserve its identity until the backing PV can be audited\",\n\t\t);\n\tconst pods = await api.list(\"pods\", namespace, \"\", signal);\n\tif (\n\t\tpods.some(\n\t\t\t(pod) =>\n\t\t\t\t![\"Succeeded\", \"Failed\"].includes(pod.status?.phase ?? \"\") &&\n\t\t\t\tArray.isArray(pod.spec.volumes) &&\n\t\t\t\tpod.spec.volumes.some(\n\t\t\t\t\t(volume) =>\n\t\t\t\t\t\t(volume as { persistentVolumeClaim?: { claimName?: string } }).persistentVolumeClaim\n\t\t\t\t\t\t\t?.claimName === name,\n\t\t\t\t),\n\t\t)\n\t)\n\t\tthrow new Error(\"Cannot retire a process volume referenced by a live Pod\");\n\tif (pvc.spec.volumeName) {\n\t\tconst pv = await api.get(\"persistentvolumes\", \"\", pvc.spec.volumeName, signal);\n\t\tif (\n\t\t\t!pv ||\n\t\t\t(pv.metadata.labels?.[\"leitwerk.dev/managed-by\"] !== undefined &&\n\t\t\t\tpv.metadata.labels[\"leitwerk.dev/managed-by\"] !== \"leitwerk\") ||\n\t\t\t(pv.metadata.labels?.[\"leitwerk.dev/instance-id\"] !== undefined &&\n\t\t\t\tpv.metadata.labels[\"leitwerk.dev/instance-id\"] !== instanceId) ||\n\t\t\tpv.metadata.ownerReferences?.length ||\n\t\t\tpv.metadata.deletionTimestamp ||\n\t\t\tpv.spec.claimRef?.uid !== pvc.metadata.uid ||\n\t\t\tpv.spec.claimRef?.name !== name ||\n\t\t\tpv.spec.claimRef?.namespace !== namespace\n\t\t)\n\t\t\tthrow new Error(\"Cannot retire a volume with ambiguous claim ownership\");\n\t\tconst csi = pv.spec.csi as { driver?: string; volumeHandle?: string } | undefined;\n\t\tif (\n\t\t\treclamation &&\n\t\t\t(!csi?.driver ||\n\t\t\t\t!csi.volumeHandle ||\n\t\t\t\tpv.metadata.annotations?.[\"pv.kubernetes.io/provisioned-by\"] !== csi.driver ||\n\t\t\t\t![\"Retain\", \"Delete\"].includes(pv.spec.persistentVolumeReclaimPolicy ?? \"\"))\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t\"Backing-storage reclamation requires an owned dynamically provisioned CSI volume\",\n\t\t\t);\n\t\tconst volumeLabels: Record<string, string> = {\n\t\t\t...pv.metadata.labels,\n\t\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t\t\"leitwerk.dev/component\": \"process-volume\",\n\t\t\t\"leitwerk.dev/instance-id\": instanceId,\n\t\t\t...(reclamation ? { \"leitwerk.dev/reclamation\": \"terminal\" } : {}),\n\t\t};\n\t\t// End pool ownership atomically: a stale pool reconciler must not restore\n\t\t// Retain after a fast process closes. Both writers use resourceVersion tests.\n\t\tdelete volumeLabels[POOL_LABEL];\n\t\tawait api.patchVolume(\n\t\t\tpv,\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\top: \"add\",\n\t\t\t\t\tpath: \"/metadata/labels\",\n\t\t\t\t\tvalue: volumeLabels,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\top: \"add\",\n\t\t\t\t\tpath: \"/metadata/annotations\",\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\t...pv.metadata.annotations,\n\t\t\t\t\t\t\"leitwerk.dev/retirement\": JSON.stringify({\n\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\t\tclaimName: name,\n\t\t\t\t\t\t\tclaimUid: pvc.metadata.uid,\n\t\t\t\t\t\t\tvolumeUid: pv.metadata.uid,\n\t\t\t\t\t\t\treason: input.reason ?? \"retention-expired\",\n\t\t\t\t\t\t\t...(reclamation\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\treclamation:\n\t\t\t\t\t\t\t\t\t\t\ttypeof reclamation === \"object\"\n\t\t\t\t\t\t\t\t\t\t\t\t? { policy: \"terminal-process\", ...reclamation }\n\t\t\t\t\t\t\t\t\t\t\t\t: { policy: \"process-deletion\" },\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t// Arm CSI reclamation before deleting the claim. A crash after this\n\t\t\t\t// patch is safe: retry either repeats it or CSI completes independently.\n\t\t\t\t...(reclamation\n\t\t\t\t\t? [{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: \"Delete\" }]\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tsignal,\n\t\t);\n\t}\n\tawait api.delete(\"persistentvolumeclaims\", namespace, pvc, signal);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;;;ACA7B,SAAS,kBAAkB;;;ACA3B,SAAS,cAAc,aAAa;AAK7B,SAAS,wBACf,SAIA,cACqB;AACrB,SAAO;AAAA,IACN,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,8BAA8B;AAAA,IAC9B,cAAc,QAAQ,gBAAgB,CAAC;AAAA,IACvC,aAAa,QAAQ,eAAe,CAAC;AAAA,IACrC,mBAAmB,QAAQ,oBAAoB,CAAC,GAAG,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE;AAAA,IAC3E,YAAY;AAAA,MACX;AAAA,QACC,MAAM;AAAA,QACN,OAAO,QAAQ;AAAA,QACf,iBAAiB,QAAQ,mBAAmB;AAAA,QAC5C,SAAS,CAAC,QAAQ,MAAM,iBAAiB;AAAA,QACzC,WAAW;AAAA,UACV,UAAU,EAAE,KAAK,MAAM,QAAQ,OAAO;AAAA,UACtC,QAAQ,EAAE,KAAK,QAAQ,QAAQ,OAAO;AAAA,QACvC;AAAA,QACA,iBAAiB;AAAA,UAChB,0BAA0B;AAAA,UAC1B,wBAAwB;AAAA,UACxB,cAAc,EAAE,MAAM,CAAC,KAAK,EAAE;AAAA,QAC/B;AAAA,QACA,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;AAAA,MACxC;AAAA,IACD;AAAA,EACD;AACD;AAWO,SAAS,4BACf,WACA,YACA,SACA,kBAAkB,YACM;AACxB,MAAI;AACJ,MAAI;AACJ,SAAO;AAAA,IACN,QAAQ;AACP,UAAI,WAAY;AAChB,mBAAa,IAAI,gBAAgB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E,OAAO,CAAC,UAAU,UAAU,MAAS;AACpF,QAAM,cAAc,YAAY,SAAS,4BAA4B,WAAW,IAAI;AACpF,SAAO,EAAE,QAAQ,QAAQ,UAAU,YAAY;AAChD;","names":["selector","createHash","createHash","pv","delay"]}
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,9 @@ function closedAtMs(process) {
|
|
|
11
11
|
return Number.isFinite(parsed) ? parsed : null;
|
|
12
12
|
}
|
|
13
13
|
function planProcessVolumeRetentionCleanup(input) {
|
|
14
|
+
return planRetainedProcesses(input).map((process) => process.id);
|
|
15
|
+
}
|
|
16
|
+
function planRetainedProcesses(input) {
|
|
14
17
|
const completedRetentionMs = retentionMs(input.policy.completedProcessRetention);
|
|
15
18
|
const abortedRetentionMs = retentionMs(
|
|
16
19
|
input.policy.abortedProcessRetention ?? input.policy.errorProcessRetention
|
|
@@ -29,29 +32,26 @@ function planProcessVolumeRetentionCleanup(input) {
|
|
|
29
32
|
}
|
|
30
33
|
const retention = process.lifecycleStatus === "completed" ? completedRetentionMs : process.lifecycleStatus === "aborted" ? abortedRetentionMs : process.lifecycleStatus === "error" ? errorRetentionMs : Number.POSITIVE_INFINITY;
|
|
31
34
|
if (nowMs - closed >= retention) {
|
|
32
|
-
candidates.push(process
|
|
35
|
+
candidates.push(process);
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
38
|
return candidates;
|
|
36
39
|
}
|
|
37
40
|
async function cleanupRetainedProcessVolumes(input) {
|
|
38
|
-
const candidates =
|
|
41
|
+
const candidates = planRetainedProcesses(input);
|
|
39
42
|
if (input.volume) {
|
|
40
|
-
for (const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
await input.volume.release(instanceId, {
|
|
43
|
+
for (const process of candidates) {
|
|
44
|
+
if (input.reclaimTerminalBackingStorage && process.closedAt && (process.lifecycleStatus === "completed" || process.lifecycleStatus === "aborted"))
|
|
45
|
+
await input.volume.release(process.id, {
|
|
44
46
|
reclaimBackingStorage: {
|
|
45
47
|
lifecycleStatus: process.lifecycleStatus,
|
|
46
48
|
closedAt: process.closedAt
|
|
47
49
|
}
|
|
48
50
|
});
|
|
49
|
-
|
|
50
|
-
await input.volume.release(instanceId);
|
|
51
|
-
}
|
|
51
|
+
else await input.volume.release(process.id);
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
-
return candidates;
|
|
54
|
+
return candidates.map((process) => process.id);
|
|
55
55
|
}
|
|
56
56
|
export {
|
|
57
57
|
cleanupRetainedProcessVolumes,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/process-volume-retention.ts"],"sourcesContent":["import type { ProcessInstance } from \"@leitwerk-dev/domain\";\nimport { parseDurationMs } from \"@leitwerk-dev/watcher-utils\";\nimport type { ProcessVolume } from \"./types.js\";\n\n/** @internal */\nexport interface ProcessVolumeRetentionPolicy {\n\t/** @internal */\n\tcompletedProcessRetention: string;\n\t/** Defaults to error retention for callers retaining non-volume artifacts. @internal */\n\tabortedProcessRetention?: string;\n\t/** @internal */\n\terrorProcessRetention: string;\n}\n\n/** @internal */\nexport interface PlanProcessVolumeRetentionCleanupInput {\n\t/** @internal */\n\tprocesses: readonly ProcessInstance[];\n\t/** @internal */\n\tnow: Date;\n\t/** @internal */\n\tpolicy: ProcessVolumeRetentionPolicy;\n\t/** @internal */\n\talreadyReleased?: ReadonlySet<string>;\n}\n\nfunction retentionMs(value: string): number {\n\treturn parseDurationMs(value, Number.POSITIVE_INFINITY, { allowHours: true });\n}\n\nfunction closedAtMs(process: ProcessInstance): number | null {\n\tif (!process.closedAt) {\n\t\treturn null;\n\t}\n\tconst parsed = Date.parse(process.closedAt);\n\treturn Number.isFinite(parsed) ? parsed : null;\n}\n\n/** @internal */\nexport function planProcessVolumeRetentionCleanup(\n\tinput: PlanProcessVolumeRetentionCleanupInput,\n): string[] {\n\tconst completedRetentionMs = retentionMs(input.policy.completedProcessRetention);\n\tconst abortedRetentionMs = retentionMs(\n\t\tinput.policy.abortedProcessRetention ?? input.policy.errorProcessRetention,\n\t);\n\tconst errorRetentionMs = retentionMs(input.policy.errorProcessRetention);\n\tconst nowMs = input.now.getTime();\n\tconst alreadyReleased = input.alreadyReleased ?? new Set<string>();\n\tconst candidates:
|
|
1
|
+
{"version":3,"sources":["../src/process-volume-retention.ts"],"sourcesContent":["import type { ProcessInstance } from \"@leitwerk-dev/domain\";\nimport { parseDurationMs } from \"@leitwerk-dev/watcher-utils\";\nimport type { ProcessVolume } from \"./types.js\";\n\n/** @internal */\nexport interface ProcessVolumeRetentionPolicy {\n\t/** @internal */\n\tcompletedProcessRetention: string;\n\t/** Defaults to error retention for callers retaining non-volume artifacts. @internal */\n\tabortedProcessRetention?: string;\n\t/** @internal */\n\terrorProcessRetention: string;\n}\n\n/** @internal */\nexport interface PlanProcessVolumeRetentionCleanupInput {\n\t/** @internal */\n\tprocesses: readonly ProcessInstance[];\n\t/** @internal */\n\tnow: Date;\n\t/** @internal */\n\tpolicy: ProcessVolumeRetentionPolicy;\n\t/** @internal */\n\talreadyReleased?: ReadonlySet<string>;\n}\n\nfunction retentionMs(value: string): number {\n\treturn parseDurationMs(value, Number.POSITIVE_INFINITY, { allowHours: true });\n}\n\nfunction closedAtMs(process: ProcessInstance): number | null {\n\tif (!process.closedAt) {\n\t\treturn null;\n\t}\n\tconst parsed = Date.parse(process.closedAt);\n\treturn Number.isFinite(parsed) ? parsed : null;\n}\n\n/** @internal */\nexport function planProcessVolumeRetentionCleanup(\n\tinput: PlanProcessVolumeRetentionCleanupInput,\n): string[] {\n\treturn planRetainedProcesses(input).map((process) => process.id);\n}\n\nfunction planRetainedProcesses(input: PlanProcessVolumeRetentionCleanupInput): ProcessInstance[] {\n\tconst completedRetentionMs = retentionMs(input.policy.completedProcessRetention);\n\tconst abortedRetentionMs = retentionMs(\n\t\tinput.policy.abortedProcessRetention ?? input.policy.errorProcessRetention,\n\t);\n\tconst errorRetentionMs = retentionMs(input.policy.errorProcessRetention);\n\tconst nowMs = input.now.getTime();\n\tconst alreadyReleased = input.alreadyReleased ?? new Set<string>();\n\tconst candidates: ProcessInstance[] = [];\n\tfor (const process of input.processes) {\n\t\tif (alreadyReleased.has(process.id)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst closed = closedAtMs(process);\n\t\tif (closed === null) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retention =\n\t\t\tprocess.lifecycleStatus === \"completed\"\n\t\t\t\t? completedRetentionMs\n\t\t\t\t: process.lifecycleStatus === \"aborted\"\n\t\t\t\t\t? abortedRetentionMs\n\t\t\t\t\t: process.lifecycleStatus === \"error\"\n\t\t\t\t\t\t? errorRetentionMs\n\t\t\t\t\t\t: Number.POSITIVE_INFINITY;\n\t\tif (nowMs - closed >= retention) {\n\t\t\tcandidates.push(process);\n\t\t}\n\t}\n\treturn candidates;\n}\n\n/** @internal */\nexport async function cleanupRetainedProcessVolumes(\n\tinput: PlanProcessVolumeRetentionCleanupInput & {\n\t\t/** @internal */\n\t\tvolume?: ProcessVolume;\n\t\t/** Terminal-process storage disposal policy; error retention is unaffected. @internal */\n\t\treclaimTerminalBackingStorage?: boolean;\n\t},\n): Promise<string[]> {\n\tconst candidates = planRetainedProcesses(input);\n\tif (input.volume) {\n\t\tfor (const process of candidates) {\n\t\t\tif (\n\t\t\t\tinput.reclaimTerminalBackingStorage &&\n\t\t\t\tprocess.closedAt &&\n\t\t\t\t(process.lifecycleStatus === \"completed\" || process.lifecycleStatus === \"aborted\")\n\t\t\t)\n\t\t\t\tawait input.volume.release(process.id, {\n\t\t\t\t\treclaimBackingStorage: {\n\t\t\t\t\t\tlifecycleStatus: process.lifecycleStatus,\n\t\t\t\t\t\tclosedAt: process.closedAt,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\telse await input.volume.release(process.id);\n\t\t}\n\t}\n\treturn candidates.map((process) => process.id);\n}\n"],"mappings":";AACA,SAAS,uBAAuB;AAyBhC,SAAS,YAAY,OAAuB;AAC3C,SAAO,gBAAgB,OAAO,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B;AAAA,YACtB,iBAAiB,QAAQ;AAAA,YACzB,UAAU,QAAQ;AAAA,UACnB;AAAA,QACD,CAAC;AAAA,UACG,OAAM,MAAM,OAAO,QAAQ,QAAQ,EAAE;AAAA,IAC3C;AAAA,EACD;AACA,SAAO,WAAW,IAAI,CAAC,YAAY,QAAQ,EAAE;AAC9C;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kubernetes-worker-runner.d.ts","sourceRoot":"","sources":["../src/kubernetes-worker-runner.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAEN,KAAK,qBAAqB,EAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAUN,KAAK,8BAA8B,EACnC,KAAK,wBAAwB,EAC7B,KAAK,2BAA2B,EAMhC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAS1E,OAAO,KAAK,EACX,wBAAwB,EACxB,oBAAoB,EACpB,qCAAqC,EACrC,aAAa,EAEb,YAAY,EAIZ,MAAM,YAAY,CAAC;AA0BpB,gBAAgB;AAChB,MAAM,WAAW,6BAA6B;IAC7C,8EAA8E;IAC9E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,gBAAgB;IAChB,YAAY,CAAC,EAAE;QACd,gBAAgB;QAChB,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,gBAAgB;QAChB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,qBAAqB,KAAK,IAAI,CAAC;KACjD,CAAC;IACF,gBAAgB;IAChB,YAAY,CAAC,EAAE;QACd,gBAAgB;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB;QAChB,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;KACpC,CAAC;IACF,gBAAgB;IAChB,MAAM,EAAE,mBAAmB,CAAC;IAC5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;KAChC,CAAC;IACF,4EAA4E;IAC5E,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,gBAAgB;IAChB,8BAA8B,CAAC,EAAE,MAAM,CAAC;IACxC,6DAA6D;IAC7D,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,gGAAgG;IAChG,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iFAAiF;IACjF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,6EAA6E;IAC7E,qBAAqB,CAAC,EAAE,KAAK,CAAC;QAC7B,gBAAgB;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,gBAAgB;QAChB,UAAU,EAAE,MAAM,CAAC;KACnB,CAAC,CAAC;IACH,gBAAgB;IAChB,GAAG,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,WAAW,CAAC,CAAC;IAClD,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yFAAyF;IACzF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,0DAA0D;IAC1D,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,wEAAwE;IACxE,YAAY,CAAC,EAAE,qCAAqC,CAAC;CACrD;AAED,gBAAgB;AAChB,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,6BAA6B,GAAG;IACrF,gBAAgB;IAChB,MAAM,EAAE,YAAY,CAAC,wBAAwB,CAAC,CAAC;IAC/C,gBAAgB;IAChB,MAAM,EAAE,aAAa,CAAC;IACtB,gBAAgB;IAChB,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,gBAAgB;IAChB,WAAW,CAAC,EAAE,UAAU,CAAC,OAAO,2BAA2B,CAAC,CAAC;CAC7D,CAmcA"}
|
|
@@ -23,18 +23,10 @@ export interface PlanProcessVolumeRetentionCleanupInput {
|
|
|
23
23
|
/** @internal */
|
|
24
24
|
export declare function planProcessVolumeRetentionCleanup(input: PlanProcessVolumeRetentionCleanupInput): string[];
|
|
25
25
|
/** @internal */
|
|
26
|
-
export declare function cleanupRetainedProcessVolumes(input: {
|
|
26
|
+
export declare function cleanupRetainedProcessVolumes(input: PlanProcessVolumeRetentionCleanupInput & {
|
|
27
27
|
/** @internal */
|
|
28
28
|
volume?: ProcessVolume;
|
|
29
29
|
/** Terminal-process storage disposal policy; error retention is unaffected. @internal */
|
|
30
30
|
reclaimTerminalBackingStorage?: boolean;
|
|
31
|
-
/** @internal */
|
|
32
|
-
processes: readonly ProcessInstance[];
|
|
33
|
-
/** @internal */
|
|
34
|
-
now: Date;
|
|
35
|
-
/** @internal */
|
|
36
|
-
policy: ProcessVolumeRetentionPolicy;
|
|
37
|
-
/** @internal */
|
|
38
|
-
alreadyReleased?: ReadonlySet<string>;
|
|
39
31
|
}): Promise<string[]>;
|
|
40
32
|
//# sourceMappingURL=process-volume-retention.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process-volume-retention.d.ts","sourceRoot":"","sources":["../src/process-volume-retention.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,gBAAgB;AAChB,MAAM,WAAW,4BAA4B;IAC5C,gBAAgB;IAChB,yBAAyB,EAAE,MAAM,CAAC;IAClC,wFAAwF;IACxF,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,gBAAgB;IAChB,qBAAqB,EAAE,MAAM,CAAC;CAC9B;AAED,gBAAgB;AAChB,MAAM,WAAW,sCAAsC;IACtD,gBAAgB;IAChB,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;IACtC,gBAAgB;IAChB,GAAG,EAAE,IAAI,CAAC;IACV,gBAAgB;IAChB,MAAM,EAAE,4BAA4B,CAAC;IACrC,gBAAgB;IAChB,eAAe,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CACtC;AAcD,gBAAgB;AAChB,wBAAgB,iCAAiC,CAChD,KAAK,EAAE,sCAAsC,GAC3C,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"process-volume-retention.d.ts","sourceRoot":"","sources":["../src/process-volume-retention.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,gBAAgB;AAChB,MAAM,WAAW,4BAA4B;IAC5C,gBAAgB;IAChB,yBAAyB,EAAE,MAAM,CAAC;IAClC,wFAAwF;IACxF,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,gBAAgB;IAChB,qBAAqB,EAAE,MAAM,CAAC;CAC9B;AAED,gBAAgB;AAChB,MAAM,WAAW,sCAAsC;IACtD,gBAAgB;IAChB,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;IACtC,gBAAgB;IAChB,GAAG,EAAE,IAAI,CAAC;IACV,gBAAgB;IAChB,MAAM,EAAE,4BAA4B,CAAC;IACrC,gBAAgB;IAChB,eAAe,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CACtC;AAcD,gBAAgB;AAChB,wBAAgB,iCAAiC,CAChD,KAAK,EAAE,sCAAsC,GAC3C,MAAM,EAAE,CAEV;AAkCD,gBAAgB;AAChB,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,sCAAsC,GAAG;IAC/C,gBAAgB;IAChB,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,yFAAyF;IACzF,6BAA6B,CAAC,EAAE,OAAO,CAAC;CACxC,GACC,OAAO,CAAC,MAAM,EAAE,CAAC,CAmBnB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leitwerk-dev/worker-runners",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/leitwerk-dev/leitwerk.git",
|
|
@@ -48,10 +48,10 @@
|
|
|
48
48
|
"build": "tsup --silent"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@leitwerk-dev/domain": "0.4.
|
|
52
|
-
"@leitwerk-dev/session-transfer": "0.4.
|
|
53
|
-
"@leitwerk-dev/watcher-utils": "0.4.
|
|
54
|
-
"@leitwerk-dev/worker-protocol": "0.4.
|
|
51
|
+
"@leitwerk-dev/domain": "0.4.4",
|
|
52
|
+
"@leitwerk-dev/session-transfer": "0.4.4",
|
|
53
|
+
"@leitwerk-dev/watcher-utils": "0.4.4",
|
|
54
|
+
"@leitwerk-dev/worker-protocol": "0.4.4"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@types/node": "^22.15.30",
|
|
@@ -165,6 +165,29 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
|
|
|
165
165
|
const podDisappearanceTimeoutMs = options.podDisappearanceTimeoutMs ?? 30_000;
|
|
166
166
|
const podDisappearancePollIntervalMs = options.podDisappearancePollIntervalMs ?? 250;
|
|
167
167
|
|
|
168
|
+
async function releaseVolume(
|
|
169
|
+
instanceId: string,
|
|
170
|
+
retirement: Pick<
|
|
171
|
+
Parameters<typeof retireKubernetesProcessVolume>[0],
|
|
172
|
+
"reason" | "reclaimBackingStorage"
|
|
173
|
+
> = {},
|
|
174
|
+
) {
|
|
175
|
+
const name = kubernetesProcessPvcName(instanceId, options.volume.namePrefix);
|
|
176
|
+
const namespace = namespaceForProcess(instanceId);
|
|
177
|
+
if (client.volumePool)
|
|
178
|
+
return retireKubernetesProcessVolume({
|
|
179
|
+
api: client.volumePool,
|
|
180
|
+
namespace,
|
|
181
|
+
name,
|
|
182
|
+
instanceId,
|
|
183
|
+
signal: AbortSignal.timeout(30_000),
|
|
184
|
+
...retirement,
|
|
185
|
+
});
|
|
186
|
+
if (retirement.reclaimBackingStorage)
|
|
187
|
+
throw new Error("Backing-storage reclamation requires Kubernetes volume inspection");
|
|
188
|
+
await client.deletePersistentVolumeClaim(name, namespace);
|
|
189
|
+
}
|
|
190
|
+
|
|
168
191
|
const samplers = new Map<string, ReturnType<typeof sampleKubernetesStartup>>();
|
|
169
192
|
const volume: ProcessVolume = {
|
|
170
193
|
async ensure(instanceId, requirements, observer) {
|
|
@@ -266,39 +289,15 @@ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOpti
|
|
|
266
289
|
namespace: manifest.metadata.namespace,
|
|
267
290
|
});
|
|
268
291
|
},
|
|
269
|
-
|
|
270
|
-
if (client.volumePool) {
|
|
271
|
-
await retireKubernetesProcessVolume({
|
|
272
|
-
api: client.volumePool,
|
|
273
|
-
namespace: namespaceForProcess(instanceId),
|
|
274
|
-
name: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
|
|
275
|
-
instanceId,
|
|
276
|
-
signal: AbortSignal.timeout(30_000),
|
|
277
|
-
reclaimBackingStorage: releaseOptions?.reclaimBackingStorage,
|
|
278
|
-
});
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
if (releaseOptions?.reclaimBackingStorage)
|
|
282
|
-
throw new Error("Backing-storage reclamation requires Kubernetes volume inspection");
|
|
283
|
-
await client.deletePersistentVolumeClaim(
|
|
284
|
-
kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
|
|
285
|
-
namespaceForProcess(instanceId),
|
|
286
|
-
);
|
|
287
|
-
},
|
|
292
|
+
release: releaseVolume,
|
|
288
293
|
async deleteProcessResources(instanceId) {
|
|
289
294
|
samplers.get(instanceId)?.stop();
|
|
290
295
|
samplers.delete(instanceId);
|
|
291
|
-
if (client.volumePool)
|
|
292
|
-
await
|
|
293
|
-
api: client.volumePool,
|
|
294
|
-
namespace: namespaceForProcess(instanceId),
|
|
295
|
-
name: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
|
|
296
|
-
instanceId,
|
|
296
|
+
if (client.volumePool)
|
|
297
|
+
await releaseVolume(instanceId, {
|
|
297
298
|
reason: "process-deleted",
|
|
298
299
|
reclaimBackingStorage: options.reclaimOnClose ? "process-deleted" : undefined,
|
|
299
|
-
signal: AbortSignal.timeout(30_000),
|
|
300
300
|
});
|
|
301
|
-
}
|
|
302
301
|
await client.deleteNamespace(namespaceForProcess(instanceId));
|
|
303
302
|
},
|
|
304
303
|
};
|
|
@@ -40,6 +40,10 @@ function closedAtMs(process: ProcessInstance): number | null {
|
|
|
40
40
|
export function planProcessVolumeRetentionCleanup(
|
|
41
41
|
input: PlanProcessVolumeRetentionCleanupInput,
|
|
42
42
|
): string[] {
|
|
43
|
+
return planRetainedProcesses(input).map((process) => process.id);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function planRetainedProcesses(input: PlanProcessVolumeRetentionCleanupInput): ProcessInstance[] {
|
|
43
47
|
const completedRetentionMs = retentionMs(input.policy.completedProcessRetention);
|
|
44
48
|
const abortedRetentionMs = retentionMs(
|
|
45
49
|
input.policy.abortedProcessRetention ?? input.policy.errorProcessRetention,
|
|
@@ -47,7 +51,7 @@ export function planProcessVolumeRetentionCleanup(
|
|
|
47
51
|
const errorRetentionMs = retentionMs(input.policy.errorProcessRetention);
|
|
48
52
|
const nowMs = input.now.getTime();
|
|
49
53
|
const alreadyReleased = input.alreadyReleased ?? new Set<string>();
|
|
50
|
-
const candidates:
|
|
54
|
+
const candidates: ProcessInstance[] = [];
|
|
51
55
|
for (const process of input.processes) {
|
|
52
56
|
if (alreadyReleased.has(process.id)) {
|
|
53
57
|
continue;
|
|
@@ -65,46 +69,37 @@ export function planProcessVolumeRetentionCleanup(
|
|
|
65
69
|
? errorRetentionMs
|
|
66
70
|
: Number.POSITIVE_INFINITY;
|
|
67
71
|
if (nowMs - closed >= retention) {
|
|
68
|
-
candidates.push(process
|
|
72
|
+
candidates.push(process);
|
|
69
73
|
}
|
|
70
74
|
}
|
|
71
75
|
return candidates;
|
|
72
76
|
}
|
|
73
77
|
|
|
74
78
|
/** @internal */
|
|
75
|
-
export async function cleanupRetainedProcessVolumes(
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
/** @internal */
|
|
85
|
-
policy: ProcessVolumeRetentionPolicy;
|
|
86
|
-
/** @internal */
|
|
87
|
-
alreadyReleased?: ReadonlySet<string>;
|
|
88
|
-
}): Promise<string[]> {
|
|
89
|
-
const candidates = planProcessVolumeRetentionCleanup(input);
|
|
79
|
+
export async function cleanupRetainedProcessVolumes(
|
|
80
|
+
input: PlanProcessVolumeRetentionCleanupInput & {
|
|
81
|
+
/** @internal */
|
|
82
|
+
volume?: ProcessVolume;
|
|
83
|
+
/** Terminal-process storage disposal policy; error retention is unaffected. @internal */
|
|
84
|
+
reclaimTerminalBackingStorage?: boolean;
|
|
85
|
+
},
|
|
86
|
+
): Promise<string[]> {
|
|
87
|
+
const candidates = planRetainedProcesses(input);
|
|
90
88
|
if (input.volume) {
|
|
91
|
-
for (const
|
|
92
|
-
const process = input.processes.find((process) => process.id === instanceId);
|
|
89
|
+
for (const process of candidates) {
|
|
93
90
|
if (
|
|
94
91
|
input.reclaimTerminalBackingStorage &&
|
|
95
|
-
process
|
|
92
|
+
process.closedAt &&
|
|
96
93
|
(process.lifecycleStatus === "completed" || process.lifecycleStatus === "aborted")
|
|
97
|
-
)
|
|
98
|
-
await input.volume.release(
|
|
94
|
+
)
|
|
95
|
+
await input.volume.release(process.id, {
|
|
99
96
|
reclaimBackingStorage: {
|
|
100
97
|
lifecycleStatus: process.lifecycleStatus,
|
|
101
98
|
closedAt: process.closedAt,
|
|
102
99
|
},
|
|
103
100
|
});
|
|
104
|
-
|
|
105
|
-
await input.volume.release(instanceId);
|
|
106
|
-
}
|
|
101
|
+
else await input.volume.release(process.id);
|
|
107
102
|
}
|
|
108
103
|
}
|
|
109
|
-
return candidates;
|
|
104
|
+
return candidates.map((process) => process.id);
|
|
110
105
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kubernetes-worker-runner.ts","../src/kubernetes-image-preload.ts","../src/kubernetes-preparation.ts","../src/kubernetes-startup-sampler.ts","../src/kubernetes-volume-pool.ts","../src/kubernetes-volume-retirement.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n\tcreateHelperProcessStateExporter,\n\texportHelperEnvironment,\n} from \"./helper-process-state-exporter.js\";\nimport type { KubernetesApiClient } from \"./kubernetes-api-client.js\";\nimport {\n\tcreateKubernetesImagePreload,\n\ttype ImagePreparationEvent,\n} from \"./kubernetes-image-preload.js\";\nimport {\n\tbuildKubernetesDockerConfigJsonSecretManifest,\n\tbuildKubernetesExportHelperPodManifest,\n\tbuildKubernetesProcessNamespaceManifest,\n\tbuildKubernetesProcessPvcManifest,\n\tbuildKubernetesServerCaConfigMapManifest,\n\tbuildKubernetesWorkerPodManifest,\n\tKUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\tKUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\tKUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\ttype KubernetesDockerPodSpecOptions,\n\ttype KubernetesPodSpecOptions,\n\ttype KubernetesProcessVolumeSpec,\n\tkubernetesExportHelperPodName,\n\tkubernetesProcessNamespaceName,\n\tkubernetesProcessPvcName,\n\tredactKubernetesDiagnostic,\n\tvolumeRefFromPvc,\n} from \"./kubernetes-manifests.js\";\nimport { createKubernetesPreparation } from \"./kubernetes-preparation.js\";\nimport { sampleKubernetesStartup, startupReceipt } from \"./kubernetes-startup-sampler.js\";\nimport { createKubernetesVolumePool } from \"./kubernetes-volume-pool.js\";\nimport { retireKubernetesProcessVolume } from \"./kubernetes-volume-retirement.js\";\nimport { UnitExitNotifier } from \"./runner-utils.js\";\nimport {\n\tSESSION_TRANSFER_HELPER_ENTRY_PATH,\n\tSESSION_TRANSFER_HELPER_MOUNT_PATH,\n} from \"./session-transfer-helper.js\";\nimport type {\n\tIsolatedStartWorkerInput,\n\tProcessStateExporter,\n\tProcessStateExportHelperRelayProvider,\n\tProcessVolume,\n\tStopWorkerOptions,\n\tWorkerRunner,\n\tWorkerUnit,\n\tWorkerUnitDescriptor,\n\tWorkerUnitRef,\n} from \"./types.js\";\nimport { WorkerStartDiagnosticError } from \"./types.js\";\nimport {\n\tmanagedExportHelperLabelSelector,\n\tmanagedProcessNamespaceLabelSelector,\n\tmanagedWorkerLabelSelector,\n\tparseWorkerUnitIdentity,\n\tWORKER_LABEL_COMPONENT,\n\tWORKER_LABEL_INSTANCE_ID,\n\tWORKER_LABEL_MANAGED_BY,\n\tWORKER_LABEL_MANAGED_BY_VALUE,\n} from \"./worker-labels.js\";\n\nconst KUBERNETES_START_DIAGNOSTIC_MAX_LENGTH = 2_048;\n\nfunction boundedKubernetesStartDiagnostic(\n\terror: unknown,\n\tsensitiveValues: readonly string[],\n): string {\n\tconst detail = error instanceof Error ? error.message : \"Kubernetes Pod admission failed\";\n\treturn redactKubernetesDiagnostic(detail, sensitiveValues).slice(\n\t\t0,\n\t\tKUBERNETES_START_DIAGNOSTIC_MAX_LENGTH,\n\t);\n}\n\n/** @internal */\nexport interface KubernetesWorkerRunnerOptions {\n\t/** Enable CSI backing reclamation for explicit process deletion. @internal */\n\treclaimOnClose?: boolean;\n\t/** @internal */\n\timagePreload?: {\n\t\t/** @internal */\n\t\timages: string[];\n\t\t/** @internal */\n\t\tonEvent?: (event: ImagePreparationEvent) => void;\n\t};\n\t/** @internal */\n\tpreProvision?: {\n\t\t/** @internal */\n\t\tcount: number;\n\t\t/** @internal */\n\t\tonError?: (error?: unknown) => void;\n\t};\n\t/** @internal */\n\tclient: KubernetesApiClient;\n\t/** Prefix used to derive one Kubernetes namespace per process instance. @internal */\n\tprocessNamespacePrefix: string;\n\t/** @internal */\n\tvolume: KubernetesProcessVolumeSpec;\n\t/** Storage and Pod wiring for process definitions that require private Docker. @internal */\n\tdocker?: KubernetesDockerPodSpecOptions & {\n\t\t/** @internal */\n\t\tprocessStorageClassName: string;\n\t};\n\t/** Maximum wait after deletion before replacement is rejected. @internal */\n\tpodDisappearanceTimeoutMs?: number;\n\t/** @internal */\n\tpodDisappearancePollIntervalMs?: number;\n\t/** Test seam for bounded disappearance polling. @internal */\n\tdelay?: (ms: number) => Promise<void>;\n\t/** Server-local CA bundle copied into each process namespace for worker TLS trust. @internal */\n\tserverCaFile?: string;\n\t/** Namespace containing operator-managed source image-pull Secrets. @internal */\n\tserverNamespace?: string;\n\t/** Docker registry Secrets copied into every process namespace. @internal */\n\timagePullSecretCopies?: Array<{\n\t\t/** @internal */\n\t\tsourceName: string;\n\t\t/** @internal */\n\t\ttargetName: string;\n\t}>;\n\t/** @internal */\n\tpod?: Omit<KubernetesPodSpecOptions, \"namespace\">;\n\t/** Stable internal URL used by PVC export helpers. @internal */\n\tserverUrl?: string;\n\t/** Trusted image containing the bundled session-transfer helper entrypoint. @internal */\n\texporterImage?: string;\n\t/** Pull policy for the trusted helper image. @internal */\n\texporterImagePullPolicy?: string;\n\t/** Server-owned relay registry used by PVC export helpers. @internal */\n\thelperRelays?: ProcessStateExportHelperRelayProvider;\n}\n\n/** @internal */\nexport function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOptions): {\n\t/** @internal */\n\trunner: WorkerRunner<IsolatedStartWorkerInput>;\n\t/** @internal */\n\tvolume: ProcessVolume;\n\t/** @internal */\n\texporter: ProcessStateExporter;\n\t/** @internal */\n\tpreparation?: ReturnType<typeof createKubernetesPreparation>;\n} {\n\tif (!options.serverUrl || !options.exporterImage || !options.helperRelays) {\n\t\tthrow new Error(\"Kubernetes transfer exporter is not configured\");\n\t}\n\tconst { client } = options;\n\tconst exporterServerUrl = options.serverUrl;\n\tconst exporterImage = options.exporterImage;\n\tconst helperRelays = options.helperRelays;\n\tconst serverCaFile = options.serverCaFile?.trim();\n\tconst serverCaConfig = serverCaFile\n\t\t? {\n\t\t\t\tserverCaConfigMap: {\n\t\t\t\t\tname: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\t\t\t\t\tkey: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\t\t\t\t\tmountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\t\t\t\t},\n\t\t\t}\n\t\t: {};\n\tconst namespaceForProcess = (instanceId: string) =>\n\t\tkubernetesProcessNamespaceName(instanceId, options.processNamespacePrefix);\n\tconst delay =\n\t\toptions.delay ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\tconst podDisappearanceTimeoutMs = options.podDisappearanceTimeoutMs ?? 30_000;\n\tconst podDisappearancePollIntervalMs = options.podDisappearancePollIntervalMs ?? 250;\n\n\tconst samplers = new Map<string, ReturnType<typeof sampleKubernetesStartup>>();\n\tconst volume: ProcessVolume = {\n\t\tasync ensure(instanceId, requirements, observer) {\n\t\t\tconst namespaceManifest = buildKubernetesProcessNamespaceManifest({\n\t\t\t\tinstanceId,\n\t\t\t\tprocessNamespacePrefix: options.processNamespacePrefix,\n\t\t\t\t...(requirements?.docker && options.docker?.isolation\n\t\t\t\t\t? { extraLabels: { \"pod-security.kubernetes.io/enforce\": \"privileged\" } }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tif (requirements?.docker && options.docker) {\n\t\t\t\tif (!client.getPersistentVolumeClaim)\n\t\t\t\t\tthrow new Error(\"Docker requires process storage inspection\");\n\t\t\t\tconst existing = await client.getPersistentVolumeClaim(\n\t\t\t\t\tkubernetesProcessPvcName(instanceId, options.volume.namePrefix),\n\t\t\t\t\tnamespaceManifest.metadata.name,\n\t\t\t\t);\n\t\t\t\tif (existing && existing.storageClass !== options.docker.processStorageClassName) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Docker requires the configured block StorageClass; preserve and migrate the existing process volume before resuming\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait client.ensureNamespace(namespaceManifest);\n\t\t\tconst copySecrets = (options.imagePullSecretCopies ?? []).map(async (copy) => {\n\t\t\t\tconst dockerConfigJson = await client.getDockerConfigJsonSecret(\n\t\t\t\t\tcopy.sourceName,\n\t\t\t\t\toptions.serverNamespace ?? \"leitwerk-system\",\n\t\t\t\t);\n\t\t\t\tawait client.ensureDockerConfigJsonSecret(\n\t\t\t\t\tbuildKubernetesDockerConfigJsonSecretManifest({\n\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\t\t\tname: copy.targetName,\n\t\t\t\t\t\tdockerConfigJson,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t});\n\t\t\tconst workerServiceAccount = options.pod?.workerServiceAccount?.trim();\n\t\t\tconst manifest = buildKubernetesProcessPvcManifest({\n\t\t\t\tinstanceId,\n\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\tvolume: {\n\t\t\t\t\t...options.volume,\n\t\t\t\t\tsize: requirements?.size ?? options.volume.size,\n\t\t\t\t\t...(requirements?.docker && options.docker\n\t\t\t\t\t\t? { storageClassName: options.docker.processStorageClassName }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\t...copySecrets,\n\t\t\t\t...(serverCaFile\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tclient.ensureConfigMap(\n\t\t\t\t\t\t\t\tbuildKubernetesServerCaConfigMapManifest({\n\t\t\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\t\t\t\t\t\tcaPem: readFileSync(serverCaFile, \"utf8\"),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t\t...(workerServiceAccount && workerServiceAccount !== \"default\"\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tclient.ensureServiceAccount(workerServiceAccount, namespaceManifest.metadata.name, {\n\t\t\t\t\t\t\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t\t\t\t\t\t\t[WORKER_LABEL_COMPONENT]: \"worker-service-account\",\n\t\t\t\t\t\t\t\t[WORKER_LABEL_INSTANCE_ID]: instanceId,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t\t(async () => {\n\t\t\t\t\tstartupReceipt(observer, \"pvc_requested\", {\n\t\t\t\t\t\tstorageClass: manifest.spec.storageClassName,\n\t\t\t\t\t});\n\t\t\t\t\tawait client.ensurePersistentVolumeClaim(manifest);\n\t\t\t\t\tstartupReceipt(observer, \"pvc_acknowledged\", {\n\t\t\t\t\t\tstorageClass: manifest.spec.storageClassName,\n\t\t\t\t\t});\n\t\t\t\t\tif (observer?.observe) {\n\t\t\t\t\t\tsamplers.get(instanceId)?.stop();\n\t\t\t\t\t\tsamplers.set(\n\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\tsampleKubernetesStartup(\n\t\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\t\tobserver,\n\t\t\t\t\t\t\t\tmanifest.metadata.namespace,\n\t\t\t\t\t\t\t\tmanifest.metadata.name,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t]);\n\t\t\treturn volumeRefFromPvc({\n\t\t\t\tinstanceId,\n\t\t\t\tpvcName: manifest.metadata.name,\n\t\t\t\tmountPath: options.volume.mountPath,\n\t\t\t\tnamespace: manifest.metadata.namespace,\n\t\t\t});\n\t\t},\n\t\tasync release(instanceId, releaseOptions) {\n\t\t\tif (client.volumePool) {\n\t\t\t\tawait retireKubernetesProcessVolume({\n\t\t\t\t\tapi: client.volumePool,\n\t\t\t\t\tnamespace: namespaceForProcess(instanceId),\n\t\t\t\t\tname: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),\n\t\t\t\t\tinstanceId,\n\t\t\t\t\tsignal: AbortSignal.timeout(30_000),\n\t\t\t\t\treclaimBackingStorage: releaseOptions?.reclaimBackingStorage,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (releaseOptions?.reclaimBackingStorage)\n\t\t\t\tthrow new Error(\"Backing-storage reclamation requires Kubernetes volume inspection\");\n\t\t\tawait client.deletePersistentVolumeClaim(\n\t\t\t\tkubernetesProcessPvcName(instanceId, options.volume.namePrefix),\n\t\t\t\tnamespaceForProcess(instanceId),\n\t\t\t);\n\t\t},\n\t\tasync deleteProcessResources(instanceId) {\n\t\t\tsamplers.get(instanceId)?.stop();\n\t\t\tsamplers.delete(instanceId);\n\t\t\tif (client.volumePool) {\n\t\t\t\tawait retireKubernetesProcessVolume({\n\t\t\t\t\tapi: client.volumePool,\n\t\t\t\t\tnamespace: namespaceForProcess(instanceId),\n\t\t\t\t\tname: kubernetesProcessPvcName(instanceId, options.volume.namePrefix),\n\t\t\t\t\tinstanceId,\n\t\t\t\t\treason: \"process-deleted\",\n\t\t\t\t\treclaimBackingStorage: options.reclaimOnClose ? \"process-deleted\" : undefined,\n\t\t\t\t\tsignal: AbortSignal.timeout(30_000),\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait client.deleteNamespace(namespaceForProcess(instanceId));\n\t\t},\n\t};\n\n\tconst exitNotifier = new UnitExitNotifier();\n\tconst unsubscribers = new Map<string, () => void>();\n\tconst disappearancePromises = new Map<string, Promise<void>>();\n\n\tfunction unitKey(namespace: string, unitId: string): string {\n\t\treturn `${namespace}/${unitId}`;\n\t}\n\n\tfunction deletePodAndWait(\n\t\tname: string,\n\t\tnamespace: string,\n\t\tgracePeriodSeconds: number,\n\t): Promise<void> {\n\t\tconst key = unitKey(namespace, name);\n\t\tconst existing = disappearancePromises.get(key);\n\t\tif (existing) return existing;\n\t\tconst operation = Promise.resolve()\n\t\t\t.then(async () => {\n\t\t\t\tconst deadline = Date.now() + podDisappearanceTimeoutMs;\n\t\t\t\tconst timeoutError = new Error(\n\t\t\t\t\t`Kubernetes worker Pod ${namespace}/${name} did not disappear within ${podDisappearanceTimeoutMs}ms; replacement was not started`,\n\t\t\t\t);\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tconst { signal } = controller;\n\t\t\t\tlet rejectTimeout!: (error: Error) => void;\n\t\t\t\tconst timedOut = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\trejectTimeout = reject;\n\t\t\t\t});\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tcontroller.abort(timeoutError);\n\t\t\t\t\trejectTimeout(timeoutError);\n\t\t\t\t}, podDisappearanceTimeoutMs);\n\t\t\t\tconst waitForDisappearance = async () => {\n\t\t\t\t\tawait client.deletePod(name, namespace, { gracePeriodSeconds, signal });\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (Date.now() >= deadline) throw timeoutError;\n\t\t\t\t\t\tconst pod = await client.getPod(name, namespace, { signal });\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (Date.now() >= deadline) throw timeoutError;\n\t\t\t\t\t\tif (!pod) return;\n\t\t\t\t\t\tawait delay(\n\t\t\t\t\t\t\tMath.min(podDisappearancePollIntervalMs, Math.max(0, deadline - Date.now())),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.race([waitForDisappearance(), timedOut]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (signal.aborted) throw timeoutError;\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => disappearancePromises.delete(key));\n\t\tdisappearancePromises.set(key, operation);\n\t\treturn operation;\n\t}\n\n\tfunction watchPod(\n\t\tunitId: string,\n\t\tnamespace: string,\n\t\tsensitiveValues: readonly string[] = [],\n\t): void {\n\t\tconst key = unitKey(namespace, unitId);\n\t\tif (unsubscribers.has(key)) return;\n\t\tconst unsubscribe = client.onPodExit(\n\t\t\tunitId,\n\t\t\tnamespace,\n\t\t\t(info) => {\n\t\t\t\texitNotifier.fireExit(key, info);\n\t\t\t\tunsubscribers.get(key)?.();\n\t\t\t\tunsubscribers.delete(key);\n\t\t\t},\n\t\t\t{ sensitiveValues },\n\t\t);\n\t\tunsubscribers.set(key, unsubscribe);\n\t}\n\n\tconst runner: WorkerRunner<IsolatedStartWorkerInput> = {\n\t\tasync start(input: IsolatedStartWorkerInput, observer): Promise<WorkerUnit> {\n\t\t\tobserver?.report(\"preparing_runtime\");\n\t\t\tif (input.docker && !options.docker) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Kubernetes Docker runtime is unavailable; configure kubernetes.docker completely\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst processNamespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);\n\t\t\tconst manifest = buildKubernetesWorkerPodManifest(input, {\n\t\t\t\tnamespace: processNamespace,\n\t\t\t\t...(options.pod ?? {}),\n\t\t\t\t...(input.docker && options.docker ? { docker: options.docker } : {}),\n\t\t\t\t...serverCaConfig,\n\t\t\t});\n\t\t\tobserver?.report(\"allocating_runtime\");\n\t\t\ttry {\n\t\t\t\tstartupReceipt(observer, \"pod_requested\", {\n\t\t\t\t\timage: input.image.reference,\n\t\t\t\t\t...input.resources,\n\t\t\t\t});\n\t\t\t\tawait client.createPod(manifest);\n\t\t\t\tstartupReceipt(observer, \"pod_acknowledged\");\n\t\t\t\tsamplers.get(input.instanceId)?.attachPod({\n\t\t\t\t\tname: manifest.metadata.name,\n\t\t\t\t\tworkerId: input.workerId,\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsamplers.get(input.instanceId)?.stop();\n\t\t\t\tsamplers.delete(input.instanceId);\n\t\t\t\tthrow new WorkerStartDiagnosticError(\n\t\t\t\t\tboundedKubernetesStartDiagnostic(error, Object.values(input.env)),\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t\tobserver?.report(\"starting_runtime\");\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tworkerId: input.workerId,\n\t\t\t\tunitId: manifest.metadata.name,\n\t\t\t\tnamespace: manifest.metadata.namespace,\n\t\t\t};\n\t\t\twatchPod(ref.unitId, ref.namespace ?? processNamespace, Object.values(input.env));\n\t\t\treturn exitNotifier.wrapUnit(ref, unitKey(ref.namespace ?? processNamespace, ref.unitId), {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t\tasync stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {\n\t\t\tsamplers.get(ref.instanceId)?.stop();\n\t\t\tsamplers.delete(ref.instanceId);\n\t\t\tawait deletePodAndWait(\n\t\t\t\tref.unitId,\n\t\t\t\tref.namespace ?? namespaceForProcess(ref.instanceId),\n\t\t\t\tMath.max(0, Math.ceil(opts.graceMs / 1000)),\n\t\t\t);\n\t\t},\n\t\tasync list(): Promise<WorkerUnitDescriptor[]> {\n\t\t\tconst namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());\n\t\t\tconst descriptors: WorkerUnitDescriptor[] = [];\n\t\t\tfor (const namespace of namespaces) {\n\t\t\t\tif (!namespace.name.startsWith(options.processNamespacePrefix)) continue;\n\t\t\t\tconst pods = await client.listPods(namespace.name, managedWorkerLabelSelector());\n\t\t\t\tfor (const pod of pods) {\n\t\t\t\t\tconst identity = parseWorkerUnitIdentity(pod.labels);\n\t\t\t\t\tif (!identity) continue;\n\t\t\t\t\tdescriptors.push({\n\t\t\t\t\t\tinstanceId: identity.instanceId,\n\t\t\t\t\t\tworkerId: identity.workerId,\n\t\t\t\t\t\tunitId: pod.name,\n\t\t\t\t\t\tnamespace: pod.namespace,\n\t\t\t\t\t\tobservedState:\n\t\t\t\t\t\t\tpod.phase === \"Failed\" || pod.phase === \"Succeeded\"\n\t\t\t\t\t\t\t\t? \"terminal\"\n\t\t\t\t\t\t\t\t: pod.phase === \"Pending\"\n\t\t\t\t\t\t\t\t\t? \"pending\"\n\t\t\t\t\t\t\t\t\t: pod.phase === \"Running\"\n\t\t\t\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t\t\t\t: \"unknown\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn descriptors;\n\t\t},\n\t\tasync adopt(descriptor: WorkerUnitDescriptor, observer): Promise<WorkerUnit> {\n\t\t\tconst podNamespace = descriptor.namespace ?? namespaceForProcess(descriptor.instanceId);\n\t\t\tconst pod = await client.getPod(descriptor.unitId, podNamespace);\n\t\t\tconst identity = pod ? parseWorkerUnitIdentity(pod.labels) : null;\n\t\t\tif (\n\t\t\t\t!identity ||\n\t\t\t\tidentity.instanceId !== descriptor.instanceId ||\n\t\t\t\tidentity.workerId !== descriptor.workerId\n\t\t\t) {\n\t\t\t\tthrow new Error(`Cannot adopt worker pod ${descriptor.unitId}: labels changed`);\n\t\t\t}\n\t\t\tif (!pod || pod.phase === \"Failed\" || pod.phase === \"Succeeded\") {\n\t\t\t\tthrow new Error(`Cannot adopt worker pod ${descriptor.unitId}: not running`);\n\t\t\t}\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: descriptor.instanceId,\n\t\t\t\tworkerId: descriptor.workerId,\n\t\t\t\tunitId: descriptor.unitId,\n\t\t\t\tnamespace: podNamespace,\n\t\t\t};\n\t\t\tif (observer?.observe && pod.pvcName) {\n\t\t\t\tsamplers.get(descriptor.instanceId)?.stop();\n\t\t\t\tconst sampler = sampleKubernetesStartup(client, observer, podNamespace, pod.pvcName);\n\t\t\t\tsampler.attachPod({ name: ref.unitId, workerId: ref.workerId, instanceId: ref.instanceId });\n\t\t\t\tsamplers.set(descriptor.instanceId, sampler);\n\t\t\t}\n\t\t\twatchPod(ref.unitId, podNamespace);\n\t\t\treturn exitNotifier.wrapUnit(ref, unitKey(podNamespace, ref.unitId), {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t};\n\n\tconst exporter = createHelperProcessStateExporter({\n\t\tvolume,\n\t\thelperRelays,\n\t\tasync launch(input) {\n\t\t\tconst namespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);\n\t\t\tconst podName = kubernetesExportHelperPodName(input.instanceId, input.exportId);\n\t\t\tconst manifest = buildKubernetesExportHelperPodManifest(\n\t\t\t\t{\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\timage: exporterImage,\n\t\t\t\t\tcommand: [\"node\", SESSION_TRANSFER_HELPER_ENTRY_PATH],\n\t\t\t\t\tenv: exportHelperEnvironment({\n\t\t\t\t\t\tserverUrl: exporterServerUrl,\n\t\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\t\tcredential: input.credential,\n\t\t\t\t\t}),\n\t\t\t\t\tvolume: { ...input.volume, mountPath: SESSION_TRANSFER_HELPER_MOUNT_PATH },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tnamespace,\n\t\t\t\t\t...(options.pod ?? {}),\n\t\t\t\t\timagePullPolicy: options.exporterImagePullPolicy,\n\t\t\t\t\t...serverCaConfig,\n\t\t\t\t},\n\t\t\t);\n\t\t\tawait client.createPod(manifest);\n\t\t\tconst exit = new Promise<{ exitCode: number | null; reason?: string }>((resolve) => {\n\t\t\t\tclient.onPodExit(podName, namespace, (info) =>\n\t\t\t\t\tresolve({ exitCode: info.exitCode, reason: info.reason }),\n\t\t\t\t);\n\t\t\t});\n\t\t\treturn {\n\t\t\t\twait: () => exit,\n\t\t\t\tremove: () => client.deletePod(podName, namespace, { gracePeriodSeconds: 0 }),\n\t\t\t};\n\t\t},\n\t\tasync reconcileHelpers() {\n\t\t\tconst namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());\n\t\t\tfor (const namespace of namespaces) {\n\t\t\t\tconst helpers = await client.listPods(namespace.name, managedExportHelperLabelSelector());\n\t\t\t\tawait Promise.all(\n\t\t\t\t\thelpers.map((helper) =>\n\t\t\t\t\t\tclient.deletePod(helper.name, helper.namespace, { gracePeriodSeconds: 0 }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t});\n\n\tconst preparationPullSecrets = (options.pod?.imagePullSecrets ?? []).map(\n\t\t(name) =>\n\t\t\toptions.imagePullSecretCopies?.find((copy) => copy.targetName === name)?.sourceName ?? name,\n\t);\n\tlet volumePool: ReturnType<typeof createKubernetesVolumePool> | undefined;\n\tif (options.preProvision) {\n\t\tif (!client.volumePool || !options.volume.storageClassName || !options.serverNamespace) {\n\t\t\tthrow new Error(\"Volume pre-provisioning requires an API, namespace and StorageClass\");\n\t\t}\n\t\tvolumePool = createKubernetesVolumePool({\n\t\t\tapi: client.volumePool,\n\t\t\tnamespace: options.serverNamespace,\n\t\t\tstorageClassName: options.volume.storageClassName,\n\t\t\tsize: options.volume.size,\n\t\t\taccessModes: options.volume.accessModes,\n\t\t\t...options.preProvision,\n\t\t\timage: exporterImage,\n\t\t\timagePullPolicy: options.exporterImagePullPolicy,\n\t\t\timagePullSecrets: preparationPullSecrets,\n\t\t\tnodeSelector: options.pod?.nodeSelector,\n\t\t\ttolerations: options.pod?.tolerations,\n\t\t});\n\t}\n\tlet imagePreload: ReturnType<typeof createKubernetesImagePreload> | undefined;\n\tif (options.imagePreload) {\n\t\tif (!client.imagePreload || !options.serverNamespace)\n\t\t\tthrow new Error(\"Image preloading requires an API and server namespace\");\n\t\timagePreload = createKubernetesImagePreload({\n\t\t\tapi: client.imagePreload,\n\t\t\tnamespace: options.serverNamespace,\n\t\t\t...options.imagePreload,\n\t\t\timagePullSecrets: preparationPullSecrets,\n\t\t\tnodeSelector: options.pod?.nodeSelector,\n\t\t\tadditionalNodeSelectors: options.docker\n\t\t\t\t? [{ ...options.pod?.nodeSelector, ...options.docker.nodeSelector }]\n\t\t\t\t: undefined,\n\t\t\ttolerations: options.pod?.tolerations,\n\t\t});\n\t}\n\tconst controllers = [volumePool, imagePreload].filter((value) => value !== undefined);\n\tconst preparation = controllers.length ? createKubernetesPreparation(controllers) : undefined;\n\treturn { runner, volume, exporter, preparation };\n}\n","import { createHash } from \"node:crypto\";\nimport type {\n\tImagePreloadApi,\n\tImagePreparationPod,\n\tPreparationNode,\n} from \"./kubernetes-image-preload-api.js\";\nimport { buildPreparationPodSpec, createPreparationController } from \"./kubernetes-preparation.js\";\n\nexport const IMAGE_PRELOAD_LABEL = \"leitwerk.dev/image-preload\";\nconst NODE_UID = \"leitwerk.dev/preparation-node-uid\";\nconst NODE_NAME = \"leitwerk.dev/preparation-node-name\";\nconst IMAGE = \"leitwerk.dev/preparation-image\";\nconst INTERVAL = 30_000;\nconst hash = (value: string) => createHash(\"sha256\").update(value).digest(\"hex\");\n\n/** @internal */\nexport interface ImagePreparationEvent {\n\t/** @internal */\n\tcomponent: \"image-preparation\";\n\t/** @internal */\n\toutcome: \"succeeded\" | \"failed\";\n\t/** @internal */\n\tnode?: string;\n\t/** @internal */\n\tnodeUid?: string;\n\t/** @internal */\n\timage?: string;\n\t/** @internal */\n\tpod?: string;\n\t/** @internal */\n\treason?: string;\n}\n\n/** @internal */\nexport function immutableWorkerImage(image: string): string {\n\tconst match = /^([a-zA-Z0-9][a-zA-Z0-9._:/-]*)@(sha256:[0-9a-f]{64})$/.exec(image);\n\tif (!match) throw new Error(\"Image preloading requires digest-qualified worker images\");\n\treturn `${match[1].replace(/:[^/:]+$/, \"\")}@${match[2]}`;\n}\n\n/** @internal */\nexport function eligiblePreparationNode(\n\tnode: PreparationNode,\n\tselector: Record<string, string>,\n\ttolerations: unknown[],\n): boolean {\n\tif (!node.metadata.uid || node.metadata.deletionTimestamp || node.spec?.unschedulable)\n\t\treturn false;\n\tif (\n\t\t!node.status?.conditions?.some(\n\t\t\t(condition) => condition.type === \"Ready\" && condition.status === \"True\",\n\t\t)\n\t)\n\t\treturn false;\n\tif (!Object.entries(selector).every(([key, value]) => node.metadata.labels?.[key] === value))\n\t\treturn false;\n\treturn (node.spec?.taints ?? []).every((taint) => {\n\t\tif (![\"NoSchedule\", \"NoExecute\"].includes(taint.effect)) return true;\n\t\treturn tolerations.some((value) => {\n\t\t\tif (!value || typeof value !== \"object\") return false;\n\t\t\tconst tolerance = value as Record<string, unknown>;\n\t\t\tif (tolerance.effect && tolerance.effect !== taint.effect) return false;\n\t\t\tif (tolerance.operator === \"Exists\") return !tolerance.key || tolerance.key === taint.key;\n\t\t\treturn (\n\t\t\t\t(!tolerance.operator || tolerance.operator === \"Equal\") &&\n\t\t\t\ttolerance.key === taint.key &&\n\t\t\t\t(tolerance.value ?? \"\") === (taint.value ?? \"\")\n\t\t\t);\n\t\t});\n\t});\n}\n\n/** @internal */\nexport function createKubernetesImagePreload(options: {\n\t/** @internal */\n\tapi: ImagePreloadApi;\n\t/** @internal */\n\tnamespace: string;\n\t/** @internal */\n\timages: string[];\n\t/** @internal */\n\timagePullSecrets?: string[];\n\t/** @internal */\n\tnodeSelector?: Record<string, string>;\n\t/** Other worker placements to prepare, deduplicated by node and image. @internal */\n\tadditionalNodeSelectors?: Record<string, string>[];\n\t/** @internal */\n\ttolerations?: unknown[];\n\t/** @internal */\n\tonEvent?: (event: ImagePreparationEvent) => void;\n}) {\n\tconst { api, namespace } = options;\n\tconst nodeSelectors = [options.nodeSelector ?? {}, ...(options.additionalNodeSelectors ?? [])];\n\tconst selectorForNode = (node: PreparationNode) =>\n\t\tnodeSelectors.find((selector) =>\n\t\t\teligiblePreparationNode(node, selector, options.tolerations ?? []),\n\t\t);\n\tconst images = [...new Set(options.images.map(immutableWorkerImage))];\n\tconst preloadId = hash(namespace).slice(0, 16);\n\tconst selector = `${IMAGE_PRELOAD_LABEL}=${preloadId}`;\n\tconst labels = {\n\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t\"leitwerk.dev/component\": \"image-preparation\",\n\t\t[IMAGE_PRELOAD_LABEL]: preloadId,\n\t};\n\tconst podName = (uid: string, image: string) =>\n\t\t`lw-image-${hash(`${uid}/${image}`).slice(0, 40)}`;\n\tconst reported = new Map<string, string>();\n\tconst failedSince = new Map<string, number>();\n\n\tfunction owned(pod: ImagePreparationPod) {\n\t\tconst annotations = pod.metadata.annotations ?? {};\n\t\tconst uid = annotations[NODE_UID];\n\t\tconst name = annotations[NODE_NAME];\n\t\tconst image = annotations[IMAGE];\n\t\tconst containers = pod.spec.containers as\n\t\t\t| Array<{\n\t\t\t\t\t/** @internal */ image?: string /** @internal */;\n\t\t\t\t\tcommand?: string[];\n\t\t\t }>\n\t\t\t| undefined;\n\t\treturn (\n\t\t\tpod.metadata.namespace === namespace &&\n\t\t\t!!pod.metadata.uid &&\n\t\t\t!!uid &&\n\t\t\t!!name &&\n\t\t\t!!image &&\n\t\t\tObject.entries(labels).every(([key, value]) => pod.metadata.labels?.[key] === value) &&\n\t\t\tpod.metadata.name === podName(uid, image) &&\n\t\t\tpod.metadata.ownerReferences?.some(\n\t\t\t\t(owner) =>\n\t\t\t\t\towner.apiVersion === \"v1\" &&\n\t\t\t\t\towner.kind === \"Node\" &&\n\t\t\t\t\towner.name === name &&\n\t\t\t\t\towner.uid === uid,\n\t\t\t) &&\n\t\t\tpod.spec.nodeName === name &&\n\t\t\tpod.spec.automountServiceAccountToken === false &&\n\t\t\tcontainers?.length === 1 &&\n\t\t\tcontainers[0].image === image &&\n\t\t\tJSON.stringify(containers[0].command) === JSON.stringify([\"node\", \"-e\", \"process.exit(0)\"])\n\t\t);\n\t}\n\tfunction report(\n\t\tpod: ImagePreparationPod,\n\t\toutcome: ImagePreparationEvent[\"outcome\"],\n\t\treason?: string,\n\t) {\n\t\tconst uid = pod.metadata.uid ?? pod.metadata.name;\n\t\tconst state = `${outcome}/${reason ?? \"\"}`;\n\t\tif (reported.get(uid) === state) return;\n\t\treported.set(uid, state);\n\t\toptions.onEvent?.({\n\t\t\tcomponent: \"image-preparation\",\n\t\t\toutcome,\n\t\t\treason,\n\t\t\tpod: pod.metadata.name,\n\t\t\tnode: pod.metadata.annotations?.[NODE_NAME],\n\t\t\tnodeUid: pod.metadata.annotations?.[NODE_UID],\n\t\t\timage: pod.metadata.annotations?.[IMAGE],\n\t\t});\n\t}\n\tfunction manifest(\n\t\tnode: PreparationNode,\n\t\timage: string,\n\t\tnodeSelector: Record<string, string>,\n\t): ImagePreparationPod {\n\t\tconst uid = node.metadata.uid ?? \"\";\n\t\treturn {\n\t\t\tapiVersion: \"v1\",\n\t\t\tkind: \"Pod\",\n\t\t\tmetadata: {\n\t\t\t\tname: podName(uid, image),\n\t\t\t\tnamespace,\n\t\t\t\tlabels,\n\t\t\t\tannotations: { [NODE_UID]: uid, [NODE_NAME]: node.metadata.name, [IMAGE]: image },\n\t\t\t\townerReferences: [{ apiVersion: \"v1\", kind: \"Node\", name: node.metadata.name, uid }],\n\t\t\t},\n\t\t\tspec: {\n\t\t\t\t...buildPreparationPodSpec({\n\t\t\t\t\t...options,\n\t\t\t\t\timage,\n\t\t\t\t\timagePullPolicy: \"IfNotPresent\",\n\t\t\t\t\tnodeSelector: { ...nodeSelector },\n\t\t\t\t}),\n\t\t\t\tnodeName: node.metadata.name,\n\t\t\t\tsecurityContext: {\n\t\t\t\t\trunAsNonRoot: true,\n\t\t\t\t\trunAsUser: 1000,\n\t\t\t\t\trunAsGroup: 1000,\n\t\t\t\t\tseccompProfile: { type: \"RuntimeDefault\" },\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\t/** @internal */\n\tasync function reconcile(signal: AbortSignal) {\n\t\tconst nodes = await api.listNodes(signal);\n\t\tconst desired = new Map<string, ImagePreparationPod>();\n\t\tfor (const node of nodes) {\n\t\t\tconst nodeSelector = selectorForNode(node);\n\t\t\tif (!nodeSelector) continue;\n\t\t\tfor (const image of images) {\n\t\t\t\tconst pod = manifest(node, image, nodeSelector);\n\t\t\t\tdesired.set(pod.metadata.name, pod);\n\t\t\t}\n\t\t}\n\t\tconst pods = await api.listPods(namespace, selector, signal);\n\t\tfor (const pod of pods) {\n\t\t\tif (desired.has(pod.metadata.name) || !owned(pod) || pod.metadata.deletionTimestamp) continue;\n\t\t\ttry {\n\t\t\t\tawait api.deletePod(namespace, pod, signal);\n\t\t\t} catch {\n\t\t\t\tif (!signal.aborted) report(pod, \"failed\", \"cleanup_failed\");\n\t\t\t}\n\t\t}\n\t\tconst liveUids = new Set(pods.map((pod) => pod.metadata.uid ?? \"\"));\n\t\tfor (const uid of reported.keys())\n\t\t\tif (!liveUids.has(uid)) {\n\t\t\t\treported.delete(uid);\n\t\t\t\tfailedSince.delete(uid);\n\t\t\t}\n\t\tfor (const expected of desired.values()) {\n\t\t\ttry {\n\t\t\t\tconst pod =\n\t\t\t\t\tpods.find((value) => value.metadata.name === expected.metadata.name) ??\n\t\t\t\t\t(await api.getPod(namespace, expected.metadata.name, signal));\n\t\t\t\tif (!pod) {\n\t\t\t\t\tawait api.createPod(namespace, expected, signal);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!owned(pod)) {\n\t\t\t\t\treport(expected, \"failed\", \"ownership_mismatch\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (pod.metadata.deletionTimestamp) continue;\n\t\t\t\tif (pod.status?.phase === \"Succeeded\") {\n\t\t\t\t\treport(pod, \"succeeded\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (pod.status?.phase === \"Failed\") {\n\t\t\t\t\treport(pod, \"failed\", \"pod_failed\");\n\t\t\t\t\tconst uid = pod.metadata.uid ?? \"\";\n\t\t\t\t\tconst finished = Date.parse(\n\t\t\t\t\t\tpod.status.containerStatuses?.[0]?.state?.terminated?.finishedAt ?? \"\",\n\t\t\t\t\t);\n\t\t\t\t\tconst since = failedSince.get(uid) ?? (Number.isFinite(finished) ? finished : Date.now());\n\t\t\t\t\tfailedSince.set(uid, since);\n\t\t\t\t\tif (Date.now() - since >= INTERVAL) {\n\t\t\t\t\t\tawait api.deletePod(namespace, pod, signal);\n\t\t\t\t\t\tawait api.createPod(namespace, expected, signal);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reason = pod.status?.containerStatuses?.[0]?.state?.waiting?.reason;\n\t\t\t\tif (\n\t\t\t\t\treason === \"ErrImagePull\" ||\n\t\t\t\t\treason === \"ImagePullBackOff\" ||\n\t\t\t\t\treason === \"InvalidImageName\"\n\t\t\t\t)\n\t\t\t\t\treport(pod, \"failed\", reason);\n\t\t\t} catch {\n\t\t\t\tif (!signal.aborted) report(expected, \"failed\", \"api_error\");\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\t/** @internal */\n\t\treconcile,\n\t\t...createPreparationController(reconcile, INTERVAL, () =>\n\t\t\toptions.onEvent?.({\n\t\t\t\tcomponent: \"image-preparation\",\n\t\t\t\toutcome: \"failed\",\n\t\t\t\treason: \"discovery_failed\",\n\t\t\t}),\n\t\t),\n\t};\n}\n","import { setTimeout as delay } from \"node:timers/promises\";\nimport type { VolumePoolOptions } from \"./kubernetes-volume-pool.js\";\nimport type { PoolObject } from \"./kubernetes-volume-pool-api.js\";\n\n/** Shared inert preparation workload; callers supply ownership and placement constraints. @internal */\nexport function buildPreparationPodSpec(\n\toptions: Pick<\n\t\tVolumePoolOptions,\n\t\t\"image\" | \"imagePullPolicy\" | \"imagePullSecrets\" | \"nodeSelector\" | \"tolerations\"\n\t>,\n\tvolumeMounts?: unknown[],\n): PoolObject[\"spec\"] {\n\treturn {\n\t\trestartPolicy: \"Never\",\n\t\tserviceAccountName: \"default\",\n\t\tautomountServiceAccountToken: false,\n\t\tnodeSelector: options.nodeSelector ?? {},\n\t\ttolerations: options.tolerations ?? [],\n\t\timagePullSecrets: (options.imagePullSecrets ?? []).map((name) => ({ name })),\n\t\tcontainers: [\n\t\t\t{\n\t\t\t\tname: \"prepare\",\n\t\t\t\timage: options.image,\n\t\t\t\timagePullPolicy: options.imagePullPolicy ?? \"IfNotPresent\",\n\t\t\t\tcommand: [\"node\", \"-e\", \"process.exit(0)\"],\n\t\t\t\tresources: {\n\t\t\t\t\trequests: { cpu: \"1m\", memory: \"32Mi\" },\n\t\t\t\t\tlimits: { cpu: \"100m\", memory: \"64Mi\" },\n\t\t\t\t},\n\t\t\t\tsecurityContext: {\n\t\t\t\t\tallowPrivilegeEscalation: false,\n\t\t\t\t\treadOnlyRootFilesystem: true,\n\t\t\t\t\tcapabilities: { drop: [\"ALL\"] },\n\t\t\t\t},\n\t\t\t\t...(volumeMounts ? { volumeMounts } : {}),\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** @internal */\nexport interface PreparationController {\n\t/** @internal */\n\tstart(): void;\n\t/** @internal */\n\tstop(): Promise<void>;\n}\n\n/** One non-overlapping loop; stopping cancels and joins its current work. @internal */\nexport function createPreparationController(\n\treconcile: (signal: AbortSignal) => Promise<void>,\n\tintervalMs: number,\n\tonError?: (error?: unknown) => void,\n\terrorIntervalMs = intervalMs,\n): PreparationController {\n\tlet controller: AbortController | undefined;\n\tlet running: Promise<void> | undefined;\n\treturn {\n\t\tstart() {\n\t\t\tif (controller) return;\n\t\t\tcontroller = new AbortController();\n\t\t\tconst { signal } = controller;\n\t\t\trunning = (async () => {\n\t\t\t\twhile (!signal.aborted) {\n\t\t\t\t\tlet interval = intervalMs;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait reconcile(signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinterval = errorIntervalMs;\n\t\t\t\t\t\tif (!signal.aborted) onError?.(error);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait delay(interval, undefined, { signal });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\t\tasync stop() {\n\t\t\tcontroller?.abort();\n\t\t\tawait running;\n\t\t\tcontroller = undefined;\n\t\t},\n\t};\n}\n\n/** Controllers own separate asynchronous reconciliation loops. @internal */\nexport function createKubernetesPreparation(controllers: PreparationController[]) {\n\treturn {\n\t\t/** @internal */\n\t\tstart() {\n\t\t\tfor (const controller of controllers) controller.start();\n\t\t},\n\t\t/** @internal */\n\t\tasync stop() {\n\t\t\tawait Promise.allSettled(controllers.map((controller) => controller.stop()));\n\t\t},\n\t};\n}\n","import type { StartupMilestone, StartupObservation } from \"@leitwerk-dev/domain\";\nimport type { KubernetesApiClient } from \"./kubernetes-api-client.js\";\nimport type { WorkerStartObserver } from \"./types.js\";\nimport { parseWorkerUnitIdentity } from \"./worker-labels.js\";\nexport function startupReceipt(\n\tobserver: WorkerStartObserver | undefined,\n\tmilestone: StartupMilestone,\n\tmetadata: StartupObservation[\"metadata\"] = {},\n): void {\n\ttry {\n\t\tobserver?.observe?.({\n\t\t\tmilestone,\n\t\t\tobservedAt: new Date().toISOString(),\n\t\t\tsourceAt: null,\n\t\t\tsourceKind: \"server\",\n\t\t\tobjectUid: null,\n\t\t\tnotBefore: null,\n\t\t\tmetadata,\n\t\t});\n\t} catch {\n\t\t/* Observation cannot fail startup. */\n\t}\n}\n/** One asynchronous collection cycle per physical worker. Never awaited by lifecycle work. */\nexport function sampleKubernetesStartup(\n\tclient: KubernetesApiClient,\n\tobserver: WorkerStartObserver,\n\tnamespace: string,\n\tpvcName: string,\n) {\n\tlet pod: { name: string; workerId: string; instanceId: string } | undefined;\n\tlet podUid: string | undefined;\n\tlet pvcUid: string | undefined;\n\tlet lastUnbound: string | null = null;\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet active: AbortController | undefined;\n\tlet failures = 0;\n\tconst seen = new Set<StartupMilestone>();\n\tconst deadline = Date.now() + 120_000;\n\tconst emit = (\n\t\tmilestone: StartupMilestone,\n\t\tobjectUid: string,\n\t\tsourceAt: string | null,\n\t\tmetadata: StartupObservation[\"metadata\"],\n\t\tsourceKind: StartupObservation[\"sourceKind\"] = \"kubernetes_status\",\n\t\tnotBefore: string | null = null,\n\t) => {\n\t\tif (\n\t\t\tstopped ||\n\t\t\tseen.has(milestone) ||\n\t\t\t(sourceAt !== null && !Number.isFinite(Date.parse(sourceAt)))\n\t\t)\n\t\t\treturn;\n\t\tobserver.observe?.({\n\t\t\tmilestone,\n\t\t\tobservedAt: new Date().toISOString(),\n\t\t\tsourceAt,\n\t\t\tobjectUid,\n\t\t\tsourceKind,\n\t\t\tnotBefore,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\t...(sourceAt !== null ? { precision: sourcePrecision(sourceAt) } : {}),\n\t\t\t},\n\t\t});\n\t\tseen.add(milestone);\n\t};\n\tconst stop = () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tactive?.abort();\n\t};\n\tconst reportFailure = () => {\n\t\tif (!stopped && failures++ < 3)\n\t\t\tconsole.warn(\"Worker startup observation unavailable: Kubernetes collection failed\");\n\t};\n\tconst cycle = async () => {\n\t\tif (stopped || observer.shouldStop?.() || Date.now() >= deadline) {\n\t\t\tstop();\n\t\t\treturn;\n\t\t}\n\t\tactive = new AbortController();\n\t\tconst timeout = setTimeout(() => active?.abort(), 1500);\n\t\tconst signal = active.signal;\n\t\tconst collectPvc = async () => {\n\t\t\tif (!seen.has(\"pvc_bound\") && client.getPersistentVolumeClaim) {\n\t\t\t\tconst pvc = await client.getPersistentVolumeClaim(pvcName, namespace, { signal });\n\t\t\t\tif (pvc?.uid) {\n\t\t\t\t\tif (pvcUid && pvcUid !== pvc.uid) {\n\t\t\t\t\t\tstop();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpvcUid = pvc.uid;\n\t\t\t\t\tif (pvc.phase === \"Bound\")\n\t\t\t\t\t\temit(\n\t\t\t\t\t\t\t\"pvc_bound\",\n\t\t\t\t\t\t\tpvc.uid,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{ storageClass: pvc.storageClass, precision: \"sampling_interval\" },\n\t\t\t\t\t\t\t\"kubernetes_status\",\n\t\t\t\t\t\t\tlastUnbound,\n\t\t\t\t\t\t);\n\t\t\t\t\telse lastUnbound = new Date().toISOString();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tconst collectPod = async () => {\n\t\t\tif (pod) {\n\t\t\t\tconst summary = await client.getPod(pod.name, namespace, { signal });\n\t\t\t\tif (!summary) {\n\t\t\t\t\tstop();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst identity = parseWorkerUnitIdentity(summary.labels);\n\t\t\t\tif (\n\t\t\t\t\t!identity ||\n\t\t\t\t\tidentity.workerId !== pod.workerId ||\n\t\t\t\t\tidentity.instanceId !== pod.instanceId ||\n\t\t\t\t\t(podUid && podUid !== summary.uid)\n\t\t\t\t) {\n\t\t\t\t\tstop();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (summary.uid) {\n\t\t\t\t\tpodUid = summary.uid;\n\t\t\t\t\tconst metadata = {\n\t\t\t\t\t\tnode: summary.node,\n\t\t\t\t\t\timageId: summary.imageId,\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tpodName: pod.name,\n\t\t\t\t\t\t...summary.resources,\n\t\t\t\t\t};\n\t\t\t\t\tif (summary.createdAt) emit(\"pod_created\", podUid, summary.createdAt, metadata);\n\t\t\t\t\tif (summary.scheduledAt) emit(\"pod_scheduled\", podUid, summary.scheduledAt, metadata);\n\t\t\t\t\tif (summary.containerStartedAt)\n\t\t\t\t\t\temit(\"container_started\", podUid, summary.containerStartedAt, metadata);\n\t\t\t\t\tconst events = await client.listPodEvents(pod.name, namespace, { signal });\n\t\t\t\t\tfor (const event of events) {\n\t\t\t\t\t\tif (event.objectUid !== podUid || event.fieldPath !== \"spec.containers{worker}\")\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tconst at = event.eventTime || event.firstTimestamp;\n\t\t\t\t\t\tif (!at) continue;\n\t\t\t\t\t\tif (event.reason === \"Pulling\")\n\t\t\t\t\t\t\temit(\"image_pull_started\", podUid, at, metadata, \"kubernetes_event\");\n\t\t\t\t\t\tif (event.reason === \"Pulled\")\n\t\t\t\t\t\t\temit(\n\t\t\t\t\t\t\t\tevent.message?.includes(\"already present\") ? \"image_cached\" : \"image_pull_finished\",\n\t\t\t\t\t\t\t\tpodUid,\n\t\t\t\t\t\t\t\tat,\n\t\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t\t\t\"kubernetes_event\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (summary.phase === \"Failed\" || summary.phase === \"Succeeded\") stop();\n\t\t\t}\n\t\t};\n\t\ttry {\n\t\t\tawait Promise.all([collectPvc().catch(reportFailure), collectPod().catch(reportFailure)]);\n\t\t\tif (\n\t\t\t\tseen.has(\"container_started\") &&\n\t\t\t\tseen.has(\"pod_scheduled\") &&\n\t\t\t\tseen.has(\"pvc_bound\") &&\n\t\t\t\t(seen.has(\"image_cached\") ||\n\t\t\t\t\t(seen.has(\"image_pull_started\") && seen.has(\"image_pull_finished\")))\n\t\t\t)\n\t\t\t\tstop();\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tactive = undefined;\n\t\t\tif (!stopped) {\n\t\t\t\ttimer = setTimeout(() => void cycle(), 250);\n\t\t\t\ttimer.unref?.();\n\t\t\t}\n\t\t}\n\t};\n\ttimer = setTimeout(() => void cycle(), 0);\n\ttimer.unref?.();\n\treturn {\n\t\tstop,\n\t\tattachPod(input: NonNullable<typeof pod>) {\n\t\t\tpod = input;\n\t\t},\n\t};\n}\n\nfunction sourcePrecision(timestamp: string): \"seconds\" | \"milliseconds\" | \"microseconds\" {\n\tconst digits = /\\.(\\d+)/.exec(timestamp)?.[1].length ?? 0;\n\treturn digits === 0 ? \"seconds\" : digits <= 3 ? \"milliseconds\" : \"microseconds\";\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { buildPreparationPodSpec, createPreparationController } from \"./kubernetes-preparation.js\";\nimport type { PoolObject, VolumePoolApi } from \"./kubernetes-volume-pool-api.js\";\n\nexport const POOL_LABEL = \"leitwerk.dev/volume-pool\";\nconst CLAIM_UID = \"leitwerk.dev/preparation-claim-uid\";\nconst CLAIM_NAME = \"leitwerk.dev/preparation-claim-name\";\nconst POLICY = \"leitwerk.dev/original-reclaim-policy\";\nconst TARGET_CLASS = \"leitwerk.dev/target-storage-class\";\nconst STATE = \"leitwerk.dev/volume-pool-state\";\nconst SIZE = \"leitwerk.dev/preparation-size\";\nconst MODES = \"leitwerk.dev/preparation-access-modes\";\n\n/** @internal */\nexport interface VolumePoolOptions {\n\t/** @internal */\n\tapi: VolumePoolApi;\n\t/** @internal */\n\tnamespace: string;\n\t/** @internal */\n\tcount: number;\n\t/** @internal */\n\tstorageClassName: string;\n\t/** @internal */\n\tsize: string;\n\t/** @internal */\n\taccessModes: string[];\n\t/** @internal */\n\timage: string;\n\t/** @internal */\n\timagePullPolicy?: string;\n\t/** @internal */\n\timagePullSecrets?: string[];\n\t/** @internal */\n\tnodeSelector?: Record<string, string>;\n\t/** @internal */\n\ttolerations?: unknown[];\n\t/** @internal */\n\tonError?: (error?: unknown) => void;\n\t/** Clock seam; Kubernetes creation times survive controller restarts. @internal */\n\tnow?: () => number;\n}\n\n/** Only the staging claim's UID authorizes rebinding; process claims are never recycled. @internal */\nexport function createKubernetesVolumePool(options: VolumePoolOptions) {\n\tconst { api, namespace } = options;\n\tif (!Number.isSafeInteger(options.count) || options.count < 0)\n\t\tthrow new Error(\"Invalid volume pool count\");\n\tconst poolId = createHash(\"sha256\")\n\t\t.update(`${namespace}/${options.storageClassName}`)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 16);\n\tconst selector = `${POOL_LABEL}=${poolId}`;\n\tconst labels = {\n\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t[POOL_LABEL]: poolId,\n\t\t\"leitwerk.dev/component\": \"volume-preparation\",\n\t};\n\n\tfunction preparationPod(claim: PoolObject): PoolObject {\n\t\treturn {\n\t\t\tapiVersion: \"v1\",\n\t\t\tkind: \"Pod\",\n\t\t\tmetadata: {\n\t\t\t\tname: claim.metadata.name,\n\t\t\t\tnamespace,\n\t\t\t\tlabels,\n\t\t\t\townerReferences: [\n\t\t\t\t\t{\n\t\t\t\t\t\tapiVersion: \"v1\",\n\t\t\t\t\t\tkind: \"PersistentVolumeClaim\",\n\t\t\t\t\t\tname: claim.metadata.name,\n\t\t\t\t\t\tuid: claim.metadata.uid ?? \"\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tspec: {\n\t\t\t\t...buildPreparationPodSpec(options, [{ name: \"volume\", mountPath: \"/volume\" }]),\n\t\t\t\tactiveDeadlineSeconds: 900,\n\t\t\t\tvolumes: [{ name: \"volume\", persistentVolumeClaim: { claimName: claim.metadata.name } }],\n\t\t\t},\n\t\t};\n\t}\n\n\tasync function advanceVolume(pv: PoolObject, signal: AbortSignal): Promise<boolean> {\n\t\tconst annotations = pv.metadata.annotations ?? {};\n\t\tconst uid = annotations[CLAIM_UID];\n\t\tconst name = annotations[CLAIM_NAME];\n\t\tconst policy = annotations[POLICY];\n\t\tif (!uid || !name || ![\"Delete\", \"Retain\"].includes(policy))\n\t\t\tthrow new Error(\"Invalid prepared-volume ownership\");\n\t\tif (pv.metadata.deletionTimestamp) return false;\n\t\tconst claim = pv.spec.claimRef;\n\t\tif (claim && claim.uid !== uid) {\n\t\t\t// A process has consumed this PV, including if it was already released again.\n\t\t\tconst remainingLabels = { ...pv.metadata.labels };\n\t\t\tdelete remainingLabels[POOL_LABEL];\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: policy },\n\t\t\t\t\t{ op: \"add\", path: \"/metadata/labels\", value: remainingLabels },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tif (claim) {\n\t\t\tif (pv.spec.persistentVolumeReclaimPolicy !== \"Retain\")\n\t\t\t\tthrow new Error(\"Staging PV must be retained before release\");\n\t\t\tconst pod = await api.get(\"pods\", namespace, name, signal);\n\t\t\tif (pod) {\n\t\t\t\tif (\n\t\t\t\t\tpod.metadata.labels?.[POOL_LABEL] !== poolId ||\n\t\t\t\t\t!pod.metadata.ownerReferences?.some((owner) => owner.uid === uid)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Preparation Pod ownership mismatch\");\n\t\t\t\tawait api.delete(\"pods\", namespace, pod, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst pvc = await api.get(\"persistentvolumeclaims\", namespace, name, signal);\n\t\t\tif (pvc) {\n\t\t\t\tif (pvc.metadata.uid !== uid) throw new Error(\"Preparation PVC ownership mismatch\");\n\t\t\t\tawait api.delete(\"persistentvolumeclaims\", namespace, pvc, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (pv.status?.phase === \"Released\") {\n\t\t\t\tawait api.patchVolume(\n\t\t\t\t\tpv,\n\t\t\t\t\t[\n\t\t\t\t\t\t{ op: \"test\", path: \"/spec/claimRef/uid\", value: uid },\n\t\t\t\t\t\t{ op: \"remove\", path: \"/spec/claimRef\" },\n\t\t\t\t\t],\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\t// Never restore Delete while the old Released status remains: a provisioner could reclaim it.\n\t\tif (pv.status?.phase === \"Available\" && annotations[STATE] !== \"ready\") {\n\t\t\tconst stagingClass = await api.getStorageClass(name, signal);\n\t\t\tif (stagingClass) {\n\t\t\t\tif (stagingClass.metadata.labels?.[POOL_LABEL] !== poolId)\n\t\t\t\t\tthrow new Error(\"Staging StorageClass ownership mismatch\");\n\t\t\t\tawait api.deleteStorageClass(stagingClass, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst targetClass = annotations[TARGET_CLASS];\n\t\t\tif (!targetClass) throw new Error(\"Target StorageClass is missing\");\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: policy },\n\t\t\t\t\t{ op: \"add\", path: \"/spec/storageClassName\", value: targetClass },\n\t\t\t\t\t{ op: \"add\", path: \"/metadata/annotations\", value: { ...annotations, [STATE]: \"ready\" } },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\tannotations[STATE] !== \"ready\" ||\n\t\t\t(annotations[SIZE] === options.size &&\n\t\t\t\tannotations[MODES] === JSON.stringify(options.accessModes))\n\t\t);\n\t}\n\n\t/** @internal */\n\tasync function reconcile(signal: AbortSignal) {\n\t\tconst volumes = await api.list(\"persistentvolumes\", \"\", selector, signal);\n\t\tconst classes = await api.listStorageClasses(selector, signal);\n\t\tconst active = new Set<string>(classes.map((value) => value.metadata.name));\n\t\tfor (const pv of volumes) {\n\t\t\tif (await advanceVolume(pv, signal)) active.add(pv.metadata.annotations?.[CLAIM_NAME] ?? \"\");\n\t\t}\n\t\tconst failures: string[] = [];\n\t\tconst claims = await api.list(\"persistentvolumeclaims\", namespace, selector, signal);\n\t\tfor (const claim of claims) {\n\t\t\tactive.add(claim.metadata.name);\n\t\t\tif (!claim.metadata.uid || claim.spec.storageClassName !== claim.metadata.name)\n\t\t\t\tthrow new Error(\"Invalid staging PVC identity\");\n\t\t\tif (\n\t\t\t\tclaim.metadata.deletionTimestamp ||\n\t\t\t\tvolumes.some((pv) => pv.metadata.annotations?.[CLAIM_UID] === claim.metadata.uid)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tconst pod = await api.get(\"pods\", namespace, claim.metadata.name, signal);\n\t\t\tif (!pod) {\n\t\t\t\tawait api.create(\"pods\", namespace, preparationPod(claim), signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tpod.metadata.labels?.[POOL_LABEL] !== poolId ||\n\t\t\t\t!pod.metadata.ownerReferences?.some((owner) => owner.uid === claim.metadata.uid)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Preparation Pod ownership mismatch\");\n\t\t\tconst created = Date.parse(claim.metadata.creationTimestamp ?? \"\");\n\t\t\tconst ageSeconds = Number.isFinite(created)\n\t\t\t\t? Math.max(0, Math.floor(((options.now?.() ?? Date.now()) - created) / 1_000))\n\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\tpod.status?.phase === \"Failed\" ||\n\t\t\t\t(pod.status?.phase !== \"Succeeded\" && ageSeconds !== undefined && ageSeconds >= 900)\n\t\t\t) {\n\t\t\t\t// Keep the failed receipt and reservation across restarts. An operator retries\n\t\t\t\t// the same PVC by deleting its Pod only after fixing storage; never allocate\n\t\t\t\t// another volume to work around replica scheduling or attach failures.\n\t\t\t\tfailures.push(\n\t\t\t\t\t`${namespace}/${pod.metadata.name}: age=${ageSeconds ?? \"unknown\"}s phase=${pod.status?.phase ?? \"unknown\"} reason=${pod.status?.reason ?? pod.status?.conditions?.find((condition) => condition.status === \"False\")?.reason ?? \"inspect Pod events and CSI/Longhorn scheduling conditions\"}`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (pod.status?.phase !== \"Succeeded\" || !claim.spec.volumeName) continue;\n\t\t\tconst pv = await api.get(\"persistentvolumes\", \"\", claim.spec.volumeName, signal);\n\t\t\tif (\n\t\t\t\t!pv ||\n\t\t\t\tpv.spec.claimRef?.uid !== claim.metadata.uid ||\n\t\t\t\tpv.metadata.ownerReferences?.length ||\n\t\t\t\tpv.metadata.deletionTimestamp\n\t\t\t)\n\t\t\t\tthrow new Error(\"Cannot safely retain staging volume\");\n\t\t\tif (pv.metadata.labels?.[POOL_LABEL]) throw new Error(\"PV already belongs to a pool\");\n\t\t\tconst policy = pv.spec.persistentVolumeReclaimPolicy;\n\t\t\tif (!policy || ![\"Delete\", \"Retain\"].includes(policy))\n\t\t\t\tthrow new Error(\"Unsupported reclaim policy\");\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/metadata/labels\",\n\t\t\t\t\t\tvalue: { ...pv.metadata.labels, [POOL_LABEL]: poolId },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/metadata/annotations\",\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\t...pv.metadata.annotations,\n\t\t\t\t\t\t\t[CLAIM_UID]: claim.metadata.uid,\n\t\t\t\t\t\t\t[CLAIM_NAME]: claim.metadata.name,\n\t\t\t\t\t\t\t[POLICY]: policy,\n\t\t\t\t\t\t\t[STATE]: \"preparing\",\n\t\t\t\t\t\t\t\"leitwerk.dev/preparation-pod-uid\": pod.metadata.uid ?? \"\",\n\t\t\t\t\t\t\t\"leitwerk.dev/preparation-image\": options.image,\n\t\t\t\t\t\t\t\"leitwerk.dev/preparation-completed-at\": new Date(\n\t\t\t\t\t\t\t\toptions.now?.() ?? Date.now(),\n\t\t\t\t\t\t\t).toISOString(),\n\t\t\t\t\t\t\t[TARGET_CLASS]: options.storageClassName,\n\t\t\t\t\t\t\t[SIZE]: claim.metadata.annotations?.[SIZE],\n\t\t\t\t\t\t\t[MODES]: claim.metadata.annotations?.[MODES],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: \"Retain\" },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\tfor (const stagingClass of classes) {\n\t\t\tconst name = stagingClass.metadata.name;\n\t\t\tif (\n\t\t\t\tstagingClass.metadata.deletionTimestamp ||\n\t\t\t\tclaims.some((claim) => claim.metadata.name === name) ||\n\t\t\t\tvolumes.some((pv) => pv.metadata.annotations?.[CLAIM_NAME] === name)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tawait api.create(\n\t\t\t\t\"persistentvolumeclaims\",\n\t\t\t\tnamespace,\n\t\t\t\t{\n\t\t\t\t\tapiVersion: \"v1\",\n\t\t\t\t\tkind: \"PersistentVolumeClaim\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tlabels,\n\t\t\t\t\t\tannotations: {\n\t\t\t\t\t\t\t[SIZE]: stagingClass.metadata.annotations?.[SIZE] ?? \"\",\n\t\t\t\t\t\t\t[MODES]: stagingClass.metadata.annotations?.[MODES] ?? \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tspec: {\n\t\t\t\t\t\tstorageClassName: name,\n\t\t\t\t\t\taccessModes: JSON.parse(stagingClass.metadata.annotations?.[MODES] ?? \"null\"),\n\t\t\t\t\t\tvolumeMode: \"Filesystem\",\n\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\trequests: {\n\t\t\t\t\t\t\t\tstorage: stagingClass.metadata.annotations?.[SIZE],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\tif (active.size < options.count) {\n\t\t\tconst source = await api.getStorageClass(options.storageClassName, signal);\n\t\t\tif (!source || [\"kubernetes.io/no-provisioner\", \"manual\"].includes(source.provisioner))\n\t\t\t\tthrow new Error(\"Volume pre-provisioning requires a dynamic StorageClass\");\n\t\t\tfor (let i = active.size; i < options.count; i++) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t// A unique staging class prevents preparation PVCs from consuming the ready pool.\n\t\t\t\tawait api.createStorageClass(\n\t\t\t\t\t{\n\t\t\t\t\t\tapiVersion: \"storage.k8s.io/v1\",\n\t\t\t\t\t\tkind: \"StorageClass\",\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tname: `lw-volume-${randomUUID()}`,\n\t\t\t\t\t\t\tlabels,\n\t\t\t\t\t\t\tannotations: {\n\t\t\t\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\t\t\t\tObject.entries(source.metadata.annotations ?? {}).filter(\n\t\t\t\t\t\t\t\t\t\t([key]) =>\n\t\t\t\t\t\t\t\t\t\t\t![\n\t\t\t\t\t\t\t\t\t\t\t\t\"storageclass.kubernetes.io/is-default-class\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"storageclass.beta.kubernetes.io/is-default-class\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"kubectl.kubernetes.io/last-applied-configuration\",\n\t\t\t\t\t\t\t\t\t\t\t].includes(key),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t[SIZE]: options.size,\n\t\t\t\t\t\t\t\t[MODES]: JSON.stringify(options.accessModes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprovisioner: source.provisioner,\n\t\t\t\t\t\tparameters: source.parameters,\n\t\t\t\t\t\treclaimPolicy: source.reclaimPolicy,\n\t\t\t\t\t\tmountOptions: source.mountOptions,\n\t\t\t\t\t\tallowVolumeExpansion: source.allowVolumeExpansion,\n\t\t\t\t\t\tvolumeBindingMode: source.volumeBindingMode,\n\t\t\t\t\t\tallowedTopologies: source.allowedTopologies,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (failures.length) throw new Error(`Volume pool preparation blocked: ${failures.join(\"; \")}`);\n\t}\n\n\treturn {\n\t\t/** @internal */\n\t\tpoolId,\n\t\t/** @internal */\n\t\treconcile,\n\t\t...createPreparationController(reconcile, 2_000, options.onError, 30_000),\n\t};\n}\n","import { POOL_LABEL } from \"./kubernetes-volume-pool.js\";\nimport type { VolumePoolApi } from \"./kubernetes-volume-pool-api.js\";\nimport type { ProcessVolumeReclamation } from \"./types.js\";\n\n/** Persist ownership and any terminal disposal authorization before PVC deletion. @internal */\nexport async function retireKubernetesProcessVolume(input: {\n\t/** @internal */\n\tapi: VolumePoolApi;\n\t/** @internal */\n\tnamespace: string;\n\t/** @internal */\n\tname: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tsignal: AbortSignal;\n\t/** @internal */\n\treason?: \"retention-expired\" | \"process-deleted\";\n\t/** @internal */\n\treclaimBackingStorage?: ProcessVolumeReclamation | \"process-deleted\";\n}): Promise<void> {\n\tconst { api, namespace, name, instanceId, signal } = input;\n\tconst reclamation = input.reclaimBackingStorage;\n\tif (\n\t\ttypeof reclamation === \"object\" &&\n\t\t(![\"completed\", \"aborted\"].includes(reclamation.lifecycleStatus) ||\n\t\t\t!Number.isFinite(Date.parse(reclamation.closedAt)) ||\n\t\t\tDate.parse(reclamation.closedAt) > Date.now())\n\t)\n\t\tthrow new Error(\"Backing-storage reclamation requires a closed terminal process\");\n\tif (reclamation === \"process-deleted\" && input.reason !== \"process-deleted\")\n\t\tthrow new Error(\"Explicit storage deletion requires a process deletion request\");\n\tconst pvc = await api.get(\"persistentvolumeclaims\", namespace, name, signal);\n\tif (!pvc) return;\n\tconst labels = pvc.metadata.labels;\n\tif (\n\t\t!pvc.metadata.uid ||\n\t\tlabels?.[\"leitwerk.dev/managed-by\"] !== \"leitwerk\" ||\n\t\tlabels[\"leitwerk.dev/component\"] !== \"process-volume\" ||\n\t\tlabels[\"leitwerk.dev/instance-id\"] !== instanceId ||\n\t\tpvc.metadata.ownerReferences?.length\n\t)\n\t\tthrow new Error(\"Cannot retire a foreign or ambiguous process PVC\");\n\tif (reclamation && !pvc.spec.volumeName)\n\t\tthrow new Error(\n\t\t\t\"PVC is still provisioning; preserve its identity until the backing PV can be audited\",\n\t\t);\n\tconst pods = await api.list(\"pods\", namespace, \"\", signal);\n\tif (\n\t\tpods.some(\n\t\t\t(pod) =>\n\t\t\t\t![\"Succeeded\", \"Failed\"].includes(pod.status?.phase ?? \"\") &&\n\t\t\t\tArray.isArray(pod.spec.volumes) &&\n\t\t\t\tpod.spec.volumes.some(\n\t\t\t\t\t(volume) =>\n\t\t\t\t\t\t(volume as { persistentVolumeClaim?: { claimName?: string } }).persistentVolumeClaim\n\t\t\t\t\t\t\t?.claimName === name,\n\t\t\t\t),\n\t\t)\n\t)\n\t\tthrow new Error(\"Cannot retire a process volume referenced by a live Pod\");\n\tif (pvc.spec.volumeName) {\n\t\tconst pv = await api.get(\"persistentvolumes\", \"\", pvc.spec.volumeName, signal);\n\t\tif (\n\t\t\t!pv ||\n\t\t\t(pv.metadata.labels?.[\"leitwerk.dev/managed-by\"] !== undefined &&\n\t\t\t\tpv.metadata.labels[\"leitwerk.dev/managed-by\"] !== \"leitwerk\") ||\n\t\t\t(pv.metadata.labels?.[\"leitwerk.dev/instance-id\"] !== undefined &&\n\t\t\t\tpv.metadata.labels[\"leitwerk.dev/instance-id\"] !== instanceId) ||\n\t\t\tpv.metadata.ownerReferences?.length ||\n\t\t\tpv.metadata.deletionTimestamp ||\n\t\t\tpv.spec.claimRef?.uid !== pvc.metadata.uid ||\n\t\t\tpv.spec.claimRef?.name !== name ||\n\t\t\tpv.spec.claimRef?.namespace !== namespace\n\t\t)\n\t\t\tthrow new Error(\"Cannot retire a volume with ambiguous claim ownership\");\n\t\tconst csi = pv.spec.csi as { driver?: string; volumeHandle?: string } | undefined;\n\t\tif (\n\t\t\treclamation &&\n\t\t\t(!csi?.driver ||\n\t\t\t\t!csi.volumeHandle ||\n\t\t\t\tpv.metadata.annotations?.[\"pv.kubernetes.io/provisioned-by\"] !== csi.driver ||\n\t\t\t\t![\"Retain\", \"Delete\"].includes(pv.spec.persistentVolumeReclaimPolicy ?? \"\"))\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t\"Backing-storage reclamation requires an owned dynamically provisioned CSI volume\",\n\t\t\t);\n\t\tconst volumeLabels: Record<string, string> = {\n\t\t\t...pv.metadata.labels,\n\t\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t\t\"leitwerk.dev/component\": \"process-volume\",\n\t\t\t\"leitwerk.dev/instance-id\": instanceId,\n\t\t\t...(reclamation ? { \"leitwerk.dev/reclamation\": \"terminal\" } : {}),\n\t\t};\n\t\t// End pool ownership atomically: a stale pool reconciler must not restore\n\t\t// Retain after a fast process closes. Both writers use resourceVersion tests.\n\t\tdelete volumeLabels[POOL_LABEL];\n\t\tawait api.patchVolume(\n\t\t\tpv,\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\top: \"add\",\n\t\t\t\t\tpath: \"/metadata/labels\",\n\t\t\t\t\tvalue: volumeLabels,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\top: \"add\",\n\t\t\t\t\tpath: \"/metadata/annotations\",\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\t...pv.metadata.annotations,\n\t\t\t\t\t\t\"leitwerk.dev/retirement\": JSON.stringify({\n\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\t\tclaimName: name,\n\t\t\t\t\t\t\tclaimUid: pvc.metadata.uid,\n\t\t\t\t\t\t\tvolumeUid: pv.metadata.uid,\n\t\t\t\t\t\t\treason: input.reason ?? \"retention-expired\",\n\t\t\t\t\t\t\t...(reclamation\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\treclamation:\n\t\t\t\t\t\t\t\t\t\t\ttypeof reclamation === \"object\"\n\t\t\t\t\t\t\t\t\t\t\t\t? { policy: \"terminal-process\", ...reclamation }\n\t\t\t\t\t\t\t\t\t\t\t\t: { policy: \"process-deletion\" },\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t// Arm CSI reclamation before deleting the claim. A crash after this\n\t\t\t\t// patch is safe: retry either repeats it or CSI completes independently.\n\t\t\t\t...(reclamation\n\t\t\t\t\t? [{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\",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