hammerkit 2.1.0-next.11 → 2.1.0-next.12

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.
@@ -16,7 +16,7 @@ stateKey = work.state.current.stateKey) {
16
16
  const cacheDir = (0, get_cache_directory_1.getCacheDirectory)((0, work_instance_id_1.getWorkInstanceId)(work));
17
17
  const { stats } = await (0, get_work_cache_stats_1.getWorkItemCacheStats)(work, environment);
18
18
  await (0, cache_metadata_1.writeCacheMetadata)(environment, work, stats, (0, work_task_cache_description_1.getWorkTaskCacheDescription)(work));
19
- await work.runtime.archive(environment, cacheDir, stateKey ?? undefined);
19
+ await work.runtime.archive(environment, cacheDir, { stateKey: stateKey ?? undefined });
20
20
  return cacheDir;
21
21
  }
22
22
  exports.archiveTaskEntry = archiveTaskEntry;
@@ -18,23 +18,76 @@ const MAX_TIMER_MS = 2 ** 31 - 1;
18
18
  // An abort signal that follows `parent` and additionally fires after `timeout`
19
19
  // ms, so a task deadline reuses the runtimes' existing abort/cleanup path. A
20
20
  // timeout beyond what a timer can wait (about 24.8 days) sets no deadline.
21
+ // `pause` stops the clock and `resume` starts it again with what was left, so a
22
+ // wait that is not the task's to count (its pod refused by the quota) does not use it.
23
+ // The pauses together may last `timeout` as well: then it fires and `waitedOut` says so.
21
24
  function withDeadline(parent, timeout) {
22
25
  const controller = new AbortController();
23
- let expired = false;
24
26
  const parentListener = (0, abort_event_1.listenOnAbort)(parent, () => controller.abort());
25
- const timer = timeout === null || timeout > MAX_TIMER_MS
26
- ? null
27
- : setTimeout(() => {
28
- expired = true;
27
+ const limit = timeout !== null && timeout <= MAX_TIMER_MS ? timeout : null;
28
+ // what is left of the time to run, and of the time to wait in pauses
29
+ let left = limit ?? 0;
30
+ let pauseLeft = limit ?? 0;
31
+ let paused = false;
32
+ let closed = false;
33
+ let ended = null;
34
+ let since = performance.now();
35
+ let timer = null;
36
+ // ends the current stretch: what it took comes off its budget
37
+ const stopClock = () => {
38
+ if (timer) {
39
+ clearTimeout(timer);
40
+ timer = null;
41
+ }
42
+ if (limit === null || ended) {
43
+ return;
44
+ }
45
+ const took = performance.now() - since;
46
+ if (paused) {
47
+ pauseLeft = Math.min(limit, Math.max(0, pauseLeft - took));
48
+ }
49
+ else {
50
+ left = Math.min(limit, Math.max(0, left - took));
51
+ }
52
+ };
53
+ const startClock = () => {
54
+ since = performance.now();
55
+ if (limit === null || controller.signal.aborted) {
56
+ return;
57
+ }
58
+ const end = paused ? 'waited-out' : 'expired';
59
+ timer = setTimeout(() => {
60
+ timer = null;
61
+ ended = end;
29
62
  controller.abort();
30
- }, timeout);
63
+ }, paused ? pauseLeft : left);
64
+ };
65
+ startClock();
31
66
  return {
32
67
  signal: controller.signal,
33
- expired: () => expired,
34
- clear() {
35
- if (timer) {
36
- clearTimeout(timer);
68
+ // it ran for its timeout
69
+ expired: () => ended === 'expired',
70
+ // its pauses together lasted its timeout
71
+ waitedOut: () => ended === 'waited-out',
72
+ pause() {
73
+ if (closed || paused || ended) {
74
+ return;
37
75
  }
76
+ stopClock();
77
+ paused = true;
78
+ startClock();
79
+ },
80
+ resume() {
81
+ if (closed || !paused || ended) {
82
+ return;
83
+ }
84
+ stopClock();
85
+ paused = false;
86
+ startClock();
87
+ },
88
+ clear() {
89
+ stopClock();
90
+ closed = true;
38
91
  parentListener.close();
39
92
  },
40
93
  };
@@ -35,7 +35,8 @@ async function restoreCache(environment, path, workTree) {
35
35
  }
36
36
  }
37
37
  exports.restoreCache = restoreCache;
38
- function* getArchivePaths(task, path) {
38
+ // `only`: the paths of the outputs to archive of a task, every one when left out
39
+ function* getArchivePaths(task, path, only) {
39
40
  if (task.type === 'container-service') {
40
41
  for (const volume of task.volumes.filter((v) => !v.inherited)) {
41
42
  yield {
@@ -59,6 +60,9 @@ function* getArchivePaths(task, path) {
59
60
  }
60
61
  }
61
62
  for (const { generate, rel } of generates) {
63
+ if (only && !only.includes(generate.path)) {
64
+ continue;
65
+ }
62
66
  let generateId = rel.split(path_1.posix.sep).join('-');
63
67
  if (holders.get(generateId) !== rel) {
64
68
  generateId += '-' + (0, crypto_1.createHash)('sha256').update(rel).digest('hex').slice(0, 12);
@@ -117,19 +117,31 @@ dependents = null) {
117
117
  daemon: options.daemon,
118
118
  publishPorts: false,
119
119
  waitForReady: true,
120
- onQuotaRefused: (refused) => options.processManager.quotaRefused(work, refused),
120
+ onQuotaRefused: (refused) => {
121
+ // the timeout counts the time it runs, not its wait for room under the quota;
122
+ // that wait may last as long as the timeout in all, besides QUOTA_TIMEOUT
123
+ if (refused) {
124
+ deadline.pause();
125
+ }
126
+ else {
127
+ deadline.resume();
128
+ }
129
+ options.processManager.quotaRefused(work, refused);
130
+ },
121
131
  });
122
132
  }
123
133
  finally {
124
134
  deadline.clear();
125
135
  }
126
- if (deadline.expired() && timeout !== null) {
136
+ if ((deadline.expired() || deadline.waitedOut()) && timeout !== null) {
127
137
  // the runtime saw an abort and cleaned up; report it as a failure
128
138
  // (never a cancellation) and stop the run like any failing task
129
139
  work.state.set({
130
140
  type: 'error',
131
141
  stateKey: cacheState.stateKey,
132
- errorMessage: `timed out after ${(0, units_1.formatDuration)(timeout)}`,
142
+ errorMessage: deadline.waitedOut()
143
+ ? `gave up waiting for room under the quota of the namespace after ${(0, units_1.formatDuration)(timeout)}, its timeout`
144
+ : `timed out after ${(0, units_1.formatDuration)(timeout)}`,
133
145
  });
134
146
  if (!options.watch) {
135
147
  environment.abortCtrl.abort();
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getFileContext = void 0;
4
+ const promises_1 = require("stream/promises");
4
5
  const fs_1 = require("fs");
5
6
  const path_1 = require("path");
6
7
  const chokidar_1 = require("chokidar");
@@ -58,14 +59,10 @@ function getFileContext(cwd) {
58
59
  writeFile(path, content) {
59
60
  return handleCallback((cb) => (0, fs_1.writeFile)(getAbsolutePath(cwd, path), content, cb));
60
61
  },
62
+ // a pipeline, so that an error of the stream (a limit it runs into, a broken source) rejects
63
+ // the write as well, and the file is closed
61
64
  async writeStream(path, stream) {
62
- const writeStream = (0, fs_1.createWriteStream)(path);
63
- await new Promise((resolve, reject) => {
64
- stream
65
- .pipe(writeStream)
66
- .on('error', (err) => reject(err))
67
- .on('close', () => resolve());
68
- });
65
+ await (0, promises_1.pipeline)(stream, (0, fs_1.createWriteStream)(path));
69
66
  },
70
67
  createWriteStream(path) {
71
68
  return (0, fs_1.createWriteStream)(path);
@@ -1,10 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
3
+ exports.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;
4
4
  const path_1 = require("path");
5
5
  const token_source_1 = require("../remote/token-source");
6
+ const fs_1 = require("fs");
7
+ const stream_1 = require("stream");
8
+ const promises_1 = require("stream/promises");
6
9
  // a write carries up to 32 MiB
7
10
  const TIMEOUT_MS = 60000;
11
+ // an output of a run carries up to runs.artifacts.maxBytes, 256 MiB by default: 30 minutes is
12
+ // what that takes at about 150 KiB/s, the slowest link the default still downloads over. A
13
+ // server with a larger maxBytes needs a longer timeout, as the download is not split up.
14
+ const DOWNLOAD_TIMEOUT_MS = 30 * 60000;
8
15
  // a run is asked for this long at a time, the log is read in between
9
16
  const POLL_WAIT = '1s';
10
17
  // a cancelled run waits this long for the server to take the cancel, before it gives up
@@ -459,6 +466,26 @@ async function getRun(connection, id) {
459
466
  return response.status === 404 ? null : json(response);
460
467
  }
461
468
  exports.getRun = getRun;
469
+ // null when the caller may not see the run (or the server keeps none of it)
470
+ async function getRunArtifacts(connection, id) {
471
+ const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts`, { missing: true });
472
+ return response.status === 404 ? null : json(response);
473
+ }
474
+ exports.getRunArtifacts = getRunArtifacts;
475
+ /**
476
+ * Writes the archive of one output of a run to `file`: a gzipped tar of its paths in the
477
+ * project. It may be large, so it is written as it comes and may take longer than a call.
478
+ */
479
+ async function downloadRunArtifact(connection, id, output, file) {
480
+ const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts/${output}`, {
481
+ timeoutMs: DOWNLOAD_TIMEOUT_MS,
482
+ });
483
+ if (!response.body) {
484
+ throw new SandboxClientError(`${connection.url} answered without the archive`);
485
+ }
486
+ await (0, promises_1.pipeline)(stream_1.Readable.fromWeb(response.body), (0, fs_1.createWriteStream)(file));
487
+ }
488
+ exports.downloadRunArtifact = downloadRunArtifact;
462
489
  /**
463
490
  * Reads the log of a run as it is now, every line or the last `tail` of them, of one task or
464
491
  * of all: also of a run that ended, as long as the server keeps it.
@@ -586,7 +613,7 @@ async function call(connection, method, path, options = {}) {
586
613
  ...(options.raw !== undefined ? { 'content-type': 'application/octet-stream' } : {}),
587
614
  },
588
615
  body: options.body !== undefined ? JSON.stringify(options.body) : options.raw,
589
- signal: AbortSignal.timeout(TIMEOUT_MS),
616
+ signal: AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS),
590
617
  // an answer from anywhere else is not the server's, and a PUT would send its file on
591
618
  redirect: 'error',
592
619
  }).catch((e) => {
@@ -45,7 +45,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
45
45
  }
46
46
  }
47
47
  for (const status of mainStatuses(pod, container)) {
48
- const failure = getContainerFailure(status, restartsEnded(pod, status), restarts);
48
+ const failure = getContainerFailure(pod, status, restartsEnded(pod, status), restarts);
49
49
  if (failure) {
50
50
  return failure;
51
51
  }
@@ -53,7 +53,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
53
53
  return null;
54
54
  }
55
55
  exports.getPodFailure = getPodFailure;
56
- function getContainerFailure(status, restartsEnded, restarts) {
56
+ function getContainerFailure(pod, status, restartsEnded, restarts) {
57
57
  const waiting = status.state?.waiting;
58
58
  const reason = waiting?.reason;
59
59
  const said = waiting?.message ? `: ${cut(waiting.message)}` : '';
@@ -78,18 +78,33 @@ function getContainerFailure(status, restartsEnded, restarts) {
78
78
  return { text: `its container could not be started (${reason})${said}`, final: false };
79
79
  case 'CrashLoopBackOff':
80
80
  return status.restartCount >= restarts
81
- ? { text: `it keeps crashing: ${describeLastExit(status)}`, final: true }
81
+ ? { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true }
82
82
  : null;
83
83
  }
84
84
  // a kubelet may leave an instance that ended as it is until its back-off is over, and say
85
85
  // CrashLoopBackOff only when it looks at the pod again, a minute later: the same crash
86
86
  if (restartsEnded && status.state?.terminated && status.restartCount >= restarts) {
87
- return { text: `it keeps crashing: ${describeLastExit(status)}`, final: true };
87
+ return { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true };
88
88
  }
89
89
  return null;
90
90
  }
91
- // How the last instance of a container ended, as the cluster says it.
92
- function describeLastExit(status) {
91
+ // The signals a container is most often ended by, by their Linux numbers: containers here
92
+ // are Linux ones, and other systems number some signals differently.
93
+ const SIGNALS = {
94
+ 1: 'SIGHUP',
95
+ 2: 'SIGINT',
96
+ 6: 'SIGABRT',
97
+ 9: 'SIGKILL',
98
+ 11: 'SIGSEGV',
99
+ 15: 'SIGTERM',
100
+ };
101
+ /**
102
+ * How the last instance of a container ended, as the cluster says it: its exit code and
103
+ * reason, and the signal of an exit code above 128. The kubelet kills a container whose
104
+ * liveness probe (its healthcheck) keeps failing, so a container of `pod` with one that was
105
+ * killed says that it may be why; one without a healthcheck never does.
106
+ */
107
+ function describeLastExit(status, pod) {
93
108
  // the instance that ended now, else the one before the one that waits or runs
94
109
  const last = status.state?.terminated ?? status.lastState?.terminated;
95
110
  const restarts = `, restarted ${status.restartCount} time${status.restartCount === 1 ? '' : 's'}`;
@@ -99,8 +114,14 @@ function describeLastExit(status) {
99
114
  if (last.reason === 'OOMKilled') {
100
115
  return `it was killed for using more memory than its limit (OOMKilled)${restarts}`;
101
116
  }
102
- // the kubelet kills a container whose liveness probe (its healthcheck) keeps failing
103
- const killed = last.exitCode === 137 || last.exitCode === 143 ? ', killed as when its healthcheck kept failing' : '';
117
+ // A shell, and the runtime for process 1, exit with 128 plus the signal that ended a
118
+ // process: 129 to 159 are the signals 1 to 31, which Linux has; a higher code is the
119
+ // process's own.
120
+ const signal = last.exitCode >= 129 && last.exitCode <= 159 ? last.exitCode - 128 : undefined;
121
+ const probed = !!pod.spec?.containers?.find((container) => container.name === status.name)?.livenessProbe;
122
+ const killed = signal === undefined
123
+ ? ''
124
+ : `, killed by ${SIGNALS[signal] ?? `signal ${signal}`}${probed && (signal === 9 || signal === 15) ? ' as when its healthcheck keeps failing' : ''}`;
104
125
  return `it exited with code ${last.exitCode}${last.reason ? ` (${last.reason})` : ''}${killed}${restarts}`;
105
126
  }
106
127
  exports.describeLastExit = describeLastExit;
@@ -125,14 +146,14 @@ function getPodWaiting(pod, container) {
125
146
  case 'RunContainerError':
126
147
  return `can not start its container yet (${waiting.reason})${said}`;
127
148
  case 'CrashLoopBackOff':
128
- return `crashed and starts again: ${describeLastExit(status)}`;
149
+ return `crashed and starts again: ${describeLastExit(status, pod)}`;
129
150
  }
130
151
  const ended = status.state?.terminated;
131
152
  if (ended && restartsEnded(pod, status)) {
132
- return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status)}`;
153
+ return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status, pod)}`;
133
154
  }
134
155
  if (status.restartCount > 0 && status.state?.running && !status.ready) {
135
- return `restarted: ${describeLastExit(status)}`;
156
+ return `restarted: ${describeLastExit(status, pod)}`;
136
157
  }
137
158
  }
138
159
  return undefined;
@@ -167,16 +188,29 @@ function describePod(pod) {
167
188
  const said = failure ?? waiting;
168
189
  const parts = [phase, ...(said ? [said] : [])];
169
190
  for (const status of crashed) {
170
- if (!said?.includes(describeLastExit(status))) {
171
- parts.push(`${status.name}: ${describeLastExit(status)}`);
191
+ const exit = describeLastExit(status, pod);
192
+ if (!said?.includes(exit)) {
193
+ parts.push(`container ${status.name}: ${exit}`);
172
194
  }
173
195
  }
174
196
  if (!said && unready.length > 0) {
175
197
  parts.push(`not ready: ${unready.join(', ')}`);
176
198
  }
177
- return `pod ${name}: ${parts.join(', ')}`;
199
+ return `pod ${name}${describeHelper(pod)}: ${parts.join(', ')}`;
178
200
  }
179
201
  exports.describePod = describePod;
202
+ // what a pod hammerkit runs beside a task or service does, so it is not taken for the item
203
+ function describeHelper(pod) {
204
+ const item = pod.metadata?.annotations?.[resources_1.ITEM_ANNOTATION];
205
+ switch (item ? pod.metadata?.annotations?.[resources_1.HELPER_ANNOTATION] : undefined) {
206
+ case 'upload':
207
+ return ` (a helper that copies the files of ${item} into its volume, not ${item} itself)`;
208
+ case 'download':
209
+ return ` (a helper that copies the outputs of ${item} out of its volume, not ${item} itself)`;
210
+ default:
211
+ return '';
212
+ }
213
+ }
180
214
  /**
181
215
  * The message of a warning event, as far as it is the cluster's: a failed probe says the
182
216
  * output of the command, which is the service's, and is left out.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensurePersistentData = exports.packSource = exports.clearStateFiles = exports.ENSURE_OUTPUT_FILES = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = exports.applyWithinQuota = exports.QUOTA_TIMEOUT = exports.TRANSFER_POD_RESOURCES = void 0;
3
+ exports.ensurePersistentData = exports.packSource = exports.clearStateFiles = exports.ENSURE_OUTPUT_FILES = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = exports.applyWithinQuota = exports.QUOTA_TIMEOUT = exports.getTransferPodScript = exports.TRANSFER_POD_RESOURCES = void 0;
4
4
  const quota_wait_1 = require("./quota-wait");
5
5
  Object.defineProperty(exports, "QUOTA_TIMEOUT", { enumerable: true, get: function () { return quota_wait_1.QUOTA_TIMEOUT; } });
6
6
  const volumes_1 = require("./volumes");
@@ -54,6 +54,15 @@ exports.TRANSFER_POD_RESOURCES = {
54
54
  requests: { cpu: '50m', memory: '64Mi' },
55
55
  limits: { memory: '512Mi' },
56
56
  };
57
+ // What the transfer pod runs while files are copied through exec: it waits, and ends at once
58
+ // and with 0 when the pod is deleted. A shell as process 1 ignores SIGTERM unless it traps it,
59
+ // and was killed at the end of the grace period of its deletion, 30 seconds later and with
60
+ // 137, which the log of a run that failed meanwhile showed as a failed pod.
61
+ // `busybox` is the one of the pod.
62
+ function getTransferPodScript(busybox) {
63
+ return `trap 'kill $! 2>/dev/null; exit 0' TERM; ${busybox} sleep 2147483647 & wait`;
64
+ }
65
+ exports.getTransferPodScript = getTransferPodScript;
57
66
  // A Job waits for room under a full quota, a pod is refused: so a transfer pod is
58
67
  // created again until the pods of the tasks it runs beside are done and make room
59
68
  async function applyWithinQuota(instance, podSpec, service, timeout = quota_wait_1.QUOTA_TIMEOUT, pollInterval = 2000,
@@ -139,6 +148,8 @@ signal, fn) {
139
148
  },
140
149
  annotations: {
141
150
  'hammerkit.dev/version': (0, version_1.getVersion)(),
151
+ [resources_1.HELPER_ANNOTATION]: type === 'write' ? 'upload' : 'download',
152
+ [resources_1.ITEM_ANNOTATION]: service.name,
142
153
  },
143
154
  },
144
155
  spec: {
@@ -156,8 +167,8 @@ signal, fn) {
156
167
  {
157
168
  name: 'volume',
158
169
  image: transfer_tools_1.HELPER_TOOLS_IMAGE,
159
- command: (0, transfer_tools_1.inTransferPod)(['sh']),
160
- tty: true,
170
+ // no tty: it kept an interactive shell waiting, which ignores SIGTERM
171
+ command: (0, transfer_tools_1.inTransferPod)(['sh', '-c', getTransferPodScript(transfer_tools_1.TRANSFER_BUSYBOX)]),
161
172
  env: transfer_tools_1.TRANSFER_TOOLS_ENV,
162
173
  volumeMounts: [...mounts, transfer_tools_1.TRANSFER_TOOLS_MOUNT],
163
174
  resources: exports.TRANSFER_POD_RESOURCES,
@@ -1,12 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeInvalidCharacters = exports.getResourceName = exports.getItemSelector = exports.getItemLabels = exports.getItemKey = exports.ID_LABEL = void 0;
3
+ exports.removeInvalidCharacters = exports.getResourceName = exports.getItemSelector = exports.getItemLabels = exports.getItemKey = exports.ITEM_ANNOTATION = exports.HELPER_ANNOTATION = exports.ID_LABEL = void 0;
4
4
  const job_placement_1 = require("./job-placement");
5
5
  // An object name is a DNS label: lowercase letters, digits and `-`, at most 63
6
6
  // characters, starting and ending with a letter or digit. The id makes a name
7
7
  // unique; the item's name is there for people and is cut to fit.
8
8
  const MAX_NAME = 63;
9
9
  exports.ID_LABEL = 'hammerkit.dev/id';
10
+ // On a pod that copies files of an item into or out of its claim: `upload` or `download`, and
11
+ // the item's name, so what the cluster says of the pod is not taken for the item
12
+ exports.HELPER_ANNOTATION = 'hammerkit.dev/helper';
13
+ exports.ITEM_ANNOTATION = 'hammerkit.dev/item';
10
14
  // What tells the objects of an item apart in its namespace: its id, and on a server the
11
15
  // run's label too. The runs of a caller execute side by side in their namespace, and two
12
16
  // of them often run the same task (the same command on two sandboxes of a repository),
@@ -10,8 +10,11 @@ const transfer_tools_1 = require("./transfer-tools");
10
10
  async function storeKubernetesData(work, kubernetes, instance, environment, path,
11
11
  // the state the outputs are of: on a service run, they are in its folder (see
12
12
  // getStateFilesDir)
13
- stateKey) {
13
+ stateKey,
14
+ // the paths of the outputs to archive, every one when left out
15
+ only) {
14
16
  const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes, stateKey);
17
+ const written = [];
15
18
  // a run stopped while the pod waits for room under the quota
16
19
  const { signal } = environment.abortCtrl;
17
20
  // an output that is a file is mounted as one: its archive holds it by its name, as on Docker
@@ -21,9 +24,10 @@ stateKey) {
21
24
  .map((generate) => generate.path)
22
25
  : []);
23
26
  await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'read', signal, async (name) => {
24
- for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path)) {
27
+ for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path, only)) {
25
28
  const writerStream = environment.file.createWriteStream(generatedArchive.filename);
26
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)(files.has(generatedArchive.path)
29
+ const isFile = files.has(generatedArchive.path);
30
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)(isFile
27
31
  ? ['tar', 'zcf', '-', '-C', path_1.posix.dirname(generatedArchive.path), path_1.posix.basename(generatedArchive.path)]
28
32
  : ['tar', 'zcf', '-', '-C', generatedArchive.path, '.']), writerStream, process.stderr, null, false, (status) => {
29
33
  work.status.write('debug', `archive ${generatedArchive.path} of ${name}: ${status}`);
@@ -42,13 +46,24 @@ stateKey) {
42
46
  work.status.write('debug', `downloaded ${generatedArchive.path} of ${name}`);
43
47
  resolve();
44
48
  });
49
+ // the file settles the wait too: a limit of the run (keepArtifacts' Budget) destroys it
50
+ // while the exec still streams into it
51
+ writerStream.on('error', (err) => reject(err));
52
+ writerStream.on('close', () => resolve());
45
53
  }
46
54
  catch (e) {
47
55
  reject(e);
48
56
  }
49
57
  });
58
+ // a file is archived by its name, a folder by its content: the entries of a folder are
59
+ // relative to it, those of a file to its folder
60
+ written.push({
61
+ filename: generatedArchive.filename,
62
+ root: isFile ? path_1.posix.dirname(generatedArchive.path) : generatedArchive.path,
63
+ });
50
64
  }
51
65
  });
66
+ return written;
52
67
  }
53
68
  exports.storeKubernetesData = storeKubernetesData;
54
69
  //# sourceMappingURL=store-kubernetes-data.js.map
@@ -19,6 +19,7 @@ function aggregateWorkRuntime() {
19
19
  },
20
20
  async archive() {
21
21
  // never pushed, see pushToBackend
22
+ return [];
22
23
  },
23
24
  async restore() {
24
25
  // never a hit, see checkCacheState
@@ -49,8 +49,8 @@ function dockerTaskRuntime(task, workEnvironment) {
49
49
  await (0, container_task_state_1.removeContainerTaskState)(environment, task);
50
50
  await restoreContainer(docker, environment, task, path);
51
51
  },
52
- async archive(environment, path) {
53
- await archiveContainer(docker, environment, task, path);
52
+ async archive(environment, path, options = {}) {
53
+ return archiveContainer(docker, environment, task, path, options.only);
54
54
  },
55
55
  async stop() {
56
56
  const containers = await docker.listContainers({
@@ -273,7 +273,7 @@ function dockerServiceRuntime(service, workEnvironment) {
273
273
  await restoreContainer(docker, environment, service, path);
274
274
  },
275
275
  async archive(environment, path) {
276
- await archiveContainer(docker, environment, service, path);
276
+ return archiveContainer(docker, environment, service, path);
277
277
  },
278
278
  async currentStateKey() {
279
279
  const containers = await docker.listContainers({
@@ -315,13 +315,14 @@ async function removeLegacyService(docker, service) {
315
315
  await (0, container_secrets_1.removeContainerSecrets)((0, work_instance_id_1.getWorkInstanceId)(legacy));
316
316
  }
317
317
  exports.removeLegacyService = removeLegacyService;
318
- async function archiveContainer(docker, environment, item, path) {
318
+ async function archiveContainer(docker, environment, item, path, only) {
319
319
  await (0, execution_steps_1.refuseHostLinks)(item, environment);
320
+ const written = [];
320
321
  await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
321
322
  const hostFiles = new Set(item.data.type === 'container-task'
322
323
  ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
323
324
  : []);
324
- for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path)) {
325
+ for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path, only)) {
325
326
  // a file output is a bind mount of a host file, so archive it from the host
326
327
  const readable = hostFiles.has(generatedArchive.path)
327
328
  ? stream_1.Readable.from((0, tar_1.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
@@ -329,7 +330,10 @@ async function archiveContainer(docker, environment, item, path) {
329
330
  path: generatedArchive.path,
330
331
  });
331
332
  await environment.file.writeStream(generatedArchive.filename, readable);
333
+ // what the container archives at a path is the entries of the path's folder, by its name
334
+ written.push({ filename: generatedArchive.filename, root: (0, path_1.dirname)(generatedArchive.path) });
332
335
  }
333
336
  });
337
+ return written;
334
338
  }
335
339
  //# sourceMappingURL=work-runtime-docker.js.map
@@ -199,8 +199,8 @@ function kubernetesTaskRuntime(task, kubernetes) {
199
199
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
200
200
  }
201
201
  },
202
- async archive(environment, path, stateKey) {
203
- await (0, store_kubernetes_data_1.storeKubernetesData)(task, kubernetes, instance, environment, path, stateKey);
202
+ async archive(environment, path, options = {}) {
203
+ return (0, store_kubernetes_data_1.storeKubernetesData)(task, kubernetes, instance, environment, path, options.stateKey, options.only);
204
204
  },
205
205
  async execute(environment, options) {
206
206
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(task.data.envs);
@@ -600,7 +600,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
600
600
  await (0, restore_kubernetes_data_1.restoreKubernetesData)(service, kubernetes, instance, environment, path);
601
601
  },
602
602
  async archive(environment, path) {
603
- await (0, store_kubernetes_data_1.storeKubernetesData)(service, kubernetes, instance, environment, path);
603
+ return (0, store_kubernetes_data_1.storeKubernetesData)(service, kubernetes, instance, environment, path);
604
604
  },
605
605
  async stop() {
606
606
  await stopKubernetesService(instance, kubernetes, service);
@@ -768,7 +768,9 @@ function kubernetesForwardRuntime(service) {
768
768
  }
769
769
  },
770
770
  async restore() { },
771
- async archive() { },
771
+ async archive() {
772
+ return [];
773
+ },
772
774
  async remove() { },
773
775
  async execute(_environment, options) {
774
776
  await (0, kubernetes_service_1.kubernetesService)(service, options);
@@ -45,8 +45,8 @@ function getLocalWorkRuntime(task) {
45
45
  await removeStateFile(environment, task);
46
46
  await restoreLocal(environment, task.data, path);
47
47
  },
48
- async archive(environment, path) {
49
- await archiveLocal(environment, task, path);
48
+ async archive(environment, path, options = {}) {
49
+ return archiveLocal(environment, task, path, options.only);
50
50
  },
51
51
  async execute(environment, options) {
52
52
  const activePid = await readActivePid(task, environment);
@@ -117,12 +117,16 @@ async function removeStateFile(environment, task) {
117
117
  await environment.file.remove(stateFile);
118
118
  }
119
119
  }
120
- async function archiveLocal(environment, task, path) {
121
- for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
120
+ async function archiveLocal(environment, task, path, only) {
121
+ const written = [];
122
+ for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path, only)) {
122
123
  await environment.file.writeStream(generatedArchive.filename,
123
124
  // tar's stream is a Minipass stream; Readable.from adapts it to a Node one
124
125
  stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
126
+ // the entries are relative to the directory of the task
127
+ written.push({ filename: generatedArchive.filename, root: task.data.cwd });
125
128
  }
129
+ return written;
126
130
  }
127
131
  async function restoreLocal(environment, task, path) {
128
132
  for (const generate of (0, event_cache_1.getArchivePaths)(task, path)) {
@@ -36,16 +36,42 @@ function remoteRepo(url) {
36
36
  }
37
37
  }
38
38
  exports.remoteRepo = remoteRepo;
39
+ // what the server takes for a commit, not for the name of a branch or tag
40
+ const COMMIT_NAME = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
41
+ const ORIGIN_BRANCHES = 'refs/remotes/origin/';
42
+ const TAGS = 'refs/tags/';
39
43
  // The checkout a directory is in: the repository of its `origin`, the branch it is on and
40
- // its commit, what can be found of them.
44
+ // its commit, what can be found of them. A detached HEAD is on no branch: `heads` are then the
45
+ // branches of origin (as the last fetch or push left them) and the tags whose head is its
46
+ // commit, branches first, as git sorts them.
41
47
  async function readCheckout(cwd) {
42
48
  if ((await git(cwd, 'rev-parse', '--is-inside-work-tree')) !== 'true') {
43
49
  return {};
44
50
  }
45
51
  const remote = await git(cwd, 'remote', 'get-url', 'origin');
46
- // a detached HEAD is on no branch
52
+ const repo = remote ? remoteRepo(remote) : undefined;
47
53
  const branch = await git(cwd, 'symbolic-ref', '--quiet', '--short', 'HEAD');
48
- return { repo: remote ? remoteRepo(remote) : undefined, branch, commit: await git(cwd, 'rev-parse', 'HEAD') };
54
+ const commit = await git(cwd, 'rev-parse', 'HEAD');
55
+ if (branch || !commit) {
56
+ return { repo, branch, commit };
57
+ }
58
+ const refs = await git(cwd, 'for-each-ref', `--points-at=${commit}`, '--format=%(refname)%09%(symref)', ORIGIN_BRANCHES, TAGS);
59
+ const heads = [];
60
+ for (const line of refs?.split('\n') ?? []) {
61
+ const [ref, symref] = line.split('\t');
62
+ // origin/HEAD names the default branch of origin, it is no branch of its own
63
+ if (symref || ref === `${ORIGIN_BRANCHES}HEAD`) {
64
+ continue;
65
+ }
66
+ const head = ref.startsWith(ORIGIN_BRANCHES)
67
+ ? { name: ref.slice(ORIGIN_BRANCHES.length), kind: 'branch' }
68
+ : { name: ref.slice(TAGS.length), kind: 'tag' };
69
+ // a name that looks like a commit would be run as that commit
70
+ if (head.name && !COMMIT_NAME.test(head.name)) {
71
+ heads.push(head);
72
+ }
73
+ }
74
+ return { repo, commit, heads };
49
75
  }
50
76
  exports.readCheckout = readCheckout;
51
77
  // Where a build file is published from: its path in its repository (or on this