@leitwerk-dev/worker-runners 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/dist/chunk-4F7EMXMU.js +119 -0
  2. package/dist/chunk-4F7EMXMU.js.map +1 -0
  3. package/dist/{chunk-HLTGLGUS.js → chunk-63BBCX7B.js} +69 -93
  4. package/dist/chunk-63BBCX7B.js.map +1 -0
  5. package/dist/{chunk-6WACBFXN.js → chunk-6BSZBMHH.js} +18 -1
  6. package/dist/chunk-6BSZBMHH.js.map +1 -0
  7. package/dist/{chunk-DL3Y3R6E.js → chunk-7NF2P2VP.js} +74 -8
  8. package/dist/chunk-7NF2P2VP.js.map +1 -0
  9. package/dist/chunk-7X5FBNT7.js +14 -0
  10. package/dist/chunk-7X5FBNT7.js.map +1 -0
  11. package/dist/chunk-D56NJQ5X.js +90 -0
  12. package/dist/chunk-D56NJQ5X.js.map +1 -0
  13. package/dist/chunk-ISEDLYKQ.js +881 -0
  14. package/dist/chunk-ISEDLYKQ.js.map +1 -0
  15. package/dist/{chunk-IRFVGUXJ.js → chunk-OSS62AOL.js} +7 -3
  16. package/dist/{chunk-IRFVGUXJ.js.map → chunk-OSS62AOL.js.map} +1 -1
  17. package/dist/chunk-UGKQOL5E.js +39 -0
  18. package/dist/chunk-UGKQOL5E.js.map +1 -0
  19. package/dist/{chunk-2TSWMVLZ.js → chunk-YBSX4N2K.js} +156 -37
  20. package/dist/chunk-YBSX4N2K.js.map +1 -0
  21. package/dist/chunk-YJMHXKNO.js +308 -0
  22. package/dist/chunk-YJMHXKNO.js.map +1 -0
  23. package/dist/{docker-engine-client-Cpmy2yma.d.ts → docker-engine-client-CnXspTGq.d.ts} +8 -21
  24. package/dist/docker-engine-client.d.ts +7 -20
  25. package/dist/docker-engine-client.d.ts.map +1 -1
  26. package/dist/docker-engine-http-client.d.ts +0 -8
  27. package/dist/docker-engine-http-client.d.ts.map +1 -1
  28. package/dist/docker-engine-http-client.js +12 -201
  29. package/dist/docker-engine-http-client.js.map +1 -1
  30. package/dist/docker-worker-runner.d.ts +11 -4
  31. package/dist/docker-worker-runner.d.ts.map +1 -1
  32. package/dist/docker-worker-runner.js +12 -235
  33. package/dist/docker-worker-runner.js.map +1 -1
  34. package/dist/fake-docker-engine-client.d.ts.map +1 -1
  35. package/dist/filesystem-process-state-exporter.d.ts +10 -0
  36. package/dist/filesystem-process-state-exporter.d.ts.map +1 -0
  37. package/dist/helper-process-state-exporter.d.ts +28 -0
  38. package/dist/helper-process-state-exporter.d.ts.map +1 -0
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +305 -9
  42. package/dist/index.js.map +1 -1
  43. package/dist/{kubernetes-api-client-BcwF2uon.d.ts → kubernetes-api-client-DD2YevYP.d.ts} +128 -85
  44. package/dist/kubernetes-api-client.d.ts +33 -6
  45. package/dist/kubernetes-api-client.d.ts.map +1 -1
  46. package/dist/kubernetes-http-client.d.ts.map +1 -1
  47. package/dist/kubernetes-http-client.js +496 -286
  48. package/dist/kubernetes-http-client.js.map +1 -1
  49. package/dist/kubernetes-manifests.d.ts +40 -77
  50. package/dist/kubernetes-manifests.d.ts.map +1 -1
  51. package/dist/kubernetes-startup-sampler.d.ts +14 -0
  52. package/dist/kubernetes-startup-sampler.d.ts.map +1 -0
  53. package/dist/kubernetes-volume-pool-api.d.ts +69 -0
  54. package/dist/kubernetes-volume-pool-api.d.ts.map +1 -0
  55. package/dist/kubernetes-volume-pool.d.ts +24 -0
  56. package/dist/kubernetes-volume-pool.d.ts.map +1 -0
  57. package/dist/kubernetes-worker-runner.d.ts +26 -2
  58. package/dist/kubernetes-worker-runner.d.ts.map +1 -1
  59. package/dist/kubernetes-worker-runner.js +12 -161
  60. package/dist/kubernetes-worker-runner.js.map +1 -1
  61. package/dist/local-worker-runner.d.ts +11 -1
  62. package/dist/local-worker-runner.d.ts.map +1 -1
  63. package/dist/local-worker-runner.js +14 -108
  64. package/dist/local-worker-runner.js.map +1 -1
  65. package/dist/runner-utils.d.ts +3 -1
  66. package/dist/runner-utils.d.ts.map +1 -1
  67. package/dist/session-transfer-helper-cli.d.ts +2 -0
  68. package/dist/session-transfer-helper-cli.d.ts.map +1 -0
  69. package/dist/session-transfer-helper-cli.js +9 -0
  70. package/dist/session-transfer-helper-cli.js.map +1 -0
  71. package/dist/session-transfer-helper.d.ts +4 -0
  72. package/dist/session-transfer-helper.d.ts.map +1 -0
  73. package/dist/session-transfer-helper.js +11 -0
  74. package/dist/session-transfer-helper.js.map +1 -0
  75. package/dist/types.d.ts +60 -17
  76. package/dist/types.d.ts.map +1 -1
  77. package/dist/types.js +6 -11
  78. package/dist/types.js.map +1 -1
  79. package/dist/worker-labels.d.ts +7 -0
  80. package/dist/worker-labels.d.ts.map +1 -1
  81. package/package.json +13 -5
  82. package/src/docker-engine-client.ts +7 -20
  83. package/src/docker-engine-http-client.ts +77 -96
  84. package/src/docker-worker-runner.ts +180 -54
  85. package/src/fake-docker-engine-client.ts +13 -41
  86. package/src/filesystem-process-state-exporter.ts +42 -0
  87. package/src/helper-process-state-exporter.ts +149 -0
  88. package/src/index.ts +14 -5
  89. package/src/kubernetes-api-client.ts +70 -10
  90. package/src/kubernetes-http-client.ts +228 -92
  91. package/src/kubernetes-manifests.ts +265 -336
  92. package/src/kubernetes-startup-sampler.ts +191 -0
  93. package/src/kubernetes-volume-pool-api.ts +187 -0
  94. package/src/kubernetes-volume-pool.ts +357 -0
  95. package/src/kubernetes-worker-runner.ts +316 -39
  96. package/src/local-worker-runner.ts +82 -6
  97. package/src/runner-utils.ts +10 -2
  98. package/src/session-transfer-helper-cli.ts +5 -0
  99. package/src/session-transfer-helper.ts +105 -0
  100. package/src/types.ts +87 -14
  101. package/src/worker-labels.ts +18 -0
  102. package/dist/chunk-2TSWMVLZ.js.map +0 -1
  103. package/dist/chunk-6WACBFXN.js.map +0 -1
  104. package/dist/chunk-DL3Y3R6E.js.map +0 -1
  105. package/dist/chunk-DUFA24LP.js +0 -401
  106. package/dist/chunk-DUFA24LP.js.map +0 -1
  107. package/dist/chunk-HLTGLGUS.js.map +0 -1
  108. package/dist/chunk-P4DIFRBH.js +0 -187
  109. package/dist/chunk-P4DIFRBH.js.map +0 -1
  110. package/dist/docker-engine-client.js +0 -10
  111. package/dist/docker-engine-client.js.map +0 -1
  112. package/dist/fake-docker-engine-client.js +0 -131
  113. package/dist/fake-docker-engine-client.js.map +0 -1
  114. package/dist/kubernetes-api-client.js +0 -142
  115. package/dist/kubernetes-api-client.js.map +0 -1
  116. package/dist/kubernetes-manifests.js +0 -379
  117. package/dist/kubernetes-manifests.js.map +0 -1
  118. package/dist/process-volume-retention.js +0 -46
  119. package/dist/process-volume-retention.js.map +0 -1
  120. package/dist/runner-utils.js +0 -36
  121. package/dist/runner-utils.js.map +0 -1
  122. package/dist/worker-labels.js +0 -83
  123. package/dist/worker-labels.js.map +0 -1
