hammerkit 2.1.0-next.2 → 2.1.0-next.21

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 (87) hide show
  1. package/build.schema.json +39 -18
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/environment/replace-env-variables.js +8 -5
  8. package/dist/environment/run-source-envs.js +2 -1
  9. package/dist/executer/archive-task-entry.js +1 -1
  10. package/dist/executer/deadline.js +63 -10
  11. package/dist/executer/event-cache.js +5 -1
  12. package/dist/executer/execute-work-task.js +15 -3
  13. package/dist/executer/runner-commands.js +36 -0
  14. package/dist/file/get-file-context.js +4 -7
  15. package/dist/harness/connect.js +12 -8
  16. package/dist/harness/reconnect.js +141 -0
  17. package/dist/harness/sandbox-client.js +241 -33
  18. package/dist/harness/service-tools.js +11 -2
  19. package/dist/kubernetes/cluster-state.js +48 -14
  20. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  21. package/dist/kubernetes/follow-pod-logs.js +8 -5
  22. package/dist/kubernetes/kept-claims.js +26 -5
  23. package/dist/kubernetes/resources.js +5 -1
  24. package/dist/kubernetes/sandbox-runner.js +526 -156
  25. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  26. package/dist/kubernetes/sync-changes.js +463 -0
  27. package/dist/kubernetes/volumes.js +23 -1
  28. package/dist/optimizer/get-work-cache-stats.js +7 -0
  29. package/dist/optimizer/work-task-cache-description.js +3 -2
  30. package/dist/planner/image-build.js +5 -0
  31. package/dist/planner/utils/dependency-outputs.js +7 -6
  32. package/dist/planner/validate.js +41 -0
  33. package/dist/planner/work-item-status.js +12 -2
  34. package/dist/planner/work-runtime-aggregate.js +1 -0
  35. package/dist/planner/work-runtime-docker.js +33 -6
  36. package/dist/planner/work-runtime-kubernetes.js +313 -70
  37. package/dist/planner/work-runtime-local.js +8 -4
  38. package/dist/planner/work-secret.js +33 -11
  39. package/dist/planner/work-service-id.js +30 -6
  40. package/dist/program.js +19 -1
  41. package/dist/remote/annotations.js +37 -5
  42. package/dist/remote/bundle.js +6 -8
  43. package/dist/remote/collect-bundle.js +3 -2
  44. package/dist/remote/device-login.js +4 -1
  45. package/dist/remote/remote-commands.js +16 -7
  46. package/dist/remote/remote-work-commands.js +266 -75
  47. package/dist/remote/server-client.js +38 -40
  48. package/dist/schema/build-file-base-task-schema.js +16 -1
  49. package/dist/schema/build-file-image-build-schema.js +5 -8
  50. package/dist/schema/reference-parser.js +108 -43
  51. package/dist/schema/work-scope-parser.js +8 -0
  52. package/dist/secrets/prefetch-secrets.js +20 -1
  53. package/dist/server/artifacts-api.js +56 -0
  54. package/dist/server/definitions-api.js +62 -8
  55. package/dist/server/executor.js +117 -30
  56. package/dist/server/http.js +4 -1
  57. package/dist/server/keep-artifacts.js +230 -0
  58. package/dist/server/kubernetes-backend.js +186 -59
  59. package/dist/server/kubernetes-sandbox-storage.js +3 -2
  60. package/dist/server/overview.js +73 -9
  61. package/dist/server/paging.js +167 -0
  62. package/dist/server/plan.js +16 -1
  63. package/dist/server/run-access.js +24 -0
  64. package/dist/server/run-artifacts.js +171 -0
  65. package/dist/server/run-logs.js +25 -1
  66. package/dist/server/run-request.js +11 -0
  67. package/dist/server/run-source-environment.js +1 -1
  68. package/dist/server/run-worker.js +267 -33
  69. package/dist/server/runs.js +527 -99
  70. package/dist/server/sandbox-files-api.js +27 -12
  71. package/dist/server/sandbox-files.js +12 -10
  72. package/dist/server/sandbox-follow.js +54 -0
  73. package/dist/server/sandbox-pod.js +1 -1
  74. package/dist/server/sandbox-storage.js +38 -1
  75. package/dist/server/sandbox-sync.js +392 -0
  76. package/dist/server/sandboxes-api.js +116 -19
  77. package/dist/server/sandboxes.js +38 -3
  78. package/dist/server/server-config.js +14 -0
  79. package/dist/server/server.js +169 -38
  80. package/dist/server/task-order.js +56 -0
  81. package/dist/utils/project-path.js +20 -0
  82. package/dist/utils/tar-files.js +52 -0
  83. package/dist/utils/tar.js +37 -1
  84. package/package.json +1 -1
  85. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  86. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  87. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -1,10 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
