hammerkit 2.1.0-next.11 → 2.1.0-next.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/executer/archive-task-entry.js +1 -1
  2. package/dist/executer/deadline.js +63 -10
  3. package/dist/executer/event-cache.js +5 -1
  4. package/dist/executer/execute-work-task.js +15 -3
  5. package/dist/file/get-file-context.js +4 -7
  6. package/dist/harness/connect.js +10 -7
  7. package/dist/harness/reconnect.js +137 -0
  8. package/dist/harness/sandbox-client.js +117 -25
  9. package/dist/kubernetes/cluster-state.js +48 -14
  10. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  11. package/dist/kubernetes/resources.js +5 -1
  12. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  13. package/dist/planner/work-runtime-aggregate.js +1 -0
  14. package/dist/planner/work-runtime-docker.js +9 -5
  15. package/dist/planner/work-runtime-kubernetes.js +6 -4
  16. package/dist/planner/work-runtime-local.js +8 -4
  17. package/dist/remote/annotations.js +29 -3
  18. package/dist/remote/bundle.js +2 -6
  19. package/dist/remote/collect-bundle.js +3 -2
  20. package/dist/remote/remote-work-commands.js +179 -15
  21. package/dist/server/artifacts-api.js +56 -0
  22. package/dist/server/executor.js +17 -0
  23. package/dist/server/http.js +4 -1
  24. package/dist/server/keep-artifacts.js +230 -0
  25. package/dist/server/run-access.js +24 -0
  26. package/dist/server/run-artifacts.js +171 -0
  27. package/dist/server/run-worker.js +29 -0
  28. package/dist/server/runs.js +18 -2
  29. package/dist/server/sandbox-files.js +2 -7
  30. package/dist/server/server-config.js +14 -0
  31. package/dist/server/server.js +49 -15
  32. package/dist/utils/project-path.js +20 -0
  33. package/dist/utils/tar.js +37 -1
  34. package/package.json +1 -1
@@ -3,23 +3,29 @@ 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");
19
+ const reconnect_1 = require("../harness/reconnect");
18
20
  const path_1 = require("path");
21
+ const promises_1 = require("fs/promises");
22
+ const os_1 = require("os");
23
+ const tar_1 = require("../utils/tar");
19
24
  const check_keys_1 = require("../optimizer/check-keys");
20
25
  const remote_status_1 = require("./remote-status");
21
26
  const timings_1 = require("../server/timings");
22
27
  const terminal_prompt_1 = require("../utils/terminal-prompt");
28
+ const project_path_1 = require("../utils/project-path");
23
29
  function describeOutcome(planned) {
24
30
  switch (planned.outcome) {
25
31
  case 'published':
@@ -169,21 +175,136 @@ function describePlan(plan) {
169
175
  ]);
170
176
  }
171
177
  exports.describePlan = describePlan;