@@ -1,9 +1,12 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import http from "node:http";
3
3
  import https from "node:https";
4
+ import { text as readText } from "node:stream/consumers";
5
+ import { setTimeout as sleep } from "node:timers/promises";
4
6
  import { URL } from "node:url";
5
7
  import type {
6
8
  KubernetesApiClient,
9
+ KubernetesApiRequestOptions,
7
10
  KubernetesNamespaceSummary,
8
11
  KubernetesPodSummary,
9
12
  } from "./kubernetes-api-client.js";
@@ -11,47 +14,95 @@ import {
11
14
  type KubernetesConfigMapManifest,
12
15
  type KubernetesDockerConfigJsonSecretManifest,
13
16
  type KubernetesPersistentVolumeClaimManifest,
17
+ type KubernetesPodEventSummary,
14
18
  type KubernetesPodManifest,
15
19
  type KubernetesProcessNamespaceManifest,
16
20
  mapKubernetesPodExit,
17
21
  } from "./kubernetes-manifests.js";
22
+ import { createVolumePoolApi } from "./kubernetes-volume-pool-api.js";
18
23
  import type { WorkerExitInfo } from "./types.js";
19
24
 
20
25
  const IN_CLUSTER_TOKEN_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token";
21
26
  const IN_CLUSTER_CA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt";
