hammerkit 2.1.0 → 2.2.0-next.2

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 (103) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cache/backends/registry/push-credentials.js +50 -0
  3. package/dist/cache/backends/registry/registry-client.js +41 -10
  4. package/dist/cache/backends/registry-cache-backend.js +6 -1
  5. package/dist/cache/cache-inventory.js +3 -0
  6. package/dist/cli.js +5 -0
  7. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  8. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  9. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/docker/item-network.js +6 -5
  12. package/dist/docker/remove-orphaned-containers.js +5 -4
  13. package/dist/environment/replace-env-variables.js +8 -5
  14. package/dist/environment/run-source-envs.js +2 -1
  15. package/dist/executer/archive-task-entry.js +1 -1
  16. package/dist/executer/check-readiness.js +8 -4
  17. package/dist/executer/docker-healthcheck.js +73 -0
  18. package/dist/executer/docker-service.js +21 -15
  19. package/dist/executer/event-cache.js +7 -1
  20. package/dist/executer/execute-work-task.js +8 -0
  21. package/dist/executer/runner-commands.js +36 -0
  22. package/dist/file/get-file-context.js +4 -7
  23. package/dist/harness/connect.js +12 -8
  24. package/dist/harness/reconnect.js +141 -0
  25. package/dist/harness/sandbox-client.js +241 -33
  26. package/dist/harness/service-tools.js +11 -2
  27. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  28. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  29. package/dist/kubernetes/follow-pod-logs.js +8 -5
  30. package/dist/kubernetes/kept-claims.js +38 -14
  31. package/dist/kubernetes/sandbox-runner.js +526 -156
  32. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  33. package/dist/kubernetes/sync-changes.js +463 -0
  34. package/dist/kubernetes/volumes.js +23 -1
  35. package/dist/network/healthcheck-request.js +38 -0
  36. package/dist/optimizer/get-work-cache-stats.js +7 -0
  37. package/dist/optimizer/work-task-cache-description.js +5 -3
  38. package/dist/planner/image-build.js +5 -0
  39. package/dist/planner/service-definition.js +2 -1
  40. package/dist/planner/utils/append-work-service.js +12 -4
  41. package/dist/planner/utils/dependency-outputs.js +7 -6
  42. package/dist/planner/validate.js +41 -0
  43. package/dist/planner/work-healthcheck.js +23 -2
  44. package/dist/planner/work-item-status.js +12 -2
  45. package/dist/planner/work-runtime-aggregate.js +1 -0
  46. package/dist/planner/work-runtime-docker.js +33 -6
  47. package/dist/planner/work-runtime-kubernetes.js +313 -70
  48. package/dist/planner/work-runtime-local.js +8 -4
  49. package/dist/planner/work-secret.js +33 -11
  50. package/dist/planner/work-service-id.js +30 -6
  51. package/dist/planner/work-service.js +2 -2
  52. package/dist/program.js +19 -1
  53. package/dist/remote/annotations.js +8 -2
  54. package/dist/remote/bundle.js +6 -8
  55. package/dist/remote/device-login.js +4 -1
  56. package/dist/remote/remote-commands.js +16 -7
  57. package/dist/remote/remote-status.js +1 -1
  58. package/dist/remote/remote-work-commands.js +220 -68
  59. package/dist/remote/server-client.js +38 -40
  60. package/dist/schema/build-file-base-task-schema.js +16 -1
  61. package/dist/schema/build-file-image-build-schema.js +5 -8
  62. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  63. package/dist/schema/reference-parser.js +108 -43
  64. package/dist/schema/work-scope-parser.js +8 -0
  65. package/dist/secrets/prefetch-secrets.js +20 -1
  66. package/dist/server/artifacts-api.js +56 -0
  67. package/dist/server/borrowed-quota.js +216 -0
  68. package/dist/server/cache-push.js +50 -0
  69. package/dist/server/capacity.js +18 -6
  70. package/dist/server/definitions-api.js +62 -8
  71. package/dist/server/executor.js +131 -31
  72. package/dist/server/http.js +4 -1
  73. package/dist/server/keep-artifacts.js +230 -0
  74. package/dist/server/kubernetes-backend.js +292 -79
  75. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  76. package/dist/server/overview.js +73 -9
  77. package/dist/server/paging.js +167 -0
  78. package/dist/server/plan.js +54 -8
  79. package/dist/server/run-access.js +24 -0
  80. package/dist/server/run-artifacts.js +171 -0
  81. package/dist/server/run-logs.js +25 -1
  82. package/dist/server/run-request.js +11 -0
  83. package/dist/server/run-source-environment.js +1 -1
  84. package/dist/server/run-worker.js +305 -40
  85. package/dist/server/runs.js +531 -105
  86. package/dist/server/sandbox-files-api.js +27 -12
  87. package/dist/server/sandbox-files.js +12 -10
  88. package/dist/server/sandbox-follow.js +54 -0
  89. package/dist/server/sandbox-pod.js +1 -1
  90. package/dist/server/sandbox-storage.js +38 -1
  91. package/dist/server/sandbox-sync.js +392 -0
  92. package/dist/server/sandboxes-api.js +116 -19
  93. package/dist/server/sandboxes.js +38 -3
  94. package/dist/server/server-config.js +133 -2
  95. package/dist/server/server.js +189 -39
  96. package/dist/server/task-order.js +56 -0
  97. package/dist/utils/project-path.js +20 -0
  98. package/dist/utils/tar-files.js +52 -0
  99. package/dist/utils/tar.js +37 -1
  100. package/package.json +1 -1
  101. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  102. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  103. 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.pushCacheNamespace = 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
  /**
@@ -61,6 +67,14 @@ function cacheNamespace(run) {
61
67
  return `${kind}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
62
68
  }
63
69
  exports.cacheNamespace = cacheNamespace;
70
+ // The local cache of a run that pushes to a registry (ADR-0010). Only the runs that push write it,
71
+ // and a pushing run restores from it and from the registry, never from the cache the other runs of
72
+ // the repository share: what an untrusted run left there is no result to push.
73
+ function pushCacheNamespace(run) {
74
+ const key = `push\0${run.source.repo}`;
75
+ return `push-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
76
+ }
77
+ exports.pushCacheNamespace = pushCacheNamespace;
64
78
  // The docker volumes of a run's services are its caller's, within the cache's source trust:
65
79
  // two callers of one repository share a cache, a task is keyed by what it reads, but not the
66
80
  // data their services keep. A service run's are its own: they stay while it sleeps and go
@@ -120,11 +134,52 @@ exports.removeServiceRunVolumes = removeServiceRunVolumes;
120
134
  * nothing else. The cache is shared by the runs of the same source, a task is keyed by
121
135
  * its definition and sources and not by where they are.
122
136
  */
