hammerkit 2.1.0-next.9 → 2.2.0-next.1

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 (70) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/executer/runner-commands.js +36 -0
  10. package/dist/file/get-file-context.js +4 -7
  11. package/dist/harness/connect.js +12 -8
  12. package/dist/harness/reconnect.js +141 -0
  13. package/dist/harness/sandbox-client.js +242 -33
  14. package/dist/harness/service-tools.js +36 -3
  15. package/dist/kubernetes/cluster-state.js +48 -14
  16. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  17. package/dist/kubernetes/follow-pod-logs.js +8 -5
  18. package/dist/kubernetes/kept-claims.js +26 -5
  19. package/dist/kubernetes/resources.js +5 -1
  20. package/dist/kubernetes/sandbox-runner.js +526 -156
  21. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  22. package/dist/kubernetes/sync-changes.js +463 -0
  23. package/dist/kubernetes/volumes.js +23 -1
  24. package/dist/optimizer/get-work-cache-stats.js +7 -0
  25. package/dist/planner/work-item-status.js +12 -2
  26. package/dist/planner/work-runtime-aggregate.js +1 -0
  27. package/dist/planner/work-runtime-docker.js +9 -5
  28. package/dist/planner/work-runtime-kubernetes.js +277 -55
  29. package/dist/planner/work-runtime-local.js +8 -4
  30. package/dist/remote/annotations.js +29 -3
  31. package/dist/remote/bundle.js +6 -8
  32. package/dist/remote/collect-bundle.js +3 -2
  33. package/dist/remote/device-login.js +4 -1
  34. package/dist/remote/remote-commands.js +16 -7
  35. package/dist/remote/remote-work-commands.js +265 -72
  36. package/dist/remote/server-client.js +38 -40
  37. package/dist/server/artifacts-api.js +56 -0
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/endpoints.js +52 -32
  40. package/dist/server/executor.js +117 -30
  41. package/dist/server/http.js +4 -1
  42. package/dist/server/keep-artifacts.js +230 -0
  43. package/dist/server/kubernetes-backend.js +186 -59
  44. package/dist/server/kubernetes-sandbox-storage.js +83 -22
  45. package/dist/server/overview.js +67 -9
  46. package/dist/server/paging.js +167 -0
  47. package/dist/server/plan.js +8 -1
  48. package/dist/server/public-paths.js +52 -0
  49. package/dist/server/run-access.js +24 -0
  50. package/dist/server/run-artifacts.js +171 -0
  51. package/dist/server/run-logs.js +25 -1
  52. package/dist/server/run-request.js +63 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-worker.js +267 -33
  55. package/dist/server/runs.js +527 -99
  56. package/dist/server/sandbox-files.js +9 -8
  57. package/dist/server/sandbox-follow.js +54 -0
  58. package/dist/server/sandbox-storage.js +38 -1
  59. package/dist/server/sandbox-sync.js +392 -0
  60. package/dist/server/sandboxes-api.js +54 -8
  61. package/dist/server/sandboxes.js +19 -0
  62. package/dist/server/server-config.js +14 -0
  63. package/dist/server/server.js +189 -46
  64. package/dist/server/service-runs.js +41 -8
  65. package/dist/server/task-order.js +56 -0
  66. package/dist/utils/project-path.js +20 -0
  67. package/dist/utils/tar-files.js +52 -0
  68. package/dist/utils/tar.js +37 -1
  69. package/package.json +1 -1
  70. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -1,11 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeSandboxRunners = exports.executeInRunner = exports.getExecExitCode = exports.buildRunnerPod = exports.getRunnerName = exports.getRunnerKey = exports.canUseRunner = exports.getWrapper = exports.RUNNER_CHANGED_EXIT = exports.getCleanUp = exports.getScratchDirectories = exports.getRunnerMounts = exports.RUNNER_SANDBOX_PATH = exports.IDLE_COMMAND = exports.RUNNER_TOOLS_IMAGE = exports.RUNNER_LABEL = void 0;
3
+ exports.removeSandboxRunners = exports.removeRunCommands = exports.executeInRunner = exports.getExecExitCode = exports.buildRunnerPod = exports.getRunnerName = exports.getRunnerKey = exports.canUseRunner = exports.getWrapper = exports.getRunnerScripts = exports.getRunCommandsDirectory = exports.getCommandDirectory = exports.RUNNER_COMMANDS_PATH = exports.RUNNER_CHANGED_EXIT = exports.getCleanUp = exports.getScratchDirectories = exports.getRunnerMounts = exports.RUNNER_SANDBOX_PATH = exports.IDLE_COMMAND = exports.RUNNER_TOOLS_IMAGE = exports.RUNNER_LABEL = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const path_1 = require("path");
6
- const string_decoder_1 = require("string_decoder");
7
6
  const stream_1 = require("stream");
8
- const promises_1 = require("stream/promises");
9
7
  const work_network_1 = require("../planner/work-network");
10
8
  const replace_env_variables_1 = require("../environment/replace-env-variables");
11
9
  const log_1 = require("../log");
@@ -18,6 +16,7 @@ const network_policy_1 = require("./network-policy");
18
16
  const resources_1 = require("./resources");
19
17
  const transfer_tools_1 = require("./transfer-tools");
20
18
  const volumes_1 = require("./volumes");