22
27
  const DEFAULT_IN_CLUSTER_API = "https://kubernetes.default.svc";
28
+ const TRANSIENT_PLAIN_BAD_REQUEST_MAX_ATTEMPTS = 3;
29
+ const TRANSIENT_PLAIN_BAD_REQUEST_BACKOFF_MS = 25;
30
+ const MAX_API_ERROR_LENGTH = 2_048;
31
+
32
+ function resourcePath(namespace: string, resource: string, name?: string): string {
33
+ return `/api/v1/namespaces/${encodeURIComponent(namespace)}/${resource}${name === undefined ? "" : `/${encodeURIComponent(name)}`}`;
34
+ }
35
+
36
+ function boundedApiError(text: string): string {
37
+ let summary = text.trim();
38
+ try {
39
+ const parsed = JSON.parse(summary) as { reason?: unknown; message?: unknown };
40
+ summary = [parsed.reason, parsed.message]
41
+ .filter((value): value is string => typeof value === "string" && value.trim() !== "")
42
+ .join(": ");
43
+ } catch {
44
+ // Plain-text API errors are already summaries.
45
+ }
46
+ if (!summary) return "no diagnostic";
47
+ return summary.length <= MAX_API_ERROR_LENGTH
48
+ ? summary
49
+ : `${summary.slice(0, MAX_API_ERROR_LENGTH - 1)}…`;
50
+ }
23
51
 
24
52
  interface KubernetesListResponse<T> {
53
+ metadata?: { continue?: string };
25
54
  items?: T[];
26
55
  }
27
56
 