3
+ exports.request = exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.downloadRunArtifact = exports.getRunArtifacts = exports.getRun = exports.followRun = exports.getMoveTarget = exports.lookupChecks = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.getServerConnection = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
4
+ const crypto_1 = require("crypto");
4
5
  const path_1 = require("path");
5
6
  const token_source_1 = require("../remote/token-source");
7
+ const reconnect_1 = require("./reconnect");
8
+ const fs_1 = require("fs");
9
+ const stream_1 = require("stream");
10
+ const promises_1 = require("stream/promises");
6
11
  // a write carries up to 32 MiB
7
12
  const TIMEOUT_MS = 60000;
13
+ // an output of a run carries up to runs.artifacts.maxBytes, 256 MiB by default: 30 minutes is
14
+ // what that takes at about 150 KiB/s, the slowest link the default still downloads over. A
15
+ // server with a larger maxBytes needs a longer timeout, as the download is not split up.
16
+ const DOWNLOAD_TIMEOUT_MS = 30 * 60000;
8
17
  // a run is asked for this long at a time, the log is read in between
9
18
  const POLL_WAIT = '1s';
10
19
  // a cancelled run waits this long for the server to take the cancel, before it gives up
@@ -19,6 +28,17 @@ class SandboxClientError extends Error {
19
28
  }
20
29
  }
21
30
  exports.SandboxClientError = SandboxClientError;
31
+ // A connection to a registered server, which says when it reconnects, on stderr unless told
32
+ // where else, and stops when the command is stopped.
33
+ function getServerConnection(environment, name, server, say = (line) => environment.stderr.write(`${line}\n`)) {
34
+ return {
35
+ url: server.url,
36
+ ...(0, token_source_1.getTokenSource)(environment, name, server),
37
+ say,
38
+ signal: environment.abortCtrl.signal,
39
+ };
40
+ }
41
+ exports.getServerConnection = getServerConnection;
22
42
  // What the agent is told of a check, on each harness.
23
43
  exports.CHECK_DESCRIPTION = 'Run a task as a check before you push, such as test or e2e: it runs on a copy of the files a push ' +
24
44
  'would commit (what .gitignore leaves out is not there, so dependencies are installed by the tasks ' +
@@ -75,6 +95,10 @@ class SandboxClient {
75
95
  this.connection = connection;
76
96
  this.sandbox = sandbox;
77
97
  this.build = build;
98
+ // What the agent last read of each file, or wrote, by its sha256. A write sends it as If-Match,
99
+ // so a write over a file that changed since is refused. A file this client never read is written
100
+ // as it is, and so is a new file: there is no hash to check.
101
+ this.seen = new Map();
78
102
  }
79
103
  get id() {
80
104
  return this.sandbox.id;
@@ -92,9 +116,14 @@ class SandboxClient {
92
116
  static async list(connection) {
93
117
  return (await json(await call(connection, 'GET', '/v1/sandboxes'))).sandboxes;
94
118
  }
95
- // checks out the ref again, what changed in the sandbox is gone
119
+ // checks out the ref again, and the server refuses that over changes of the sandbox. Not sent
120
+ // again after a lost answer: the server may have moved the sandbox already, and a second
121
+ // fetch would move it again, past what the agent did since.
96
122
  static async fetch(connection, id, ref) {
97
- return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, { body: { ref } }));
123
+ return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, {
124
+ body: { ref },
125
+ repeat: 'unsent',
126
+ }));
98
127
  }
