hammerkit 2.2.0-next.7 → 2.2.0-next.8

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.
@@ -10,6 +10,7 @@ const log_1 = require("../log");
10
10
  const sleep_1 = require("../utils/sleep");
11
11
  const version_1 = require("../version");
12
12
  const apply_1 = require("./apply");
13
+ const cluster_state_1 = require("./cluster-state");
13
14
  const container_resources_1 = require("./container-resources");
14
15
  const job_placement_1 = require("./job-placement");
15
16
  const network_policy_1 = require("./network-policy");
@@ -902,11 +903,10 @@ root, cwd, command, scripts, where, task, abort) {
902
903
  return await stopped();
903
904
  }
904
905
  const now = parseCommandState(status.out);
905
- if (!now) {
906
- throw new Error(`the command in the runner of the sandbox ended without an exit code: ${status.message ?? followed.message ?? 'the connection closed'}`);
907
- }
908
- if (now.type === 'none') {
909
- throw new Error('the command in the runner of the sandbox ended without an exit code: its runner went');
906
+ if (!now || now.type === 'none') {
907
+ // what the status said: the exec's error, or that the runner went
908
+ const said = now ? 'its runner went' : status.message ?? followed.message ?? 'the connection closed';
909
+ throw new Error(`the command in the runner of the sandbox ended without an exit code: ${said}; ${await describeRunner(instance, namespace, pod)}`);
910
910
  }
911
911
  if (followed.exitCode === 0) {
912
912
  if (now.type === 'cancelled') {
@@ -936,6 +936,37 @@ root, cwd, command, scripts, where, task, abort) {
936
936
  abort.removeEventListener('abort', aborted);
937
937
  }
938
938
  }
939
+ // What the cluster says of the runner's pod and container, for a command whose exit code can not
940
+ // be had: the pod is gone, or its container ended (how, as describeLastExit says) or waits
941
+ async function describeRunner(instance, namespace, pod) {
942
+ let runner;
943
+ try {
944
+ runner = await instance.coreApi.readNamespacedPod({ name: pod, namespace });
945
+ }
946
+ catch (e) {
947
+ if ((0, apply_1.statusCodeOf)(e) === 404) {
948
+ return 'its pod is gone';
949
+ }
950
+ // the detail of an API error can name the service account of the server: it goes to the
951
+ // server's own log, not to the run
952
+ process.stderr.write(`hammerkit: reading the runner ${pod} failed: ${(0, log_1.getErrorMessage)(e)}\n`);
953
+ return 'its pod could not be read';
954
+ }
955
+ if (runner.metadata?.deletionTimestamp) {
956
+ return 'its pod is being deleted';
957
+ }
958
+ const container = runner.status?.containerStatuses?.find((status) => status.name === RUNNER_CONTAINER);
959
+ if (!container) {
960
+ return `its pod is ${runner.status?.phase ?? 'unknown'} and has no status of its runner container`;
961
+ }
962
+ if (container.state?.waiting) {
963
+ return `the runner's container waits: ${container.state.waiting.reason ?? 'for no reason it names'}`;
964
+ }
965
+ if (container.state?.terminated || container.lastState?.terminated) {
966
+ return `the runner's container ended: ${(0, cluster_state_1.describeLastExit)(container, runner)}`;
967
+ }
968
+ return `the runner's container is ${container.state?.running ? 'running' : 'not running'}, its pod is ${runner.status?.phase ?? 'unknown'}`;
969
+ }
939
970
  // Runs `fn` again while it answers no exit code (its connection broke), RECONNECTS times at most
940
971
  async function reconnecting(abort, fn) {
941
972
  let result = await fn();
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AnswerReader = exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
3
+ exports.AnswerReader = exports.ConnectionClosedError = exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const promises_1 = require("fs/promises");
6
6
  const path_1 = require("path");
@@ -514,7 +514,11 @@ class KubernetesSandboxStorage {
514
514
  await (0, git_checkout_1.git)([`--git-dir=${repository}`, 'fetch', '--quiet', '--depth', '1', '--', fetch.url, fetch.ref], fetch.env, fetch.signal, what);
515
515
  await (0, git_checkout_1.git)([`--git-dir=${repository}`, 'update-ref', `refs/heads/${sandbox_pod_1.INCOMING_REF}`, 'FETCH_HEAD'], fetch.env, fetch.signal, what, op);
516
516
  const incoming = `${CLAIM_PATH}/${sandbox_pod_1.INCOMING}`;
517
- await this.withPod(key, (pod) => this.exec(pod, ['sh', '-c', 'rm -rf "$1" && mkdir -p "$1" && tar xf - -C "$1"', 'sh', incoming], stream_1.Readable.from((0, tar_2.packArchive)({ cwd: repository, portable: true }, ['.'])), null, fetch.signal));
517
+ const upload = () => this.withPod(key, (pod) => this.exec(pod, ['sh', '-c', 'rm -rf "$1" && mkdir -p "$1" && tar xf - -C "$1"', 'sh', incoming], stream_1.Readable.from((0, tar_2.packArchive)({ cwd: repository, portable: true }, ['.'])), null, fetch.signal));
518
+ // a connection that closed in the middle of the upload is tried once more, with the whole
519
+ // archive: the pod unpacks it into a directory it empties first. Not once the fetch was
520
+ // cancelled: the cancel is the answer, not a retry.
521
+ await upload().catch((e) => e instanceof ConnectionClosedError && !fetch.signal.aborted ? upload() : Promise.reject(e));
518
522
  return (await this.request(key, { op, id: key.id }, fetch.signal)).result;
519
523
  }
520
524
  finally {
@@ -867,37 +871,59 @@ class KubernetesSandboxStorage {
867
871
  let status;
868
872
  // the stdin of the command waits on the connection, which is there once it started
869
873
  const connection = {};
870
- const socket = await this.instance.exec.exec(pod.namespace, pod.name, 'files', command, stdout ?? new stream_1.Writable({ write: (_chunk, _encoding, callback) => callback() }), errors, stdin && throttle(stdin, () => connection.socket), false, (received) => {
871
- status = received;
872
- });
873
- connection.socket = socket;
874
- if (stdout) {
875
- holdBack(socket, stdout);
876
- }
877
- await new Promise((resolve, reject) => {
878
- const abort = () => {
879
- socket.close();
880
- reject(new Error(`${command[0]} in the pod of the sandbox was cancelled`));
881
- };
882
- if (signal.aborted) {
883
- abort();
884
- return;
885
- }
886
- signal.addEventListener('abort', abort, { once: true });
887
- socket.on('error', (e) => {
888
- signal.removeEventListener('abort', abort);
889
- reject(e);
874
+ // whether all of stdin was handed to an open connection: the client drops what it is given
875
+ // once the connection closed, so a stdin that did not end while it was open is an upload
876
+ // cut short (ConnectionClosedError)
877
+ let stdinSent = stdin === null;
878
+ const settled = new AbortController();
879
+ const sent = stdin && throttle(stdin, () => connection.socket, settled.signal);
880
+ // a chunk that the connection did not take ends the stream with an error, read below
881
+ sent?.on('error', () => undefined);
882
+ sent?.on('end', () => (stdinSent = connection.socket?.readyState === WS_OPEN));
883
+ try {
884
+ const socket = await this.instance.exec.exec(pod.namespace, pod.name, 'files', command, stdout ?? new stream_1.Writable({ write: (_chunk, _encoding, callback) => callback() }), errors, sent ?? null, false, (received) => {
885
+ status = received;
890
886
  });
891
- socket.on('close', () => {
892
- signal.removeEventListener('abort', abort);
893
- if (status?.status === 'Success') {
894
- resolve();
887
+ connection.socket = socket;
888
+ if (stdout) {
889
+ holdBack(socket, stdout);
890
+ }
891
+ await new Promise((resolve, reject) => {
892
+ const abort = () => {
893
+ socket.close();
894
+ reject(new Error(`${command[0]} in the pod of the sandbox was cancelled`));
895
+ };
896
+ if (signal.aborted) {
897
+ abort();
895
898
  return;
896
899
  }
897
- const reason = stderr.trim().split('\n').pop() || status?.message || 'the connection to the pod closed';
898
- reject(new Error(`${command[0]} in the pod of the sandbox failed: ${reason}`));
900
+ signal.addEventListener('abort', abort, { once: true });
901
+ socket.on('error', (e) => {
902
+ signal.removeEventListener('abort', abort);
903
+ reject(stdinSent ? e : new ConnectionClosedError(e));
904
+ });
905
+ socket.on('close', () => {
906
+ signal.removeEventListener('abort', abort);
907
+ if (!stdinSent) {
908
+ reject(new ConnectionClosedError());
909
+ return;
910
+ }
911
+ if (status?.status === 'Success') {
912
+ resolve();
913
+ return;
914
+ }
915
+ const reason = stderr.trim().split('\n').pop() || status?.message || 'the connection to the pod closed';
916
+ reject(new Error(`${command[0]} in the pod of the sandbox failed: ${reason}`));
917
+ });
899
918
  });
900
- });
919
+ }
920
+ finally {
921
+ // what a failed attempt left of its archive and of the throttle that reads it: the throttle
922
+ // stops waiting, and its stream is destroyed
923
+ settled.abort();
924
+ sent?.destroy();
925
+ stdin?.destroy();
926
+ }
901
927
  }
902
928
  }
903
929
  exports.KubernetesSandboxStorage = KubernetesSandboxStorage;
@@ -932,13 +958,39 @@ function defined(env) {
932
958
  }
933
959
  return result;
934
960
  }
961
+ // The readyState values of a websocket (ws), which is only a type in this file
962
+ const WS_CONNECTING = 0;
963
+ const WS_OPEN = 1;
964
+ // A command's connection to the files pod closed before all of its stdin was sent: what the
965
+ // client sends after the close is dropped, so the command could only have read its input short
966
+ class ConnectionClosedError extends Error {
967
+ constructor(cause) {
968
+ super('the connection to the files pod closed during the upload', { cause });
969
+ this.name = 'ConnectionClosedError';
970
+ }
971
+ }
972
+ exports.ConnectionClosedError = ConnectionClosedError;
935
973
  // The client of the cluster sends what stdin has as fast as it comes: this waits while the
936
- // connection has more than MAX_STDIN_BUFFERED not sent yet.
937
- function throttle(stdin, connection) {
974
+ // connection has more than MAX_STDIN_BUFFERED not sent yet, and hands a chunk on only while the
975
+ // connection is open, else it fails with ConnectionClosedError (the client would drop it).
976
+ // `settled` ends the wait: once the exec is over, no connection comes for the chunk, and the
977
+ // stream returns instead of polling for one.
978
+ function throttle(stdin, connection, settled) {
938
979
  return stream_1.Readable.from((async function* () {
939
980
  for await (const chunk of stdin) {
940
- while ((connection()?.bufferedAmount ?? 0) > MAX_STDIN_BUFFERED) {
981
+ let socket = connection();
982
+ while (!settled.aborted && (socket === undefined || socket.readyState === WS_CONNECTING)) {
941
983
  await (0, sleep_1.sleep)(10);
984
+ socket = connection();
985
+ }
986
+ while (!settled.aborted && socket?.readyState === WS_OPEN && socket.bufferedAmount > MAX_STDIN_BUFFERED) {
987
+ await (0, sleep_1.sleep)(10);
988
+ }
989
+ if (settled.aborted) {
990
+ return;
991
+ }
992
+ if (socket?.readyState !== WS_OPEN) {
993
+ throw new ConnectionClosedError();
942
994
  }
943
995
  yield chunk;
944
996
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.MAX_PATH_LENGTH = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
3
+ exports.HostSandboxFiles = exports.ripgrepBinary = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.MAX_PATH_LENGTH = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const fs_1 = require("fs");
@@ -199,6 +199,13 @@ function fileType(stats) {
199
199
  */
200
200
  // the ignore files ripgrep reads in the folders above the path it searches
201
201
  const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
202
+ // The ripgrep a search runs: HAMMERKIT_RG_PATH, rg on the PATH when it is not set. It is the
203
+ // operator's setting, read from the server's own environment, never from a run's: a run's
204
+ // variables reach ripgrep as its environment (this.env), not here.
205
+ function ripgrepBinary(env) {
206
+ return env.HAMMERKIT_RG_PATH || 'rg';
207
+ }
208
+ exports.ripgrepBinary = ripgrepBinary;
202
209
  class HostSandboxFiles {
203
210
  constructor(root, git,
204
211
  // the environment of ripgrep: the variables runs see
@@ -719,7 +726,7 @@ class HostSandboxFiles {
719
726
  }
720
727
  }
721
728
  return new Promise((resolve, reject) => {
722
- const child = (0, child_process_1.spawn)('rg', args, {
729
+ const child = (0, child_process_1.spawn)(ripgrepBinary(process.env), args, {
723
730
  cwd: target.cwd,
724
731
  env,
725
732
  stdio: ['pipe', 'pipe', 'pipe'],
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.2.0-next.7",
4
+ "version": "2.2.0-next.8",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",
@@ -80,6 +80,7 @@
80
80
  "@typescript-eslint/eslint-plugin": "^6.16.0",
81
81
  "@typescript-eslint/parser": "^6.16.0",
82
82
  "@vitest/coverage-istanbul": "^2.1.8",
83
+ "@vscode/ripgrep": "1.18.0",
83
84
  "@yao-pkg/pkg": "^6.20.0",
84
85
  "eslint": "^8.56.0",
85
86
  "fast-check": "^4.10.2",