hammerkit 2.1.0-next.2 → 2.1.0-next.21

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 (87) hide show
  1. package/build.schema.json +39 -18
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/environment/replace-env-variables.js +8 -5
  8. package/dist/environment/run-source-envs.js +2 -1
  9. package/dist/executer/archive-task-entry.js +1 -1
  10. package/dist/executer/deadline.js +63 -10
  11. package/dist/executer/event-cache.js +5 -1
  12. package/dist/executer/execute-work-task.js +15 -3
  13. package/dist/executer/runner-commands.js +36 -0
  14. package/dist/file/get-file-context.js +4 -7
  15. package/dist/harness/connect.js +12 -8
  16. package/dist/harness/reconnect.js +141 -0
  17. package/dist/harness/sandbox-client.js +241 -33
  18. package/dist/harness/service-tools.js +11 -2
  19. package/dist/kubernetes/cluster-state.js +48 -14
  20. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  21. package/dist/kubernetes/follow-pod-logs.js +8 -5
  22. package/dist/kubernetes/kept-claims.js +26 -5
  23. package/dist/kubernetes/resources.js +5 -1
  24. package/dist/kubernetes/sandbox-runner.js +526 -156
  25. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  26. package/dist/kubernetes/sync-changes.js +463 -0
  27. package/dist/kubernetes/volumes.js +23 -1
  28. package/dist/optimizer/get-work-cache-stats.js +7 -0
  29. package/dist/optimizer/work-task-cache-description.js +3 -2
  30. package/dist/planner/image-build.js +5 -0
  31. package/dist/planner/utils/dependency-outputs.js +7 -6
  32. package/dist/planner/validate.js +41 -0
  33. package/dist/planner/work-item-status.js +12 -2
  34. package/dist/planner/work-runtime-aggregate.js +1 -0
  35. package/dist/planner/work-runtime-docker.js +33 -6
  36. package/dist/planner/work-runtime-kubernetes.js +313 -70
  37. package/dist/planner/work-runtime-local.js +8 -4
  38. package/dist/planner/work-secret.js +33 -11
  39. package/dist/planner/work-service-id.js +30 -6
  40. package/dist/program.js +19 -1
  41. package/dist/remote/annotations.js +37 -5
  42. package/dist/remote/bundle.js +6 -8
  43. package/dist/remote/collect-bundle.js +3 -2
  44. package/dist/remote/device-login.js +4 -1
  45. package/dist/remote/remote-commands.js +16 -7
  46. package/dist/remote/remote-work-commands.js +266 -75
  47. package/dist/remote/server-client.js +38 -40
  48. package/dist/schema/build-file-base-task-schema.js +16 -1
  49. package/dist/schema/build-file-image-build-schema.js +5 -8
  50. package/dist/schema/reference-parser.js +108 -43
  51. package/dist/schema/work-scope-parser.js +8 -0
  52. package/dist/secrets/prefetch-secrets.js +20 -1
  53. package/dist/server/artifacts-api.js +56 -0
  54. package/dist/server/definitions-api.js +62 -8
  55. package/dist/server/executor.js +117 -30
  56. package/dist/server/http.js +4 -1
  57. package/dist/server/keep-artifacts.js +230 -0
  58. package/dist/server/kubernetes-backend.js +186 -59
  59. package/dist/server/kubernetes-sandbox-storage.js +3 -2
  60. package/dist/server/overview.js +73 -9
  61. package/dist/server/paging.js +167 -0
  62. package/dist/server/plan.js +16 -1
  63. package/dist/server/run-access.js +24 -0
  64. package/dist/server/run-artifacts.js +171 -0
  65. package/dist/server/run-logs.js +25 -1
  66. package/dist/server/run-request.js +11 -0
  67. package/dist/server/run-source-environment.js +1 -1
  68. package/dist/server/run-worker.js +267 -33
  69. package/dist/server/runs.js +527 -99
  70. package/dist/server/sandbox-files-api.js +27 -12
  71. package/dist/server/sandbox-files.js +12 -10
  72. package/dist/server/sandbox-follow.js +54 -0
  73. package/dist/server/sandbox-pod.js +1 -1
  74. package/dist/server/sandbox-storage.js +38 -1
  75. package/dist/server/sandbox-sync.js +392 -0
  76. package/dist/server/sandboxes-api.js +116 -19
  77. package/dist/server/sandboxes.js +38 -3
  78. package/dist/server/server-config.js +14 -0
  79. package/dist/server/server.js +169 -38
  80. package/dist/server/task-order.js +56 -0
  81. package/dist/utils/project-path.js +20 -0
  82. package/dist/utils/tar-files.js +52 -0
  83. package/dist/utils/tar.js +37 -1
  84. package/package.json +1 -1
  85. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  86. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  87. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostExecutor = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
