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,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.startServer = exports.runsTheSame = exports.refuseWake = exports.getDiscoveryDocument = exports.SERVER_PROTOCOL = exports.DISCOVERY_PATH = void 0;
4
+ const promises_1 = require("fs/promises");
4
5
  const http_1 = require("http");
5
6
  const https_1 = require("https");
6
7
  const tls_1 = require("tls");
@@ -9,6 +10,7 @@ const server_config_1 = require("./server-config");
9
10
  const discovery_1 = require("./discovery");
10
11
  const oauth_1 = require("./oauth");
11
12
  const policy_1 = require("./policy");
13
+ const cache_push_1 = require("./cache-push");
12
14
  const repo_1 = require("./repo");
13
15
  const run_store_1 = require("./run-store");
14
16
  const runs_1 = require("./runs");
@@ -18,6 +20,7 @@ const executor_1 = require("./executor");
18
20
  const capacity_1 = require("./capacity");
19
21
  const execute_docker_1 = require("../executer/execute-docker");
20
22
  const timings_1 = require("./timings");
23
+ const task_order_1 = require("./task-order");
21
24
  const kubernetes_backend_1 = require("./kubernetes-backend");
22
25
  const run_plan_1 = require("./run-plan");
23
26
  const run_source_environment_1 = require("./run-source-environment");
@@ -34,6 +37,8 @@ const proposals_api_1 = require("./proposals-api");
34
37
  const proposals_1 = require("./proposals");
35
38
  const sources_1 = require("./sources");
36
39
  const sources_api_1 = require("./sources-api");
40
+ const sandbox_follow_1 = require("./sandbox-follow");
41
+ const sandbox_sync_1 = require("./sandbox-sync");
37
42
  const sandboxes_1 = require("./sandboxes");
38
43
  const sandbox_storage_1 = require("./sandbox-storage");
39
44
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
@@ -48,7 +53,11 @@ const get_cache_directory_1 = require("../optimizer/get-cache-directory");
48
53
  const path_1 = require("path");
49
54
  const checks_1 = require("./checks");
50
55
  const checks_api_1 = require("./checks-api");
56
+ const run_artifacts_1 = require("./run-artifacts");
57
+ const artifacts_api_1 = require("./artifacts-api");
58
+ const run_access_1 = require("./run-access");
51
59
  const overview_1 = require("./overview");
60
+ const paging_1 = require("./paging");
52
61
  var discovery_2 = require("./discovery");
53
62
  Object.defineProperty(exports, "DISCOVERY_PATH", { enumerable: true, get: function () { return discovery_2.DISCOVERY_PATH; } });
54
63
  Object.defineProperty(exports, "SERVER_PROTOCOL", { enumerable: true, get: function () { return discovery_2.SERVER_PROTOCOL; } });
@@ -79,6 +88,8 @@ const HEARTBEAT_MS = 15000;
79
88
  const MAX_WAIT_MS = 50000;
80
89
  // how often checks older than `runs.checksKeep` are removed
81
90
  const CHECK_SWEEP_MS = 6 * 60 * 60 * 1000;
91
+ // how often the outputs of runs that are over their time are removed
92
+ const ARTIFACT_SWEEP_MS = 60 * 60 * 1000;
82
93
  // Server-sent events: `id` is the sequence number, so a client that lost the
83
94
  // connection continues with Last-Event-ID (or ?after=) and misses nothing.
