hammerkit 2.1.0-next.12 → 2.1.0-next.14

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.
@@ -7,7 +7,6 @@ const work_item_status_1 = require("../planner/work-item-status");
7
7
  const host_config_1 = require("../remote/host-config");
8
8
  const redact_1 = require("../utils/redact");
9
9
  const empty_writable_1 = require("../utils/empty-writable");
10
- const token_source_1 = require("../remote/token-source");
11
10
  const bundle_1 = require("../remote/bundle");
12
11
  const sandbox_client_1 = require("./sandbox-client");
13
12
  exports.DEFAULT_SHELL_TASK = 'sh';
@@ -34,7 +33,9 @@ exports.hasShell = hasShell;
34
33
  * The registered server a harness works on and the published version it runs, checked:
35
34
  * what the clients need to list the tasks of the version before they take a sandbox.
36
35
  */
37
- async function connectServer(environment, options) {
36
+ async function connectServer(environment, options,
37
+ // where the connection says that it reconnects; stderr when left out
38
+ say) {
38
39
  const config = await (0, host_config_1.readHostConfig)(environment);
39
40
  const name = (0, host_config_1.chooseServer)(config, options.server || undefined, 'with HAMMERKIT_SERVER or --server');
40
41
  if (!options.build) {
@@ -45,11 +46,13 @@ async function connectServer(environment, options) {
45
46
  throw new Error(`${options.build} is not the hash of a published version (sha256:...), name it as hammerkit remote publish printed it (HAMMERKIT_BUILD or --build)`);
46
47
  }
47
48
  const server = (0, host_config_1.getRegisteredServer)(config, name);
48
- return { name, connection: { url: server.url, ...(0, token_source_1.getTokenSource)(environment, name, server) }, build: options.build };
49
+ return { name, connection: (0, sandbox_client_1.getServerConnection)(environment, name, server, say), build: options.build };
49
50
  }
50
51
  exports.connectServer = connectServer;
51
- async function connectSandbox(environment, options, log = () => undefined) {
52
- const { name, connection, build } = await connectServer(environment, options);
52
+ async function connectSandbox(environment, options, log) {
53
+ // the environment of a harness that loads hammerkit as a plugin writes nowhere: what the
54
+ // connection says goes where the harness shows what happens
55
+ const { name, connection, build } = await connectServer(environment, options, log);
53
56
  let sandbox;
54
57
  if (options.sandbox) {
55
58
  sandbox = await sandbox_client_1.SandboxClient.get(connection, options.sandbox);
@@ -57,11 +60,11 @@ async function connectSandbox(environment, options, log = () => undefined) {
57
60
  else if (options.repo && options.ref) {
58
61
  sandbox = await reuseSandbox(connection, options.repo, options.ref);
59
62
  if (sandbox) {
60
- log(`took sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, it had no changes`);
63
+ log?.(`took sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, it had no changes`);
61
64
  }
62
65
  else {
63
66
  sandbox = await sandbox_client_1.SandboxClient.create(connection, options.repo, options.ref);
64
- log(`created sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, ` +
67
+ log?.(`created sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, ` +
65
68
  `set HAMMERKIT_SANDBOX=${sandbox.id} to come back to it`);
66
69
  }
67
70
  }
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Reconnecting = exports.showUrl = exports.RECONNECT_TIMING = void 0;
4
+ const http_1 = require("../server/http");
5
+ const units_1 = require("../utils/units");
6
+ // a restart of the server takes a few minutes while its new pod starts
7
+ exports.RECONNECT_TIMING = { windowMs: 10 * 60000, firstDelayMs: 1000, maxDelayMs: 15000 };
8
+ // what a proxy or the server answers while the server is away or shuts down
9
+ const AWAY_STATUSES = [502, 503, 504];
10
+ // the call never got to the server. A connect timeout is one: the connection was never
11
+ // made, so nothing of the request was sent.
12
+ const NOT_SENT = ['ECONNREFUSED', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT'];
13
+ // the connection broke or timed out, maybe after the server took the call
14
+ const LOST = [
15
+ 'ECONNRESET',
16
+ 'ECONNABORTED',
17
+ 'EPIPE',
18
+ 'ETIMEDOUT',
19
+ 'UND_ERR_SOCKET',
20
+ 'UND_ERR_HEADERS_TIMEOUT',
21
+ 'UND_ERR_BODY_TIMEOUT',
22
+ ];
23
+ // The codes of the error a fetch failed with: node's fetch keeps it as the cause, with one
24
+ // error for each address it tried when a name has several.
25
+ function failureCodes(e) {
26
+ if (e instanceof Error && e.name === 'TimeoutError') {
27
+ return ['ETIMEDOUT'];
28
+ }
29
+ const cause = e?.cause;
30
+ const codes = cause?.errors?.length ? cause.errors.map((error) => error?.code) : [cause?.code];
31
+ return codes.map((code) => (typeof code === 'string' ? code : ''));
32
+ }
33
+ function isAway(response) {
34
+ return AWAY_STATUSES.includes(response.status);
35
+ }
36
+ function mayRepeat(attempt, repeat) {
37
+ if ('response' in attempt) {
38
+ return repeat === 'always'
39
+ ? isAway(attempt.response)
40
+ : attempt.response.status === 503 && attempt.response.headers.get(http_1.RETRY_HEADER) === 'safe';
41
+ }
42
+ const codes = failureCodes(attempt.error);
43
+ return repeat === 'always'
44
+ ? codes.some((code) => NOT_SENT.includes(code) || LOST.includes(code))
45
+ : codes.every((code) => NOT_SENT.includes(code));
46
+ }
47
+ // The address of a server as it is said, without a user or password it may hold.
48
+ function showUrl(url) {
49
+ try {
50
+ const parsed = new URL(url);
51
+ if (!parsed.username && !parsed.password) {
52
+ return url;
53
+ }
54
+ parsed.username = '';
55
+ parsed.password = '';
56
+ return url.endsWith('/') ? parsed.toString() : parsed.toString().replace(/\/$/, '');
57
+ }
58
+ catch {
59
+ return url;
60
+ }
61
+ }
62
+ exports.showUrl = showUrl;
63
+ /**
64
+ * The window of one call: every send of it, a send again after a new token included, waits
65
+ * for the server at most the window, counted from the start of the first try that failed.
66
+ */
67
+ class Reconnecting {
68
+ constructor(options) {
69
+ this.options = options;
70
+ this.away = false;
71
+ this.delay = options.timing.firstDelayMs;
72
+ }
73
+ // the window ran out
74
+ get exhausted() {
75
+ return this.deadline !== undefined && this.deadline <= Date.now();
76
+ }
77
+ // how long the next try may take: no longer than what is left of the window, once it started
78
+ timeoutMs(own) {
79
+ return this.deadline === undefined ? own : Math.max(1, Math.min(own, this.deadline - Date.now()));
80
+ }
81
+ /**
82
+ * Sends a call until the server answers it, as long as it may be sent again and the server
83
+ * comes back within the window: an answer other than one of a server that is away is the
84
+ * caller's, an error that is no sign of one fails at once.
85
+ */
86
+ async send(send, repeat) {
87
+ const { url, timing, say, signal, fail } = this.options;
88
+ const shown = showUrl(url);
89
+ for (;;) {
90
+ const started = Date.now();
91
+ const attempt = await send();
92
+ if (!mayRepeat(attempt, repeat)) {
93
+ if ('response' in attempt) {
94
+ if (this.away && !isAway(attempt.response)) {
95
+ this.away = false;
96
+ say?.(`${shown} is back`);
97
+ }
98
+ return attempt.response;
99
+ }
100
+ throw fail(attempt.message);
101
+ }
102
+ const reason = 'response' in attempt ? `${shown} answered ${attempt.response.status}` : attempt.message;
103
+ if ('response' in attempt) {
104
+ await attempt.response.body?.cancel().catch(() => undefined);
105
+ }
106
+ const window = (0, units_1.formatDuration)(timing.windowMs);
107
+ this.deadline ?? (this.deadline = started + timing.windowMs);
108
+ if (!this.away) {
109
+ this.away = true;
110
+ say?.(`${reason}, reconnecting for up to ${window}`);
111
+ }
112
+ const left = this.deadline - Date.now();
113
+ if (left <= 0) {
114
+ throw fail(`${shown} did not come back within ${window}: ${reason}`);
115
+ }
116
+ if (signal?.aborted || !(await pause(Math.min(this.delay, left), signal))) {
117
+ throw fail(reason);
118
+ }
119
+ this.delay = Math.min(this.delay * 2, timing.maxDelayMs);
120
+ }
121
+ }
122
+ }
123
+ exports.Reconnecting = Reconnecting;
124
+ // false when the signal ended the pause
125
+ function pause(ms, signal) {
126
+ return new Promise((resolve) => {
127
+ const done = (waited) => {
128
+ clearTimeout(timer);
129
+ signal?.removeEventListener('abort', aborted);
130
+ resolve(waited);
131
+ };
132
+ const aborted = () => done(false);
133
+ const timer = setTimeout(() => done(true), ms);
134
+ signal?.addEventListener('abort', aborted, { once: true });
135
+ });
136
+ }
137
+ //# sourceMappingURL=reconnect.js.map
@@ -1,8 +1,9 @@
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.downloadRunArtifact = exports.getRunArtifacts = 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.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
4
  const path_1 = require("path");
5
5
  const token_source_1 = require("../remote/token-source");
6
+ const reconnect_1 = require("./reconnect");
6
7
  const fs_1 = require("fs");
7
8
  const stream_1 = require("stream");
8
9
  const promises_1 = require("stream/promises");
@@ -26,6 +27,17 @@ class SandboxClientError extends Error {
26
27
  }
27
28
  }
28
29
  exports.SandboxClientError = SandboxClientError;
30
+ // A connection to a registered server, which says when it reconnects, on stderr unless told
31
+ // where else, and stops when the command is stopped.
32
+ function getServerConnection(environment, name, server, say = (line) => environment.stderr.write(`${line}\n`)) {
33
+ return {
34
+ url: server.url,
35
+ ...(0, token_source_1.getTokenSource)(environment, name, server),
36
+ say,
37
+ signal: environment.abortCtrl.signal,
38
+ };
39
+ }
40
+ exports.getServerConnection = getServerConnection;
29
41
  // What the agent is told of a check, on each harness.
30
42
  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 ' +
31
43
  'would commit (what .gitignore leaves out is not there, so dependencies are installed by the tasks ' +
@@ -99,9 +111,12 @@ class SandboxClient {
99
111
  static async list(connection) {
100
112
  return (await json(await call(connection, 'GET', '/v1/sandboxes'))).sandboxes;
101
113
  }
102
- // checks out the ref again, what changed in the sandbox is gone
114
+ // checks out the ref again, what changed in the sandbox is gone: the same however often it comes
103
115
  static async fetch(connection, id, ref) {
104
- return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, { body: { ref } }));
116
+ return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, {
117
+ body: { ref },
118
+ repeat: 'always',
119
+ }));
105
120
  }
106
121
  async stat(path) {
107
122
  if (checkSandboxPath(path) === '') {
@@ -129,11 +144,15 @@ class SandboxClient {
129
144
  return json(await call(this.connection, 'GET', `${this.base()}/tree`, { query: { ...query } }));
130
145
  }
131
146
  async search(query) {
132
- return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query }));
147
+ return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query, repeat: 'always' }));
133
148
  }