137
+ /**
138
+ * What a line the worker of a run wrote on its standard output does: the message it carries goes
139
+ * to the matching handler (a `sync-failed` one is told with the run's id). A line that is not a
140
+ * message is not the run's, and is left alone.
141
+ */
142
+ function relayWorkerLine(line, runId, relay) {
143
+ try {
144
+ const message = JSON.parse(line);
145
+ if (message.kind === 'event') {
146
+ relay.emit(message.event);
147
+ }
148
+ else if (message.kind === 'up') {
149
+ relay.up?.(message.targets);
150
+ }
151
+ else if (message.kind === 'sync-failed') {
152
+ relay.syncFailed?.(runId);
153
+ }
154
+ else if (message.kind === 'result') {
155
+ relay.result(message);
156
+ }
157
+ }
158
+ catch {
159
+ // not ours: whatever else the process prints is not an event of the run
160
+ }
161
+ }
162
+ exports.relayWorkerLine = relayWorkerLine;
123
163
  class HostExecutor {
124
164
  constructor(options) {
125
165
  this.options = options;
126
166
  // the directories of the executions that run now
127
167
  this.directories = new Set();
168
+ // the processes of the runs that run now, by run id, while they take input
169
+ this.children = new Map();
170
+ }
171
+ /**
172
+ * Hands the changed files of a sandbox to the process of a service run that is up here, which
173
+ * syncs them into its services (see run-worker). The archive goes in the line itself, so
174
+ * nothing is staged on this server. False when no process of the run runs here.
175
+ */
176
+ syncChildFiles(runId, changes) {
177
+ const child = this.children.get(runId);
178
+ if (!child?.stdin) {
179
+ return false;
180
+ }
181
+ child.stdin.write(`sync ${JSON.stringify({ ...changes, archive: changes.archive.toString('base64') })}\n`);
182
+ return true;
128
183
  }
129
184
  // the docker daemon the runs' services are on, as their processes reach it
130
185
  docker() {
@@ -212,6 +267,17 @@ class HostExecutor {
212
267
  if (refused) {
213
268
  throw new Error(refused);
214
269
  }
270
+ // the outputs of a run are not handed out when anything reads a credential, or when the
271
+ // local tasks of this host could write them: then the run keeps none and says why
272
+ const wanted = context.artifacts && !run.up ? context.artifacts : undefined;
273
+ const noArtifacts = wanted ? this.artifactsRefusal(planned.plan) : null;
274
+ const artifacts = noArtifacts ? undefined : wanted;
275
+ if (wanted && noArtifacts) {
276
+ const manifest = { refused: noArtifacts, outputs: [], left: [] };
277
+ await (0, promises_1.mkdir)(wanted.directory, { recursive: true });
278
+ await (0, promises_1.writeFile)((0, path_1.join)(wanted.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
279
+ context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `keeps no outputs: ${noArtifacts}` });
280
+ }
215
281
  const abortCtrl = new AbortController();
216
282
  const abort = () => abortCtrl.abort();
217
283
  if (context.signal.aborted) {
@@ -239,12 +305,21 @@ class HostExecutor {
239
305
  // does a run that was approved: what was approved is those files, and the sandbox has
240
306
  // more (its ignored files, node_modules, outputs), which its owner and their runs write
241
307
  // while the run waits and runs.
242
- const copied = source.type === 'sandbox' && (source.check || (run.approvals?.length ?? 0) > 0);
308
+ // A service run from a sandbox on a cluster gets a copy of the files too: its pods mount no
309
+ // claim of the sandbox, and the files of later edits reach it by a move (RunRegistry.follow)
310
+ const approved = (run.approvals?.length ?? 0) > 0;
311
+ const onCluster = !!run.up && !!this.options.placement;
312
+ const copied = source.type === 'sandbox' && (source.check || approved || onCluster);
243
313
  // (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
244
314
  if (source.type === 'sandbox' && copied) {
245
- const { registry, network } = sandboxes;
246
- const what = source.check ? 'the check' : 'the approved run';
247
- if (!source.check) {
315
+ const { registry, network, started } = sandboxes;
316
+ const kind = source.check ? 'check' : approved ? 'approved run' : 'service run';
317
+ if (onCluster) {
318
+ // before the copy: a change from here on is one the services have not got
319
+ await started?.(run);
320
+ }
321
+ const what = `the ${kind}`;
322
+ if (!source.check && approved) {
248
323
  // what was approved is what runs: the files may have changed since, by a run
249
324
  // before this one on the sandbox (the copy checks it again, under the sandbox's lock)
250
325
  const state = await registry.state(source.id, abortCtrl.signal);
@@ -266,7 +341,7 @@ class HostExecutor {
266
341
  type: 'log',
267
342
  task: 'hammerkit',
268
343
  stream: 'stdout',
269
- text: `${source.check ? 'check' : 'approved run'} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
344
+ text: `${kind} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
270
345
  });
271
346
  // the tasks see the published build files in place of the sandbox's own
272
347
  await this.writeBundle(work, bundle.files);
@@ -329,7 +404,10 @@ class HostExecutor {
329
404
  emitPhase(context, 'source', sourceStarted);
330
405
  const home = (0, path_1.join)(root, 'home');
331
406
  await (0, promises_1.mkdir)(home, { recursive: true });
332
- const cache = (0, path_1.join)(this.options.cache, cacheNamespace(run));
407
+ // a run writes a registry cache only with the server's credential for it (ADR-0010); a run
408
+ // that does has a local cache of its own, which no other run writes
409
+ const push = this.options.cachePush?.(run) ?? null;
410
+ const cache = (0, path_1.join)(this.options.cache, push ? pushCacheNamespace(run) : cacheNamespace(run));
333
411
  await (0, promises_1.mkdir)(cache, { recursive: true });
334
412
  const placement = this.options.placement;
335
413
  const namespaceStarted = new Date();
@@ -342,26 +420,36 @@ class HostExecutor {
342
420
  ...input,
343
421
  tasks: run.tasks,
344
422
  options: run.options,
423
+ ...(push ? { cachePush: push } : {}),
424
+ cacheRegistries: this.options.cacheRegistries ?? [],
345
425
  accounts: run.accounts,
346
426
  volumeScope: volumeScope(run, this.options.directory),
347
427
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
428
  ...(context.durations ? { durations: context.durations } : {}),
429
+ // the commands it started in a sandbox's runner; the logs of its pods go in the
430
+ // cluster's environment (KubernetesExecutor)
431
+ ...(context.resumed?.outputs ? { resumed: { outputs: context.resumed.outputs } } : {}),
432
+ ...(artifacts ? { artifacts } : {}),
349
433
  catalog: planning.environment.hosted?.catalog,
350
434
  ...(run.up
351
435
  ? {
352
436
  up: {
353
437
  services: run.up.services,
354
438
  endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
439
+ ...(run.up.restart ? { restart: run.up.restart } : {}),
355
440
  },
356
441
  }
357
442
  : {}),
358
443
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
359
444
  ...(!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);
445
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed, run.id);
361
446
  }
362
447
  finally {
363
448
  if (placement && placed) {
364
- await placement.release(run, context);
449
+ // a run that resumes with the next server finds its Jobs and services where they are
450
+ if (!(0, runs_1.isDetached)(context)) {
451
+ await placement.release(run, context);
452
+ }
365
453
  }
366
454
  else if (run.up && !context.keep?.()) {
367
455
  // the services are gone with the process, their volumes stay only while the run sleeps
@@ -372,6 +460,9 @@ class HostExecutor {
372
460
  finally {
373
461
  context.signal.removeEventListener('abort', abort);
374
462
  attachment?.release?.();
463
+ if (run.up && this.options.placement) {
464
+ await sandboxes?.ended?.(run);
465
+ }
375
466
  await this.removeRunDirectory(run, root, context);
376
467
  this.directories.delete(root);
377
468
  if (source.type === 'sandbox') {
@@ -380,6 +471,10 @@ class HostExecutor {
380
471
  }
381
472
  }
382
473
  }
474
+ // why a run keeps none of its outputs: a credential its tasks read, or local tasks on this host
475
+ artifactsRefusal(plan) {
476
+ return this.options.localTasksOnHost ? run_artifacts_1.LOCAL_TASKS_REFUSAL : (0, run_artifacts_1.refuseArtifacts)(plan);
477
+ }
383
478
  directoryOf(run) {
384
479
  for (let execution = 1;; execution++) {
385
480
  const root = (0, path_1.join)(this.options.directory, execution === 1 ? run.id : `${run.id}-${execution}`);
@@ -428,7 +523,10 @@ class HostExecutor {
428
523
  // engine stops its tasks and removes its containers; a signal on Windows would end the
429
524
  // process at once and leave its tasks running in the directory of the run. The process is
430
525
  // killed if it has not stopped after the grace period.
431
- runInProcess(command, input, cwd, env, context, signal) {
526
+ // A run that the server leaves to the next one (RunContext.detached) and whose tasks are on
527
+ // a cluster: the process is killed at once, so its Jobs and services stay. One whose tasks
528
+ // are on this machine stops them as a cancel does, in less time.
529
+ runInProcess(command, input, cwd, env, context, signal, onCluster, runId) {
432
530
  return new Promise((resolvePromise, reject) => {
433
531
  const child = (0, child_process_1.spawn)(command[0], command.slice(1), {
434
532
  cwd,
@@ -439,16 +537,23 @@ class HostExecutor {
439
537
  child.stdin.on('error', () => undefined);
440
538
  // the run first, so a cancel comes after it; kept open, it is how a cancel reaches the process
441
539
  child.stdin.write(`${JSON.stringify(input)}\n`);
540
+ this.children.set(runId, child);
442
541
  let result;
443
542
  let stderr = '';
444
543
  let killTimer;
445
544
  const stop = () => {
545
+ const detaching = (0, runs_1.isDetached)(context);
546
+ if (detaching && onCluster) {
547
+ child.kill('SIGKILL');
548
+ return;
549
+ }
446
550
  child.stdin.write('cancel\n', (e) => {
447
551
  if (e) {
448
552
  child.kill();
449
553
  }
450
554
  });
451
- killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopGraceMs ?? STOP_GRACE_MS);
555
+ const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
556
+ killTimer = setTimeout(() => child.kill('SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
452
557
  killTimer.unref();
453
558
  };
454
559
  if (signal.aborted) {
@@ -457,25 +562,17 @@ class HostExecutor {
457
562
  else {
458
563
  signal.addEventListener('abort', stop, { once: true });
459
564
  }
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
- });
565
+ (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => relayWorkerLine(line, runId, {
566
+ emit: (event) => context.emit(event),
567
+ up: (targets) => context.up?.(targets),
568
+ syncFailed: (id) => this.options.sandboxes?.syncFailed?.(id),
569
+ result: (message) => {
570
+ result = message;
571
+ // nothing left to tell the process
572
+ this.children.delete(runId);
573
+ child.stdin.end();
574
+ },
575
+ }));
479
576
  child.stderr.on('data', (chunk) => {
480
577
  stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR);
481
578
  });
@@ -487,6 +584,9 @@ class HostExecutor {
487
584
  child.on('close', (code, killed) => {
488
585
  signal.removeEventListener('abort', stop);
489
586
  clearTimeout(killTimer);
587
+ if (this.children.get(runId) === child) {
588
+ this.children.delete(runId);
589
+ }
490
590
  if (result?.ok) {
491
591
  resolvePromise();
492
592
  }
@@ -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