19
+ const runner_commands_1 = require("../executer/runner-commands");
21
20
  /**
22
21
  * The runner of a sandbox: one pod that the commands of a run on the sandbox are exec'd
23
22
  * into, one after the other, in place of a Job each. A Job's pod takes seconds to be
@@ -33,9 +32,15 @@ const volumes_1 = require("./volumes");
33
32
  * so a change starts a new one and the one before goes. Its first process only waits.
34
33
  * - Every command runs in a wrapper that first and last kills every other process of the
35
34
  * container and empties /tmp and /dev/shm (unless a mount of the task is in one): the
36
- * container is reused, what a command started is not. A command cancelled, out of time or whose connection broke is killed
37
- * the same way, or the pod is deleted. The first process and the wrapper run a static
38
- * busybox from a read-only mount, so a command can not replace what cleans up after it.
35
+ * container is reused, what a command started is not. A command cancelled or out of time
36
+ * is killed the same way, or the pod is deleted. The first process and the wrapper run a
37
+ * static busybox from a read-only mount, so a command can not replace what cleans up
38
+ * after it.
39
+ * - The wrapper runs detached from the exec that starts it, and writes the command's output
40
+ * and exit code to files of the sandbox (getCommandDirectory), which the process of the
41
+ * run follows: a connection that breaks, or a restart of the server, leaves the command
42
+ * running. A run that resumes takes it up again from where its log got (RunnerCommands),
43
+ * or reads how it ended, rather than running it again.
39
44
  * - Under a limited network it has a NetworkPolicy of its own and, under `allow`, the
40
45
  * sandbox's egress proxy, both keyed like the pod. They carry no run, and go with the
41
46
  * pod of the sandbox's files, which owns them and the runner: the runner stays while
@@ -82,43 +87,181 @@ function getScratchDirectories(mounts) {
82
87
  exports.getScratchDirectories = getScratchDirectories;
83
88
  // Kills every process of the container but the first and the shell itself (`kill` is the
84
89
  // shell's own), again while one forked meanwhile, then empties the scratch directories
85
- function getCleanUp(directories) {
90
+ function getCleanUp(directories, busybox = BUSYBOX) {
86
91
  const patterns = directories.flatMap((directory) => [`${directory}/*`, `${directory}/.[!.]*`, `${directory}/..?*`]);
87
92
  return [
88
93
  'i=0',
89
94
  'while kill -KILL -1 2>/dev/null && [ $i -lt 10 ]; do i=$((i+1)); done',
90
- ...(patterns.length > 0 ? [`${BUSYBOX} rm -rf ${patterns.join(' ')} 2>/dev/null`] : []),
95
+ ...(patterns.length > 0 ? [`${busybox} rm -rf ${patterns.join(' ')} 2>/dev/null`] : []),
91
96
  ].join('\n');
92
97
  }
93
98
  exports.getCleanUp = getCleanUp;
94
- // What the wrapper says on stderr, with RUNNER_CHANGED_EXIT, when a command before changed
95
- // the runner: the command did not run, the runner goes and the task fails
99
+ // The exit code of a command that did not run as a command before changed the runner: the
100
+ // wrapper marks it so in the command's directory (`changed`), the runner goes and the task fails
96
101
  exports.RUNNER_CHANGED_EXIT = 125;
97
- const RUNNER_CHANGED_MARK = `hammerkit-runner-changed-${(0, crypto_1.randomBytes)(8).toString('hex')}`;
98
- // Runs `"$@"` in the directory `$3`, alone in the container: what an earlier command left
99
- // is cleaned up before, what this one left after. The directory of the run `$2` is a link
100
- // to the sandbox's files first. Before the command runs, each of `mountPaths` must still be
101
- // the mount it was made as (the kernel's mountinfo, which no command writes): a command
102
- // before could have moved a folder a mount is in and put files of its own in its place.
103
- // When not, it says `$1` and exits RUNNER_CHANGED_EXIT. Else its exit code is the command's.
104
- function getWrapper(cleanUp, mountPaths) {
105
- const sandbox = shellQuote(exports.RUNNER_SANDBOX_PATH);
102
+ // Where the commands of runs keep their output and exit code: in the sandbox's files, which
103
+ // only its owner's runs and requests reach (RUNNER_COMMANDS_DIRECTORY). A directory per run,
104
+ // and in it one per command, both named by a hash (COMMAND_ID_PATTERN).
105
+ exports.RUNNER_COMMANDS_PATH = `${exports.RUNNER_SANDBOX_PATH}/${runner_commands_1.RUNNER_COMMANDS_DIRECTORY}`;
106
+ const hash = (value) => (0, crypto_1.createHash)('sha256').update(value).digest('hex').slice(0, 24);
107
+ // The directory of a command of a run: the same for the same command of the run in every
108
+ // process of it, so one that resumes after a restart finds what the one before started.
109
+ // `execution`: how often the task ran in the run before, in the runner.
110
+ function getCommandDirectory(run, task, step, execution) {
111
+ return path_1.posix.join(getRunCommandsDirectory(run), hash(JSON.stringify([run, task, step, execution])));
112
+ }
113
+ exports.getCommandDirectory = getCommandDirectory;
114
+ function getRunCommandsDirectory(run) {
115
+ return path_1.posix.join(exports.RUNNER_COMMANDS_PATH, hash(run));
116
+ }
117
+ exports.getRunCommandsDirectory = getRunCommandsDirectory;
118
+ const RUNNER_TOOLS = { busybox: BUSYBOX, sandbox: exports.RUNNER_SANDBOX_PATH };
119
+ // How long a command waits for one of its run that still runs before it starts (s)
120
+ const RUN_COMMAND_WAIT = 3600;
121
+ /**
122
+ * The scripts that start a command in the runner and follow, stop, find and remove the
123
+ * commands of a run, each run as `sh -c <script> hammerkit <args>`. `cleanUp` is what kills
124
+ * what a command left (getCleanUp), `mountPaths` the mounts the wrapper checks.
125
+ */
126
+ function getRunnerScripts(cleanUp, mountPaths, tools = RUNNER_TOOLS) {
127
+ const b = tools.busybox;
128
+ // How a script finds a command in the directory `$1`: `cancelled`, `finished <code>` (and
129
+ // ` changed` when a command before changed the runner), or `running` while its wrapper runs
130
+ // in this pod, which the wrapper's arguments name; else (not started, or its pod went with
131
+ // it) it fails. The pid is not taken alone: one of another process, a zombie, or one a
132
+ // command wrote there does not count.
133
+ const state = [
134
+ `host=$(${b} hostname)`,
135
+ [
136
+ 'alive() {',
137
+ '[ -e "$1/pid" ] && read -r h p < "$1/pid" && [ "$h" = "$host" ] || return 1',
138
+ `case "$p" in ''|*[!0-9]*) return 1 ;; esac`,
139
+ `[ -r "/proc/$p/cmdline" ] && ${b} tr '\\0' '\\n' < "/proc/$p/cmdline" | ${b} grep -qxF -- "$1"`,
140
+ '}',
141
+ ].join('\n'),
142
+ [
143
+ 'state() {',
144
+ 'if [ -e "$1/cancelled" ]; then echo cancelled',
145
+ `elif [ -e "$1/exit" ]; then echo "finished $(${b} cat "$1/exit")$([ -e "$1/changed" ] && echo ' changed')"`,
146
+ 'elif alive "$1"; then echo running',
147
+ 'else return 1; fi',
148
+ '}',
149
+ ].join('\n'),
150
+ // the process group of the command of the directory `$1`, when it runs in this pod
151
+ 'group() { alive "$1" && read -r h p < "$1/pid" && kill -KILL -"$p" 2>/dev/null; }',
152
+ ].join('\n');
153
+ const id = '[0-9a-f]'.repeat(24);
154
+ const wrapper = getWrapper(cleanUp, mountPaths, tools);
155
+ return {
156
+ // Starts the wrapper for the command directory `$1` and says `started`. `$2` `fresh`: a
157
+ // command the run has not started, whatever its directory holds goes first. `adopt`: one
158
+ // the run started, which is not started again: it says what it is (`state`). With a nonce
159
+ // `$3`, only the start that wrote that nonce is taken (a start again after its connection
160
+ // broke). A command of the same run that still runs (a task before it that runs again as
161
+ // the run resumed) ends first, for an hour at most; what anything else left is killed, and
162
+ // the files of other runs go. The wrapper is a session of its own, its output goes to
163
+ // files: the exec ends at once. One start of a command at a time, a cancel wins over it.
164
+ start: [
165
+ state,
166
+ 'd=$1; mode=$2; nonce=$3; shift 3',
167
+ `run=$(${b} dirname "$d")`,
168
+ `${b} mkdir -p "$run" && exec 9> "$d.lock" && ${b} flock 9 || exit 126`,
169
+ '[ -e "$d/cancelled" ] && { echo cancelled; exit 0; }',
170
+ `[ "$mode" = adopt ] && { [ -z "$nonce" ] || [ "$(${b} cat "$d/nonce" 2>/dev/null)" = "$nonce" ]; } && state "$d" && exit 0`,
171
+ 'w=0',
172
+ `for o in "$run"/*; do [ "$o" != "$d" ] && [ -d "$o" ] || continue; while [ $w -lt ${RUN_COMMAND_WAIT} ] && [ ! -e "$o/exit" ] && alive "$o"; do ${b} sleep 1; w=$((w+1)); done; done`,
173
+ cleanUp,
174
+ `for o in "$(${b} dirname "$run")"/*; do case "\${o##*/}" in ${id}) [ "$o" = "$run" ] || ${b} rm -rf "$o" ;; esac; done`,
175
+ `${b} rm -rf "$d" && ${b} mkdir -p "$d" && echo "$nonce" > "$d/nonce" || exit 126`,
176
+ `${b} setsid ${b} sh -c ${shellQuote(wrapper)} hammerkit "$d" "$@" </dev/null >/dev/null 2>&1 9>&- &`,
177
+ 'echo "$host $!" > "$d/pid"',
178
+ 'echo started',
179
+ ].join('\n'),
180
+ // Says how the command of the directory `$1` is (`state`), `none` when it is not
181
+ status: [state, 'state "$1" || echo none'].join('\n'),
182
+ // Prints the output of the command of the directory `$1` from the byte `$2` of its stdout
183
+ // and `$3` of its stderr on, as it comes, and exits 0 once it printed all of it. 3: the
184
+ // command ended without an exit code, its pod went with it.
185
+ follow: [
186
+ state,
187
+ 'd=$1; o=$2; e=$3',
188
+ `size() { ${b} stat -c %s "$1" 2>/dev/null || echo 0; }`,
189
+ 'while :; do',
190
+ ' [ -e "$d/exit" ] || [ -e "$d/cancelled" ] && end=1 || end=0',
191
+ ` n=$(size "$d/out"); [ "$n" -gt "$o" ] && ${b} tail -c +$((o+1)) "$d/out" | ${b} head -c $((n-o)) && o=$n`,
192
+ ` n=$(size "$d/err"); [ "$n" -gt "$e" ] && ${b} tail -c +$((e+1)) "$d/err" | ${b} head -c $((n-e)) >&2 && e=$n`,
193
+ ' [ $end = 1 ] && exit 0',
194
+ ' alive "$d" || [ -e "$d/exit" ] || [ -e "$d/cancelled" ] || exit 3',
195
+ ` ${b} sleep 0.2`,
196
+ 'done',
197
+ ].join('\n'),
198
+ // Stops the command of the directory `$1` for good: it is marked cancelled first, so it is
199
+ // not taken for one whose pod went and a start that comes after does not start it, then its
200
+ // process group and everything else is killed (a start under way too)
201
+ cancel: [state, `${b} mkdir -p "$1" && : > "$1/cancelled"`, 'group "$1"', cleanUp, 'exit 0'].join('\n'),
202
+ // Says `yes` when a command of the run's directory `$1` runs in this pod
203
+ find: [
204
+ state,
205
+ 'for o in "$1"/*; do [ -d "$o" ] && [ ! -e "$o/exit" ] && [ ! -e "$o/cancelled" ] && alive "$o" && { echo yes; exit 0; }; done',
206
+ 'echo no',
207
+ ].join('\n'),
208
+ // Kills the commands of the run's directory `$1` that run in this pod and removes it; with
209
+ // `$2` `clean`, what they left is cleaned up too (the run holds the sandbox still)
210
+ remove: [
211
+ state,
212
+ 'for o in "$1"/*; do [ -d "$o" ] && group "$o"; done',
213
+ 'if [ "$2" = clean ]; then',
214
+ cleanUp,
215
+ 'fi',
216
+ `${b} rm -rf "$1"`,
217
+ ].join('\n'),
218
+ };
219
+ }
220
+ exports.getRunnerScripts = getRunnerScripts;
221
+ // Runs `"$@"` in the directory `$3` with its output in the command directory `$1`, as
222
+ // `out` and `err` of at most MAX_OUTPUT_BYTES each, and its exit code in `exit` once
223
+ // all of it is there. The directory of the run `$2` is a link to the sandbox's files
224
+ // first. Before the command runs, each of `mountPaths` must still be the mount it was made
225
+ // as (the kernel's mountinfo, which no command writes): a command before could have moved
226
+ // a folder a mount is in and put files of its own in its place. When not, it marks the
227
+ // directory `changed` and ends with RUNNER_CHANGED_EXIT. Else its exit code is the command's.
228
+ // What the command left is cleaned up after it (the start cleans up before).
229
+ function getWrapper(cleanUp, mountPaths, tools = RUNNER_TOOLS) {
230
+ const b = tools.busybox;
231
+ const sandbox = shellQuote(tools.sandbox);
106
232
  return [
107
- cleanUp,
108
- `changed() { echo "$1" >&2; exit ${exports.RUNNER_CHANGED_EXIT}; }`,
109
- `${BUSYBOX} mkdir -p "$(${BUSYBOX} dirname "$2")" && ${BUSYBOX} ln -sfn ${sandbox} "$2" || changed "$1"`,
233
+ 'd=$1; shift',
234
+ // the output is all in the files before the exit code is; what the command left and
235
+ // still writes there is not waited for long
236
+ [
237
+ 'end() {',
238
+ 'exec >/dev/null 2>&1',
239
+ `j=0; while { kill -0 "$co" || kill -0 "$ce"; } 2>/dev/null && [ $j -lt 20 ]; do ${b} sleep 0.05; j=$((j+1)); done`,
240
+ cleanUp,
241
+ `echo "$1" > "$d/exit.tmp" && ${b} mv -f "$d/exit.tmp" "$d/exit"`,
242
+ 'exit "$1"',
243
+ '}',
244
+ ].join('\n'),
245
+ // past the limit the output is read and dropped, the command goes on
246
+ `cap() { ${b} head -c ${MAX_OUTPUT_BYTES} > "$1"; ${b} cat > /dev/null; }`,
247
+ 'f=/tmp/.hammerkit-output-$$',
248
+ `${b} mkfifo "$f-out" "$f-err" || end 126`,
249
+ 'cap "$d/out" < "$f-out" & co=$!',
250
+ 'cap "$d/err" < "$f-err" & ce=$!',
251
+ 'exec > "$f-out" 2> "$f-err"',
252
+ `${b} rm -f "$f-out" "$f-err"`,
253
+ `changed() { : > "$d/changed"; end ${exports.RUNNER_CHANGED_EXIT}; }`,
254
+ `${b} mkdir -p "$(${b} dirname "$1")" && ${b} ln -sfn ${sandbox} "$1" || changed`,
110
255
  ...mountPaths.map((path) => {
111
256
  const quoted = shellQuote(path);
112
257
  const field = shellQuote(`^[^ ]* [^ ]* [^ ]* [^ ]* ${toMountInfoPattern(path)} `);
113
- return `[ "$(${BUSYBOX} realpath ${quoted})" = ${quoted} ] && ${BUSYBOX} grep -q ${field} /proc/self/mountinfo || changed "$1"`;
258
+ return `[ "$(${b} realpath ${quoted})" = ${quoted} ] && ${b} grep -q ${field} /proc/self/mountinfo || changed`;
114
259
  }),
115
- 'cd "$3" || exit 126',
116
- `case "$(pwd -P)" in ${sandbox}|${sandbox}/*) ;; *) changed "$1" ;; esac`,
117
- 'shift 3',
260
+ 'cd "$2" || end 126',
261
+ `case "$(pwd -P)" in ${sandbox}|${sandbox}/*) ;; *) changed ;; esac`,
262
+ 'shift 2',
118
263
  '"$@"',
119
- 'code=$?',
120
- cleanUp,
121
- 'exit $code',
264
+ 'end $?',
122
265
  ].join('\n');
123
266
  }
