hammerkit 2.1.0-next.10 → 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.
Files changed (41) 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/file/get-file-context.js +4 -7
  10. package/dist/harness/sandbox-client.js +29 -2
  11. package/dist/kubernetes/cluster-state.js +48 -14
  12. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  13. package/dist/kubernetes/resources.js +5 -1
  14. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  15. package/dist/planner/work-runtime-aggregate.js +1 -0
  16. package/dist/planner/work-runtime-docker.js +9 -5
  17. package/dist/planner/work-runtime-kubernetes.js +6 -4
  18. package/dist/planner/work-runtime-local.js +8 -4
  19. package/dist/remote/annotations.js +29 -3
  20. package/dist/remote/bundle.js +6 -8
  21. package/dist/remote/collect-bundle.js +3 -2
  22. package/dist/remote/remote-work-commands.js +161 -8
  23. package/dist/server/artifacts-api.js +56 -0
  24. package/dist/server/definitions-api.js +62 -8
  25. package/dist/server/executor.js +17 -0
  26. package/dist/server/keep-artifacts.js +230 -0
  27. package/dist/server/overview.js +67 -9
  28. package/dist/server/paging.js +167 -0
  29. package/dist/server/run-access.js +24 -0
  30. package/dist/server/run-artifacts.js +171 -0
  31. package/dist/server/run-worker.js +29 -0
  32. package/dist/server/runs.js +8 -0
  33. package/dist/server/sandbox-files.js +2 -7
  34. package/dist/server/sandboxes-api.js +54 -8
  35. package/dist/server/server-config.js +14 -0
  36. package/dist/server/server.js +122 -27
  37. package/dist/server/task-order.js +56 -0
  38. package/dist/utils/project-path.js +20 -0
  39. package/dist/utils/tar.js +37 -1
  40. package/package.json +1 -1
  41. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -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
@@ -1,26 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HASH_PATTERN = exports.hashBundle = exports.bundleSchema = exports.annotationsSchema = exports.MAX_ANNOTATIONS = exports.isBundlePath = exports.MAX_BUNDLE_BYTES = exports.MAX_BUNDLE_FILES = exports.DEFAULT_ENTRY = void 0;
3
+ exports.HASH_PATTERN = exports.hashBundle = exports.bundleSchema = exports.annotationsSchema = exports.ANNOTATION_KEY_PATTERN = exports.MAX_ANNOTATIONS = exports.isBundlePath = exports.MAX_BUNDLE_BYTES = exports.MAX_BUNDLE_FILES = exports.DEFAULT_ENTRY = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const zod_1 = require("zod");
6
+ const project_path_1 = require("../utils/project-path");
6
7
  exports.DEFAULT_ENTRY = '.hammerkit.yaml';
7
8
  exports.MAX_BUNDLE_FILES = 200;
8
9
  exports.MAX_BUNDLE_BYTES = 1024 * 1024;
9
10
  // A path inside the bundle: relative, forward slashes, nothing that climbs out.
10
11
  function isBundlePath(path) {
11
- return (path.length > 0 &&
12
- path.length <= 200 &&
13
- !path.startsWith('/') &&
14
- !path.includes('\\') &&
15
- !path.includes('\0') &&
16
- !path.split('/').some((part) => part === '' || part === '.' || part === '..'));
12
+ return (0, project_path_1.isRelativePath)(path, 200);
17
13
  }
18
14
  exports.isBundlePath = isBundlePath;
19
15
  exports.MAX_ANNOTATIONS = 20;
16
+ // the key of an annotation
17
+ exports.ANNOTATION_KEY_PATTERN = /^[a-z][a-z0-9._-]{0,63}$/;
20
18
  exports.annotationsSchema = zod_1.z