84
95
  function streamEvents(registry, config, principal, id, req, res, url) {
@@ -89,7 +100,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
89
100
  if (event.type === 'state' && (0, runs_1.isFinal)(event.state)) {
90
101
  end();
91
102
  }
92
- }, accountsOf(config, principal));
103
+ }, (0, run_access_1.accountsOf)(config, principal));
93
104
  if (!watch) {
94
105
  (0, http_2.send)(res, 404, { error: 'not found' });
95
106
  return;
@@ -122,18 +133,45 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
122
133
  if (method === 'GET') {
123
134
  // the results of each task are read one run at a time
124
135
  const viewer = (0, overview_1.getViewer)(config, principal);
125
- let filter;
136
+ let filter, page, values;
126
137
  try {
127
138
  filter = (0, overview_1.parseRunFilter)(url.searchParams, viewer.grant);
139
+ values = (0, paging_1.parseValues)(url.searchParams, overview_1.RUN_FIELDS);
140
+ page = values ? undefined : (0, paging_1.parsePage)(url.searchParams);
128
141
  }
129
142
  catch (e) {
130
143
  (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
131
144
  return true;
132
145
  }
133
146
  const runs = filter.scope === 'mine' ? registry.list(principal) : registry.all();
134
- (0, http_2.send)(res, 200, {
135
- runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, definitions, viewer, run)),
136
- });
147
+ const list = (run) => listRun(registry, definitions, viewer, run);
148
+ try {
149
+ if (values) {
150
+ // a value of the field is counted over the runs the other filters let through
151
+ const { of, order } = (0, overview_1.runValues)(values.field);
152
+ const counted = (0, paging_1.countValues)((0, overview_1.filterRuns)(runs, viewer, (0, overview_1.withoutField)(filter, values.field)), of, values, order);
153
+ (0, http_2.send)(res, 200, (0, paging_1.answerPage)('values', counted));
154
+ }
155
+ else if (page) {
156
+ // newest first, as the registry keeps them
157
+ const found = (0, overview_1.filterRuns)(runs, viewer, filter);
158
+ const oldest = found[found.length - 1]?.createdAt;
159
+ const answered = (0, paging_1.pageByKey)(found, page, runKey);
160
+ (0, http_2.send)(res, 200, {
161
+ ...(0, paging_1.answerPage)('runs', { ...answered, items: answered.items.map(list) }),
162
+ ...(oldest ? { oldest } : {}),
163
+ });
164
+ }
165
+ else {
166
+ (0, http_2.send)(res, 200, { runs: (0, overview_1.filterRuns)(runs, viewer, filter).map(list) });
167
+ }
168
+ }
169
+ catch (e) {
170
+ if (!(e instanceof paging_1.ListParamError)) {
171
+ throw e;
172
+ }
173
+ (0, http_2.send)(res, 400, { error: e.message });
174
+ }
137
175
  }
138
176
  else if (method === 'POST') {
139
177
  await submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res);
@@ -152,7 +190,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
152
190
  return true;
153
191
  }
154
192
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
155
- const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
193
+ const run = registry.cancel(principal, id, (0, run_access_1.accountsOf)(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
156
194
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
157
195
  run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
158
196
  }
@@ -207,12 +245,14 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
207
245
  (0, http_2.send)(res, 400, { error: e instanceof Error ? e.message : String(e) });
208
246
  return true;
209
247
  }
210
- // an entitlement with `observe` reads the log of every run
211
- const logs = registry.logs(principal, id, accountsOf(config, principal)) ??
212
- ((0, policy_1.getGrant)(config.entitlements, principal).observe ? registry.logsOf(id) : undefined);
248
+ // who may read the run reads its log, an entitlement with `observe` every run's
249
+ const logs = (0, run_access_1.findReadableRun)(config, registry, principal, id) ? registry.logsOf(id) : undefined;
213
250
  // with the tasks, services and the server's own lines (`hammerkit`) the log has
214
251
  logs
215
- ? (0, http_2.send)(res, 200, { ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated), names: logs.index.names() })
252
+ ? (0, http_2.send)(res, 200, {
253
+ ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated, logs.lostAfter),
254
+ names: logs.index.names(),
255
+ })
216
256
  : (0, http_2.send)(res, 404, { error: 'not found' });
217
257
  }
218
258
  else {
@@ -232,7 +272,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
232
272
  res.on('close', () => gone.abort());
233
273
  const viewer = (0, overview_1.getViewer)(config, principal);
234
274
  // an entitlement with `observe` reads every run as it is, without waiting
235
- const run = (await registry.wait(principal, id, wait, accountsOf(config, principal), gone.signal)) ??
275
+ const run = (await registry.wait(principal, id, wait, (0, run_access_1.accountsOf)(config, principal), gone.signal)) ??
236
276
  (viewer.grant.observe ? registry.peek(id) : undefined);
237
277
  if (!gone.signal.aborted) {
238
278
  const may = run && (0, overview_1.runActions)(viewer, run);
@@ -246,11 +286,6 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
246
286
  }
247
287
  return true;
248
288
  }