57
+ interface KubernetesTerminationState {
58
+ startedAt?: string;
59
+ exitCode?: number;
60
+ reason?: string;
61
+ signal?: number;
62
+ message?: string;
63
+ }
64
+
28
65
  interface KubernetesObjectResponse {
66
+ spec?: {
67
+ nodeName?: string;
68
+ storageClassName?: string;
69
+ volumes?: Array<{ persistentVolumeClaim?: { claimName?: string } }>;
70
+ containers?: Array<{
71
+ name?: string;
72
+ resources?: { limits?: { cpu?: string; memory?: string } };
73
+ }>;
74
+ };
75
+ involvedObject?: { uid?: string; fieldPath?: string };
76
+ firstTimestamp?: string;
77
+ eventTime?: string;
29
78
  metadata?: {
79
+ uid?: string;
80
+ creationTimestamp?: string;
30
81
  name?: string;
31
82
  namespace?: string;
32
83
  labels?: Record<string, string>;
33
84
  };
34
85
  status?: {
86
+ conditions?: Array<{ type?: string; status?: string; lastTransitionTime?: string }>;
35
87
  phase?: string;
36
88
  reason?: string;
37
89
  containerStatuses?: Array<{
90
+ name?: string;
91
+ imageID?: string;
38
92
  state?: {
39
- terminated?: {
40
- exitCode?: number;
41
- reason?: string;
42
- signal?: number;
43
- };
93
+ running?: { startedAt?: string };
94
+ terminated?: KubernetesTerminationState;
44
95
  };
45
96
  lastState?: {
46
- terminated?: {
47
- exitCode?: number;
48
- reason?: string;
49
- signal?: number;
50
- };
97
+ terminated?: KubernetesTerminationState;
51
98
  };
52
99
  }>;
53
100
  };
54
101
  type?: string;
102
+ reason?: string;
103
+ message?: string;
104
+ count?: number;
105
+ lastTimestamp?: string;
55
106
  data?: Record<string, string>;
56
107
  }
57
108
 
@@ -90,46 +141,62 @@ export function createKubernetesHttpApiClient(options: {
90
141
  body?: unknown;
91
142
  contentType?: string;
92
143
  ok?: readonly number[];
144
+ signal?: AbortSignal;
93
145
  }): Promise<{ status: number; body: T | null; text: string }> {
94
146
  const url = new URL(input.path, baseUrl);
95
147
  const serialized = input.body === undefined ? undefined : JSON.stringify(input.body);
96
148
  const headers: Record<string, string> = {
97
149
  Accept: "application/json",
98
150
  ...(serialized !== undefined
99
- ? { "Content-Type": input.contentType ?? "application/json" }
151
+ ? {
152
+ "Content-Type": input.contentType ?? "application/json",
153
+ "Content-Length": String(Buffer.byteLength(serialized)),
154
+ }
100
155
  : {}),
101
156
  ...(options.bearerToken ? { Authorization: `Bearer ${options.bearerToken}` } : {}),
102
157
  };
103
158
  const transport = url.protocol === "http:" ? http : https;
104
- const response = await new Promise<{ statusCode: number; text: string }>((resolve, reject) => {
105
- const req = transport.request(
106
- url,
107
- {
108
- method: input.method,
109
- headers,
110
- ...(url.protocol === "https:" && options.ca ? { ca: options.ca } : {}),
111
- },
112
- (res) => {
113
- const chunks: Buffer[] = [];
114
- res.on("data", (chunk: Buffer | string) =>
115
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)),
116
- );
117
- res.on("end", () => {
118
- resolve({
119
- statusCode: res.statusCode ?? 0,
120
- text: Buffer.concat(chunks).toString("utf8"),
121
- });
122
- });
123
- },
124
- );
125
- req.on("error", reject);
126
- if (serialized !== undefined) req.write(serialized);
127
- req.end();
128
- });
159
+ let response: { statusCode: number; text: string };
160
+ for (let attempt = 1; ; attempt += 1) {
161
+ input.signal?.throwIfAborted();
162
+ response = await new Promise<{ statusCode: number; text: string }>((resolve, reject) => {
163
+ const req = transport.request(
164
+ url,
165
+ {
166
+ method: input.method,
167
+ headers,
168
+ signal: input.signal,
169
+ ...(url.protocol === "https:" && options.ca ? { ca: options.ca } : {}),
170
+ },
171
+ (res) => {
172
+ readText(res).then(
173
+ (text) => resolve({ statusCode: res.statusCode ?? 0, text }),
174
+ reject,
175
+ );
176
+ },
177
+ );
178
+ req.on("error", reject);
179
+ if (serialized !== undefined) req.write(serialized);
180
+ req.end();
181
+ });
182
+ const retryableMethod = input.method === "GET" || input.method === "DELETE";
183
+ const transientPlainBadRequest =
184
+ response.statusCode === 400 && response.text.trim() === "400 Bad Request";
185
+ if (
186
+ !retryableMethod ||
187
+ !transientPlainBadRequest ||
188
+ attempt >= TRANSIENT_PLAIN_BAD_REQUEST_MAX_ATTEMPTS
189
+ ) {
190
+ break;
191
+ }
192
+ await sleep(TRANSIENT_PLAIN_BAD_REQUEST_BACKOFF_MS * attempt, undefined, {
193
+ signal: input.signal,
194
+ });
195
+ }
129
196
  const ok = input.ok ?? [200, 201, 202];