21
19
  .record(zod_1.z
22
20
  .string()
23
- .regex(/^[a-z][a-z0-9._-]{0,63}$/, 'use lower case letters, digits, ".", "_" and "-", starting with a letter'), zod_1.z.string().min(1).max(500))
21
+ .regex(exports.ANNOTATION_KEY_PATTERN, 'use lower case letters, digits, ".", "_" and "-", starting with a letter'), zod_1.z.string().min(1).max(500))
24
22
  .refine((annotations) => Object.keys(annotations).length <= exports.MAX_ANNOTATIONS, {
25
23
  message: `at most ${exports.MAX_ANNOTATIONS} annotations`,
26
24
  });
@@ -15,9 +15,10 @@ const bundle_1 = require("./bundle");
15
15
  // where a file really is too: a link to a file outside of the directory is refused
16
16
  // rather than followed, so publishing a checkout never sends a file of this machine
17
17
  // that the checkout only points to.
18
- async function collectBundle(fileName, environment) {
18
+ // `missing` is what to do when there is no build file, said after that.
19
+ async function collectBundle(fileName, environment, options = {}) {
19
20
  if (!(await environment.file.exists(fileName))) {
20
- throw new Error(`there is no build file at ${fileName}`);
21
+ throw new Error(`there is no build file at ${fileName}${options.missing ? `. ${options.missing}` : ''}`);
21
22
  }
22
23
  const entryPath = (0, path_1.resolve)(fileName);
23
24
  const root = (0, path_1.dirname)(entryPath);
@@ -3,23 +3,28 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.registerWorkCommands = exports.describePlan = exports.describeApproval = exports.keepRuns = exports.describeListedRun = exports.describeRunEnd = void 0;
6
+ exports.registerWorkCommands = exports.describeArtifacts = exports.selectArtifacts = exports.keptProjectOutputs = exports.isProjectPath = exports.describePlan = exports.describeApproval = exports.keepRuns = exports.describeListedRun = exports.describeRunEnd = void 0;
7
7
  const commander_1 = require("commander");
8
8
  const colors_1 = __importDefault(require("colors"));
9
9
  const token_source_1 = require("./token-source");
10
10
  const collect_bundle_1 = require("./collect-bundle");
11
11
  const bundle_1 = require("./bundle");
12
12
  const annotations_1 = require("./annotations");
13
+ const repo_1 = require("../server/repo");
13
14
  const server_client_1 = require("./server-client");
14
15
  const bundle_text_1 = require("./bundle-text");
15
16
  const sandbox_client_1 = require("../harness/sandbox-client");
16
17
  const units_1 = require("../utils/units");
17
18
  const service_tools_1 = require("../harness/service-tools");
18
19
  const path_1 = require("path");
20
+ const promises_1 = require("fs/promises");
21
+ const os_1 = require("os");
22
+ const tar_1 = require("../utils/tar");
19
23
  const check_keys_1 = require("../optimizer/check-keys");
20
24
  const remote_status_1 = require("./remote-status");
21
25
  const timings_1 = require("../server/timings");
22
26
  const terminal_prompt_1 = require("../utils/terminal-prompt");
27
+ const project_path_1 = require("../utils/project-path");
23
28
  function describeOutcome(planned) {
24
29
  switch (planned.outcome) {
25
30
  case 'published':
@@ -169,21 +174,128 @@ function describePlan(plan) {
169
174
  ]);
170
175
  }
171
176
  exports.describePlan = describePlan;
177
+ // A path in the project, as the server names an output: relative, `/` separated, no `.` or
178
+ // `..` in it. A file is written at it.
179
+ function isProjectPath(path) {
180
+ return (0, project_path_1.isRelativePath)(path, 4096);
181
+ }
182
+ exports.isProjectPath = isProjectPath;
183
+ // `--path` as written: `./app/screenshots/` is `app/screenshots`
184
+ function projectPath(value) {
185
+ const path = path_1.posix
186
+ .normalize(value.replace(/\\/g, '/'))
187
+ .replace(/^(\.\/)+/, '')
188
+ .replace(/\/+$/, '');
189
+ if (!isProjectPath(path)) {
190
+ throw new Error('--path is a path in the project, such as app/cypress/screenshots');
191
+ }
192
+ return path;
193
+ }
194
+ // The outputs a server names that are paths in the project: one that is not is written nowhere,
195
+ // whatever the server says of it.
196
+ function keptProjectOutputs(outputs) {
197
+ return outputs.filter((output) => isProjectPath(output.path));
198
+ }
199
+ exports.keptProjectOutputs = keptProjectOutputs;
200
+ /**
201
+ * The outputs `remote artifacts` takes, each with what of it: of one task, and the output at a
202
+ * path, the outputs below it, or the files below it of the output it is in.
203
+ */
204
+ function selectArtifacts(outputs, options) {
205
+ return outputs
206
+ .filter((output) => options.task === undefined || output.task === options.task)
207
+ .flatMap((output) => {
208
+ const path = options.path;
209
+ if (path === undefined || output.path.startsWith(`${path}/`)) {
210
+ return [{ output, below: output.path }];
211
+ }
212
+ return path === output.path || path.startsWith(`${output.path}/`) ? [{ output, below: path }] : [];
213
+ });
214
+ }
215
+ exports.selectArtifacts = selectArtifacts;
216
+ // Writes the chosen outputs into `out`, each at its paths in the project. Only entries of the
217
+ // output, or of the path asked for, are written, and no link out of them: the archives come
218
+ // from a server.
219
+ async function downloadArtifacts(connection, id, chosen, out, write) {
220
+ const staging = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-artifacts-'));
221
+ try {
222
+ await (0, promises_1.mkdir)(out, { recursive: true });
223
+ for (const { output, below } of chosen) {
224
+ const file = (0, path_1.join)(staging, `${output.id}.tgz`);
225
+ await (0, sandbox_client_1.downloadRunArtifact)(connection, id, output.id, file);
226
+ await (0, tar_1.extractOutput)(file, out, below, true);
227
+ write(`${(0, server_client_1.printable)(below)} of ${(0, server_client_1.printable)(output.task)} -> ${(0, path_1.join)(out, below)}`);
228
+ }
229
+ }
230
+ finally {
231
+ await (0, promises_1.rm)(staging, { recursive: true, force: true });
232
+ }
233
+ }
234
+ function describeArtifacts(id, serverName, kept, outputs) {
235
+ const left = kept.left.map((output) => `did not keep ${(0, server_client_1.printable)(output.path)} of ${(0, server_client_1.printable)(output.task)}: ${(0, server_client_1.printable)(output.reason)}`);
236
+ if (outputs.length === 0) {
237
+ return [
238
+ `${(0, server_client_1.printable)(id)} on ${serverName} kept no outputs${kept.reason ? `: ${(0, server_client_1.printable)(kept.reason)}` : ''}`,
239
+ ...left,
240
+ ];
241
+ }
242
+ const tasks = Math.max(...outputs.map((output) => (0, server_client_1.printable)(output.task).length));
243
+ const paths = Math.max(...outputs.map((output) => (0, server_client_1.printable)(output.path).length));
244
+ return [
245
+ `${(0, server_client_1.printable)(id)} on ${serverName} kept ${outputs.length} ${outputs.length === 1 ? 'output' : 'outputs'}, until ${(0, server_client_1.printable)(kept.expiresAt ?? '-')}:`,
246
+ ...outputs.map((output) => ` ${(0, server_client_1.printable)(output.task).padEnd(tasks)} ${(0, server_client_1.printable)(output.path).padEnd(paths)} ${(0, units_1.formatSize)(output.bytes)}`),
247
+ ...left,
248
+ `download them with: hammerkit remote artifacts ${(0, server_client_1.printable)(id)} --out <dir>`,
249
+ ];
250
+ }
251
+ exports.describeArtifacts = describeArtifacts;
252
+ // The ref of a detached checkout: the one branch or tag of origin at its commit. The server
253
+ // would also fetch the commit itself, but an account limited to some branches (`refs`) never
254
+ // runs for a commit, and the run would not say where its code comes from. A branch and a tag
255
+ // of the same name are two heads, which the server can not tell apart by the name.
256
+ function onlyHead(heads) {
257
+ return heads?.length === 1 ? heads[0].name : undefined;
258
+ }
259
+ // why the ref of a run is not known, and what to do
260
+ function describeMissingRef(repo, ours, checkout) {
261
+ if (!checkout.commit) {
262
+ return `name the branch or tag of ${(0, server_client_1.printable)(repo)} with --ref, there is no commit checked out here`;
263
+ }
264
+ if (!ours) {
265
+ return `name the branch or tag of ${(0, server_client_1.printable)(repo)} with --ref, the checkout here is on no branch and ${checkout.repo ? `of ${(0, server_client_1.printable)(checkout.repo)}` : 'has no origin it can be told by'}`;
266
+ }
267
+ const heads = checkout.heads ?? [];
268
+ if (heads.length === 0) {
269
+ return (`the checkout here is on no branch, and no branch or tag of origin is at its commit ${checkout.commit}: ` +
270
+ 'name the branch or tag with --ref');
271
+ }
272
+ const names = heads.map((head) => `${head.kind} ${(0, server_client_1.printable)(head.name)}`);
273
+ const twice = heads.find((head, i) => heads.findIndex((other) => other.name === head.name) !== i);
274
+ return (`the checkout here is on no branch, and its commit ${checkout.commit} is the head of ` +
275
+ `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]} of origin: ` +
276
+ (twice
277
+ ? `${(0, server_client_1.printable)(twice.name)} is a branch and a tag, which --ref can not tell apart: ` +
278
+ `name another, or the commit with --ref ${checkout.commit}`
279
+ : 'name one with --ref'));
280
+ }
172
281
  function registerWorkCommands(remote, context) {
173
282
  const { environment, buildFile, getServer, guarded, passthrough, fail } = context;
174
283
  // the ref a run starts from: what the options name, else the checkout here
175
284
  const refSource = async (options) => {
176
285
  const checkout = options.repo && options.ref ? {} : await (0, annotations_1.readCheckout)((0, path_1.dirname)(buildFile));
177
286
  const repo = options.repo ?? checkout.repo;
178
- const ref = options.ref ?? checkout.branch;
179
- // the commit checked out here is the code meant, when the ref is the branch it is on
180
- const commit = options.commit ?? (options.ref ? undefined : checkout.commit);
181
287
  if (!repo) {
182
288
  throw new Error('name the repository with --repo, the checkout here has no origin it can be told by');
183
289
  }
290
+ // the heads of origin name refs of the repository of the run only when origin is that one
291
+ const ours = !!checkout.repo && (0, repo_1.normalizeRepo)(repo) === checkout.repo;
292
+ const ref = options.ref ?? checkout.branch ?? (ours ? onlyHead(checkout.heads) : undefined);
184
293
  if (!ref) {
185
- throw new Error('name the branch or tag with --ref, the checkout here is on no branch');
294
+ throw new Error(describeMissingRef(repo, ours, checkout));
186
295
  }
296
+ // the commit checked out here is the code meant, when the ref is the branch it is on, or
297
+ // the one branch or tag of a detached checkout: when it moved since, the server refuses the run
298
+ const commit = options.commit ?? (options.ref ? undefined : checkout.commit);
187
299
  return { type: 'ref', repo, ref, ...(commit ? { commit } : {}) };
188
300
  };
189
301
  const connect = async (name, how) => {
@@ -246,7 +358,11 @@ function registerWorkCommands(remote, context) {
246
358
  }
247
359
  return { definition: named };
248
360
  }
249
- const local = await (0, collect_bundle_1.collectBundle)(buildFile, environment);
361
+ const local = await (0, collect_bundle_1.collectBundle)(buildFile, environment, {
362
+ // most often run in another folder than the checkout meant
363
+ missing: 'Run this in the checkout whose build file the server has, ' +
364
+ 'or name a published version with --build <hash>, listed by: hammerkit remote versions',
365
+ });
250
366
  return { definition: (0, bundle_1.hashBundle)(local), local };
251
367
  };
252
368
  // Submits a run of a published version. When the server does not have the build file
@@ -343,7 +459,8 @@ function registerWorkCommands(remote, context) {
343
459
  .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
344
460
  .addOption(new commander_1.Option('--build <hash>', 'the published version to run (sha256:...), or HAMMERKIT_BUILD; the hash of the build file here when left out'))
345
461
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
346
- .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out'))
462
+ .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out, ' +
463
+ 'or the one branch or tag of origin at the commit of a detached checkout'))
347
464
  .addOption(new commander_1.Option('--commit <sha>', 'the commit the ref has to be at, else the run is refused; the commit checked out here when --ref is left out'))
348
465
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
349
466
  .addOption(new commander_1.Option('--cache <method>', 'as --cache of run').choices(['checksum', 'modify-date', 'none']))
@@ -416,7 +533,8 @@ function registerWorkCommands(remote, context) {
416
533
  'starts other services or another build file; the addresses stay; the branch when left out'))