249
- // The accounts the caller uses: who approves a run on them follows and stops it.
250
- function accountsOf(config, principal) {
251
- const grant = (0, policy_1.getGrant)(config.entitlements, principal);
252
- return (account) => (0, policy_1.canUse)(grant, account);
253
- }
254
289
  async function extendRun(config, registry, log, principal, id, req, res) {
255
290
  const body = (await (0, http_2.readJson)(req));
256
291
  let ttl;
@@ -357,11 +392,15 @@ function toRunResponse(run, queue, named = false, nameOf) {
357
392
  ...(queue ? { queue } : {}),
358
393
  };
359
394
  }
395
+ // where a page of runs ends: when the last run was created, and which it is
396
+ const runKey = (run) => [run.createdAt, run.id];
360
397
  function listRun(registry, definitions, viewer, run) {
361
398
  return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
362
399
  }
363
400
  // where in its repository the build file of a version is
364
401
  const entryOf = (definitions) => (definition) => definitions.find(definition)?.entry;
402
+ // a full commit hash, 40 or 64 hex digits: the ref of a run that names its commit
403
+ const FULL_COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
365
404
  async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res) {
366
405
  const parsed = run_request_1.runRequestSchema.safeParse(await (0, http_2.readJson)(req));
367
406
  if (!parsed.success) {
@@ -377,7 +416,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
377
416
  // an approval where they need one, never the owner's (run-retry.ts).
378
417
  async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
379
418
  const viewer = (0, overview_1.getViewer)(config, principal);
380
- const run = registry.get(principal, id, accountsOf(config, principal)) ?? (viewer.grant.observe ? registry.peek(id) : undefined);
419
+ const run = (0, run_access_1.findReadableRun)(config, registry, principal, id);
381
420
  if (!run) {
382
421
  (0, http_2.send)(res, 404, { error: 'not found' });
383
422
  return;
@@ -453,6 +492,14 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
453
492
  (0, http_2.send)(res, 400, { error: 'sleepTtl: a service run from a sandbox does not sleep, start it from a branch' });
454
493
  return;
455
494
  }
495
+ // only a Kubernetes backend syncs the changed files of a sandbox into the services; a host
496
+ // runs them on the sandbox's own files, so a restart would do nothing there
497
+ if (request.restart?.length && config.backend.type !== 'kubernetes') {
498
+ (0, http_2.send)(res, 400, {
499
+ error: `restart: this server (backend ${config.backend.type}) has no file sync, a host's services run on the sandbox's files`,
500
+ });
501
+ return;
502
+ }
456
503
  const sleepTtlText = request.source.type === 'ref' ? request.sleepTtl ?? config.runs.up.sleepTtl : undefined;
457
504
  const sleepTtl = request.services.length > 0 && sleepTtlText ? (0, units_1.parseDuration)(sleepTtlText) : undefined;
458
505
  const argued = (request.options.args ?? []).length > 0 ? request.tasks[0] : undefined;
@@ -476,12 +523,6 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
476
523
  return;
477
524
  }
478
525
  }
479
- if (request.services.length > 0 && request.source.type === 'sandbox' && config.backend.type === 'kubernetes') {
480
- (0, http_2.send)(res, 400, {
481
- error: 'on a cluster a service run starts from a branch, push the sandbox and start it from there',
482
- });
483
- return;
484
- }
485
526
  const sandbox = request.source.type === 'sandbox' ? sandboxes.registry.get(principal, request.source.id) : undefined;
486
527
  if (request.source.type === 'sandbox') {
487
528
  if (!sandbox) {
@@ -598,7 +639,18 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
598
639
  (0, http_2.send)(res, 409, { error });
599
640
  return;
600
641
  }
601
- source = { type: 'ref', repo: request.source.repo, ref: request.source.ref, commit };
642
+ // a branch at that commit, or a tag or a commit: only a branch's run may write a cache. A
643
+ // full commit names no branch, whatever the repository says of it.
644
+ const branch = FULL_COMMIT.test(request.source.ref)
645
+ ? false
646
+ : await repos.resolve(request.source.repo, request.source.ref, undefined, 'branch').then((found) => found === commit, () => false);
647
+ source = {
648
+ type: 'ref',
649
+ repo: request.source.repo,
650
+ ref: request.source.ref,
651
+ commit,
652
+ ...(branch ? { branch: true } : {}),
653
+ };
602
654
  }