178
+ // A path in the project, as the server names an output: relative, `/` separated, no `.` or
179
+ // `..` in it. A file is written at it.
180
+ function isProjectPath(path) {
181
+ return (0, project_path_1.isRelativePath)(path, 4096);
182
+ }
183
+ exports.isProjectPath = isProjectPath;
184
+ // `--path` as written: `./app/screenshots/` is `app/screenshots`
185
+ function projectPath(value) {
186
+ const path = path_1.posix
187
+ .normalize(value.replace(/\\/g, '/'))
188
+ .replace(/^(\.\/)+/, '')
189
+ .replace(/\/+$/, '');
190
+ if (!isProjectPath(path)) {
191
+ throw new Error('--path is a path in the project, such as app/cypress/screenshots');
192
+ }
193
+ return path;
194
+ }
195
+ // The outputs a server names that are paths in the project: one that is not is written nowhere,
196
+ // whatever the server says of it.
197
+ function keptProjectOutputs(outputs) {
198
+ return outputs.filter((output) => isProjectPath(output.path));
199
+ }
200
+ exports.keptProjectOutputs = keptProjectOutputs;
201
+ /**
202
+ * The outputs `remote artifacts` takes, each with what of it: of one task, and the output at a
203
+ * path, the outputs below it, or the files below it of the output it is in.
204
+ */
205
+ function selectArtifacts(outputs, options) {
206
+ return outputs
207
+ .filter((output) => options.task === undefined || output.task === options.task)
208
+ .flatMap((output) => {
209
+ const path = options.path;
210
+ if (path === undefined || output.path.startsWith(`${path}/`)) {
211
+ return [{ output, below: output.path }];
212
+ }
213
+ return path === output.path || path.startsWith(`${output.path}/`) ? [{ output, below: path }] : [];
214
+ });
215
+ }
216
+ exports.selectArtifacts = selectArtifacts;
217
+ // Writes the chosen outputs into `out`, each at its paths in the project. Only entries of the
218
+ // output, or of the path asked for, are written, and no link out of them: the archives come
219
+ // from a server.
220
+ async function downloadArtifacts(connection, id, chosen, out, write) {
221
+ const staging = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-artifacts-'));
222
+ try {
223
+ await (0, promises_1.mkdir)(out, { recursive: true });
224
+ for (const { output, below } of chosen) {
225
+ const file = (0, path_1.join)(staging, `${output.id}.tgz`);
226
+ await (0, sandbox_client_1.downloadRunArtifact)(connection, id, output.id, file);
227
+ await (0, tar_1.extractOutput)(file, out, below, true);
228
+ write(`${(0, server_client_1.printable)(below)} of ${(0, server_client_1.printable)(output.task)} -> ${(0, path_1.join)(out, below)}`);
229
+ }
230
+ }
231
+ finally {
232
+ await (0, promises_1.rm)(staging, { recursive: true, force: true });
233
+ }
234
+ }
235
+ function describeArtifacts(id, serverName, kept, outputs) {
236
+ 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)}`);
237
+ if (outputs.length === 0) {
238
+ return [
239
+ `${(0, server_client_1.printable)(id)} on ${serverName} kept no outputs${kept.reason ? `: ${(0, server_client_1.printable)(kept.reason)}` : ''}`,
240
+ ...left,
241
+ ];
242
+ }
243
+ const tasks = Math.max(...outputs.map((output) => (0, server_client_1.printable)(output.task).length));
244
+ const paths = Math.max(...outputs.map((output) => (0, server_client_1.printable)(output.path).length));
245
+ return [
246
+ `${(0, server_client_1.printable)(id)} on ${serverName} kept ${outputs.length} ${outputs.length === 1 ? 'output' : 'outputs'}, until ${(0, server_client_1.printable)(kept.expiresAt ?? '-')}:`,
247
+ ...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)}`),
248
+ ...left,
249
+ `download them with: hammerkit remote artifacts ${(0, server_client_1.printable)(id)} --out <dir>`,
250
+ ];
251
+ }
252
+ exports.describeArtifacts = describeArtifacts;
253
+ // The ref of a detached checkout: the one branch or tag of origin at its commit. The server
254
+ // would also fetch the commit itself, but an account limited to some branches (`refs`) never
255
+ // runs for a commit, and the run would not say where its code comes from. A branch and a tag
256
+ // of the same name are two heads, which the server can not tell apart by the name.
257
+ function onlyHead(heads) {
258
+ return heads?.length === 1 ? heads[0].name : undefined;
259
+ }
260
+ // why the ref of a run is not known, and what to do
261
+ function describeMissingRef(repo, ours, checkout) {
262
+ if (!checkout.commit) {
263
+ return `name the branch or tag of ${(0, server_client_1.printable)(repo)} with --ref, there is no commit checked out here`;
264
+ }
265
+ if (!ours) {
266
+ 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'}`;
267
+ }
268
+ const heads = checkout.heads ?? [];
269
+ if (heads.length === 0) {
270
+ return (`the checkout here is on no branch, and no branch or tag of origin is at its commit ${checkout.commit}: ` +
271
+ 'name the branch or tag with --ref');
272
+ }
273
+ const names = heads.map((head) => `${head.kind} ${(0, server_client_1.printable)(head.name)}`);
274
+ const twice = heads.find((head, i) => heads.findIndex((other) => other.name === head.name) !== i);
275
+ return (`the checkout here is on no branch, and its commit ${checkout.commit} is the head of ` +
276
+ `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]} of origin: ` +
277
+ (twice
278
+ ? `${(0, server_client_1.printable)(twice.name)} is a branch and a tag, which --ref can not tell apart: ` +
279
+ `name another, or the commit with --ref ${checkout.commit}`
280
+ : 'name one with --ref'));
281
+ }
282
+ // A call the server refused, said as `callServer` says it: by the server and what it answered
283
+ function describeRefusal(url, e) {
284
+ if (!(e instanceof sandbox_client_1.SandboxClientError) || e.status === undefined || e.status === 401) {
285
+ return e;
286
+ }
287
+ const said = e.message.startsWith(`${(0, reconnect_1.showUrl)(url)} answered`) ? '' : `: ${(0, server_client_1.printable)(e.message)}`;
288
+ return new server_client_1.ServerError(`${(0, reconnect_1.showUrl)(url)} answered ${e.status}${said}`, e.status);
289
+ }
172
290
  function registerWorkCommands(remote, context) {
173
291
  const { environment, buildFile, getServer, guarded, passthrough, fail } = context;
174
292
  // the ref a run starts from: what the options name, else the checkout here
175
293
  const refSource = async (options) => {
176
294
  const checkout = options.repo && options.ref ? {} : await (0, annotations_1.readCheckout)((0, path_1.dirname)(buildFile));
177
295
  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
296
  if (!repo) {
182
297
  throw new Error('name the repository with --repo, the checkout here has no origin it can be told by');
183
298
  }
299
+ // the heads of origin name refs of the repository of the run only when origin is that one
300
+ const ours = !!checkout.repo && (0, repo_1.normalizeRepo)(repo) === checkout.repo;
301
+ const ref = options.ref ?? checkout.branch ?? (ours ? onlyHead(checkout.heads) : undefined);
184
302
  if (!ref) {
185
- throw new Error('name the branch or tag with --ref, the checkout here is on no branch');
303
+ throw new Error(describeMissingRef(repo, ours, checkout));
186
304
  }
305
+ // the commit checked out here is the code meant, when the ref is the branch it is on, or
306
+ // the one branch or tag of a detached checkout: when it moved since, the server refuses the run
307
+ const commit = options.commit ?? (options.ref ? undefined : checkout.commit);
187
308
  return { type: 'ref', repo, ref, ...(commit ? { commit } : {}) };
188
309
  };
189
310
  const connect = async (name, how) => {
@@ -246,7 +367,11 @@ function registerWorkCommands(remote, context) {
246
367
  }
247
368
  return { definition: named };
248
369
  }
249
- const local = await (0, collect_bundle_1.collectBundle)(buildFile, environment);
370
+ const local = await (0, collect_bundle_1.collectBundle)(buildFile, environment, {
371
+ // most often run in another folder than the checkout meant
372
+ missing: 'Run this in the checkout whose build file the server has, ' +
373
+ 'or name a published version with --build <hash>, listed by: hammerkit remote versions',
374
+ });
250
375
  return { definition: (0, bundle_1.hashBundle)(local), local };
251
376
  };