3
+ exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const checks_1 = require("./checks");
@@ -10,10 +10,12 @@ const path_1 = require("path");
10
10
  const readline_1 = require("readline");
11
11
  const resolve_git_source_1 = require("../includes/resolve-git-source");
12
12
  const git_checkout_1 = require("./git-checkout");
13
+ const runs_1 = require("./runs");
13
14
  const run_plan_1 = require("./run-plan");
14
15
  const work_network_1 = require("../planner/work-network");
15
16
  const execute_docker_1 = require("../executer/execute-docker");
16
17
  const run_source_environment_1 = require("./run-source-environment");
18
+ const run_artifacts_1 = require("./run-artifacts");
17
19
  // `.git` as a file system may read it: any case, and a name Windows reads without its
18
20
  // trailing dots and spaces, or by its short name
19
21
  function isGitDirectory(segment) {
@@ -21,8 +23,12 @@ function isGitDirectory(segment) {
21
23
  return name === '.git' || name === 'git~1';
22
24
  }
23
25
  // A cancelled run gets this long to stop its tasks and remove its containers, after that
24
- // its process is killed
26
+ // its process is killed. A server without a store waits for it on close (CLOSE_TIMEOUT in
27
+ // runs.ts bounds only a server that detaches its runs)
25
28
  const STOP_GRACE_MS = 15000;
29
+ // A run the server leaves to the next one gets this long to stop its tasks on this machine: the
30
+ // rest of what CLOSE_TIMEOUT gives it is for its execution to end (its directory, its volumes)
31
+ const DETACH_GRACE_MS = runs_1.CLOSE_TIMEOUT - 5000;
26
32
  // what is kept of the error output of a process that died without saying why
27
33
  const MAX_STDERR = 2 * 1024;
28
34
  /**
@@ -120,11 +126,52 @@ exports.removeServiceRunVolumes = removeServiceRunVolumes;
120
126
  * nothing else. The cache is shared by the runs of the same source, a task is keyed by
121
127
  * its definition and sources and not by where they are.
122
128
  */
129
+ /**
130
+ * What a line the worker of a run wrote on its standard output does: the message it carries goes
131
+ * to the matching handler (a `sync-failed` one is told with the run's id). A line that is not a
132
+ * message is not the run's, and is left alone.
133
+ */
134
+ function relayWorkerLine(line, runId, relay) {
135
+ try {
136
+ const message = JSON.parse(line);
137
+ if (message.kind === 'event') {
138
+ relay.emit(message.event);
139
+ }
140
+ else if (message.kind === 'up') {
141
+ relay.up?.(message.targets);
142
+ }
143
+ else if (message.kind === 'sync-failed') {
144
+ relay.syncFailed?.(runId);
145
+ }
146
+ else if (message.kind === 'result') {
147
+ relay.result(message);
148
+ }
149
+ }
150
+ catch {
151
+ // not ours: whatever else the process prints is not an event of the run
152
+ }
153
+ }
154
+ exports.relayWorkerLine = relayWorkerLine;
123
155
  class HostExecutor {
124
156
  constructor(options) {
125
157
  this.options = options;
126
158
  // the directories of the executions that run now
127
159
  this.directories = new Set();
160
+ // the processes of the runs that run now, by run id, while they take input
161
+ this.children = new Map();
162
+ }
163
+ /**
164
+ * Hands the changed files of a sandbox to the process of a service run that is up here, which
165
+ * syncs them into its services (see run-worker). The archive goes in the line itself, so
166
+ * nothing is staged on this server. False when no process of the run runs here.
167
+ */
168
+ syncChildFiles(runId, changes) {
169
+ const child = this.children.get(runId);
170
+ if (!child?.stdin) {
171
+ return false;
172
+ }
173
+ child.stdin.write(`sync ${JSON.stringify({ ...changes, archive: changes.archive.toString('base64') })}\n`);
174
+ return true;
128
175
  }
129
176
  // the docker daemon the runs' services are on, as their processes reach it
130
177
  docker() {
@@ -212,6 +259,17 @@ class HostExecutor {
212
259
  if (refused) {
213
260
  throw new Error(refused);
214
261
  }
262
+ // the outputs of a run are not handed out when anything reads a credential, or when the
263
+ // local tasks of this host could write them: then the run keeps none and says why
264
+ const wanted = context.artifacts && !run.up ? context.artifacts : undefined;
265
+ const noArtifacts = wanted ? this.artifactsRefusal(planned.plan) : null;
266
+ const artifacts = noArtifacts ? undefined : wanted;
267
+ if (wanted && noArtifacts) {
268
+ const manifest = { refused: noArtifacts, outputs: [], left: [] };
269
+ await (0, promises_1.mkdir)(wanted.directory, { recursive: true });
270
+ await (0, promises_1.writeFile)((0, path_1.join)(wanted.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
271
+ context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `keeps no outputs: ${noArtifacts}` });
272
+ }
215
273
  const abortCtrl = new AbortController();
216
274
  const abort = () => abortCtrl.abort();
217
275
  if (context.signal.aborted) {
@@ -239,12 +297,21 @@ class HostExecutor {
239
297
  // does a run that was approved: what was approved is those files, and the sandbox has
240
298
  // more (its ignored files, node_modules, outputs), which its owner and their runs write
241
299
  // while the run waits and runs.
242
- const copied = source.type === 'sandbox' && (source.check || (run.approvals?.length ?? 0) > 0);
300
+ // A service run from a sandbox on a cluster gets a copy of the files too: its pods mount no
301
+ // claim of the sandbox, and the files of later edits reach it by a move (RunRegistry.follow)
302
+ const approved = (run.approvals?.length ?? 0) > 0;
303
+ const onCluster = !!run.up && !!this.options.placement;
304
+ const copied = source.type === 'sandbox' && (source.check || approved || onCluster);
243
305
  // (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
244
306
  if (source.type === 'sandbox' && copied) {
245
- const { registry, network } = sandboxes;
246
- const what = source.check ? 'the check' : 'the approved run';
247
- if (!source.check) {
307
+ const { registry, network, started } = sandboxes;
308
+ const kind = source.check ? 'check' : approved ? 'approved run' : 'service run';
309
+ if (onCluster) {
310
+ // before the copy: a change from here on is one the services have not got
311
+ await started?.(run);
312
+ }
313
+ const what = `the ${kind}`;
314
+ if (!source.check && approved) {
248
315
  // what was approved is what runs: the files may have changed since, by a run
249
316
  // before this one on the sandbox (the copy checks it again, under the sandbox's lock)
250
317
  const state = await registry.state(source.id, abortCtrl.signal);
@@ -266,7 +333,7 @@ class HostExecutor {
266
333
  type: 'log',
267
334
  task: 'hammerkit',
268
335
  stream: 'stdout',
269
- text: `${source.check ? 'check' : 'approved run'} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
336
+ text: `${kind} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
270
337
  });
271
338
  // the tasks see the published build files in place of the sandbox's own
272
339
  await this.writeBundle(work, bundle.files);
@@ -346,22 +413,30 @@ class HostExecutor {
346
413
  volumeScope: volumeScope(run, this.options.directory),
347
414
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
415
  ...(context.durations ? { durations: context.durations } : {}),
416
+ // the commands it started in a sandbox's runner; the logs of its pods go in the
417
+ // cluster's environment (KubernetesExecutor)
418
+ ...(context.resumed?.outputs ? { resumed: { outputs: context.resumed.outputs } } : {}),
419
+ ...(artifacts ? { artifacts } : {}),
349
420
  catalog: planning.environment.hosted?.catalog,
350
421
  ...(run.up
351
422
  ? {
352
423
  up: {
353
424
  services: run.up.services,
354
425
  endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
426
+ ...(run.up.restart ? { restart: run.up.restart } : {}),
355
427
  },
356
428
  }
357
429
  : {}),
358
430
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
359
431
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
360
- }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal);
432
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed, run.id);
361
433
  }
362
434
  finally {
363
435
  if (placement && placed) {
364
- await placement.release(run, context);
436
+ // a run that resumes with the next server finds its Jobs and services where they are
437
+ if (!(0, runs_1.isDetached)(context)) {
438
+ await placement.release(run, context);
439
+ }
365
440
  }
366
441
  else if (run.up && !context.keep?.()) {
367
442
  // the services are gone with the process, their volumes stay only while the run sleeps
@@ -372,6 +447,9 @@ class HostExecutor {
372
447
  finally {
373
448
  context.signal.removeEventListener('abort', abort);
374
449
  attachment?.release?.();
450
+ if (run.up && this.options.placement) {
451
+ await sandboxes?.ended?.(run);
452
+ }
375
453
  await this.removeRunDirectory(run, root, context);
376
454
  this.directories.delete(root);
377
455
  if (source.type === 'sandbox') {
@@ -380,6 +458,10 @@ class HostExecutor {
380
458
  }
381
459
  }
382
460
  }
461
+ // why a run keeps none of its outputs: a credential its tasks read, or local tasks on this host
462
+ artifactsRefusal(plan) {
463
+ return this.options.localTasksOnHost ? run_artifacts_1.LOCAL_TASKS_REFUSAL : (0, run_artifacts_1.refuseArtifacts)(plan);
464
+ }
383
465
  directoryOf(run) {
384
466
  for (let execution = 1;; execution++) {
385
467
  const root = (0, path_1.join)(this.options.directory, execution === 1 ? run.id : `${run.id}-${execution}`);
@@ -428,7 +510,10 @@ class HostExecutor {
428
510
  // engine stops its tasks and removes its containers; a signal on Windows would end the
429
511
  // process at once and leave its tasks running in the directory of the run. The process is
430
512
  // killed if it has not stopped after the grace period.
431
- runInProcess(command, input, cwd, env, context, signal) {
513
+ // A run that the server leaves to the next one (RunContext.detached) and whose tasks are on
514
+ // a cluster: the process is killed at once, so its Jobs and services stay. One whose tasks
515
+ // are on this machine stops them as a cancel does, in less time.
516
+ runInProcess(command, input, cwd, env, context, signal, onCluster, runId) {
432
517
  return new Promise((resolvePromise, reject) => {
433
518
  const child = (0, child_process_1.spawn)(command[0], command.slice(1), {
434
519
  cwd,
@@ -439,16 +524,23 @@ class HostExecutor {
439
524
  child.stdin.on('error', () => undefined);
440
525
  // the run first, so a cancel comes after it; kept open, it is how a cancel reaches the process
441
526
  child.stdin.write(`${JSON.stringify(input)}\n`);
527
+ this.children.set(runId, child);
442
528
  let result;
443
529
  let stderr = '';
444
530
  let killTimer;
445
531
  const stop = () => {
532
+ const detaching = (0, runs_1.isDetached)(context);
533
+ if (detaching && onCluster) {
534
+ child.kill('SIGKILL');
535
+ return;
536
+ }
446
537
  child.stdin.write('cancel\n', (e) => {
447
538
  if (e) {
448
539
  child.kill();
449
540
  }
450
541
  });
451
- killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopGraceMs ?? STOP_GRACE_MS);
542
+ const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
543
+ killTimer = setTimeout(() => child.kill('SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
452
544
  killTimer.unref();
453
545
  };
454
546
  if (signal.aborted) {
@@ -457,25 +549,17 @@ class HostExecutor {
457
549
  else {
458
550
  signal.addEventListener('abort', stop, { once: true });
459
551
  }
460
- (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => {
461
- try {
462
- const message = JSON.parse(line);
463
- if (message.kind === 'event') {
464
- context.emit(message.event);
465
- }
466
- else if (message.kind === 'up') {
467
- context.up?.(message.targets);
468
- }
469
- else if (message.kind === 'result') {
470
- result = message;
471
- // nothing left to tell the process
472
- child.stdin.end();
473
- }
474
- }
475
- catch {
476
- // not ours: whatever else the process prints is not an event of the run
477
- }
478
- });
552
+ (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => relayWorkerLine(line, runId, {
553
+ emit: (event) => context.emit(event),
554
+ up: (targets) => context.up?.(targets),
555
+ syncFailed: (id) => this.options.sandboxes?.syncFailed?.(id),
556
+ result: (message) => {
557
+ result = message;
558
+ // nothing left to tell the process
559
+ this.children.delete(runId);
560
+ child.stdin.end();
561
+ },
562
+ }));
479
563
  child.stderr.on('data', (chunk) => {
480
564
  stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR);
481
565
  });
@@ -487,6 +571,9 @@ class HostExecutor {
487
571
  child.on('close', (code, killed) => {
488
572
  signal.removeEventListener('abort', stop);
489
573
  clearTimeout(killTimer);
574
+ if (this.children.get(runId) === child) {
575
+ this.children.delete(runId);
576
+ }
490
577
  if (result?.ok) {
491
578
  resolvePromise();
492
579
  }
@@ -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