417
534
  .addOption(new commander_1.Option('--build <hash>', 'the published version to run (sha256:...), or HAMMERKIT_BUILD; the hash of the build file here when left out'))
418
535
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository; origin of the checkout here when left out'))
419
- .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to start; the branch checked out here when left out'))
536
+ .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to start; the branch checked out here when left out, ' +
537
+ 'or the one branch or tag of origin at the commit of a detached checkout'))
420
538
  .addOption(new commander_1.Option('--commit <sha>', 'the commit the ref has to be at; the commit checked out here when --ref is left out'))
421
539
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
422
540
  .addOption(new commander_1.Option('--publish', 'publish the build file here first when the server does not have it, without asking; for CI and scripts'))
@@ -663,6 +781,41 @@ function registerWorkCommands(remote, context) {
663
781
  environment.stdout.write(`${(0, server_client_1.printable)(run.id)} is ${(0, server_client_1.printable)(run.state)}, follow it with --follow\n`);
664
782
  }
665
783
  }));
784
+ remote
785
+ .command('artifacts <run> [server]')
786
+ .description('list or download the outputs the tasks of a run that ended export (generates with export: true, ' +
787
+ 'or export: always also of a task that failed); none of a run in which anything reads a secret')
788
+ .addOption(new commander_1.Option('--task <name>', 'only the outputs of this task'))
789
+ .addOption(new commander_1.Option('--path <path>', 'only the output at this path in the project, or the files of one below it'))
790
+ .addOption(new commander_1.Option('--out <dir>', 'download them into this directory, at their paths in the project; else they are listed'))
791
+ .action(guarded('Remote artifacts was not successful', async (id, name, options) => {
792
+ if (!RUN_ID.test(id)) {
793
+ throw new Error(`${(0, server_client_1.printable)(id)} is not a run id (run_...), list them with: hammerkit remote runs`);
794
+ }
795
+ const path = options.path === undefined ? undefined : projectPath(options.path);
796
+ const { name: serverName, server } = await getServer(name);
797
+ const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
798
+ const kept = await (0, sandbox_client_1.getRunArtifacts)(connection, id);
799
+ if (!kept) {
800
+ throw new Error(`${serverName} keeps no run ${(0, server_client_1.printable)(id)} you may see, list them with: hammerkit remote runs`);
801
+ }
802
+ const outputs = keptProjectOutputs(kept.outputs);
803
+ const chosen = selectArtifacts(outputs, { task: options.task, path });
804
+ const selecting = options.task !== undefined || path !== undefined;
805
+ if (chosen.length === 0 && selecting) {
806
+ const all = outputs.map((output) => (0, server_client_1.printable)(output.path)).join(' and ') || 'nothing';
807
+ throw new Error(`the run kept nothing ${path !== undefined ? `at or below ${(0, server_client_1.printable)(path)}` : `of ${(0, server_client_1.printable)(options.task)}`}, it kept ${all}`);
808
+ }
809
+ // nothing to download (or no --out): the listing, before anything is made
810
+ if (options.out === undefined || chosen.length === 0) {
811
+ const shown = selecting ? chosen.map(({ output }) => output) : outputs;
812
+ for (const line of describeArtifacts(id, serverName, kept, shown)) {
813
+ environment.stdout.write(`${line}\n`);
814
+ }
815
+ return;
816
+ }
817
+ await downloadArtifacts(connection, id, chosen, (0, path_1.resolve)(environment.cwd, options.out), (line) => environment.stdout.write(`${line}\n`));
818
+ }));
666
819
  remote