130
197
  if (!ok.includes(response.statusCode)) {
131
198
  throw new Error(
132
- `Kubernetes API ${input.method} ${input.path} failed with HTTP ${response.statusCode}: ${response.text}`,
199
+ `Kubernetes API ${input.method} ${input.path} failed with HTTP ${response.statusCode}: ${boundedApiError(response.text)}`,
133
200
  );
134
201
  }
135
202
  const text = response.text.trim();
@@ -140,30 +207,29 @@ export function createKubernetesHttpApiClient(options: {
140
207
  };
141
208
  }
142
209
 
210
+ function readObject(path: string, signal?: AbortSignal) {
211
+ return request<KubernetesObjectResponse>({ method: "GET", path, ok: [200, 404], signal });
212
+ }
213
+
143
214
  async function exists(path: string): Promise<KubernetesObjectResponse | null> {
144
- const result = await request<KubernetesObjectResponse>({
145
- method: "GET",
146
- path,
147
- ok: [200, 404],
148
- });
215
+ const result = await readObject(path);
149
216
  return result.status === 404 ? null : result.body;
150
217
  }
151
218
 
152
219
  /** Idempotent create-or-patch for K8s resources. */
153
220
  async function upsertResource(input: {
154
- existsPath: string;
221
+ path: string;
155
222
  createPath: string;
156
223
  createBody: unknown;
157
- patchPath: string;
158
224
  patchBody: unknown;
159
225
  }): Promise<void> {
160
- const existing = await exists(input.existsPath);
226
+ const existing = await exists(input.path);
161
227
  if (!existing) {
162
228
  await request({ method: "POST", path: input.createPath, body: input.createBody });
163
229
  } else {
164
230
  await request({
165
231
  method: "PATCH",
166
- path: input.patchPath,
232
+ path: input.path,
167
233
  contentType: "application/merge-patch+json",
168
234
  body: input.patchBody,
169
235
  });
@@ -186,16 +252,71 @@ export function createKubernetesHttpApiClient(options: {
186
252
  const name = item.metadata?.name;
187
253
  const namespace = item.metadata?.namespace;
188
254
  if (!name || !namespace) return null;
255
+ const worker = item.status?.containerStatuses?.find((container) => container.name === "worker");
189
256
  return {
190
257
  name,
191
258
  namespace,
192
259
  labels: { ...(item.metadata?.labels ?? {}) },
260
+ uid: item.metadata?.uid,
261
+ createdAt: item.metadata?.creationTimestamp,
262
+ scheduledAt: item.status?.conditions?.find(
263
+ (c) => c.type === "PodScheduled" && c.status === "True",
264
+ )?.lastTransitionTime,
265
+ containerStartedAt: worker?.state?.running?.startedAt ?? worker?.state?.terminated?.startedAt,
266
+ imageId: worker?.imageID,
267
+ node: item.spec?.nodeName,
268
+ pvcName: item.spec?.volumes?.find((v) => v.persistentVolumeClaim)?.persistentVolumeClaim
269
+ ?.claimName,
270
+ resources: item.spec?.containers?.find((c) => c.name === "worker")?.resources?.limits,
193
271
  phase: item.status?.phase,
194
272
  };
195
273
  }
196
274
 
197
- function podExitInfo(item: KubernetesObjectResponse | null): WorkerExitInfo {
198
- if (!item) return { exitCode: 0, signal: null, reason: "Deleted" };
275
+ async function listPodEvents(
276
+ name: string,
277
+ namespace: string,
278
+ options?: KubernetesApiRequestOptions,
279
+ ): Promise<KubernetesPodEventSummary[]> {
280
+ const events: KubernetesPodEventSummary[] = [];
281
+ let continuation = "";
282
+ do {
283
+ const result = await request<KubernetesListResponse<KubernetesObjectResponse>>({
284
+ method: "GET",
285
+ signal: options?.signal,
286
+ path: `${resourcePath(namespace, "events")}?fieldSelector=${encodeURIComponent(`involvedObject.kind=Pod,involvedObject.name=${name}`)}&limit=100${continuation ? `&continue=${encodeURIComponent(continuation)}` : ""}`,
287
+ });
288
+ events.push(
289
+ ...(result.body?.items ?? []).map((event) => ({
290
+ type: event.type,
291
+ reason: event.reason,
292
+ message: event.message,
293
+ count: event.count,
294
+ lastTimestamp: event.lastTimestamp,
295
+ firstTimestamp: event.firstTimestamp,
296
+ eventTime: event.eventTime,
297
+ objectUid: event.involvedObject?.uid,
298
+ fieldPath: event.involvedObject?.fieldPath,
299
+ })),
300
+ );
301
+ continuation = result.body?.metadata?.continue ?? "";
302
+ } while (continuation);
303
+ return events;
304
+ }
305
+
306
+ function podExitInfo(
307
+ item: KubernetesObjectResponse | null,
308
+ events?: KubernetesPodEventSummary[],
309
+ sensitiveValues: readonly string[] = [],
310
+ ): WorkerExitInfo {
311
+ if (!item) {
312
+ return mapKubernetesPodExit({
313
+ reason: "Deleted",
314
+ exitCode: 0,
315
+ signal: null,
316
+ events,
317
+ sensitiveValues,
318
+ });
319
+ }
199
320
  const statusWithTermination = item.status?.containerStatuses?.find(
200
321
  (s) => s.state?.terminated || s.lastState?.terminated,
201
322
  );
@@ -207,17 +328,20 @@ export function createKubernetesHttpApiClient(options: {
207
328
  exitCode: status?.exitCode,
208
329
  signal: status?.signal ? `SIG${status.signal}` : null,
209
330
  oomKilled: status?.reason === "OOMKilled",
331
+ terminationMessage: status?.message,
332
+ events,
333
+ sensitiveValues,
210
334
  });
211
335
  }
212
336
 
213
337
  return {
338
+ volumePool: createVolumePoolApi(request),
214
339
  async ensureNamespace(manifest: KubernetesProcessNamespaceManifest): Promise<void> {
215
340
  const name = manifest.metadata.name;
216
341
  await upsertResource({
217
- existsPath: `/api/v1/namespaces/${encodeURIComponent(name)}`,
342
+ path: `/api/v1/namespaces/${encodeURIComponent(name)}`,
218
343
  createPath: "/api/v1/namespaces",
219
344
  createBody: manifest,
220
- patchPath: `/api/v1/namespaces/${encodeURIComponent(name)}`,
221
345
  patchBody: { metadata: { labels: manifest.metadata.labels } },
222
346
  });
223
347
  },
@@ -237,37 +361,29 @@ export function createKubernetesHttpApiClient(options: {
237
361
  return (result.body?.items ?? []).map(namespaceSummary).filter((item) => item !== null);
238
362
  },
239
363
  async ensureServiceAccount(name, namespace, labels): Promise<void> {
240
- const enc = (s: string) => encodeURIComponent(s);
241
364
  await upsertResource({
242
- existsPath: `/api/v1/namespaces/${enc(namespace)}/serviceaccounts/${enc(name)}`,
243
- createPath: `/api/v1/namespaces/${enc(namespace)}/serviceaccounts`,
365
+ path: resourcePath(namespace, "serviceaccounts", name),
366
+ createPath: resourcePath(namespace, "serviceaccounts"),
244
367
  createBody: {
245
368
  apiVersion: "v1",
246
369
  kind: "ServiceAccount",
247
370
  metadata: { name, namespace, labels },
248
371
  automountServiceAccountToken: false,
249
372
  },
250
- patchPath: `/api/v1/namespaces/${enc(namespace)}/serviceaccounts/${enc(name)}`,
251
373
  patchBody: { metadata: { labels } },
252
374
  });
253
375
  },
254
376
  async ensureConfigMap(manifest: KubernetesConfigMapManifest): Promise<void> {
255
- const name = encodeURIComponent(manifest.metadata.name);
256
- const namespace = encodeURIComponent(manifest.metadata.namespace);
377
+ const { name, namespace } = manifest.metadata;
257
378
  await upsertResource({
258
- existsPath: `/api/v1/namespaces/${namespace}/configmaps/${name}`,
259
- createPath: `/api/v1/namespaces/${namespace}/configmaps`,
379
+ path: resourcePath(namespace, "configmaps", name),
380
+ createPath: resourcePath(namespace, "configmaps"),
260
381
  createBody: manifest,
261
- patchPath: `/api/v1/namespaces/${namespace}/configmaps/${name}`,
262
382
  patchBody: { metadata: { labels: manifest.metadata.labels }, data: manifest.data },
263
383
  });
264
384
  },
265
385
  async getDockerConfigJsonSecret(name: string, namespace: string): Promise<string> {
266
- const result = await request<KubernetesObjectResponse>({
267
- method: "GET",
268
- path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/secrets/${encodeURIComponent(name)}`,
269
- ok: [200, 404],
270
- });
386
+ const result = await readObject(resourcePath(namespace, "secrets", name));
271
387
  if (result.status === 404) {
272
388
  throw new Error(`Kubernetes image-pull Secret ${namespace}/${name} was not found`);
273
389
  }
@@ -287,18 +403,17 @@ export function createKubernetesHttpApiClient(options: {
287
403
  async ensureDockerConfigJsonSecret(
288
404
  manifest: KubernetesDockerConfigJsonSecretManifest,
289
405
  ): Promise<void> {
290
- const namespace = encodeURIComponent(manifest.metadata.namespace);
291
- const name = encodeURIComponent(manifest.metadata.name);
406
+ const { namespace, name } = manifest.metadata;
292
407
  const created = await request({
293
408
  method: "POST",
294
- path: `/api/v1/namespaces/${namespace}/secrets`,
409
+ path: resourcePath(namespace, "secrets"),
295
410
  body: manifest,
296
411
  ok: [201, 409],
297
412
  });
298
413
  if (created.status === 409) {
299
414
  await request({
300
415
  method: "PATCH",
301
- path: `/api/v1/namespaces/${namespace}/secrets/${name}`,
416
+ path: resourcePath(namespace, "secrets", name),
302
417
  contentType: "application/merge-patch+json",
303
418
  body: {
304
419
  metadata: { labels: manifest.metadata.labels },
@@ -311,15 +426,12 @@ export function createKubernetesHttpApiClient(options: {
311
426
  async ensurePersistentVolumeClaim(
312
427
  manifest: KubernetesPersistentVolumeClaimManifest,
313
428
  ): Promise<void> {
314
- const name = encodeURIComponent(manifest.metadata.name);
315
- const namespace = encodeURIComponent(manifest.metadata.namespace);
316
- const existing = await exists(
317
- `/api/v1/namespaces/${namespace}/persistentvolumeclaims/${name}`,
318
- );
429
+ const { name, namespace } = manifest.metadata;
430
+ const existing = await exists(resourcePath(namespace, "persistentvolumeclaims", name));
319
431
  if (!existing) {
320
432
  await request({
321
433
  method: "POST",
322
- path: `/api/v1/namespaces/${namespace}/persistentvolumeclaims`,
434
+ path: resourcePath(namespace, "persistentvolumeclaims"),
323
435
  body: manifest,
324
436
  });
325
437
  }
@@ -327,33 +439,48 @@ export function createKubernetesHttpApiClient(options: {
327
439
  async deletePersistentVolumeClaim(name: string, namespace: string): Promise<void> {
328
440
  await request({
329
441
  method: "DELETE",
330
- path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/persistentvolumeclaims/${encodeURIComponent(name)}`,
442
+ path: resourcePath(namespace, "persistentvolumeclaims", name),
331
443
  ok: [200, 202, 404],
332
444
  });
333
445
  },
334
446
  async createPod(manifest: KubernetesPodManifest): Promise<void> {
335
447
  await request({
336
448
  method: "POST",
337
- path: `/api/v1/namespaces/${encodeURIComponent(manifest.metadata.namespace)}/pods`,
449
+ path: resourcePath(manifest.metadata.namespace, "pods"),
338
450
  body: manifest,
339
451
  });
340
452
  },
341
- async deletePod(name: string, namespace: string, options: { gracePeriodSeconds: number }) {
453
+ async deletePod(name, namespace, options) {
342
454
  await request({
343
455
  method: "DELETE",
344
- path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/pods/${encodeURIComponent(name)}`,
345
- body: { gracePeriodSeconds: options.gracePeriodSeconds },
456
+ path: resourcePath(namespace, "pods", name),
457
+ body: {
458
+ apiVersion: "v1",
459
+ kind: "DeleteOptions",
460
+ gracePeriodSeconds: options.gracePeriodSeconds,
461
+ },
346
462
  ok: [200, 202, 404],
463
+ signal: options.signal,
347
464
  });
348
465
  },
349
- async getPod(name: string, namespace: string): Promise<KubernetesPodSummary | null> {
350
- const result = await request<KubernetesObjectResponse>({
351
- method: "GET",
352
- path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/pods/${encodeURIComponent(name)}`,
353
- ok: [200, 404],
354
- });
466
+ async getPod(name, namespace, options): Promise<KubernetesPodSummary | null> {
467
+ const result = await readObject(resourcePath(namespace, "pods", name), options?.signal);
355
468
  return result.status === 404 ? null : podSummary(result.body ?? {});
356
469
  },
470
+ async getPersistentVolumeClaim(name, namespace, options) {
471
+ const result = await readObject(
472
+ resourcePath(namespace, "persistentvolumeclaims", name),
473
+ options?.signal,
474
+ );
475
+ return result.status === 404
476
+ ? null
477
+ : {
478
+ uid: result.body?.metadata?.uid,
479
+ phase: result.body?.status?.phase,
480
+ storageClass: result.body?.spec?.storageClassName,
481
+ };
482
+ },
483
+ listPodEvents,
357
484
  async listPods(
358
485
  namespace: string,
359
486
  labels: Record<string, string>,
@@ -361,7 +488,7 @@ export function createKubernetesHttpApiClient(options: {
361
488
  const selector = labelSelector(labels);
362
489
  const result = await request<KubernetesListResponse<KubernetesObjectResponse>>({
363
490
  method: "GET",
364
- path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/pods?labelSelector=${encodeURIComponent(selector)}`,
491
+ path: `${resourcePath(namespace, "pods")}?labelSelector=${encodeURIComponent(selector)}`,
365
492
  });
366
493
  return (result.body?.items ?? []).map(podSummary).filter((item) => item !== null);
367
494
  },
@@ -369,23 +496,32 @@ export function createKubernetesHttpApiClient(options: {
369
496
  name: string,
370
497
  namespace: string,
371
498
  listener: (info: WorkerExitInfo) => void,
499
+ options,
372
500
  ): () => void {
373
501
  let stopped = false;
374
502
  const timer = setInterval(async () => {
375
503
  if (stopped) return;
376
504
  try {
377
- const result = await request<KubernetesObjectResponse>({
378
- method: "GET",
379
- path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/pods/${encodeURIComponent(name)}`,
380
- ok: [200, 404],
381
- });
505
+ const result = await readObject(resourcePath(namespace, "pods", name));
382
506
  if (
383
507
  result.status === 404 ||
384
508
  ["Failed", "Succeeded"].includes(result.body?.status?.phase ?? "")
385
509
  ) {
386
510
  stopped = true;
387
511
  clearInterval(timer);
388
- listener(podExitInfo(result.status === 404 ? null : result.body));
512
+ let events: KubernetesPodEventSummary[] = [];
513
+ try {
514
+ events = await listPodEvents(name, namespace);
515
+ } catch {
516
+ // Exit status remains useful when event access fails transiently.
517
+ }
518
+ listener(
519
+ podExitInfo(
520
+ result.status === 404 ? null : result.body,
521
+ events,
522
+ options?.sensitiveValues,
523
+ ),
524
+ );
389
525
  }
390
526
  } catch {
391
527
  // Transient API failures are handled by the next poll; the supervisor's