252
377
  // Submits a run of a published version. When the server does not have the build file
@@ -343,7 +468,8 @@ function registerWorkCommands(remote, context) {
343
468
  .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
469
  .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
470
  .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'))
471
+ .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out, ' +
472
+ 'or the one branch or tag of origin at the commit of a detached checkout'))
347
473
  .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
474
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
349
475
  .addOption(new commander_1.Option('--cache <method>', 'as --cache of run').choices(['checksum', 'modify-date', 'none']))
@@ -356,7 +482,7 @@ function registerWorkCommands(remote, context) {
356
482
  const source = await refSource(options);
357
483
  const ref = source.ref;
358
484
  const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
359
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
485
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
360
486
  const runOptions = {};
361
487
  for (const key of ['env', 'cache', 'timeout', 'maxTimeout']) {
362
488
  if (options[key] !== undefined) {
@@ -416,7 +542,8 @@ function registerWorkCommands(remote, context) {
416
542
  'starts other services or another build file; the addresses stay; the branch when left out'))
417
543
  .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
544
  .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'))
545
+ .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to start; the branch checked out here when left out, ' +
546
+ 'or the one branch or tag of origin at the commit of a detached checkout'))
420
547
  .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
548
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
422
549
  .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'))
@@ -425,7 +552,7 @@ function registerWorkCommands(remote, context) {
425
552
  const endpoints = (options.endpoint ?? []).map(service_tools_1.parseEndpoint);
426
553
  const source = await refSource(options);
427
554
  const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
428
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
555
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
429
556
  const submitted = await submitPublishing({ serverName, server, connection }, {
430
557
  definition,
431
558
  services,
@@ -632,7 +759,7 @@ function registerWorkCommands(remote, context) {
632
759
  throw new Error('--follow prints the whole log, leave --tail out');
633
760
  }
634
761
  const { name: serverName, server } = await getServer(name);
635
- const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
762
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
636
763
  const found = await (0, sandbox_client_1.getRun)(connection, id);
637
764
  if (!found) {
638
765
  throw new Error(`${serverName} keeps no run ${(0, server_client_1.printable)(id)} you may see, list them with: hammerkit remote runs`);
@@ -663,6 +790,41 @@ function registerWorkCommands(remote, context) {
663
790
  environment.stdout.write(`${(0, server_client_1.printable)(run.id)} is ${(0, server_client_1.printable)(run.state)}, follow it with --follow\n`);
664
791
  }
665
792
  }));
793
+ remote
794
+ .command('artifacts <run> [server]')
795
+ .description('list or download the outputs the tasks of a run that ended export (generates with export: true, ' +
796
+ 'or export: always also of a task that failed); none of a run in which anything reads a secret')
797
+ .addOption(new commander_1.Option('--task <name>', 'only the outputs of this task'))
798
+ .addOption(new commander_1.Option('--path <path>', 'only the output at this path in the project, or the files of one below it'))
799
+ .addOption(new commander_1.Option('--out <dir>', 'download them into this directory, at their paths in the project; else they are listed'))
800
+ .action(guarded('Remote artifacts was not successful', async (id, name, options) => {
801
+ if (!RUN_ID.test(id)) {
802
+ throw new Error(`${(0, server_client_1.printable)(id)} is not a run id (run_...), list them with: hammerkit remote runs`);
803
+ }
804
+ const path = options.path === undefined ? undefined : projectPath(options.path);
805
+ const { name: serverName, server } = await getServer(name);
806
+ const connection = (0, sandbox_client_1.getServerConnection)(environment, serverName, server);
807
+ const kept = await (0, sandbox_client_1.getRunArtifacts)(connection, id);
808
+ if (!kept) {
809
+ throw new Error(`${serverName} keeps no run ${(0, server_client_1.printable)(id)} you may see, list them with: hammerkit remote runs`);
810
+ }
811
+ const outputs = keptProjectOutputs(kept.outputs);
812
+ const chosen = selectArtifacts(outputs, { task: options.task, path });
813
+ const selecting = options.task !== undefined || path !== undefined;
814
+ if (chosen.length === 0 && selecting) {
815
+ const all = outputs.map((output) => (0, server_client_1.printable)(output.path)).join(' and ') || 'nothing';
816
+ 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}`);
817
+ }
818
+ // nothing to download (or no --out): the listing, before anything is made
819
+ if (options.out === undefined || chosen.length === 0) {
820
+ const shown = selecting ? chosen.map(({ output }) => output) : outputs;
821
+ for (const line of describeArtifacts(id, serverName, kept, shown)) {
822
+ environment.stdout.write(`${line}\n`);
823
+ }
824
+ return;
825
+ }
826
+ await downloadArtifacts(connection, id, chosen, (0, path_1.resolve)(environment.cwd, options.out), (line) => environment.stdout.write(`${line}\n`));
827
+ }));
666
828
  remote
667
829
  .command('extend <run> <ttl> [server]')
668
830
  .description('keep a service run that is up for this long from now, such as 8h, at most the maxTtl of the server')
@@ -723,15 +885,17 @@ function registerWorkCommands(remote, context) {
723
885
  keys.push({ task, key: found.key });
724
886
  }
725
887
  }
726
- const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
888
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
727
889
  const answer = keys.length > 0
728
- ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
729
- : { body: { checks: [] } };
890
+ ? await (0, sandbox_client_1.lookupChecks)((0, sandbox_client_1.getServerConnection)(environment, serverName, server), repo, keys).catch((e) => {
891
+ throw describeRefusal(server.url, e);
892
+ })
893
+ : { checks: [] };
730
894
  const missing = [];
731
895
  // by what was asked, never by what was answered: a task the answer leaves out, or
732
896
  // answers for another key, is not verified
733
897
  for (const { task, key } of keys) {
734
- const check = answer.body.checks.find((answered) => answered.task === task && answered.key === key);
898
+ const check = answer.checks.find((answered) => answered.task === task && answered.key === key);
735
899
  if (check?.passed) {
736
900
  environment.stdout.write(`${(0, server_client_1.printable)(task)}: ${(0, server_client_1.printable)(describePassed(check.passed))}\n`);
737
901
  }
@@ -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
@@ -14,6 +14,7 @@ const run_plan_1 = require("./run-plan");
14
14
  const work_network_1 = require("../planner/work-network");
15
15
  const execute_docker_1 = require("../executer/execute-docker");
16
16
  const run_source_environment_1 = require("./run-source-environment");
17
+ const run_artifacts_1 = require("./run-artifacts");
17
18
  // `.git` as a file system may read it: any case, and a name Windows reads without its
18
19
  // trailing dots and spaces, or by its short name
19
20
  function isGitDirectory(segment) {
@@ -212,6 +213,17 @@ class HostExecutor {
212
213
  if (refused) {
213
214
  throw new Error(refused);
214
215
  }
216
+ // the outputs of a run are not handed out when anything reads a credential, or when the
217
+ // local tasks of this host could write them: then the run keeps none and says why
218
+ const wanted = context.artifacts && !run.up ? context.artifacts : undefined;
219
+ const noArtifacts = wanted ? this.artifactsRefusal(planned.plan) : null;
220
+ const artifacts = noArtifacts ? undefined : wanted;
221
+ if (wanted && noArtifacts) {
222
+ const manifest = { refused: noArtifacts, outputs: [], left: [] };
223
+ await (0, promises_1.mkdir)(wanted.directory, { recursive: true });
224
+ await (0, promises_1.writeFile)((0, path_1.join)(wanted.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
225
+ context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `keeps no outputs: ${noArtifacts}` });
226
+ }
215
227
  const abortCtrl = new AbortController();
216
228
  const abort = () => abortCtrl.abort();
217
229
  if (context.signal.aborted) {
@@ -346,6 +358,7 @@ class HostExecutor {
346
358
  volumeScope: volumeScope(run, this.options.directory),
347
359
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
360
  ...(context.durations ? { durations: context.durations } : {}),
361
+ ...(artifacts ? { artifacts } : {}),
349
362
  catalog: planning.environment.hosted?.catalog,
350
363
  ...(run.up
351
364
  ? {
@@ -380,6 +393,10 @@ class HostExecutor {
380
393
  }
381
394
  }
382
395
  }
396
+ // why a run keeps none of its outputs: a credential its tasks read, or local tasks on this host
397
+ artifactsRefusal(plan) {
398
+ return this.options.localTasksOnHost ? run_artifacts_1.LOCAL_TASKS_REFUSAL : (0, run_artifacts_1.refuseArtifacts)(plan);
399
+ }
383
400
  directoryOf(run) {
384
401
  for (let execution = 1;; execution++) {
385
402
  const root = (0, path_1.join)(this.options.directory, execution === 1 ? run.id : `${run.id}-${execution}`);
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readJson = exports.MAX_BODY_BYTES = exports.HttpError = exports.send = void 0;
3
+ exports.readJson = exports.MAX_BODY_BYTES = exports.HttpError = exports.send = exports.RETRY_HEADER = void 0;
4
+ // Set to `safe` on an answer to a request the server took nothing of, such as a submit while it
5
+ // shuts down: a client may send it again, also a request it never sends twice otherwise.
6
+ exports.RETRY_HEADER = 'hammerkit-retry';
4
7
  function send(res, status, body, headers = {}) {
5
8
  res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers });
6
9
  res.end(JSON.stringify(body));
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keepArtifacts = exports.MAX_OUTPUT_ENTRIES = void 0;
4
+ const fs_1 = require("fs");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const stream_1 = require("stream");
8
+ const promises_2 = require("stream/promises");
9
+ const log_1 = require("../log");
10
+ const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
11
+ const work_task_1 = require("../planner/work-task");
12
+ const tar_1 = require("../utils/tar");
13
+ const units_1 = require("../utils/units");
14
+ const run_artifacts_1 = require("./run-artifacts");
15
+ // The most entries an output may have when it is unpacked: what the server packs again.
16
+ exports.MAX_OUTPUT_ENTRIES = 10000;
17
+ // Why the outputs of a task that came from the cache are not kept: a cache is shared by the
18
+ // runs of the server, and its key holds no value of a secret, so what an entry holds may be
19
+ // what a run that read a secret wrote, and this run may read none.
20
+ const CACHE_REASON = 'it came from the cache: the cache is shared by the runs of this server and its key holds no secret value, ' +
21
+ 'so what it holds may be what a run that read a secret wrote';
22
+ /**
23
+ * Keeps the outputs of the tasks of a run that the build file says to copy out (`export`),
24
+ * as a run on a dev machine copies them out of their containers: those of a task that
25
+ * completed, and those with `export: always` of one that failed too. Each goes through the
26
+ * runtime its task ran on, as `hammerkit store` takes it, and is kept as a gzipped tar of
27
+ * its paths in the project, so a download is laid out the same whatever ran it.
28
+ */
29
+ async function keepArtifacts(workTree, environment, options) {
30
+ const manifest = { outputs: [], left: [] };
31
+ const staging = (0, path_1.join)(options.directory, '.staging');
32
+ await (0, promises_1.mkdir)(staging, { recursive: true });
33
+ // a failed task aborts the run's controller, the archives still have to be made
34
+ const keeping = { ...environment, abortCtrl: new AbortController() };
35
+ let bytes = 0;
36
+ try {
37
+ const tasks = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].sort((a, b) => a.name.localeCompare(b.name));
38
+ for (const task of tasks) {
39
+ for (const generate of getKeptOutputs(task)) {
40
+ const path = toPosix((0, path_1.relative)(options.root, generate.path));
41
+ const file = `${manifest.outputs.length + manifest.left.length}.tgz`;
42
+ const target = (0, path_1.join)(options.directory, file);
43
+ if (options.cancelled()) {
44
+ manifest.left.push({ task: task.name, path, reason: 'the run was cancelled' });
45
+ continue;
46
+ }
47
+ if (isFromCache(task)) {
48
+ manifest.left.push({ task: task.name, path, reason: CACHE_REASON });
49
+ continue;
50
+ }
51
+ try {
52
+ const kept = await keepOutput(task, generate, keeping, {
53
+ staging,
54
+ target,
55
+ root: options.root,
56
+ maxBytes: options.maxBytes,
57
+ remaining: options.maxBytes - bytes,
58
+ });
59
+ if (kept === null) {
60
+ manifest.left.push({ task: task.name, path, reason: 'the task left nothing there' });
61
+ }
62
+ else {
63
+ bytes += kept;
64
+ manifest.outputs.push({ task: task.name, path, file, bytes: kept });
65
+ }
66
+ }
67
+ catch (e) {
68
+ await (0, promises_1.rm)(target, { force: true });
69
+ // what this module says of the limit is ours to say, what else went wrong is redacted
70
+ const reason = e instanceof Refused ? e.message : options.redact((0, log_1.getErrorMessage)(e)).slice(0, 500);
71
+ manifest.left.push({ task: task.name, path, reason });
72
+ }
73
+ }
74
+ }
75
+ }
76
+ finally {
77
+ await (0, promises_1.rm)(staging, { recursive: true, force: true });
78
+ }
79
+ await (0, promises_1.writeFile)((0, path_1.join)(options.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
80
+ return manifest;
81
+ }
82
+ exports.keepArtifacts = keepArtifacts;
83
+ // The outputs of a task a run may keep: what its build file exports, of a task that completed,
84
+ // and what it exports always of one that failed. What it inherits is its dependency's to keep.
85
+ // A task that was skipped, as nothing needed it, has none. Those of a task that came from the
86
+ // cache are candidates too, and are refused in keepArtifacts (isFromCache).
87
+ function getKeptOutputs(task) {
88
+ const state = task.state.current;
89
+ if ((0, work_task_1.isAggregateTask)(task.data)) {
90
+ return [];
91
+ }
92
+ const completed = state.type === 'completed' && !state.skipped;
93
+ const failed = state.type === 'crash' || state.type === 'error';
94
+ return task.data.generates.filter((generate) => !generate.inherited && (generate.exportAlways || (generate.export && completed)) && (completed || failed));
95
+ }
96
+ function isFromCache(task) {
97
+ const state = task.state.current;
98
+ return state.type === 'completed' && !!state.cached;
99
+ }
100
+ // A refusal of one output, with what the run may say of it.
101
+ class Refused extends Error {
102
+ }
103
+ function overBudget(maxBytes, detail) {
104
+ return `more than the ${(0, units_1.formatSize)(maxBytes)} a run keeps (runs.artifacts.maxBytes)${detail ? `, ${detail}` : ''}`;
105
+ }
106
+ /**
107
+ * What the archives of one output may still take: the rest of the run's budget. Past it a
108
+ * write is refused and the stream writing the archive stops there, so a task can not fill the
109
+ * disk of the server with an output that is refused in the end.
110
+ */
111
+ class Budget {
112
+ constructor(limit, reason) {
113
+ this.limit = limit;
114
+ this.reason = reason;
115
+ this.used = 0;
116
+ }
117
+ take(bytes) {
118
+ this.used += bytes;
119
+ if (this.used > this.limit) {
120
+ throw new Refused(this.reason);
121
+ }
122
+ }
123
+ // a stream that writes an archive, metered: what passes it counts
124
+ meter() {
125
+ return new stream_1.Transform({
126
+ transform: (chunk, _encoding, callback) => {
127
+ try {
128
+ this.take(chunk.length);
129
+ callback(null, chunk);
130
+ }
131
+ catch (e) {
132
+ callback(e);
133
+ }
134
+ },
135
+ });
136
+ }
137
+ // a file an archive is written to, metered at its writes: past the limit it is destroyed
138
+ count(file) {
139
+ const write = file.write.bind(file);
140
+ file.on('error', (error) => {
141
+ this.refusal ?? (this.refusal = error);
142
+ });
143
+ file.write = ((chunk, ...rest) => {
144
+ if (this.refusal) {
145
+ return false;
146
+ }
147
+ try {
148
+ this.take(Buffer.byteLength(chunk));
149
+ }
150
+ catch (e) {
151
+ file.destroy(e);
152
+ return false;
153
+ }
154
+ return write(chunk, ...rest);
155
+ });
156
+ return file;
157
+ }
158
+ // throws what refused a write, when a stream did not say it by itself
159
+ check() {
160
+ if (this.refusal) {
161
+ throw this.refusal;
162
+ }
163
+ }
164
+ }
165
+ // The environment with its writes of archives counted by the budget: the runtimes write their
166
+ // archives through `file`, so every byte an output is archived with is counted here.
167
+ function budgeted(environment, budget) {
168
+ const { file } = environment;
169
+ return {
170
+ ...environment,
171
+ file: {
172
+ ...file,
173
+ writeStream: (path, stream) => {
174
+ const metered = budget.meter();
175
+ // the source is stopped where the meter stops it; the error reaches the write through `metered`
176
+ (0, promises_2.pipeline)(stream, metered).catch(() => undefined);
177
+ return file.writeStream(path, metered);
178
+ },
179
+ createWriteStream: (path) => budget.count(file.createWriteStream(path)),
180
+ },
181
+ };
182
+ }
183
+ // The archive of one output as the runtime of its task makes it, made again with the paths
184
+ // in the project: the size of the new archive, or null when there is nothing.
185
+ async function keepOutput(task, generate, environment, options) {
186
+ const raw = (0, path_1.join)(options.staging, 'raw');
187
+ const tree = (0, path_1.join)(options.staging, 'tree');
188
+ await (0, promises_1.rm)(raw, { recursive: true, force: true });
189
+ await (0, promises_1.rm)(tree, { recursive: true, force: true });
190
+ await (0, promises_1.mkdir)(raw, { recursive: true });
191
+ const budget = new Budget(options.remaining, overBudget(options.maxBytes));
192
+ const [archive] = await task.runtime.archive(budgeted(environment, budget), raw, { only: [generate.path] });
193
+ budget.check();
194
+ if (!archive || !(0, fs_1.existsSync)(archive.filename)) {
195
+ return null;
196
+ }
197
+ await checkArchive(archive, options);
198
+ const into = (0, path_1.join)(tree, (0, path_1.relative)(options.root, archive.root));
199
+ if ((0, path_1.relative)(tree, into).startsWith('..') || (0, path_1.isAbsolute)((0, path_1.relative)(tree, into))) {
200
+ throw new Error(`${archive.root} is not in the project`);
201
+ }
202
+ await (0, promises_1.mkdir)(into, { recursive: true });
203
+ // only entries of the output, and no link out of it: whatever the task wrote there
204
+ await (0, tar_1.extractOutput)(archive.filename, into, toPosix((0, path_1.relative)(archive.root, generate.path)) || '.', true);
205
+ const path = (0, path_1.relative)(options.root, generate.path);
206
+ if (!(0, fs_1.existsSync)((0, path_1.join)(tree, path))) {
207
+ return null;
208
+ }
209
+ await (0, tar_1.packArchive)({ cwd: tree, file: options.target, gzip: true, portable: true }, [toPosix(path)]);
210
+ const packed = (await (0, promises_1.stat)(options.target)).size;
211
+ if (packed > options.remaining) {
212
+ throw new Refused(overBudget(options.maxBytes, `${(0, units_1.formatSize)(packed)} packed`));
213
+ }
214
+ return packed;
215
+ }
216
+ // What an archive holds once it is unpacked is measured before it is, so a few bytes packed
217
+ // from a huge file, or from many files, are refused before anything is written.
218
+ async function checkArchive(archive, options) {
219
+ const measured = await (0, tar_1.measureArchive)(archive.filename, { entries: exports.MAX_OUTPUT_ENTRIES, bytes: options.remaining });
220
+ if (measured.entries > exports.MAX_OUTPUT_ENTRIES) {
221
+ throw new Refused(`more than ${exports.MAX_OUTPUT_ENTRIES} files in it`);
222
+ }
223
+ if (measured.bytes > options.remaining) {
224
+ throw new Refused(overBudget(options.maxBytes, `${(0, units_1.formatSize)(measured.bytes)} unpacked`));
225
+ }
226
+ }
227
+ function toPosix(path) {
228
+ return path.split(path_1.sep).join(path_1.posix.sep);
229
+ }
230
+ //# sourceMappingURL=keep-artifacts.js.map