667
820
  .command('extend <run> <ttl> [server]')
668
821
  .description('keep a service run that is up for this long from now, such as 8h, at most the maxTtl of the server')
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleArtifacts = void 0;
4
+ const promises_1 = require("stream/promises");
5
+ const http_1 = require("./http");
6
+ const run_access_1 = require("./run-access");
7
+ const runs_1 = require("./runs");
8
+ /**
9
+ * The outputs a run's tasks exported, kept by the server once the run ended (ArtifactStore):
10
+ *
11
+ * GET /v1/runs/<id>/artifacts what it kept, by number, until when, or why it kept none
12
+ * GET /v1/runs/<id>/artifacts/<n> one of them, a gzipped tar of its paths in the project
13
+ *
14
+ * Who may read the run's log may read them (its owner, who decided about it, `observe`): a
15
+ * task could print what it writes there into its log all the same. What a credential can
16
+ * reach is never kept (refuseArtifacts).
17
+ */
18
+ async function handleArtifacts(config, registry, artifacts, log, principal, req, res, url, now) {
19
+ const match = /^\/v1\/runs\/([^/]+)\/artifacts(?:\/([^/]+))?$/.exec(url.pathname);
20
+ if (!match) {
21
+ return false;
22
+ }
23
+ const [, id, output] = match;
24
+ if (req.method !== 'GET') {
25
+ (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
26
+ return true;
27
+ }
28
+ const run = (0, run_access_1.findReadableRun)(config, registry, principal, id);
29
+ if (!run || (output !== undefined && !/^\d{1,6}$/.test(output))) {
30
+ (0, http_1.send)(res, 404, { error: 'not found' });
31
+ return true;
32
+ }
33
+ if (!(0, runs_1.isFinal)(run.state)) {
34
+ (0, http_1.send)(res, 409, { error: `the run is ${run.state}, what it keeps is there once it ended` });
35
+ return true;
36
+ }
37
+ if (output === undefined) {
38
+ (0, http_1.send)(res, 200, await artifacts.read(run, now()));
39
+ return true;
40
+ }
41
+ const opened = await artifacts.open(run, Number(output), now());
42
+ if (!opened) {
43
+ (0, http_1.send)(res, 404, { error: 'not found' });
44
+ return true;
45
+ }
46
+ log(`artifacts iss=${principal.iss} sub=${principal.sub} run=${run.id} output=${output}`);
47
+ res.writeHead(200, {
48
+ 'content-type': 'application/gzip',
49
+ 'content-length': String(opened.bytes),
50
+ 'cache-control': 'no-store',
51
+ });
52
+ await (0, promises_1.pipeline)(opened.stream(), res).catch(() => res.destroy());
53
+ return true;
54
+ }
55
+ exports.handleArtifacts = handleArtifacts;
56
+ //# sourceMappingURL=artifacts-api.js.map