99
128
  async stat(path) {
100
129
  if (checkSandboxPath(path) === '') {
@@ -109,25 +138,54 @@ class SandboxClient {
109
138
  if (response.headers.get('x-hammerkit-type') === 'directory') {
110
139
  throw new SandboxClientError(`${path} is a directory`, 400);
111
140
  }
112
- return Buffer.from(await response.arrayBuffer());
141
+ const content = Buffer.from(await response.arrayBuffer());
142
+ this.remember(checkSandboxPath(path), sha256Of(content));
143
+ return content;
113
144
  }
145
+ // not sent again after a lost answer: a write sent again would write over what the agent did since.
146
+ // Refused with 412 when the file changed since the agent read it (see `seen`).
114
147
  async writeRaw(path, content) {
115
- return json(await call(this.connection, 'PUT', this.file(path), { raw: content }));
148
+ const key = checkSandboxPath(path);
149
+ const written = await json(await call(this.connection, 'PUT', this.file(path), {
150
+ raw: content,
151
+ repeat: 'unsent',
152
+ ifMatch: this.seen.get(key),
153
+ }));
154
+ this.remember(key, sha256Of(content));
155
+ return written;
116
156
  }
117
157
  // numbered lines, like `cat -n`
118
158
  async read(path, offset, limit) {
119
- return json(await call(this.connection, 'GET', this.file(path), { query: { offset, limit } }));
159
+ const read = await json(await call(this.connection, 'GET', this.file(path), { query: { offset, limit } }));
160
+ // the hash is of the whole file, however many lines were asked for
161
+ this.remember(checkSandboxPath(path), read.sha256);
162
+ return read;
120
163
  }
121
164
  async tree(query) {
122
165
  return json(await call(this.connection, 'GET', `${this.base()}/tree`, { query: { ...query } }));
123
166
  }
124
167
  async search(query) {
125
- return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query }));
168
+ return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query, repeat: 'always' }));
126
169
  }
127
- // all or nothing
170
+ // all or nothing; a replace or a patch sent again would not find what it changed, so only a
171
+ // dry run is sent again on a broken connection
128
172
  async edit(ops, dryRun = false) {
129
- const answer = await call(this.connection, 'POST', `${this.base()}/edits`, { body: { dryRun, ops } });
130
- return (await json(answer)).files;
173
+ const answer = await call(this.connection, 'POST', `${this.base()}/edits`, {
174
+ body: { dryRun, ops: this.withHashes(ops) },
175
+ repeat: dryRun ? 'always' : 'unsent',
176
+ });
177
+ const files = (await json(answer)).files;
178
+ // a dry run changes nothing, so what the agent read stays as it was
179
+ if (!dryRun) {
180
+ for (const file of files) {
181
+ const key = fileKey(file.path);
182
+ // a file the edit left without a hash is one the agent has to read again
183
+ if (key !== undefined) {
184
+ this.remember(key, file.change === 'deleted' ? undefined : file.sha256);
185
+ }
186
+ }
187
+ }
188
+ return files;
131
189
  }
132
190
  async changes() {
133
191
  return json(await call(this.connection, 'GET', `${this.base()}/changes`));
@@ -204,15 +262,16 @@ class SandboxClient {
204
262
  ...(request.ttl ? { ttl: request.ttl } : {}),
205
263
  ...(request.sleepTtl ? { sleepTtl: request.sleepTtl } : {}),
206
264
  ...(request.name ? { name: request.name } : {}),
265
+ ...(request.restart?.length ? { restart: request.restart } : {}),
207
266
  source: request.branch
208
267
  ? { type: 'ref', repo: this.sandbox.repo, ref: request.branch }
209
268
  : { type: 'sandbox', id: this.id },
210
269
  });
211
270
  return followRun(this.connection, submitted, { signal: options.signal, untilUp: true });
212
271
  }
213
- // Stops a run: a service run takes its services and endpoints down.
272
+ // Stops a run: a service run takes its services and endpoints down. The same however often it comes.
214
273
  async stop(id) {
215
- return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`));
274
+ return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`, { repeat: 'always' }));
216
275
  }