124
267
  exports.getWrapper = getWrapper;
@@ -131,9 +274,6 @@ function toMountInfoPattern(path) {
131
274
  const escaped = path.replace(/[\\ \t\n]/g, (c) => `\\${c.charCodeAt(0).toString(8).padStart(3, '0')}`);
132
275
  return escaped.replace(/[.[\]*^$\\]/g, (c) => `\\${c}`);
133
276
  }
134
- // the sandboxes whose runner a task of this process uses: one command at a time each, the
135
- // other tasks of the run run as Jobs meanwhile
136
- const inUse = new Set();
137
277
  // per sandbox, the runners whose container ended as it started (an image without `sh`, or
138
278
  // one that can not be pulled): their tasks run as Jobs while that pod of the files stays
139
279
  const failed = new Map();
@@ -259,14 +399,18 @@ function getExecExitCode(status) {
259
399
  return code !== undefined && /^\d+$/.test(code) ? Number(code) : undefined;
260
400
  }
261
401
  exports.getExecExitCode = getExecExitCode;
402
+ // what a process that is not the one of a run on a server knows of its commands: nothing
403
+ const processCommands = (0, runner_commands_1.createRunnerCommands)();
262
404
  /**
263
405
  * Runs the task's commands in the sandbox's runner, started when there is none (or one of
264
406
  * something else). `unavailable` when the task can not use it now (the runner is in use by
265
407
  * another task of the run, the pod of the sandbox's files went, or the runner did not
266
- * start): the task then runs as Jobs.
408
+ * start): the task then runs as Jobs. In a run that resumed, a command that runs on is
409
+ * followed where it runs, one that ended is not run again (RunnerCommands).
267
410
  */