603
655
  catch (e) {
604
656
  const message = e instanceof Error ? e.message : String(e);
@@ -638,6 +690,7 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
638
690
  ...(sleepTtl ? { sleepTtl } : {}),
639
691
  name: serviceName,
640
692
  endpoints: (0, service_runs_1.toRunEndpoints)(request.endpoints, (0, service_runs_1.getEndpointHosts)(serviceName, principal, request.endpoints), endpointUrl, request.publicPaths),
693
+ ...(request.restart?.length ? { restart: request.restart } : {}),
641
694
  }
642
695
  : undefined;
643
696
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
@@ -704,7 +757,8 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
704
757
  }
705
758
  catch (e) {
706
759
  if (e instanceof runs_1.RunError) {
707
- (0, http_2.send)(res, e.status, { error: e.message });
760
+ // a proxy answers 503 too, also after the server took the request: this one is safe to send again
761
+ (0, http_2.send)(res, e.status, { error: e.message }, e instanceof runs_1.ShuttingDownError ? { [http_2.RETRY_HEADER]: 'safe' } : {});
708
762
  return;
709
763
  }
710
764
  if (e instanceof sandboxes_1.SandboxError) {
@@ -773,7 +827,7 @@ async function handle(api, verifier, req, res) {
773
827
  * dashboard, which asks the same API for what its pages show (dashboard.ts).
774
828
  */
775
829
  async function handleApi(api, principal, req, res, url) {
776
- const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, capacity, log, } = api;
830
+ const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, artifacts, capacity, log, now, } = api;
777
831
  const path = url.pathname;
778
832
  if (await (0, accounts_api_1.handleAccounts)(config, log, principal, req, res, url)) {
779
833
  return;
@@ -787,6 +841,9 @@ async function handleApi(api, principal, req, res, url) {
787
841
  if (await (0, sandboxes_api_1.handleSandboxes)(config, sandboxes.registry, repos, log, principal, req, res, url)) {
788
842
  return;
789
843
  }
844
+ if (await (0, artifacts_api_1.handleArtifacts)(config, registry, artifacts, log, principal, req, res, url, now)) {
845
+ return;
846
+ }
790
847
  if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, (host) => gateway?.url(host) ?? host, log, principal, req, res, url)) {
791
848
  return;
792
849
  }
@@ -822,22 +879,53 @@ async function handleApi(api, principal, req, res, url) {
822
879
  if (!params.has('scope')) {
823
880
  params.set('scope', 'visible');
824
881
  }
825
- let filter;
882
+ // the text is looked for in the tasks, not in the runs they ran in
883
+ params.delete('q');
884
+ let filter, page, values, order;
885
+ const text = (0, paging_1.readText)(url.searchParams);
826
886
  try {
827
887
  filter = (0, overview_1.parseRunFilter)(params, viewer.grant);
888
+ values = (0, paging_1.parseValues)(url.searchParams, task_order_1.TASK_FIELDS);
889
+ page = values ? undefined : (0, paging_1.parsePage)(url.searchParams);
890
+ order = (0, task_order_1.parseTaskOrder)(url.searchParams);
828
891
  }
829
892
  catch (e) {
830
893
  (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
831
894
  return;
832
895
  }
833
- const runs = (0, overview_1.filterRuns)(registry.all(), viewer, filter).map((run) => (0, overview_1.toListedRun)(viewer, run));
834
- const oldest = (0, timings_1.getOldestCounted)(runs);
835
- // where in the repository the build file of the last run is, as its version says
836
- const tasks = (0, timings_1.getTaskStats)(runs, Date.now()).map((stats) => {
837
- const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
838
- return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
839
- });
840
- (0, http_2.send)(res, 200, { tasks, ...(oldest ? { oldest } : {}) });
896
+ const statsOf = (over) => {
897
+ const runs = (0, overview_1.filterRuns)(registry.all(), viewer, over).map((run) => (0, overview_1.toListedRun)(viewer, run));
898
+ // where in the repository the build file of the last run is, as its version says
899
+ const tasks = (0, timings_1.getTaskStats)(runs, Date.now())
900
+ .map((stats) => {
901
+ const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
902
+ return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
903
+ })
904
+ .filter((stats) => !text || (0, paging_1.hasText)([stats.repo, stats.task, stats.last.entry], text));
905
+ return { runs, tasks };
906
+ };
907
+ try {
908
+ if (values) {
909
+ const { sources, ...others } = filter;
910
+ void sources;
911
+ const counted = (0, paging_1.countValues)(statsOf(others).tasks, (stats) => [(0, task_order_1.taskSource)(stats)], values);
912
+ (0, http_2.send)(res, 200, (0, paging_1.answerPage)('values', counted));
913
+ return;
914
+ }
915
+ const { runs, tasks } = statsOf(filter);
916
+ const oldest = (0, timings_1.getOldestCounted)(runs);
917
+ const sorted = order ? (0, task_order_1.sortTasks)(tasks, order) : tasks;
918
+ (0, http_2.send)(res, 200, {
919
+ ...(page ? (0, paging_1.answerPage)('tasks', (0, paging_1.pageByPosition)(sorted, page)) : { tasks: sorted }),
920
+ ...(oldest ? { oldest } : {}),
921
+ });
922
+ }
923
+ catch (e) {
924
+ if (!(e instanceof paging_1.ListParamError)) {
925
+ throw e;
926
+ }
927
+ (0, http_2.send)(res, 400, { error: e.message });
928
+ }
841
929
  return;
842
930
  }
843
931
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -862,7 +950,8 @@ async function startServer(config, environment, options = {}) {
862
950
  const log = (line) => write(line.replace(/\p{Cc}/gu, '?').slice(0, 1000));
863
951
  if (config.runtimes.includes('local') && config.backend.type === 'host') {
864
952
  log('warning: the local runtime is allowed, local tasks run as the user of this server and read all it can read; ' +
865
- 'an account is then an approval class, not a credential boundary');
953
+ 'an account is then an approval class, not a credential boundary, and the server keeps no outputs of its runs ' +
954
+ '(remote artifacts)');
866
955
  }
867
956
  // build files are read, planned and run as the server's runs see the world: the
868
957
  // operator's accounts and the allowlisted environment, nothing of the server's own
@@ -875,6 +964,8 @@ async function startServer(config, environment, options = {}) {
875
964
  },
876
965
  policy: {
877
966
  envs: config.runs.env.allow,
967
+ // the registries a build file's cache may name: the operator's, see cache-push.ts
968
+ cacheRegistries: (0, cache_push_1.cacheRegistriesOf)(config),
878
969
  reserved: (0, server_config_1.getServerAccounts)(config),
879
970
  runtimes: config.runtimes,
880
971
  backend: config.backend.type,
@@ -942,6 +1033,18 @@ async function startServer(config, environment, options = {}) {
942
1033
  if (config.backend.type === 'host' || config.entitlements.some((entitlement) => entitlement.sandboxes?.length)) {
943
1034
  await sandboxes.registry.load();
944
1035
  }
1036
+ // a local task of a host runs as the user of this server: what it can write is never served
1037
+ const localTasksOnHost = config.backend.type === 'host' && config.runtimes.includes('local');
1038
+ // a service run from a sandbox on a cluster gets the changed files of the sandbox into its
1039
+ // services, batched (SandboxFollow), as the files that changed since the services last got theirs
1040
+ // the folder a server before the direct sync staged the changes in is no longer used
1041
+ await (0, promises_1.rm)((0, path_1.join)(storage, 'sandboxes', 'sync'), { recursive: true, force: true });
1042
+ const sandboxSync = new sandbox_sync_1.SandboxSync({
1043
+ files: (owner, id) => sandboxes.registry.files(owner, id),
1044
+ upOn: (id) => registry.upOn(id),
1045
+ send: (run, changes) => registry.syncFiles(run, changes),
1046
+ log,
1047
+ });
945
1048
  const executorOptions = {
946
1049
  definitions,
947
1050
  planning,
@@ -949,7 +1052,17 @@ async function startServer(config, environment, options = {}) {
949
1052
  directory: (0, path_1.join)(storage, 'runs'),
950
1053
  cache: (0, path_1.join)(storage, 'cache'),
951
1054
  worker: options.worker,
952
- sandboxes: { ...sandboxes, network: config.sandboxes.network },
1055
+ sandboxes: {
1056
+ ...sandboxes,
1057
+ network: config.sandboxes.network,
1058
+ started: async (run) => sandboxSync.started(run),
1059
+ ended: async (run) => sandboxSync.forget(run.id),
1060
+ syncFailed: (runId) => sandboxSync.failed(runId),
1061
+ },
1062
+ localTasksOnHost,
1063
+ // the registry a trusted run writes its cache to, with the password of this server's environment
1064
+ cachePush: (run) => (0, cache_push_1.cachePushOf)(run, config, environment.processEnvs),
1065
+ cacheRegistries: (0, cache_push_1.cacheRegistriesOf)(config),
953
1066
  ...(config.backend.type === 'host' && config.backend.capabilities
954
1067
  ? { capabilityRuntime: config.backend.capabilities.runtime }
955
1068
  : {}),
@@ -970,6 +1083,11 @@ async function startServer(config, environment, options = {}) {
970
1083
  void sweepChecks();
971
1084
  const sweeping = setInterval(sweepChecks, CHECK_SWEEP_MS);
972
1085
  sweeping.unref();
1086
+ const artifacts = new run_artifacts_1.ArtifactStore((0, path_1.join)(storage, 'artifacts'), {
1087
+ keep: (0, units_1.parseDuration)(config.runs.artifacts.keep),
1088
+ total: (0, units_1.parseSize)(config.runs.artifacts.total),
1089
+ localTasksOnHost,
1090
+ });
973
1091
  const registry = new runs_1.RunRegistry({
974
1092
  executor,
975
1093
  maxConcurrent: config.runs.maxConcurrent,
@@ -996,12 +1114,32 @@ async function startServer(config, environment, options = {}) {
996
1114
  .then(() => log(`checks run=${run.id} passed=[${passed.map((record) => record.task).join(',')}]`))
997
1115
  .catch((e) => log(`the checks of run ${run.id} were not kept: ${e instanceof Error ? e.message : e}`));
998
1116
  }
1117
+ // what the run kept counts against the total of all runs from now
1118
+ void sweepArtifacts();
1119
+ },
1120
+ artifacts: {
1121
+ directoryOf: (id) => artifacts.directoryOf(id),
1122
+ maxBytes: (0, units_1.parseSize)(config.runs.artifacts.maxBytes),
999
1123
  },
1000
1124
  log,
1001
1125
  });
1002
- // the executor hears which service runs sleep with their volumes kept, and removes what it
1003
- // kept for any other (RunExecutor.restored)
1126
+ const now = options.now ?? Date.now;
1127
+ // what is over its time goes within the hour, what is over the total when a run ends
1128
+ const sweepArtifacts = () => artifacts
1129
+ .sweep((id) => registry.peek(id), now())
1130
+ .then((removed) => {
1131
+ if (removed.length > 0) {
1132
+ log(`removed the outputs of ${removed.length} runs: ${removed.join(', ')}`);
1133
+ }
1134
+ })
1135
+ .catch((e) => log(`the outputs of old runs could not be removed: ${e instanceof Error ? e.message : e}`));
1136
+ const sweepingArtifacts = setInterval(sweepArtifacts, ARTIFACT_SWEEP_MS);
1137
+ sweepingArtifacts.unref();
1138
+ // the runs the server before stopped resume, and the executor hears which service runs sleep
1139
+ // with their volumes kept and which runs resume, and removes what it kept for any other
1140
+ // (RunExecutor.restored)
1004
1141
  await registry.restore();
1142
+ void sweepArtifacts();
1005
1143
  const proposals = new proposals_1.ProposalRegistry({
1006
1144
  maxWaiting: config.approvals.maxWaiting,
1007
1145
  timeout: (0, units_1.parseDuration)(config.approvals.timeout),
@@ -1037,14 +1175,23 @@ async function startServer(config, environment, options = {}) {
1037
1175
  planning,
1038
1176
  repos,
1039
1177
  checks,
1178
+ artifacts,
1040
1179
  capacity,
1041
1180
  log,
1181
+ now,
1042
1182
  };
1043
1183
  await gateway?.load();
1044
1184
  sandboxes.registry.useRuns({
1045
1185
  holder: (id) => registry.holder(id),
1046
1186
  stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
1047
1187
  });
1188
+ // A service run from a sandbox follows the files of the sandbox: a burst of edits or runs that
1189
+ // wrote is synced once, when the sandbox has been quiet for a moment (SandboxFollow)
1190
+ const follower = new sandbox_follow_1.SandboxFollow({
1191
+ follow: (id) => sandboxSync.follow(id),
1192
+ log: (line) => log(`follow ${line}`),
1193
+ });
1194
+ sandboxes.registry.onChange((id) => follower.changed(id));
1048
1195
  const listener = (req, res) => {
1049
1196
  handle(api, verifier, req, res).catch((e) => {
1050
1197
  if (e instanceof http_2.HttpError) {
@@ -1138,7 +1285,10 @@ async function startServer(config, environment, options = {}) {
1138
1285
  },
1139
1286
  close: async () => {
1140
1287
  clearInterval(sweeping);
1288
+ clearInterval(sweepingArtifacts);
1141
1289
  proposals.close();
1290
+ follower.close();
1291
+ sandboxSync.close();
1142
1292
  await registry.close();
1143
1293
  await new Promise((resolve, reject) => {
1144
1294
  server.close((err) => (err ? reject(err) : resolve()));
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sortTasks = exports.parseTaskOrder = exports.taskSource = exports.TASK_FIELDS = void 0;
4
+ const paging_1 = require("./paging");
5
+ // what GET /v1/tasks?values= answers the values of: where the tasks ran from
6
+ exports.TASK_FIELDS = ['source'];
7
+ // where the runs of a task are from, as the source filter of the runs names it
8
+ function taskSource(stats) {
9
+ return stats.repo === 'an upload' ? 'upload' : stats.repo;
10
+ }
11
+ exports.taskSource = taskSource;
12
+ // of its runs, how many came from the cache, and how many ended well (cached passed before)
13
+ const rate = (part, stats) => (stats.runs ? part / stats.runs : undefined);
14
+ // what `sort` of GET /v1/tasks orders by: the columns of the Tasks page
15
+ const SORT_BY = {
16
+ task: (stats) => stats.task,
17
+ last: (stats) => Date.parse(stats.last.at),
18
+ runs: (stats) => stats.runs,
19
+ cache: (stats) => rate(stats.cached, stats),
20
+ success: (stats) => rate(stats.runs - stats.failed, stats),
21
+ median: (stats) => stats.medianMs,
22
+ p90: (stats) => stats.p90Ms,
23
+ total: (stats) => stats.totalMs,
24
+ };
25
+ // `sort` and `order` (asc or desc, desc when left out): undefined when the caller names no sort.
26
+ function parseTaskOrder(params) {
27
+ const sort = params.get('sort');
28
+ if (sort === null) {
29
+ return undefined;
30
+ }
31
+ if (!(sort in SORT_BY)) {
32
+ throw new paging_1.ListParamError(`sort: one of ${Object.keys(SORT_BY).join(', ')}`);
33
+ }
34
+ const order = params.get('order') ?? 'desc';
35
+ if (order !== 'asc' && order !== 'desc') {
36
+ throw new paging_1.ListParamError('order: asc or desc');
37
+ }
38
+ return { sort, order };
39
+ }
40
+ exports.parseTaskOrder = parseTaskOrder;
41
+ // The tasks in that order, those without a value last, and by repository and name when equal.
42
+ function sortTasks(tasks, { sort, order }) {
43
+ const value = SORT_BY[sort];
44
+ return [...tasks].sort((a, b) => {
45
+ const x = value(a);
46
+ const y = value(b);
47
+ if (x === undefined || y === undefined) {
48
+ return x === y ? tie(a, b) : x === undefined ? 1 : -1;
49
+ }
50
+ const compared = typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y));
51
+ return (order === 'asc' ? compared : -compared) || tie(a, b);
52
+ });
53
+ }
54
+ exports.sortTasks = sortTasks;
55
+ const tie = (a, b) => a.repo.localeCompare(b.repo) || a.task.localeCompare(b.task);
56
+ //# sourceMappingURL=task-order.js.map
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRelativePath = void 0;
4
+ /**
5
+ * A path relative to a root (of a project, a bundle, a sandbox), as the API and the CLI take
6
+ * it: at most `maxLength` characters, `/` between names, no `.` or `..` or empty name, no
7
+ * backslash, no NUL, nothing absolute (`/x`, `C:x`). The one rule every path an input names
8
+ * is checked by, so the places that check it can not drift apart.
9
+ */
10
+ function isRelativePath(path, maxLength) {
11
+ return (path.length > 0 &&
12
+ path.length <= maxLength &&
13
+ !path.startsWith('/') &&
14
+ !/^[A-Za-z]:/.test(path) &&
15
+ !path.includes('\\') &&
16
+ !path.includes('\0') &&
17
+ !path.split('/').some((part) => part === '' || part === '.' || part === '..'));
18
+ }
19
+ exports.isRelativePath = isRelativePath;
20
+ //# sourceMappingURL=project-path.js.map
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tarFiles = void 0;
4
+ const tar_1 = require("tar");
5
+ const path_1 = require("path");
6
+ const BLOCK = 512;
7
+ // the header of an entry, encoded in one block (node-tar cuts a long name to fit it)
8
+ function block(header) {
9
+ const buf = Buffer.alloc(BLOCK);
10
+ header.encode(buf, 0);
11
+ return buf;
12
+ }
13
+ // the bytes of `content` padded to whole blocks
14
+ function padded(content) {
15
+ const rest = content.length % BLOCK;
16
+ return rest === 0 ? content : Buffer.concat([content, Buffer.alloc(BLOCK - rest)]);
17
+ }
18
+ /**
19
+ * The archive of `files`: each at its path, with its mode, mtime and content. An empty list is
20
+ * an empty archive, the two blocks that end one.
21
+ */
22
+ function tarFiles(files) {
23
+ const blocks = [];
24
+ for (const file of files) {
25
+ const mtime = file.mtime ?? new Date();
26
+ const header = new tar_1.Header({
27
+ path: file.path,
28
+ mode: file.mode,
29
+ size: file.content.length,
30
+ type: 'File',
31
+ mtime,
32
+ });
33
+ // encoding sets `needPax` when the path does not fit a ustar header
34
+ const head = block(header);
35
+ if (header.needPax) {
36
+ const body = Buffer.from(new tar_1.Pax({ path: file.path }, false).encodeBody());
37
+ const extended = new tar_1.Header({
38
+ path: `PaxHeader/${path_1.posix.basename(file.path)}`.slice(0, 100),
39
+ mode: 0o644,
40
+ size: body.length,
41
+ type: 'ExtendedHeader',
42
+ mtime,
43
+ });
44
+ blocks.push(block(extended), padded(body));
45
+ }
46
+ blocks.push(head, padded(file.content));
47
+ }
48
+ blocks.push(Buffer.alloc(BLOCK * 2));
49
+ return Buffer.concat(blocks);
50
+ }
51
+ exports.tarFiles = tarFiles;
52
+ //# sourceMappingURL=tar-files.js.map
package/dist/utils/tar.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.onlyBelow = exports.extractOutput = exports.packArchive = void 0;
3
+ exports.onlyBelow = exports.extractOutput = exports.measureArchive = exports.packArchive = void 0;
4
+ const fs_1 = require("fs");
4
5
  const tar_1 = require("tar");
5
6
  const path_1 = require("path");
6
7
  function packArchive(options, files) {
@@ -34,6 +35,41 @@ const NOT_PACKED = '\0';
34
35
  function isExact(key) {
35
36
  return key.split(':').every((part) => Number.isSafeInteger(Number(part)));
36
37
  }
38
+ // The entries of an archive and the bytes of their content, unpacked, measured before anything
39
+ // is extracted from it. Reading stops at the first entry that takes it past `limit`, so what
40
+ // is returned is then more than the limit, and the rest of the archive is not read.
41
+ function measureArchive(file, limit) {
42
+ return new Promise((resolve, reject) => {
43
+ const measured = { entries: 0, bytes: 0 };
44
+ let done = false;
45
+ const source = (0, fs_1.createReadStream)(file);
46
+ const parser = new tar_1.Parser({
47
+ onReadEntry: (entry) => {
48
+ if (done) {
49
+ entry.resume();
50
+ return;
51
+ }
52
+ measured.entries++;
53
+ measured.bytes += entry.size ?? 0;
54
+ entry.resume();
55
+ if (measured.entries > limit.entries || measured.bytes > limit.bytes) {
56
+ done = true;
57
+ source.unpipe(parser);
58
+ source.destroy();
59
+ resolve({ ...measured });
60
+ }
61
+ },
62
+ });
63
+ parser.on('end', () => {
64
+ done = true;
65
+ resolve({ ...measured });
66
+ });
67
+ parser.on('error', reject);
68
+ source.on('error', reject);
69
+ source.pipe(parser);
70
+ });
71
+ }
72
+ exports.measureArchive = measureArchive;
37
73
  // Extracts the archive of one output (a path relative to `cwd`) into `cwd`. An archive
38
74
  // comes from a cache another run, or whoever writes to the cache backend, filled, so only
39
75
  // entries of that output are taken: one beside it (another output, a source of the task, a
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.1.0",
4
+ "version": "2.2.0-next.2",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",