217
276
  /**
218
277
  * A page of an endpoint of a service run, as the caller sees it: only at an address the
@@ -276,6 +335,41 @@ class SandboxClient {
276
335
  base() {
277
336
  return `/v1/sandboxes/${encodeURIComponent(this.id)}`;
278
337
  }
338
+ // The ops of an edit as they go to the server, with the paths the server checks. The first op on
339
+ // a file carries the hash the agent read of it. The server checks a file as the edit has changed
340
+ // it so far, so an op after one that changed its file, a move's destination included, or after a
341
+ // patch (which names files of its own, with no hash), carries none. An invalid path goes as it is.
342
+ withHashes(ops) {
343
+ const changed = new Set();
344
+ let patched = false;
345
+ return ops.map((op) => {
346
+ if (op.op === 'patch') {
347
+ patched = true;
348
+ return op;
349
+ }
350
+ const key = fileKey(op.path);
351
+ if (key === undefined) {
352
+ return op;
353
+ }
354
+ const hash = !patched && !changed.has(key) ? this.seen.get(key) : undefined;
355
+ changed.add(key);
356
+ const to = op.op === 'move' ? fileKey(op.to) : undefined;
357
+ if (to !== undefined) {
358
+ changed.add(to);
359
+ }
360
+ const sent = op.op === 'move' ? { ...op, path: key, to: to ?? op.to } : { ...op, path: key };
361
+ return hash === undefined || op.ifHash !== undefined ? sent : { ...sent, ifHash: hash };
362
+ });
363
+ }
364
+ // a hash the server gave that is not a sha256 is not one the agent read, so the file is read again
365
+ remember(key, sha256) {
366
+ if (sha256 !== undefined && SHA256.test(sha256)) {
367
+ this.seen.set(key, sha256);
368
+ }
369
+ else {
370
+ this.seen.delete(key);
371
+ }
372
+ }
279
373
  file(path) {
280
374
  const clean = checkSandboxPath(path);
281
375
  if (!clean) {
@@ -285,6 +379,20 @@ class SandboxClient {
285
379
  }
286
380
  }
287
381
  exports.SandboxClient = SandboxClient;
382
+ // The key of a file in the record of what the agent read: its clean path, or undefined for a path
383
+ // outside the sandbox, which the server refuses anyway
384
+ function fileKey(path) {
385
+ try {
386
+ return checkSandboxPath(path);
387
+ }
388
+ catch {
389
+ return undefined;
390
+ }
391
+ }
392
+ const SHA256 = /^[0-9a-f]{64}$/;
393
+ function sha256Of(content) {
394
+ return (0, crypto_1.createHash)('sha256').update(content).digest('hex');
395
+ }
288
396
  // The first lines of every shell command: it stops when the working directory is empty,
289
397
  // links included, without any tool but the shell itself.
290
398
  const EMPTY_MARKER = 'hammerkit: the shell sees no files';
@@ -346,6 +454,12 @@ async function submitRun(connection, request) {
346
454
  return json(await call(connection, 'POST', '/v1/runs', { body: request }));
347
455
  }
348
456
  exports.submitRun = submitRun;
457
+ // The newest passed run of each check key, as `POST /v1/checks/lookup` answers it: a read,
458
+ // asked again while the server is away.
459
+ async function lookupChecks(connection, repo, keys) {
460
+ return json(await call(connection, 'POST', '/v1/checks/lookup', { body: { repo, keys }, repeat: 'always' }));
461
+ }
462
+ exports.lookupChecks = lookupChecks;
349
463
  /**
350
464
  * Follows a run to its end: its log as it grows, and its state. A signal cancels the run
351
465
  * on the server and fails the follow. A service run that moved to another commit is followed
@@ -372,29 +486,70 @@ function isThere(run, submitted) {
372
486
  }
373
487
  async function followRun(connection, submitted, options = {}) {
374
488
  const path = `/v1/runs/${encodeURIComponent(submitted.id)}`;
489
+ // the stop of the follow, or of the command when it names none
490
+ const signal = options.signal ?? connection.signal;
375
491
  let cancelling;
376
492
  const cancel = () => {
377
493
  if (!submitted.moved) {
378
- cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`).catch(() => undefined));
494
+ // the same however often it comes, and waited for only as long as the follow waits for it
495
+ cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`, {
496
+ repeat: 'always',
497
+ reconnectMs: CANCEL_WAIT_MS,
498
+ signal: null,
499
+ }).catch(() => undefined));
379
500
  }
380
501
  };
381
502
  if (!options.detach) {
382
- options.signal?.addEventListener('abort', cancel, { once: true });
503
+ signal?.addEventListener('abort', cancel, { once: true });
383
504
  }
384
505
  const lines = [];
385
506
  let from = submitted.moved?.logFrom ?? 1;
386
507
  let truncated = false;
508
+ // where the log went on after a server that was killed lost its end (LogPage.lost), as the
509
+ // follow last heard it, and the last line it read itself: it reads again from `lost` only
510
+ // when it read lines there, which are gone, not when it started past it (a moved run)
511
+ let lost;
512
+ let read = 0;
387
513
  const add = (line) => {
388
514
  lines.push(line);
389
515
  options.onLine?.(line);
390
516
  };
517
+ // a server that is away is waited for until the signal stops the follow, which goes on then
518
+ // as a stopped one
519
+ const stoppable = (read) => read.catch((e) => {
520
+ if (signal?.aborted) {
521
+ return undefined;
522
+ }
523
+ throw e;
524
+ });
391
525
  const readLog = async () => {
392
526
  for (;;) {
393
- const page = await json(await call(connection, 'GET', `${path}/logs`, { query: { task: options.task, from, limit: 1000 } }));
527
+ const page = await stoppable(call(connection, 'GET', `${path}/logs`, {
528
+ query: { task: options.task, from, limit: 1000 },
529
+ signal,
530
+ }).then(json));
531
+ if (!page) {
532
+ return;
533
+ }
394
534
  truncated = page.truncated;
535
+ if (page.lost !== undefined && page.lost !== lost) {
536
+ lost = page.lost;
537
+ if (read >= page.lost) {
538
+ // the lines from there on are not the ones read before: they are gone with the server
539
+ add({
540
+ line: 0,
541
+ task: 'hammerkit',
542
+ stream: 'stderr',
543
+ text: `… the server restarted and lost the last lines it had sent, the log goes on from line ${page.lost}`,
544
+ });
545
+ from = page.lost;
546
+ continue;
547
+ }
548
+ }
395
549
  for (const line of page.lines) {
396
550
  add(line);
397
551
  from = line.line + 1;
552
+ read = line.line;
398
553
  }
399
554
  if (!page.next) {
400
555
  return;
@@ -405,10 +560,10 @@ async function followRun(connection, submitted, options = {}) {
405
560
  let run = submitted;
406
561
  let waitingSaid = false;
407
562
  for (;;) {
408
- if (options.signal?.aborted && options.detach) {
563
+ if (signal?.aborted && options.detach) {
409
564
  break;
410
565
  }
411
- if (options.signal?.aborted) {
566
+ if (signal?.aborted) {
412
567
  // the process may exit after this, so the cancel has to reach the server first
413
568
  cancel();
414
569
  let timer;
@@ -424,7 +579,8 @@ async function followRun(connection, submitted, options = {}) {
424
579
  if (exports.FINAL_RUN_STATES.includes(run.state) || (options.untilUp && isThere(run, submitted))) {
425
580
  break;
426
581
  }
427
- run = await json(await call(connection, 'GET', path, { query: { wait: POLL_WAIT } }));
582
+ run =
583
+ (await stoppable(call(connection, 'GET', path, { query: { wait: POLL_WAIT }, signal }).then(json))) ?? run;
428
584
  }
429
585
  if (truncated) {
430
586
  truncatedEnd(run, options.task).forEach(add);
@@ -432,7 +588,7 @@ async function followRun(connection, submitted, options = {}) {
432
588
  return { run, lines, truncated };
433
589
  }
434
590
  finally {
435
- options.signal?.removeEventListener('abort', cancel);
591
+ signal?.removeEventListener('abort', cancel);
436
592
  }
437
593
  }
438
594
  exports.followRun = followRun;
@@ -459,6 +615,26 @@ async function getRun(connection, id) {
459
615
  return response.status === 404 ? null : json(response);
460
616
  }
461
617
  exports.getRun = getRun;
618
+ // null when the caller may not see the run (or the server keeps none of it)
619
+ async function getRunArtifacts(connection, id) {
620
+ const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts`, { missing: true });
621
+ return response.status === 404 ? null : json(response);
622
+ }
623
+ exports.getRunArtifacts = getRunArtifacts;
624
+ /**
625
+ * Writes the archive of one output of a run to `file`: a gzipped tar of its paths in the
626
+ * project. It may be large, so it is written as it comes and may take longer than a call.
627
+ */
628
+ async function downloadRunArtifact(connection, id, output, file) {
629
+ const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts/${output}`, {
630
+ timeoutMs: DOWNLOAD_TIMEOUT_MS,
631
+ });
632
+ if (!response.body) {
633
+ throw new SandboxClientError(`${connection.url} answered without the archive`);
634
+ }
635
+ await (0, promises_1.pipeline)(stream_1.Readable.fromWeb(response.body), (0, fs_1.createWriteStream)(file));
636
+ }
637
+ exports.downloadRunArtifact = downloadRunArtifact;
462
638
  /**
463
639
  * Reads the log of a run as it is now, every line or the last `tail` of them, of one task or
464
640
  * of all: also of a run that ended, as long as the server keeps it.
@@ -565,42 +741,74 @@ exports.quotePosix = quotePosix;
565
741
  function json(response) {
566
742
  return response.json();
567
743
  }
568
- async function call(connection, method, path, options = {}) {
744
+ /**
745
+ * The answer to a call, whatever its status. A call the server is away for is sent again as
746
+ * `repeat` allows, within the window of the connection; a token the server does not accept is
747
+ * renewed once and the call sent again.
748
+ */
749
+ async function request(connection, method, path, options = {}) {
569
750
  const url = new URL(`${connection.url.replace(/\/$/, '')}${path}`);
570
751
  for (const [key, value] of Object.entries(options.query ?? {})) {
571
752
  if (value !== undefined) {
572
753
  url.searchParams.set(key, String(value));
573
754
  }
574
755
  }
575
- const send = async () => {
576
- const token = await connection.token();
577
- if (!(0, token_source_1.isToken)(token)) {
756
+ const shown = (0, reconnect_1.showUrl)(connection.url);
757
+ // the stop of the command, unless the call names its own or none
758
+ const stop = options.signal === undefined ? connection.signal : options.signal ?? undefined;
759
+ const timing = connection.reconnect ?? reconnect_1.RECONNECT_TIMING;
760
+ const reconnecting = new reconnect_1.Reconnecting({
761
+ url: connection.url,
762
+ timing: options.reconnectMs !== undefined ? { ...timing, windowMs: options.reconnectMs } : timing,
763
+ say: connection.say,
764
+ signal: stop,
765
+ fail: options.fail ?? ((message) => new SandboxClientError(message)),
766
+ });
767
+ const attempt = async () => {
768
+ const token = 'token' in connection ? await connection.token() : undefined;
769
+ if (token !== undefined && !(0, token_source_1.isToken)(token)) {
578
770
  // a header refuses such a value and would quote it whole in its error
579
771
  throw new SandboxClientError('the token is not a single line of visible characters');
580
772
  }
773
+ // a try after one that failed takes no longer than what is left of the window
774
+ const timeout = AbortSignal.timeout(reconnecting.timeoutMs(options.timeoutMs ?? TIMEOUT_MS));
581
775
  return fetch(url, {
582
776
  method,
583
777
  headers: {
584
- authorization: `Bearer ${token}`,
778
+ ...(token !== undefined ? { authorization: `Bearer ${token}` } : {}),
585
779
  ...(options.body !== undefined ? { 'content-type': 'application/json' } : {}),
586
780
  ...(options.raw !== undefined ? { 'content-type': 'application/octet-stream' } : {}),
781
+ ...(options.ifMatch !== undefined ? { 'if-match': `"${options.ifMatch}"` } : {}),
587
782
  },
588
783
  body: options.body !== undefined ? JSON.stringify(options.body) : options.raw,
589
- signal: AbortSignal.timeout(TIMEOUT_MS),
784
+ signal: stop ? AbortSignal.any([timeout, stop]) : timeout,
590
785
  // an answer from anywhere else is not the server's, and a PUT would send its file on
591
786
  redirect: 'error',
592
- }).catch((e) => {
593
- throw new SandboxClientError(`unable to reach ${connection.url}: ${redact(fetchFailure(e), token)}`);
594
- });
787
+ }).then((response) => ({ response }), (e) => ({
788
+ error: e,
789
+ message: stop?.aborted
790
+ ? `stopped while asking ${shown}`
791
+ : `unable to reach ${shown}: ${token === undefined ? fetchFailure(e) : redact(fetchFailure(e), token)}`,
792
+ }));
595
793
  };
596
- let response = await send();
597
- if (response.status === 401 && connection.renew) {
794
+ const repeat = options.repeat ?? (method === 'GET' || method === 'PUT' ? 'always' : 'unsent');
795
+ let response = await reconnecting.send(attempt, repeat);
796
+ // a new token is asked for within the window the call has left, not after it ran out
797
+ if (response.status === 401 && 'token' in connection && connection.renew && !reconnecting.exhausted) {
598
798
  await connection.renew();
599
- response = await send();
799
+ response = await reconnecting.send(attempt, repeat);
600
800
  }
801
+ return response;
802
+ }
803
+ exports.request = request;
804
+ // The body of a call that answers 2xx (or a 404 it was asked to take as an answer); any other
805
+ // status is an error, which says what the server answered.
806
+ async function call(connection, method, path, options = {}) {
807
+ const response = await request(connection, method, path, options);
601
808
  if (response.ok || (options.missing && response.status === 404)) {
602
809
  return response;
603
810
  }
811
+ const shown = (0, reconnect_1.showUrl)(connection.url);
604
812
  let said = '';
605
813
  try {
606
814
  const body = await json(response);
@@ -610,8 +818,8 @@ async function call(connection, method, path, options = {}) {
610
818
  // no JSON
611
819
  }
612
820
  if (response.status === 401) {
613
- throw new SandboxClientError(`${connection.url} did not accept the token`, 401);
821
+ throw new SandboxClientError(`${shown} did not accept the token`, 401);
614
822
  }
615
- throw new SandboxClientError(said || `${connection.url} answered ${response.status}`, response.status);
823
+ throw new SandboxClientError(said || `${shown} answered ${response.status}`, response.status);
616
824
  }
617
825
  //# sourceMappingURL=sandbox-client.js.map
@@ -71,8 +71,11 @@ exports.SERVICE_TOOLS = [
71
71
  description: 'Start services of the published build file on the hammerkit server, with the files of the sandbox (or of ' +
72
72
  'a branch), and keep them up for a person to look at: each endpoint (service:port) gets an address of its ' +
73
73
  'own behind the sign-in of the server. Answers once they are up, with the addresses and until when they ' +
74
- 'stay. A second start with the same name replaces the first, so its addresses stay the same. A server on ' +
75
- 'Kubernetes starts services from a branch only: push the sandbox and pass branch.',
74
+ 'stay. A second start with the same name replaces the first, so its addresses stay the same. Services from ' +
75
+ 'the sandbox on a Kubernetes server follow its edits a few seconds after each one: the changed files go into ' +
76
+ 'the services that watch their files (continuous), and the others keep the files they started with, unless ' +
77
+ 'restart names them, which starts them again with the new files. On a host the services run on the sandbox ' +
78
+ 'files themselves, so there is nothing to follow and restart is refused.',
76
79
  parameters: {
77
80
  services: { type: 'string[]', description: 'The services to start, as the build file names them' },
78
81
  endpoints: { type: 'string[]', description: 'The ports to publish, as service:port, such as web:8080' },
@@ -93,6 +96,11 @@ exports.SERVICE_TOOLS = [
93
96
  type: 'string',
94
97
  description: 'Start from this pushed branch of the repository instead of the files of the sandbox',
95
98
  },
99
+ restart: {
100
+ type: 'string[]',
101
+ description: 'The services that start again with the files of the sandbox after an edit of it; the others keep ' +
102
+ 'the files they started with. Only with the sandbox, not with branch',
103
+ },
96
104
  },
97
105
  required: ['services'],
98
106
  async call(client, args, signal) {
@@ -103,6 +111,7 @@ exports.SERVICE_TOOLS = [
103
111
  sleepTtl: args.sleepTtl || undefined,
104
112
  name: args.name || undefined,
105
113
  branch: args.branch || undefined,
114
+ restart: args.restart?.length ? args.restart : undefined,
106
115
  }, { signal });
107
116
  return describeServiceRun(followed.run);
108
117
  },
@@ -45,7 +45,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
45
45
  }
46
46
  }
47
47
  for (const status of mainStatuses(pod, container)) {
48
- const failure = getContainerFailure(status, restartsEnded(pod, status), restarts);
48
+ const failure = getContainerFailure(pod, status, restartsEnded(pod, status), restarts);
49
49
  if (failure) {
50
50
  return failure;
51
51
  }
@@ -53,7 +53,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
53
53
  return null;
54
54
  }
55
55
  exports.getPodFailure = getPodFailure;
56
- function getContainerFailure(status, restartsEnded, restarts) {
56
+ function getContainerFailure(pod, status, restartsEnded, restarts) {
57
57
  const waiting = status.state?.waiting;
58
58
  const reason = waiting?.reason;
59
59
  const said = waiting?.message ? `: ${cut(waiting.message)}` : '';
@@ -78,18 +78,33 @@ function getContainerFailure(status, restartsEnded, restarts) {
78
78
  return { text: `its container could not be started (${reason})${said}`, final: false };
79
79
  case 'CrashLoopBackOff':
80
80
  return status.restartCount >= restarts
81
- ? { text: `it keeps crashing: ${describeLastExit(status)}`, final: true }
81
+ ? { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true }
82
82
  : null;
83
83
  }
84
84
  // a kubelet may leave an instance that ended as it is until its back-off is over, and say
85
85
  // CrashLoopBackOff only when it looks at the pod again, a minute later: the same crash
86
86
  if (restartsEnded && status.state?.terminated && status.restartCount >= restarts) {
87
- return { text: `it keeps crashing: ${describeLastExit(status)}`, final: true };
87
+ return { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true };
88
88
  }
89
89
  return null;
90
90
  }
91
- // How the last instance of a container ended, as the cluster says it.
92
- function describeLastExit(status) {
91
+ // The signals a container is most often ended by, by their Linux numbers: containers here
92
+ // are Linux ones, and other systems number some signals differently.
93
+ const SIGNALS = {
94
+ 1: 'SIGHUP',
95
+ 2: 'SIGINT',
96
+ 6: 'SIGABRT',
97
+ 9: 'SIGKILL',
98
+ 11: 'SIGSEGV',
99
+ 15: 'SIGTERM',
100
+ };
101
+ /**
102
+ * How the last instance of a container ended, as the cluster says it: its exit code and
103
+ * reason, and the signal of an exit code above 128. The kubelet kills a container whose
104
+ * liveness probe (its healthcheck) keeps failing, so a container of `pod` with one that was
105
+ * killed says that it may be why; one without a healthcheck never does.
106
+ */
107
+ function describeLastExit(status, pod) {
93
108
  // the instance that ended now, else the one before the one that waits or runs
94
109
  const last = status.state?.terminated ?? status.lastState?.terminated;
95
110
  const restarts = `, restarted ${status.restartCount} time${status.restartCount === 1 ? '' : 's'}`;
@@ -99,8 +114,14 @@ function describeLastExit(status) {
99
114
  if (last.reason === 'OOMKilled') {
100
115
  return `it was killed for using more memory than its limit (OOMKilled)${restarts}`;
101
116
  }
102
- // the kubelet kills a container whose liveness probe (its healthcheck) keeps failing
103
- const killed = last.exitCode === 137 || last.exitCode === 143 ? ', killed as when its healthcheck kept failing' : '';
117
+ // A shell, and the runtime for process 1, exit with 128 plus the signal that ended a
118
+ // process: 129 to 159 are the signals 1 to 31, which Linux has; a higher code is the
119
+ // process's own.
120
+ const signal = last.exitCode >= 129 && last.exitCode <= 159 ? last.exitCode - 128 : undefined;
121
+ const probed = !!pod.spec?.containers?.find((container) => container.name === status.name)?.livenessProbe;
122
+ const killed = signal === undefined
123
+ ? ''
124
+ : `, killed by ${SIGNALS[signal] ?? `signal ${signal}`}${probed && (signal === 9 || signal === 15) ? ' as when its healthcheck keeps failing' : ''}`;
104
125
  return `it exited with code ${last.exitCode}${last.reason ? ` (${last.reason})` : ''}${killed}${restarts}`;
105
126
  }
106
127
  exports.describeLastExit = describeLastExit;
@@ -125,14 +146,14 @@ function getPodWaiting(pod, container) {
125
146
  case 'RunContainerError':
126
147
  return `can not start its container yet (${waiting.reason})${said}`;
127
148
  case 'CrashLoopBackOff':
128
- return `crashed and starts again: ${describeLastExit(status)}`;
149
+ return `crashed and starts again: ${describeLastExit(status, pod)}`;
129
150
  }
130
151
  const ended = status.state?.terminated;
131
152
  if (ended && restartsEnded(pod, status)) {
132
- return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status)}`;
153
+ return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status, pod)}`;
133
154
  }
134
155
  if (status.restartCount > 0 && status.state?.running && !status.ready) {
135
- return `restarted: ${describeLastExit(status)}`;
156
+ return `restarted: ${describeLastExit(status, pod)}`;
136
157
  }
137
158
  }
138
159
  return undefined;
@@ -167,16 +188,29 @@ function describePod(pod) {
167
188
  const said = failure ?? waiting;
168
189
  const parts = [phase, ...(said ? [said] : [])];
169
190
  for (const status of crashed) {
170
- if (!said?.includes(describeLastExit(status))) {
171
- parts.push(`${status.name}: ${describeLastExit(status)}`);
191
+ const exit = describeLastExit(status, pod);
192
+ if (!said?.includes(exit)) {
193
+ parts.push(`container ${status.name}: ${exit}`);
172
194
  }
173
195
  }
174
196
  if (!said && unready.length > 0) {
175
197
  parts.push(`not ready: ${unready.join(', ')}`);
176
198
  }
177
- return `pod ${name}: ${parts.join(', ')}`;
199
+ return `pod ${name}${describeHelper(pod)}: ${parts.join(', ')}`;
178
200
  }
179
201
  exports.describePod = describePod;
202
+ // what a pod hammerkit runs beside a task or service does, so it is not taken for the item
203
+ function describeHelper(pod) {
204
+ const item = pod.metadata?.annotations?.[resources_1.ITEM_ANNOTATION];
205
+ switch (item ? pod.metadata?.annotations?.[resources_1.HELPER_ANNOTATION] : undefined) {
206
+ case 'upload':
207
+ return ` (a helper that copies the files of ${item} into its volume, not ${item} itself)`;
208
+ case 'download':
209
+ return ` (a helper that copies the outputs of ${item} out of its volume, not ${item} itself)`;
210
+ default:
211
+ return '';
212
+ }
213
+ }
180
214
  /**
181
215
  * The message of a warning event, as far as it is the cluster's: a failed probe says the
182
216
  * output of the command, which is the service's, and is left out.