268
- async function executeInRunner(instance, task, kubernetes, persistence, abort) {
411
+ async function executeInRunner(instance, task, kubernetes, persistence, abort, commands = processCommands) {
269
412
  const workspace = kubernetes.server.workspace;
413
+ const inUse = commands.inUse;
270
414
  if (inUse.has(workspace.label)) {
271
415
  return { type: 'unavailable' };
272
416
  }
@@ -276,6 +420,18 @@ async function executeInRunner(instance, task, kubernetes, persistence, abort) {
276
420
  if (!filesPod) {
277
421
  return { type: 'unavailable' };
278
422
  }
423
+ const run = kubernetes.server.run;
424
+ const execute = (name) => executeCommands(instance, task, kubernetes, persistence, abort, commands, name);
425
+ if (commands.resumed) {
426
+ // a command of the run that still runs keeps its runner, of an older server say, until
427
+ // it ended: a runner of the task's key would replace it, and a command of it run first
428
+ // kill it
429
+ const holding = await findRunnerOfRun(instance, kubernetes.namespace, workspace.label, filesPod.uid, run, abort);
430
+ if (holding) {
431
+ task.status.write('debug', `a command of the run runs on in the runner ${holding} of the sandbox`);
432
+ return await execute(holding);
433
+ }
434
+ }
279
435
  const key = getRunnerKey(task, kubernetes, persistence);
280
436
  const name = getRunnerName(key);
281
437
  const failedOf = failed.get(workspace.label);
@@ -325,26 +481,7 @@ async function executeInRunner(instance, task, kubernetes, persistence, abort) {
325
481
  else {
326
482
  task.status.write('debug', `runs in the runner ${name} of the sandbox`);
327
483
  }
328
- const mounts = getRunnerMounts(workspace, persistence);
329
- const cleanUp = getCleanUp(getScratchDirectories(mounts));
330
- const wrapper = getWrapper(cleanUp, mounts.map((mount) => mount.mountPath));
331
- for (const cmd of task.data.cmds) {
332
- task.status.write('debug', `execute ${cmd.cmd} in the runner of the sandbox`);
333
- const exitCode = await execInRunner(instance, kubernetes.namespace, name, workspace.root, cmd.cwd, [task.data.shell, '-c', cmd.cmd], { wrapper, cleanUp }, task, abort);
334
- if (abort.aborted) {
335
- return { type: 'canceled' };
336
- }
337
- if (exitCode === 'changed') {
338
- // a fresh pod for the next task; this one fails rather than running again as a Job,
339
- // since a command can say so itself after it ran
340
- await removeSandboxRunners(instance, kubernetes.namespace, workspace.label, (pod) => pod.metadata?.name !== name);
341
- throw new Error('a command changed the runner of the sandbox, it was removed: run the task again');
342
- }
343
- if (exitCode !== 0) {
344
- return { type: 'crash', exitCode };
345
- }
346
- }
347
- return { type: 'done' };
484
+ return await execute(name);
348
485
  }
349
486
  finally {
350
487
  network.close();
@@ -355,6 +492,96 @@ async function executeInRunner(instance, task, kubernetes, persistence, abort) {
355
492
  }
356
493
  }
357
494
  exports.executeInRunner = executeInRunner;
495
+ // Runs the task's commands one after the other in the runner `name`, until one fails
496
+ async function executeCommands(instance, task, kubernetes, persistence, abort, commands, name) {
497
+ const workspace = kubernetes.server.workspace;
498
+ const mounts = getRunnerMounts(workspace, persistence);
499
+ const scripts = getRunnerScripts(getCleanUp(getScratchDirectories(mounts)), mounts.map((mount) => mount.mountPath));
500
+ const execution = commands.executions.get(task.name) ?? 0;
501
+ commands.executions.set(task.name, execution + 1);
502
+ for (const [step, cmd] of task.data.cmds.entries()) {
503
+ task.status.write('debug', `execute ${cmd.cmd} in the runner of the sandbox`);
504
+ const exitCode = await execInRunner(instance, kubernetes.namespace, name, workspace.root, cmd.cwd, [task.data.shell, '-c', cmd.cmd], scripts, {
505
+ directory: getCommandDirectory(kubernetes.server.run, task.name, step, execution),
506
+ record: { task: task.name, step, execution },
507
+ commands,
508
+ }, task, abort);
509
+ if (abort.aborted) {
510
+ return { type: 'canceled' };
511
+ }
512
+ if (exitCode === 'changed') {
513
+ // a fresh pod for the next task; this one fails rather than running again as a Job,
514
+ // since a command can say so itself after it ran
515
+ await removeSandboxRunners(instance, kubernetes.namespace, workspace.label, (pod) => pod.metadata?.name !== name);
516
+ throw new Error('a command changed the runner of the sandbox, it was removed: run the task again');
517
+ }
518
+ if (exitCode !== 0) {
519
+ return { type: 'crash', exitCode };
520
+ }
521
+ }
522
+ return { type: 'done' };
523
+ }
524
+ // The runners of a sandbox, those that run of the pod of its files `owner` when it is named
525
+ async function listRunnerPods(instance, namespace, sandbox, owner) {
526
+ const pods = await instance.coreApi.listNamespacedPod({
527
+ namespace,
528
+ labelSelector: `${volumes_1.SANDBOX_LABEL}=${sandbox},${exports.RUNNER_LABEL}`,
529
+ });
530
+ return owner === undefined
531
+ ? pods.items
532
+ : pods.items.filter((pod) => !!pod.metadata?.name &&
533
+ !pod.metadata.deletionTimestamp &&
534
+ isRunning(pod) &&
535
+ (pod.metadata.ownerReferences ?? []).some((reference) => reference.uid === owner));
536
+ }
537
+ // The runner of the sandbox, of the pod of its files, in which a command of the run runs. One
538
+ // that can not be asked fails the task: a new runner would replace the pod the command runs in.
539
+ // A runner that does not run (it ended, or is going) holds no command that runs.
540
+ async function findRunnerOfRun(instance, namespace, sandbox, owner, run, abort) {
541
+ const scripts = getRunnerScripts('', []);
542
+ for (const pod of await listRunnerPods(instance, namespace, sandbox, owner)) {
543
+ const name = pod.metadata.name;
544
+ const found = await reconnecting(abort, () => runScript(instance, namespace, name, scripts.find, [getRunCommandsDirectory(run)], { timeout: KILL_TIMEOUT_MS }));
545
+ if (found.exitCode === undefined) {
546
+ throw new Error(`the runner ${name} of the sandbox could not be asked for the commands of the run: ${found.message}`);
547
+ }
548
+ if (found.out.trim() === 'yes') {
549
+ return name;
550
+ }
551
+ }
552
+ return undefined;
553
+ }
554
+ /**
555
+ * Kills what the commands of the run `run` run in the runners of the sandbox and removes their
556
+ * directory (getRunCommandsDirectory). `clean`: the run still holds the sandbox, what the
557
+ * commands left is cleaned up too. Without a runner that runs it all went with the runners,
558
+ * and the next command on the sandbox removes the files of other runs.
559
+ */
560
+ async function removeRunCommands(instance, namespace, sandbox, run, options) {
561
+ const failures = [];
562
+ for (const pod of await listRunnerPods(instance, namespace, sandbox)) {
563
+ const name = pod.metadata?.name;
564
+ if (!name || pod.metadata?.deletionTimestamp || !isRunning(pod)) {
565
+ continue;
566
+ }
567
+ // the scratch directories of this pod, as its commands clean them up: none a mount is in
568
+ const scripts = getRunnerScripts(getCleanUp(getScratchDirectories(getScratchMounts(pod))), []);
569
+ const removed = await runScript(instance, namespace, name, scripts.remove, [getRunCommandsDirectory(run), options.clean ? 'clean' : ''], { timeout: KILL_TIMEOUT_MS });
570
+ if (removed.exitCode === undefined) {
571
+ failures.push(`${name}: ${removed.message}`);
572
+ }
573
+ }
574
+ if (failures.length > 0) {
575
+ throw new Error(`the commands of the run could not be removed in ${failures.join(', ')}`);
576
+ }
577
+ }
578
+ exports.removeRunCommands = removeRunCommands;
579
+ // The mounts of the runner's container that its scratch directories have to keep clear of:
580
+ // all but its own /tmp, which is one of them
581
+ function getScratchMounts(pod) {
582
+ const container = pod.spec?.containers?.find((candidate) => candidate.name === RUNNER_CONTAINER);
583
+ return (container?.volumeMounts ?? []).filter((mount) => mount.name !== TMP_VOLUME);
584
+ }
358
585
  // The pod of the sandbox's files the run holds, as long as it is still that pod
359
586
  async function getFilesPod(instance, namespace, workspace) {
360
587
  if (!workspace.pod) {
@@ -472,11 +699,7 @@ async function removeSandboxRunners(instance, namespace, sandbox, keep) {
472
699
  // all of the sandbox's runners go: so does what was remembered of them
473
700
  failed.delete(sandbox);
474
701
  }
475
- const pods = await instance.coreApi.listNamespacedPod({
476
- namespace,
477
- labelSelector: `${volumes_1.SANDBOX_LABEL}=${sandbox},${exports.RUNNER_LABEL}`,
478
- });
479
- for (const pod of pods.items) {
702
+ for (const pod of await listRunnerPods(instance, namespace, sandbox)) {
480
703
  const name = pod.metadata?.name;
481
704
  const key = pod.metadata?.labels?.[resources_1.ID_LABEL];
482
705
  if (!name || keep?.(pod)) {
@@ -504,124 +727,271 @@ async function setPolicyOwners(instance, namespace, name, owners) {
504
727
  metadata: { name, namespace, ownerReferences: owners },
505
728
  }, undefined, undefined, undefined, undefined, 'application/merge-patch+json');
506
729
  }
507
- // Runs a command in the runner and answers its exit code. Its output goes to the task's,
508
- // line by line as it comes. On abort (cancel, timeout) every process of the command is
509
- // killed, or the runner goes when that fails.
730
+ // a connection to the runner that broke, or a follow that failed, is tried again this often in a
731
+ // row without getting further, then the task fails
732
+ const RECONNECTS = 5;
733
+ function parseCommandState(out) {
734
+ const line = out.trim().split('\n').pop() ?? '';
735
+ const finished = /^finished (\d+)( changed)?$/.exec(line);
736
+ if (finished) {
737
+ return { type: 'finished', exitCode: Number(finished[1]), changed: !!finished[2] };
738
+ }
739
+ return line === 'started' || line === 'running' || line === 'cancelled' || line === 'none'
740
+ ? { type: line }
741
+ : undefined;
742
+ }
743
+ // Runs a command in the runner and answers its exit code. The command runs detached from
744
+ // the exec that starts it, and its output goes to the task's as it comes, line by line, read
745
+ // from its files: a connection that breaks is opened again and goes on from the byte the
746
+ // log got to, which RunnerCommands.reached is told of. A command the run started before (the
747
+ // process of the run before a restart) is not started again: one that runs is followed from
748
+ // where the log of the run got (RunnerCommands.resumed), one that ended says the rest. Any
749
+ // other command starts anew, whatever its directory holds. On abort (cancel, timeout) every
750
+ // process of the command is killed, or the runner goes when that fails; a command that can not
751
+ // be followed to its end is killed too.
510
752
  async function execInRunner(instance, namespace, pod,
511
753
  // the directory of the run's sandbox, and the command's in it
512
- root, cwd, command, scripts, task, abort) {
513
- const { cleanUp } = scripts;
514
- const output = { bytes: 0, cut: false };
515
- let changed = false;
516
- const lines = (stream) => {
517
- let rest = '';
518
- // a character split between two chunks stays whole
519
- const decoder = new string_decoder_1.StringDecoder('utf8');
520
- const writable = new stream_1.Writable({
521
- write(chunk, _encoding, callback) {
522
- if (output.bytes < MAX_OUTPUT_BYTES) {
523
- output.bytes += chunk.length;
524
- const parts = (rest + decoder.write(chunk)).split(/\r?\n/);
525
- rest = parts.pop() ?? '';
526
- for (const line of parts) {
527
- if (stream === 'stderr' && line === RUNNER_CHANGED_MARK) {
528
- changed = true;
529
- continue;
530
- }
531
- task.status.console(stream, line);
532
- }
533
- }
534
- else if (!output.cut) {
535
- output.cut = true;
536
- task.status.write('warn', `the output of ${task.name} was cut at ${MAX_OUTPUT_BYTES} bytes`);
537
- }
538
- callback();
539
- },
540
- final(callback) {
541
- rest += decoder.end();
542
- if (rest.length > 0) {
543
- task.status.console(stream, rest);
544
- }
545
- callback();
546
- },
547
- });
548
- return writable;
549
- };
550
- const stdout = lines('stdout');
551
- const stderr = lines('stderr');
552
- let status;
553
- const socket = await instance.exec.exec(namespace, pod, RUNNER_CONTAINER, [BUSYBOX, 'sh', '-c', scripts.wrapper, 'hammerkit', RUNNER_CHANGED_MARK, root, cwd, ...command], stdout, stderr, null, false, (received) => {
554
- status = received;
555
- });
556
- const closed = new Promise((resolve, reject) => {
557
- socket.on('close', () => resolve());
558
- socket.on('error', (e) => reject(e));
754
+ root, cwd, command, scripts, where, task, abort) {
755
+ if (abort.aborted) {
756
+ return 137;
757
+ }
758
+ const { directory, record, commands } = where;
759
+ const id = path_1.posix.basename(directory);
760
+ const resumed = commands.resumed?.[id];
761
+ // the log said that the output was cut, once also over a restart (CommandRecord.cut)
762
+ let cutSaid = !!resumed?.cut;
763
+ const report = (outputs, done = false) => commands.reached?.(id, {
764
+ ...record,
765
+ ...outputs,
766
+ ...(done ? { done: true } : {}),
767
+ ...(cutSaid ? { cut: true } : {}),
559
768
  });
769
+ let current;
770
+ const opened = (socket) => {
771
+ current = socket;
772
+ };
773
+ const cancel = () => runScript(instance, namespace, pod, scripts.cancel, [directory], { timeout: KILL_TIMEOUT_MS });
560
774
  const kill = async () => {
561
- try {
562
- await killInRunner(instance, namespace, pod, cleanUp);
563
- }
564
- catch (e) {
565
- task.status.write('debug', `the command could not be stopped in the runner, it goes: ${(0, log_1.getErrorMessage)(e)}`);
775
+ const killed = await cancel();
776
+ if (killed.exitCode === undefined) {
777
+ task.status.write('debug', `the command could not be stopped in the runner, it goes: ${killed.message ?? 'the kill did not end'}`);
566
778
  await deletePod(instance, namespace, pod).catch(() => undefined);
567
779
  }
568
- // what the command printed after it was killed is not waited for long
569
- await Promise.race([closed.catch(() => undefined), (0, sleep_1.sleep)(KILL_TIMEOUT_MS)]);
570
- socket.close();
780
+ current?.close();
571
781
  };
782
+ let killing;
572
783
  const aborted = () => {
573
- void kill();
784
+ killing ?? (killing = kill());
574
785
  };
575
- if (abort.aborted) {
786
+ const stopped = async () => {
576
787
  aborted();
577
- }
578
- else {
579
- abort.addEventListener('abort', aborted, { once: true });
580
- }
581
- let broken;
788
+ await killing;
789
+ return 137;
790
+ };
791
+ abort.addEventListener('abort', aborted, { once: true });
582
792
  try {
583
- await closed.catch((e) => {
584
- broken = e;
585
- });
586
- if (!abort.aborted && getExecExitCode(status) === undefined) {
587
- // the connection broke while the command may still run: it ends here as on a cancel,
588
- // before the run lets go of the sandbox
589
- await kill();
793
+ // a start again after its connection broke takes the command it started, by its nonce
794
+ const nonce = (0, crypto_1.randomBytes)(12).toString('hex');
795
+ const start = (mode) => runScript(instance, namespace, pod, scripts.start, [directory, mode, resumed ? '' : nonce, root, cwd, ...command], { opened });
796
+ let started = await start(resumed ? 'adopt' : 'fresh');
797
+ for (let attempt = 0; started.exitCode === undefined && attempt < RECONNECTS && !abort.aborted; attempt++) {
798
+ await (0, sleep_1.sleep)(RUNNER_POLL_MS * 2 ** attempt);
799
+ started = await start('adopt');
800
+ }
801
+ if (abort.aborted) {
802
+ return await stopped();
803
+ }
804
+ const state = parseCommandState(started.out);
805
+ if (!state || state.type === 'none') {
806
+ throw new Error(`the command could not be started in the runner of the sandbox: ${started.message ?? `exit code ${started.exitCode}`}`);
807
+ }
808
+ if (state.type === 'cancelled') {
809
+ throw new Error('the command was cancelled in the runner of the sandbox');
810
+ }
811
+ // a command started now has all its output to say; one that was there already what the
812
+ // log of the run does not hold yet
813
+ const offsets = state.type === 'started'
814
+ ? { stdout: 0, stderr: 0 }
815
+ : { stdout: resumed?.stdout ?? 0, stderr: resumed?.stderr ?? 0 };
816
+ if (!resumed) {
817
+ // the run started it (or a start of it again took it, after its connection broke): a run
818
+ // that resumes takes it up again
819
+ report(offsets);
820
+ }
821
+ if (state.type !== 'started') {
822
+ task.status.write('debug', `the command was started before, it is ${state.type === 'running' ? 'followed' : 'over'}`);
823
+ }
824
+ const output = { bytes: offsets.stdout + offsets.stderr };
825
+ const cut = (what) => {
826
+ if (!cutSaid) {
827
+ cutSaid = true;
828
+ task.status.write('warn', `${what} of ${task.name} was cut at ${MAX_OUTPUT_BYTES} bytes`);
829
+ }
830
+ };
831
+ const say = (stream, bytes) => {
832
+ offsets[stream] += bytes.length;
833
+ if (output.bytes < MAX_OUTPUT_BYTES) {
834
+ output.bytes += bytes.length;
835
+ for (const line of bytes
836
+ .toString('utf8')
837
+ .replace(/\r?\n$/, '')
838
+ .split(/\r?\n/)) {
839
+ task.status.console(stream, line);
840
+ }
841
+ }
842
+ if (output.bytes >= MAX_OUTPUT_BYTES) {
843
+ cut('the output');
844
+ }
845
+ else if (offsets[stream] >= MAX_OUTPUT_BYTES) {
846
+ // the file of the stream holds no more, what the command says after is dropped
847
+ cut(`the ${stream}`);
848
+ }
849
+ report(offsets);
850
+ };
851
+ // whole lines as they come; what is left of a line when the exec ends is read again by
852
+ // the next, or said once the command ended
853
+ const lines = (stream) => {
854
+ let pending = Buffer.alloc(0);
855
+ const writable = new stream_1.Writable({
856
+ write(chunk, _encoding, callback) {
857
+ pending = Buffer.concat([pending, chunk]);
858
+ const end = pending.lastIndexOf(0x0a);
859
+ if (end >= 0) {
860
+ say(stream, pending.subarray(0, end + 1));
861
+ pending = pending.subarray(end + 1);
862
+ }
863
+ callback();
864
+ },
865
+ });
866
+ return {
867
+ writable,
868
+ rest: () => {
869
+ if (pending.length > 0) {
870
+ say(stream, pending);
871
+ }
872
+ },
873
+ };
874
+ };
875
+ for (let failures = 0;;) {
876
+ const before = offsets.stdout + offsets.stderr;
877
+ const stdout = lines('stdout');
878
+ const stderr = lines('stderr');
879
+ const followed = await runScript(instance, namespace, pod, scripts.follow, [directory, String(offsets.stdout), String(offsets.stderr)], { stdout: stdout.writable, stderr: stderr.writable, opened });
880
+ if (abort.aborted) {
881
+ return await stopped();
882
+ }
883
+ if (followed.exitCode === 3) {
884
+ throw new Error('the command in the runner of the sandbox ended without an exit code: its runner went');
885
+ }
886
+ // 0: all of it was said. Else what followed it ended before: the end of the command killed
887
+ // it (137), its connection broke, it failed. It is followed again, a few times in a row
888
+ // without getting further at most: a command that keeps killing what follows it too
889
+ if (followed.exitCode !== 0) {
890
+ failures = offsets.stdout + offsets.stderr > before ? 1 : failures + 1;
891
+ if (failures > RECONNECTS) {
892
+ throw new Error(`the command in the runner of the sandbox could not be followed: ${followed.message ?? `exit code ${followed.exitCode}`}`);
893
+ }
894
+ }
895
+ const status = await reconnecting(abort, () => runScript(instance, namespace, pod, scripts.status, [directory], { timeout: KILL_TIMEOUT_MS }));
896
+ if (abort.aborted) {
897
+ return await stopped();
898
+ }
899
+ const now = parseCommandState(status.out);
900
+ if (!now) {
901
+ throw new Error(`the command in the runner of the sandbox ended without an exit code: ${status.message ?? followed.message ?? 'the connection closed'}`);
902
+ }
903
+ if (now.type === 'none') {
904
+ throw new Error('the command in the runner of the sandbox ended without an exit code: its runner went');
905
+ }
906
+ if (followed.exitCode === 0) {
907
+ if (now.type === 'cancelled') {
908
+ throw new Error('the command was cancelled in the runner of the sandbox');
909
+ }
910
+ if (now.type === 'finished') {
911
+ stdout.rest();
912
+ stderr.rest();
913
+ report(offsets, true);
914
+ return now.exitCode === exports.RUNNER_CHANGED_EXIT && now.changed ? 'changed' : now.exitCode;
915
+ }
916
+ }
917
+ await (0, sleep_1.sleep)(RUNNER_POLL_MS);
590
918
  }
591
919
  }
592
- finally {
593
- abort.removeEventListener('abort', aborted);
594
- for (const stream of [stdout, stderr]) {
595
- if (!stream.writableEnded) {
596
- stream.end();
920
+ catch (e) {
921
+ if (!abort.aborted) {
922
+ // what can not be followed to its end does not run on unseen
923
+ const killed = await cancel();
924
+ if (killed.exitCode === undefined) {
925
+ task.status.write('debug', `the command could not be stopped in the runner: ${killed.message}`);
597
926
  }
598
927
  }
599
- await Promise.all([(0, promises_1.finished)(stdout), (0, promises_1.finished)(stderr)]).catch(() => undefined);
928
+ throw e;
600
929
  }
601
- if (abort.aborted) {
602
- return 137;
930
+ finally {
931
+ abort.removeEventListener('abort', aborted);
603
932
  }
604
- const exitCode = getExecExitCode(status);
605
- if (exitCode === undefined) {
606
- throw new Error(`the command in the runner of the sandbox ended without an exit code: ${status?.message ?? (broken ? (0, log_1.getErrorMessage)(broken) : 'the connection closed')}`);
933
+ }
934
+ // Runs `fn` again while it answers no exit code (its connection broke), RECONNECTS times at most
935
+ async function reconnecting(abort, fn) {
936
+ let result = await fn();
937
+ for (let attempt = 0; result.exitCode === undefined && attempt < RECONNECTS && !abort.aborted; attempt++) {
938
+ await (0, sleep_1.sleep)(RUNNER_POLL_MS * 2 ** attempt);
939
+ result = await fn();
607
940
  }
608
- return exitCode === exports.RUNNER_CHANGED_EXIT && changed ? 'changed' : exitCode;
941
+ return result;
609
942
  }
610
- async function killInRunner(instance, namespace, pod, cleanUp) {
943
+ // Runs a script of the runner's busybox with `args` as `$1`… in the runner
944
+ async function runScript(instance, namespace, pod, script, args, options = {}) {
945
+ let out = '';
946
+ const stdout = options.stdout ??
947
+ new stream_1.Writable({
948
+ write(chunk, _encoding, callback) {
949
+ out += chunk.toString('utf8');
950
+ callback();
951
+ },
952
+ });
611
953
  let status;
612
- const socket = await instance.exec.exec(namespace, pod, RUNNER_CONTAINER, [BUSYBOX, 'sh', '-c', cleanUp], null, null, null, false, (received) => {
613
- status = received;
614
- });
615
- await Promise.race([
616
- new Promise((resolve, reject) => {
954
+ let broken;
955
+ try {
956
+ const socket = await instance.exec.exec(namespace, pod, RUNNER_CONTAINER, [BUSYBOX, 'sh', '-c', script, 'hammerkit', ...args], stdout, options.stderr ?? null, null, false, (received) => {
957
+ status = received;
958
+ });
959
+ options.opened?.(socket);
960
+ const closed = new Promise((resolve) => {
617
961
  socket.on('close', () => resolve());
618
- socket.on('error', reject);
619
- }),
620
- (0, sleep_1.sleep)(KILL_TIMEOUT_MS).then(() => Promise.reject(new Error('the kill did not answer'))),
621
- ]);
622
- // what it answers does not matter, that it answered does
623
- if (getExecExitCode(status) === undefined) {
624
- throw new Error(status?.message ?? 'the kill did not end');
962
+ socket.on('error', (e) => {
963
+ broken = e;
964
+ resolve();
965
+ });
966
+ });
967
+ if (options.timeout) {
968
+ let timer;
969
+ await Promise.race([
970
+ closed,
971
+ new Promise((resolve) => {
972
+ timer = setTimeout(() => {
973
+ broken ?? (broken = new Error('it did not answer'));
974
+ socket.close();
975
+ resolve();
976
+ }, options.timeout);
977
+ }),
978
+ ]);
979
+ clearTimeout(timer);
980
+ }
981
+ else {
982
+ await closed;
983
+ }
625
984
  }
985
+ catch (e) {
986
+ broken = e;
987
+ }
988
+ const exitCode = broken && !status ? undefined : getExecExitCode(status);
989
+ return {
990
+ out,
991
+ ...(exitCode !== undefined ? { exitCode } : {}),
992
+ ...(exitCode === undefined
993
+ ? { message: status?.message ?? (broken ? (0, log_1.getErrorMessage)(broken) : 'the connection closed') }
994
+ : {}),
995
+ };
626
996
  }
627
997
  //# sourceMappingURL=sandbox-runner.js.map