134
- // all or nothing
149
+ // all or nothing; a replace or a patch sent again would not find what it changed, so only a
150
+ // dry run is sent again on a broken connection
135
151
  async edit(ops, dryRun = false) {
136
- const answer = await call(this.connection, 'POST', `${this.base()}/edits`, { body: { dryRun, ops } });
152
+ const answer = await call(this.connection, 'POST', `${this.base()}/edits`, {
153
+ body: { dryRun, ops },
154
+ repeat: dryRun ? 'always' : 'unsent',
155
+ });
137
156
  return (await json(answer)).files;
138
157
  }
139
158
  async changes() {
@@ -217,9 +236,9 @@ class SandboxClient {
217
236
  });
218
237
  return followRun(this.connection, submitted, { signal: options.signal, untilUp: true });
219
238
  }
220
- // Stops a run: a service run takes its services and endpoints down.
239
+ // Stops a run: a service run takes its services and endpoints down. The same however often it comes.
221
240
  async stop(id) {
222
- return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`));
241
+ return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`, { repeat: 'always' }));
223
242
  }
224
243
  /**
225
244
  * A page of an endpoint of a service run, as the caller sees it: only at an address the
@@ -353,6 +372,12 @@ async function submitRun(connection, request) {
353
372
  return json(await call(connection, 'POST', '/v1/runs', { body: request }));
354
373
  }
355
374
  exports.submitRun = submitRun;
375
+ // The newest passed run of each check key, as `POST /v1/checks/lookup` answers it: a read,
376
+ // asked again while the server is away.
377
+ async function lookupChecks(connection, repo, keys) {
378
+ return json(await call(connection, 'POST', '/v1/checks/lookup', { body: { repo, keys }, repeat: 'always' }));
379
+ }
380
+ exports.lookupChecks = lookupChecks;
356
381
  /**
357
382
  * Follows a run to its end: its log as it grows, and its state. A signal cancels the run
358
383
  * on the server and fails the follow. A service run that moved to another commit is followed
@@ -379,29 +404,70 @@ function isThere(run, submitted) {
379
404
  }
380
405
  async function followRun(connection, submitted, options = {}) {
381
406
  const path = `/v1/runs/${encodeURIComponent(submitted.id)}`;
407
+ // the stop of the follow, or of the command when it names none
408
+ const signal = options.signal ?? connection.signal;
382
409
  let cancelling;
383
410
  const cancel = () => {
384
411
  if (!submitted.moved) {
385
- cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`).catch(() => undefined));
412
+ // the same however often it comes, and waited for only as long as the follow waits for it
413
+ cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`, {
414
+ repeat: 'always',
415
+ reconnectMs: CANCEL_WAIT_MS,
416
+ signal: null,
417
+ }).catch(() => undefined));
386
418
  }
387
419
  };
388
420
  if (!options.detach) {
389
- options.signal?.addEventListener('abort', cancel, { once: true });
421
+ signal?.addEventListener('abort', cancel, { once: true });
390
422
  }
391
423
  const lines = [];
392
424
  let from = submitted.moved?.logFrom ?? 1;
393
425
  let truncated = false;
426
+ // where the log went on after a server that was killed lost its end (LogPage.lost), as the
427
+ // follow last heard it, and the last line it read itself: it reads again from `lost` only
428
+ // when it read lines there, which are gone, not when it started past it (a moved run)
429
+ let lost;
430
+ let read = 0;
394
431
  const add = (line) => {
395
432
  lines.push(line);
396
433
  options.onLine?.(line);
397
434
  };
435
+ // a server that is away is waited for until the signal stops the follow, which goes on then
436
+ // as a stopped one
437
+ const stoppable = (read) => read.catch((e) => {
438
+ if (signal?.aborted) {
439
+ return undefined;
440
+ }
441
+ throw e;
442
+ });
398
443
  const readLog = async () => {
399
444
  for (;;) {
400
- const page = await json(await call(connection, 'GET', `${path}/logs`, { query: { task: options.task, from, limit: 1000 } }));
445
+ const page = await stoppable(call(connection, 'GET', `${path}/logs`, {
446
+ query: { task: options.task, from, limit: 1000 },
447
+ signal,
448
+ }).then(json));
449
+ if (!page) {
450
+ return;
451
+ }
401
452
  truncated = page.truncated;
453
+ if (page.lost !== undefined && page.lost !== lost) {
454
+ lost = page.lost;
455
+ if (read >= page.lost) {
456
+ // the lines from there on are not the ones read before: they are gone with the server
457
+ add({
458
+ line: 0,
459
+ task: 'hammerkit',
460
+ stream: 'stderr',
461
+ text: `… the server restarted and lost the last lines it had sent, the log goes on from line ${page.lost}`,
462
+ });
463
+ from = page.lost;
464
+ continue;
465
+ }
466
+ }
402
467
  for (const line of page.lines) {
403
468
  add(line);
404
469
  from = line.line + 1;
470
+ read = line.line;
405
471
  }
406
472
  if (!page.next) {
407
473
  return;
@@ -412,10 +478,10 @@ async function followRun(connection, submitted, options = {}) {
412
478
  let run = submitted;
413
479
  let waitingSaid = false;
414
480
  for (;;) {
415
- if (options.signal?.aborted && options.detach) {
481
+ if (signal?.aborted && options.detach) {
416
482
  break;
417
483
  }
418
- if (options.signal?.aborted) {
484
+ if (signal?.aborted) {
419
485
  // the process may exit after this, so the cancel has to reach the server first
420
486
  cancel();
421
487
  let timer;
@@ -431,7 +497,8 @@ async function followRun(connection, submitted, options = {}) {
431
497
  if (exports.FINAL_RUN_STATES.includes(run.state) || (options.untilUp && isThere(run, submitted))) {
432
498
  break;
433
499
  }
434
- run = await json(await call(connection, 'GET', path, { query: { wait: POLL_WAIT } }));
500
+ run =
501
+ (await stoppable(call(connection, 'GET', path, { query: { wait: POLL_WAIT }, signal }).then(json))) ?? run;
435
502
  }
436
503
  if (truncated) {
437
504
  truncatedEnd(run, options.task).forEach(add);
@@ -439,7 +506,7 @@ async function followRun(connection, submitted, options = {}) {
439
506
  return { run, lines, truncated };
440
507
  }
441
508
  finally {
442
- options.signal?.removeEventListener('abort', cancel);
509
+ signal?.removeEventListener('abort', cancel);
443
510
  }
444
511
  }
445
512
  exports.followRun = followRun;
@@ -599,12 +666,25 @@ async function call(connection, method, path, options = {}) {
599
666
  url.searchParams.set(key, String(value));
600
667
  }
601
668
  }
602
- const send = async () => {
669
+ const shown = (0, reconnect_1.showUrl)(connection.url);
670
+ // the stop of the command, unless the call names its own or none
671
+ const stop = options.signal === undefined ? connection.signal : options.signal ?? undefined;
672
+ const timing = connection.reconnect ?? reconnect_1.RECONNECT_TIMING;
673
+ const reconnecting = new reconnect_1.Reconnecting({
674
+ url: connection.url,
675
+ timing: options.reconnectMs !== undefined ? { ...timing, windowMs: options.reconnectMs } : timing,
676
+ say: connection.say,
677
+ signal: stop,
678
+ fail: (message) => new SandboxClientError(message),
679
+ });
680
+ const attempt = async () => {
603
681
  const token = await connection.token();
604
682
  if (!(0, token_source_1.isToken)(token)) {
605
683
  // a header refuses such a value and would quote it whole in its error
606
684
  throw new SandboxClientError('the token is not a single line of visible characters');
607
685
  }
686
+ // a try after one that failed takes no longer than what is left of the window
687
+ const timeout = AbortSignal.timeout(reconnecting.timeoutMs(options.timeoutMs ?? TIMEOUT_MS));
608
688
  return fetch(url, {
609
689
  method,
610
690
  headers: {
@@ -613,17 +693,22 @@ async function call(connection, method, path, options = {}) {
613
693
  ...(options.raw !== undefined ? { 'content-type': 'application/octet-stream' } : {}),
614
694
  },
615
695
  body: options.body !== undefined ? JSON.stringify(options.body) : options.raw,
616
- signal: AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS),
696
+ signal: stop ? AbortSignal.any([timeout, stop]) : timeout,
617
697
  // an answer from anywhere else is not the server's, and a PUT would send its file on
618
698
  redirect: 'error',
619
- }).catch((e) => {
620
- throw new SandboxClientError(`unable to reach ${connection.url}: ${redact(fetchFailure(e), token)}`);
621
- });
699
+ }).then((response) => ({ response }), (e) => ({
700
+ error: e,
701
+ message: stop?.aborted
702
+ ? `stopped while asking ${shown}`
703
+ : `unable to reach ${shown}: ${redact(fetchFailure(e), token)}`,
704
+ }));
622
705
  };
623
- let response = await send();
624
- if (response.status === 401 && connection.renew) {
706
+ const repeat = options.repeat ?? (method === 'GET' || method === 'PUT' ? 'always' : 'unsent');
707
+ let response = await reconnecting.send(attempt, repeat);
708
+ // a new token is asked for within the window the call has left, not after it ran out
709
+ if (response.status === 401 && connection.renew && !reconnecting.exhausted) {
625
710
  await connection.renew();
626
- response = await send();
711
+ response = await reconnecting.send(attempt, repeat);
627
712
  }
628
713
  if (response.ok || (options.missing && response.status === 404)) {
629
714
  return response;
@@ -637,8 +722,8 @@ async function call(connection, method, path, options = {}) {
637
722
  // no JSON
638
723
  }
639
724
  if (response.status === 401) {
640
- throw new SandboxClientError(`${connection.url} did not accept the token`, 401);
725
+ throw new SandboxClientError(`${shown} did not accept the token`, 401);
641
726
  }
642
- throw new SandboxClientError(said || `${connection.url} answered ${response.status}`, response.status);
727
+ throw new SandboxClientError(said || `${shown} answered ${response.status}`, response.status);
643
728
  }
644
729
  //# sourceMappingURL=sandbox-client.js.map
@@ -16,6 +16,7 @@ const bundle_text_1 = require("./bundle-text");
16
16
  const sandbox_client_1 = require("../harness/sandbox-client");
17
17
  const units_1 = require("../utils/units");
18
18
  const service_tools_1 = require("../harness/service-tools");
19
+ const reconnect_1 = require("../harness/reconnect");
19
20
  const path_1 = require("path");
20
21
  const promises_1 = require("fs/promises");
21
22
  const os_1 = require("os");
@@ -278,6 +279,14 @@ function describeMissingRef(repo, ours, checkout) {
278
279
  `name another, or the commit with --ref ${checkout.commit}`
279
280
  : 'name one with --ref'));
280
281
  }
282
+ // A call the server refused, said as `callServer` says it: by the server and what it answered
283
+ function describeRefusal(url, e) {
284
+ if (!(e instanceof sandbox_client_1.SandboxClientError) || e.status === undefined || e.status === 401) {
285
+ return e;
286
+ }
287
+ const said = e.message.startsWith(`${(0, reconnect_1.showUrl)(url)} answered`) ? '' : `: ${(0, server_client_1.printable)(e.message)}`;
288
+ return new server_client_1.ServerError(`${(0, reconnect_1.showUrl)(url)} answered ${e.status}${said}`, e.status);
289
+ }
281
290
  function registerWorkCommands(remote, context) {
282
291
  const { environment, buildFile, getServer, guarded, passthrough, fail } = context;
283
292
  // the ref a run starts from: what the options name, else the checkout here
@@ -473,7 +482,7 @@ function registerWorkCommands(remote, context) {
473
482
  const source = await refSource(options);
474
483
  const ref = source.ref;
475
484
  const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
476
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
485
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
477
486
  const runOptions = {};
478
487
  for (const key of ['env', 'cache', 'timeout', 'maxTimeout']) {
479
488
  if (options[key] !== undefined) {
@@ -543,7 +552,7 @@ function registerWorkCommands(remote, context) {
543
552
  const endpoints = (options.endpoint ?? []).map(service_tools_1.parseEndpoint);
544
553
  const source = await refSource(options);
545
554
  const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
546
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
555
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
547
556
  const submitted = await submitPublishing({ serverName, server, connection }, {
548
557
  definition,
549
558
  services,
@@ -750,7 +759,7 @@ function registerWorkCommands(remote, context) {
750
759
  throw new Error('--follow prints the whole log, leave --tail out');
751
760
  }
752
761
  const { name: serverName, server } = await getServer(name);
753
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
762
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
754
763
  const found = await (0, sandbox_client_1.getRun)(connection, id);
755
764
  if (!found) {
756
765
  throw new Error(`${serverName} keeps no run ${(0, server_client_1.printable)(id)} you may see, list them with: hammerkit remote runs`);
@@ -794,7 +803,7 @@ function registerWorkCommands(remote, context) {
794
803
  }
795
804
  const path = options.path === undefined ? undefined : projectPath(options.path);
796
805
  const { name: serverName, server } = await getServer(name);
797
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
806
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
798
807
  const kept = await (0, sandbox_client_1.getRunArtifacts)(connection, id);
799
808
  if (!kept) {
800
809
  throw new Error(`${serverName} keeps no run ${(0, server_client_1.printable)(id)} you may see, list them with: hammerkit remote runs`);
@@ -876,15 +885,17 @@ function registerWorkCommands(remote, context) {
876
885
  keys.push({ task, key: found.key });
877
886
  }
878
887
  }
879
- const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
888
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
880
889
  const answer = keys.length > 0
881
- ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
882
- : { body: { checks: [] } };
890
+ ? await (0, sandbox_client_1.lookupChecks)((0, sandbox_client_1.getServerConnection)(environment, serverName, server), repo, keys).catch((e) => {
891
+ throw describeRefusal(server.url, e);
892
+ })
893
+ : { checks: [] };
883
894
  const missing = [];
884
895
  // by what was asked, never by what was answered: a task the answer leaves out, or
885
896
  // answers for another key, is not verified
886
897
  for (const { task, key } of keys) {
887
- const check = answer.body.checks.find((answered) => answered.task === task && answered.key === key);
898
+ const check = answer.checks.find((answered) => answered.task === task && answered.key === key);
888
899
  if (check?.passed) {
889
900
  environment.stdout.write(`${(0, server_client_1.printable)(task)}: ${(0, server_client_1.printable)(describePassed(check.passed))}\n`);
890
901
  }
@@ -10,6 +10,7 @@ const path_1 = require("path");
10
10
  const readline_1 = require("readline");
11
11
  const resolve_git_source_1 = require("../includes/resolve-git-source");
12
12
  const git_checkout_1 = require("./git-checkout");
13
+ const runs_1 = require("./runs");
13
14
  const run_plan_1 = require("./run-plan");
14
15
  const work_network_1 = require("../planner/work-network");
15
16
  const execute_docker_1 = require("../executer/execute-docker");
@@ -22,8 +23,12 @@ function isGitDirectory(segment) {
22
23
  return name === '.git' || name === 'git~1';
23
24
  }
24
25
  // A cancelled run gets this long to stop its tasks and remove its containers, after that
25
- // its process is killed
26
+ // its process is killed. A server without a store waits for it on close (CLOSE_TIMEOUT in
27
+ // runs.ts bounds only a server that detaches its runs)
26
28
  const STOP_GRACE_MS = 15000;
29
+ // A run the server leaves to the next one gets this long to stop its tasks on this machine: the
30
+ // rest of what CLOSE_TIMEOUT gives it is for its execution to end (its directory, its volumes)
31
+ const DETACH_GRACE_MS = runs_1.CLOSE_TIMEOUT - 5000;
27
32
  // what is kept of the error output of a process that died without saying why
28
33
  const MAX_STDERR = 2 * 1024;
29
34
  /**
@@ -370,11 +375,14 @@ class HostExecutor {
370
375
  : {}),
371
376
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
372
377
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
373
- }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal);
378
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed);
374
379
  }
375
380
  finally {
376
381
  if (placement && placed) {
377
- await placement.release(run, context);
382
+ // a run that resumes with the next server finds its Jobs and services where they are
383
+ if (!(0, runs_1.isDetached)(context)) {
384
+ await placement.release(run, context);
385
+ }
378
386
  }
379
387
  else if (run.up && !context.keep?.()) {
380
388
  // the services are gone with the process, their volumes stay only while the run sleeps
@@ -445,7 +453,10 @@ class HostExecutor {
445
453
  // engine stops its tasks and removes its containers; a signal on Windows would end the
446
454
  // process at once and leave its tasks running in the directory of the run. The process is
447
455
  // killed if it has not stopped after the grace period.
448
- runInProcess(command, input, cwd, env, context, signal) {
456
+ // A run that the server leaves to the next one (RunContext.detached) and whose tasks are on
457
+ // a cluster: the process is killed at once, so its Jobs and services stay. One whose tasks
458
+ // are on this machine stops them as a cancel does, in less time.
459
+ runInProcess(command, input, cwd, env, context, signal, onCluster) {
449
460
  return new Promise((resolvePromise, reject) => {
450
461
  const child = (0, child_process_1.spawn)(command[0], command.slice(1), {
451
462
  cwd,
@@ -460,12 +471,18 @@ class HostExecutor {
460
471
  let stderr = '';
461
472
  let killTimer;
462
473
  const stop = () => {
474
+ const detaching = (0, runs_1.isDetached)(context);
475
+ if (detaching && onCluster) {
476
+ child.kill('SIGKILL');
477
+ return;
478
+ }
463
479
  child.stdin.write('cancel\n', (e) => {
464
480
  if (e) {
465
481
  child.kill();
466
482
  }
467
483
  });
468
- killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopGraceMs ?? STOP_GRACE_MS);
484
+ const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
485
+ killTimer = setTimeout(() => child.kill('SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
469
486
  killTimer.unref();
470
487
  };
471
488
  if (signal.aborted) {
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readJson = exports.MAX_BODY_BYTES = exports.HttpError = exports.send = void 0;
3
+ exports.readJson = exports.MAX_BODY_BYTES = exports.HttpError = exports.send = exports.RETRY_HEADER = void 0;
4
+ // Set to `safe` on an answer to a request the server took nothing of, such as a submit while it
5
+ // shuts down: a client may send it again, also a request it never sends twice otherwise.
6
+ exports.RETRY_HEADER = 'hammerkit-retry';
4
7
  function send(res, status, body, headers = {}) {
5
8
  res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers });
6
9
  res.end(JSON.stringify(body));