hammerkit 2.1.0-next.12 → 2.1.0-next.13

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,14 +404,21 @@ 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;
@@ -395,9 +427,23 @@ async function followRun(connection, submitted, options = {}) {
395
427
  lines.push(line);
396
428
  options.onLine?.(line);
397
429
  };
430
+ // a server that is away is waited for until the signal stops the follow, which goes on then
431
+ // as a stopped one
432
+ const stoppable = (read) => read.catch((e) => {
433
+ if (signal?.aborted) {
434
+ return undefined;
435
+ }
436
+ throw e;
437
+ });
398
438
  const readLog = async () => {
399
439
  for (;;) {
400
- const page = await json(await call(connection, 'GET', `${path}/logs`, { query: { task: options.task, from, limit: 1000 } }));
440
+ const page = await stoppable(call(connection, 'GET', `${path}/logs`, {
441
+ query: { task: options.task, from, limit: 1000 },
442
+ signal,
443
+ }).then(json));
444
+ if (!page) {
445
+ return;
446
+ }
401
447
  truncated = page.truncated;
402
448
  for (const line of page.lines) {
403
449
  add(line);
@@ -412,10 +458,10 @@ async function followRun(connection, submitted, options = {}) {
412
458
  let run = submitted;
413
459
  let waitingSaid = false;
414
460
  for (;;) {
415
- if (options.signal?.aborted && options.detach) {
461
+ if (signal?.aborted && options.detach) {
416
462
  break;
417
463
  }
418
- if (options.signal?.aborted) {
464
+ if (signal?.aborted) {
419
465
  // the process may exit after this, so the cancel has to reach the server first
420
466
  cancel();
421
467
  let timer;
@@ -431,7 +477,8 @@ async function followRun(connection, submitted, options = {}) {
431
477
  if (exports.FINAL_RUN_STATES.includes(run.state) || (options.untilUp && isThere(run, submitted))) {
432
478
  break;
433
479
  }
434
- run = await json(await call(connection, 'GET', path, { query: { wait: POLL_WAIT } }));
480
+ run =
481
+ (await stoppable(call(connection, 'GET', path, { query: { wait: POLL_WAIT }, signal }).then(json))) ?? run;
435
482
  }
436
483
  if (truncated) {
437
484
  truncatedEnd(run, options.task).forEach(add);
@@ -439,7 +486,7 @@ async function followRun(connection, submitted, options = {}) {
439
486
  return { run, lines, truncated };
440
487
  }
441
488
  finally {
442
- options.signal?.removeEventListener('abort', cancel);
489
+ signal?.removeEventListener('abort', cancel);
443
490
  }
444
491
  }
445
492
  exports.followRun = followRun;
@@ -599,12 +646,25 @@ async function call(connection, method, path, options = {}) {
599
646
  url.searchParams.set(key, String(value));
600
647
  }
601
648
  }
602
- const send = async () => {
649
+ const shown = (0, reconnect_1.showUrl)(connection.url);
650
+ // the stop of the command, unless the call names its own or none
651
+ const stop = options.signal === undefined ? connection.signal : options.signal ?? undefined;
652
+ const timing = connection.reconnect ?? reconnect_1.RECONNECT_TIMING;
653
+ const reconnecting = new reconnect_1.Reconnecting({
654
+ url: connection.url,
655
+ timing: options.reconnectMs !== undefined ? { ...timing, windowMs: options.reconnectMs } : timing,
656
+ say: connection.say,
657
+ signal: stop,
658
+ fail: (message) => new SandboxClientError(message),
659
+ });
660
+ const attempt = async () => {
603
661
  const token = await connection.token();
604
662
  if (!(0, token_source_1.isToken)(token)) {
605
663
  // a header refuses such a value and would quote it whole in its error
606
664
  throw new SandboxClientError('the token is not a single line of visible characters');
607
665
  }
666
+ // a try after one that failed takes no longer than what is left of the window
667
+ const timeout = AbortSignal.timeout(reconnecting.timeoutMs(options.timeoutMs ?? TIMEOUT_MS));
608
668
  return fetch(url, {
609
669
  method,
610
670
  headers: {
@@ -613,17 +673,22 @@ async function call(connection, method, path, options = {}) {
613
673
  ...(options.raw !== undefined ? { 'content-type': 'application/octet-stream' } : {}),
614
674
  },
615
675
  body: options.body !== undefined ? JSON.stringify(options.body) : options.raw,
616
- signal: AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS),
676
+ signal: stop ? AbortSignal.any([timeout, stop]) : timeout,
617
677
  // an answer from anywhere else is not the server's, and a PUT would send its file on
618
678
  redirect: 'error',
619
- }).catch((e) => {
620
- throw new SandboxClientError(`unable to reach ${connection.url}: ${redact(fetchFailure(e), token)}`);
621
- });
679
+ }).then((response) => ({ response }), (e) => ({
680
+ error: e,
681
+ message: stop?.aborted
682
+ ? `stopped while asking ${shown}`
683
+ : `unable to reach ${shown}: ${redact(fetchFailure(e), token)}`,
684
+ }));
622
685
  };
623
- let response = await send();
624
- if (response.status === 401 && connection.renew) {
686
+ const repeat = options.repeat ?? (method === 'GET' || method === 'PUT' ? 'always' : 'unsent');
687
+ let response = await reconnecting.send(attempt, repeat);
688
+ // a new token is asked for within the window the call has left, not after it ran out
689
+ if (response.status === 401 && connection.renew && !reconnecting.exhausted) {
625
690
  await connection.renew();
626
- response = await send();
691
+ response = await reconnecting.send(attempt, repeat);
627
692
  }
628
693
  if (response.ok || (options.missing && response.status === 404)) {
629
694
  return response;
@@ -637,8 +702,8 @@ async function call(connection, method, path, options = {}) {
637
702
  // no JSON
638
703
  }
639
704
  if (response.status === 401) {
640
- throw new SandboxClientError(`${connection.url} did not accept the token`, 401);
705
+ throw new SandboxClientError(`${shown} did not accept the token`, 401);
641
706
  }
642
- throw new SandboxClientError(said || `${connection.url} answered ${response.status}`, response.status);
707
+ throw new SandboxClientError(said || `${shown} answered ${response.status}`, response.status);
643
708
  }
644
709
  //# 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
  }
@@ -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));
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.RunError = exports.RUN_PHASES = exports.isFinal = void 0;
3
+ exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.ShuttingDownError = exports.RunError = exports.RUN_PHASES = exports.isFinal = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const oauth_1 = require("./oauth");
6
6
  const run_logs_1 = require("./run-logs");
@@ -38,6 +38,14 @@ class RunError extends Error {
38
38
  }
39
39
  }
40
40
  exports.RunError = RunError;
41
+ // The server shuts down and took nothing of the request: a client may send it again, to the
42
+ // server that comes up after it
43
+ class ShuttingDownError extends RunError {
44
+ constructor() {
45
+ super('the server is shutting down');
46
+ }
47
+ }
48
+ exports.ShuttingDownError = ShuttingDownError;
41
49
  // A caller is over one of their limits, others may still submit
42
50
  class QuotaError extends RunError {
43
51
  constructor() {
@@ -217,7 +225,7 @@ class RunRegistry {
217
225
  // are queued at once.
218
226
  submit(owner, spec, approvalAccounts = []) {
219
227
  if (this.closed) {
220
- throw new RunError('the server is shutting down');
228
+ throw new ShuttingDownError();
221
229
  }
222
230
  const waiting = approvalAccounts.length > 0;
223
231
  if (waiting && this.waiting().length >= this.maxWaiting) {
@@ -722,7 +722,8 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
722
722
  }
723
723
  catch (e) {
724
724
  if (e instanceof runs_1.RunError) {
725
- (0, http_2.send)(res, e.status, { error: e.message });
725
+ // a proxy answers 503 too, also after the server took the request: this one is safe to send again
726
+ (0, http_2.send)(res, e.status, { error: e.message }, e instanceof runs_1.ShuttingDownError ? { [http_2.RETRY_HEADER]: 'safe' } : {});
726
727
  return;
727
728
  }
728
729
  if (e instanceof sandboxes_1.SandboxError) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.1.0-next.12",
4
+ "version": "2.1.0-next.13",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",