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
@@ -55,6 +55,8 @@ const UNSCHEDULABLE_MS = 10000;
55
55
  // how long a pod may take to start, its image pull included
56
56
  const POD_START_MS = 5 * 60 * 1000;
57
57
  const REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
58
+ // how long a pod of the files may take to be deleted, before the requests that wait for it go on
59
+ const POD_REMOVE_MS = 2 * 60 * 1000;
58
60
  const FETCH_TIMEOUT_MS = 10 * 60 * 1000;
59
61
  // an answer is read into memory up to this; a diff is up to 64 MiB, as JSON a bit more
60
62
  const MAX_ANSWER_BYTES = 160 * 1024 * 1024;
@@ -110,6 +112,8 @@ class KubernetesSandboxStorage {
110
112
  // one request at a time per sandbox, as a host has it: the objects `state` writes are
111
113
  // pruned again in the pod, which must not meet another request that still needs them
112
114
  this.queues = new Map();
115
+ // per sandbox, the pod that is being taken away: until it is gone no pod of the sandbox starts
116
+ this.leaving = new Map();
113
117
  this.backend = config.backend;
114
118
  const access = (0, kubernetes_backend_1.getClusterAccess)(config.backend, env);
115
119
  this.instance =
@@ -311,7 +315,8 @@ class KubernetesSandboxStorage {
311
315
  const names = getSandboxNames(key.id);
312
316
  const namespace = this.namespaces.name(key.owner);
313
317
  const pod = await this.usePod(key);
314
- pod.runs++;
318
+ // the pod counts this run only once the copy is over: until then the pod is a request
319
+ // under way, which a pod that makes way for another run waits for (makeWayForRun)
315
320
  const leave = () => {
316
321
  pod.runs--;
317
322
  this.leavePod(key, pod);
@@ -325,12 +330,13 @@ class KubernetesSandboxStorage {
325
330
  await (0, promises_1.mkdir)(into, { recursive: true });
326
331
  await this.copyOut(key, ['tar', 'cf', '-', '-C', `${CLAIM_PATH}/${key.id}/files`, '.'], into,
327
332
  // what the run plans with: files, directories and links, nothing outside of it
328
- (_path, type) => ['File', 'OldFile', 'ContiguousFile', 'Directory', 'SymbolicLink'].includes(type), AbortSignal.timeout(FETCH_TIMEOUT_MS));
333
+ (_path, type) => ['File', 'OldFile', 'ContiguousFile', 'Directory', 'SymbolicLink'].includes(type), AbortSignal.timeout(FETCH_TIMEOUT_MS), pod);
329
334
  }
330
335
  catch (e) {
331
- leave();
336
+ this.leavePod(key, pod);
332
337
  throw e;
333
338
  }
339
+ pod.runs++;
334
340
  const watching = new AbortController();
335
341
  void this.makeWayForRun(key, pod, watching.signal);
336
342
  return {
@@ -376,16 +382,14 @@ class KubernetesSandboxStorage {
376
382
  condition.reason === 'Unschedulable' &&
377
383
  Date.now() - new Date(condition.lastTransitionTime ?? Date.now()).getTime() >= UNSCHEDULABLE_MS));
378
384
  if (stuck && !signal.aborted && this.pods.get(key.id) === pod) {
379
- // requests under way are answered first; the next one starts a pod next to the run's
380
- this.pods.delete(key.id);
381
- clearTimeout(pod.idle);
382
- for (let i = 0; pod.busy > pod.runs && i < REQUEST_TIMEOUT_MS / 100; i++) {
383
- await (0, sleep_1.sleep)(100);
384
- }
385
- // what it owns stays for the run (the egress proxies of its tasks) and goes
386
- // when the run released it
387
- pod.movedAside = true;
388
- await this.deletePod(pod.namespace, pod.name, 'Orphan');
385
+ // requests under way are answered first; the next one starts a pod next to the run's,
386
+ // once this one is gone: it has the name of this one, and would be the one deleted
387
+ await this.retire(key.id, pod, () => pod.runs, async () => {
388
+ // what it owns stays for the run (the egress proxies of its tasks) and goes
389
+ // when the run released it
390
+ await this.deletePod(pod.namespace, pod.name, 'Orphan', pod.uid);
391
+ pod.movedAside = true;
392
+ });
389
393
  return;
390
394
  }
391
395
  }
@@ -396,7 +400,9 @@ class KubernetesSandboxStorage {
396
400
  }
397
401
  // What a tar in the pod writes, extracted into `into`: the entries `keep` takes, up to
398
402
  // the bytes a sandbox may take.
399
- async copyOut(key, command, into, keep, signal) {
403
+ async copyOut(key, command, into, keep, signal,
404
+ // the pod a caller holds already: asking for one again would wait for a pod that goes
405
+ held) {
400
406
  let bytes = 0;
401
407
  const extract = (0, tar_1.extract)({
402
408
  cwd: into,
@@ -416,7 +422,12 @@ class KubernetesSandboxStorage {
416
422
  });
417
423
  extracted.catch(() => undefined);
418
424
  counted.pipe(extract);
419
- await this.withPod(key, (pod) => this.exec(pod, command, null, counted, signal));
425
+ if (held) {
426
+ await this.exec(held, command, null, counted, signal);
427
+ }
428
+ else {
429
+ await this.withPod(key, (pod) => this.exec(pod, command, null, counted, signal));
430
+ }
420
431
  counted.end();
421
432
  await extracted;
422
433
  }
@@ -569,6 +580,10 @@ class KubernetesSandboxStorage {
569
580
  }
570
581
  // The running pod of the sandbox's files, which stays until `leavePod`.
571
582
  async usePod(key) {
583
+ // a pod that goes (stopPod, makeWayForRun) has the name the next one gets
584
+ while (this.leaving.has(key.id)) {
585
+ await this.leaving.get(key.id);
586
+ }
572
587
  let pod = this.pods.get(key.id);
573
588
  if (pod?.started !== undefined && pod.busy === 0 && Date.now() - pod.started > POD_RENEW_MS) {
574
589
  // nothing uses it and its deadline nears: a new one, before a run needs it for long
@@ -620,34 +635,80 @@ class KubernetesSandboxStorage {
620
635
  }
621
636
  // Takes the pod of the sandbox's files down, once the requests under way are answered.
622
637
  async stopPod(key, namespace = this.namespaces.name(key.owner)) {
623
- const pod = this.pods.get(key.id);
638
+ // no await between the last look at `leaving` and `retire`, which sets it
639
+ while (this.leaving.has(key.id)) {
640
+ await this.leaving.get(key.id);
641
+ }
642
+ await this.retire(key.id, this.pods.get(key.id), () => 0, () => this.deletePod(namespace, getSandboxNames(key.id).pod));
643
+ }
644
+ /**
645
+ * Takes `pod` (if there is one) out of use, waits until no more than `keep()` of its users are
646
+ * left (the requests under way are answered, the runs that hold it stay) and then runs
647
+ * `remove`, for at most POD_REMOVE_MS. A pod after it has the same name, so none starts
648
+ * (usePod) before this is over: it would take the pod that goes, or be deleted by its name.
649
+ */
650
+ async retire(id, pod, keep, remove) {
624
651
  if (pod) {
625
- this.pods.delete(key.id);
652
+ if (this.pods.get(id) === pod) {
653
+ this.pods.delete(id);
654
+ }
626
655
  clearTimeout(pod.idle);
627
- for (let i = 0; pod.busy > 0 && i < REQUEST_TIMEOUT_MS / 100; i++) {
656
+ }
657
+ const gone = (async () => {
658
+ for (let i = 0; pod && pod.busy > keep() && i < REQUEST_TIMEOUT_MS / 100; i++) {
628
659
  await (0, sleep_1.sleep)(100);
629
660
  }
661
+ let timer;
662
+ try {
663
+ await Promise.race([
664
+ remove(),
665
+ new Promise((_resolve, reject) => {
666
+ timer = setTimeout(() => reject(new Error('the pod of the sandbox did not go in time')), POD_REMOVE_MS);
667
+ }),
668
+ ]);
669
+ }
670
+ finally {
671
+ clearTimeout(timer);
672
+ }
673
+ })();
674
+ // a remove that is stuck must not hold the requests of the sandbox: `leaving` always settles
675
+ const settled = gone.catch(() => undefined);
676
+ this.leaving.set(id, settled);
677
+ try {
678
+ await gone;
679
+ }
680
+ finally {
681
+ await settled;
682
+ if (this.leaving.get(id) === settled) {
683
+ this.leaving.delete(id);
684
+ }
630
685
  }
631
- await this.deletePod(namespace, getSandboxNames(key.id).pod);
632
686
  }
633
- async deletePod(namespace, name, propagationPolicy) {
687
+ // Deletes a pod and waits until it is gone. With its `uid` only that pod goes: one that has
688
+ // the name now is another, which a late delete must not remove.
689
+ async deletePod(namespace, name, propagationPolicy, uid) {
634
690
  try {
635
691
  await this.instance.coreApi.deleteNamespacedPod({
636
692
  name,
637
693
  namespace,
638
694
  gracePeriodSeconds: 0,
639
695
  ...(propagationPolicy ? { propagationPolicy } : {}),
696
+ ...(uid ? { body: { preconditions: { uid } } } : {}),
640
697
  });
641
698
  }
642
699
  catch (e) {
643
- if ((0, apply_1.statusCodeOf)(e) === 404) {
700
+ // 409: the precondition failed, the pod of that uid is gone
701
+ if ((0, apply_1.statusCodeOf)(e) === 404 || (uid && (0, apply_1.statusCodeOf)(e) === 409)) {
644
702
  return;
645
703
  }
646
704
  throw e;
647
705
  }
648
706
  for (let attempt = 0; attempt < 120; attempt++) {
649
707
  try {
650
- await this.instance.coreApi.readNamespacedPod({ name, namespace });
708
+ const found = await this.instance.coreApi.readNamespacedPod({ name, namespace });
709
+ if (uid && found.metadata?.uid !== uid) {
710
+ return;
711
+ }
651
712
  }
652
713
  catch (e) {
653
714
  if ((0, apply_1.statusCodeOf)(e) === 404) {
@@ -1030,8 +1091,9 @@ class KubernetesSandboxFiles {
1030
1091
  changes() {
1031
1092
  return this.ask({ op: 'changes' });
1032
1093
  }
1033
- diff(format, author) {
1034
- return this.ask({ op: 'diff', format, author });
1094
+ diff(format, author, paths) {
1095
+ // a pod of an older image leaves `paths` out and answers the whole diff
1096
+ return this.ask({ op: 'diff', format, author, ...(paths ? { paths } : {}) });
1035
1097
  }
1036
1098
  async commit(author) {
1037
1099
  return (await this.ask({ op: 'commit', author })) ?? undefined;
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.visibleCapacity = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.mayRetry = exports.runActions = exports.getViewer = exports.describeWait = void 0;
3
+ exports.visibleCapacity = exports.withoutField = exports.runValues = exports.runSource = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.STATES = exports.RUN_FIELDS = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.mayRetry = exports.runActions = exports.getViewer = exports.describeWait = void 0;
4
4
  const policy_1 = require("./policy");
5
5
  const runs_1 = require("./runs");
6
6
  const service_runs_1 = require("./service-runs");
7
7
  const repo_1 = require("./repo");
8
8
  const units_1 = require("../utils/units");
9
+ const paging_1 = require("./paging");
9
10
  var wait_reason_1 = require("./wait-reason");
10
11
  Object.defineProperty(exports, "describeWait", { enumerable: true, get: function () { return wait_reason_1.describeWait; } });
11
12
  function getViewer(config, principal) {
@@ -227,7 +228,9 @@ exports.getOverview = getOverview;
227
228
  function meter(runs, limit) {
228
229
  return { used: runs.length, ...(limit !== undefined ? { limit } : {}), runs: [...runs] };
229
230
  }
230
- const STATES = [
231
+ // what the filters of the runs page narrow by, and GET /v1/runs?values= answers the values of
232
+ exports.RUN_FIELDS = ['state', 'source', 'task'];
233
+ exports.STATES = [
231
234
  'awaiting-approval',
232
235
  'queued',
233
236
  'running',
@@ -238,7 +241,8 @@ const STATES = [
238
241
  'cancelled',
239
242
  'rejected',
240
243
  ];
241
- // `scope`, `state` (a comma separated list) and `kind` of GET /v1/runs.
244
+ // `scope`, `state` (a comma separated list, or repeated), `kind`, `id`, `sandbox`, `since`,
245
+ // `until`, `source` and `task` (each repeated for more than one) and `q` of GET /v1/runs.
242
246
  function parseRunFilter(params, grant, now = Date.now()) {
243
247
  const scope = params.get('scope') ?? 'mine';
244
248
  if (scope !== 'mine' && scope !== 'visible' && scope !== 'all') {
@@ -247,11 +251,14 @@ function parseRunFilter(params, grant, now = Date.now()) {
247
251
  if (scope === 'all' && !grant.observe) {
248
252
  throw new FilterRefused('scope all needs an entitlement with observe');
249
253
  }
250
- const state = params.get('state');
251
- const states = state
252
- ? state.split(',').map((value) => {
253
- if (!STATES.includes(value)) {
254
- throw new Error(`state: one or more of ${STATES.join(', ')}`);
254
+ const state = params
255
+ .getAll('state')
256
+ .flatMap((value) => value.split(','))
257
+ .filter(Boolean);
258
+ const states = state.length
259
+ ? state.map((value) => {
260
+ if (!exports.STATES.includes(value)) {
261
+ throw new Error(`state: one or more of ${exports.STATES.join(', ')}`);
255
262
  }
256
263
  return value;
257
264
  })
@@ -264,18 +271,29 @@ function parseRunFilter(params, grant, now = Date.now()) {
264
271
  if (id !== undefined && !/^run_[A-Za-z0-9_-]{16}$/.test(id)) {
265
272
  throw new Error('id: the id of a run, run_...');
266
273
  }
274
+ const sandbox = params.get('sandbox') ?? undefined;
275
+ if (sandbox !== undefined && !runs_1.SANDBOX_ID_PATTERN.test(sandbox)) {
276
+ throw new Error('sandbox: the id of a sandbox, sbx_...');
277
+ }
267
278
  const since = parseMoment(params.get('since'), now, 'since');
268
279
  const until = parseMoment(params.get('until'), now, 'until');
269
280
  if (since !== undefined && until !== undefined && until < since) {
270
281
  throw new Error('until: after since');
271
282
  }
283
+ const sources = (0, paging_1.readList)(params, 'source');
284
+ const tasks = (0, paging_1.readList)(params, 'task');
285
+ const text = (0, paging_1.readText)(params);
272
286
  return {
273
287
  scope,
274
288
  ...(states ? { states } : {}),
275
289
  ...(kind ? { kind } : {}),
276
290
  ...(id ? { id } : {}),
291
+ ...(sandbox ? { sandbox } : {}),
277
292
  ...(since !== undefined ? { since } : {}),
278
293
  ...(until !== undefined ? { until } : {}),
294
+ ...(sources ? { sources } : {}),
295
+ ...(tasks ? { tasks } : {}),
296
+ ...(text ? { text } : {}),
279
297
  };
280
298
  }
281
299
  exports.parseRunFilter = parseRunFilter;
@@ -299,12 +317,58 @@ exports.FilterRefused = FilterRefused;
299
317
  function filterRuns(runs, viewer, filter) {
300
318
  return runs.filter((run) => (filter.scope === 'mine' ? owns(viewer, run) : maySee(viewer, run)) &&
301
319
  (!filter.id || run.id === filter.id) &&
320
+ (!filter.sandbox || (run.source.type === 'sandbox' && run.source.id === filter.sandbox)) &&
302
321
  (!filter.states || filter.states.includes(run.state)) &&
303
322
  (!filter.kind || (filter.kind === 'services') === !!run.up) &&
304
323
  (filter.since === undefined || Date.parse(run.createdAt) >= filter.since) &&
305
- (filter.until === undefined || Date.parse(run.createdAt) <= filter.until));
324
+ (filter.until === undefined || Date.parse(run.createdAt) <= filter.until) &&
325
+ (!filter.sources || filter.sources.includes(runSource(run))) &&
326
+ (!filter.tasks || runWork(run).some((name) => filter.tasks?.includes(name))) &&
327
+ (!filter.text || (0, paging_1.hasText)(runText(viewer, run), filter.text)));
306
328
  }
307
329
  exports.filterRuns = filterRuns;
330
+ // where a run is from, as the source filter names it: its repository, or `upload`
331
+ function runSource(run) {
332
+ return run.source.type === 'upload' ? 'upload' : run.source.repo;
333
+ }
334
+ exports.runSource = runSource;
335
+ // the tasks a run runs, or the services it keeps up
336
+ function runWork(run) {
337
+ return [...run.tasks, ...(run.up?.services ?? [])];
338
+ }
339
+ // what of a run the text of a search is looked for in: what the list shows of it
340
+ function runText(viewer, run) {
341
+ return [
342
+ run.id,
343
+ run.owner.sub,
344
+ run.owner.name ?? viewer.nameOf?.(run.owner),
345
+ ...runWork(run),
346
+ run.up?.name,
347
+ run.source.type === 'upload' ? undefined : run.source.repo,
348
+ run.source.type === 'ref' ? run.source.ref : undefined,
349
+ ];
350
+ }
351
+ // The values a field of the runs has, as GET /v1/runs?values= answers them: the states in the
352
+ // order a run goes through them, the others the most used first.
353
+ function runValues(field) {
354
+ switch (field) {
355
+ case 'state':
356
+ return { of: (run) => [run.state], order: exports.STATES };
357
+ case 'source':
358
+ return { of: (run) => [runSource(run)] };
359
+ case 'task':
360
+ return { of: runWork };
361
+ }
362
+ }
363
+ exports.runValues = runValues;
364
+ // The filter without the one of a field: what the values of that field are counted over.
365
+ function withoutField(filter, field) {
366
+ const key = { state: 'states', source: 'sources', task: 'tasks' }[field];
367
+ const { [key]: dropped, ...rest } = filter;
368
+ void dropped;
369
+ return rest;
370
+ }
371
+ exports.withoutField = withoutField;
308
372
  // The machines and what the runs take, with whose the namespaces are where the caller may
309
373
  // know: their own, and every one with `observe`.
310
374
  function visibleCapacity(capacity, viewer) {
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * The pages of a list the API answers, and the values its filters can take.
4
+ *
5
+ * A list asked with `limit` answers that many at most, and `next` while more remain: the
6
+ * `cursor` that asks for the page after it. A cursor is opaque to callers. Without `limit` a
7
+ * list answers everything, as before lists were paged.
8
+ *
9
+ * A list asked with `values=<field>` answers the values that field has instead, each with how
10
+ * many of the list have it, narrowed by `search` and paged the same way: what a filter offers
11
+ * to choose from.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.hasText = exports.readText = exports.readList = exports.countValues = exports.parseValues = exports.answerPage = exports.pageByPosition = exports.pageByKey = exports.newestFirst = exports.parsePage = exports.ListParamError = exports.VALUES_LIMIT = exports.MAX_LIMIT = void 0;
15
+ // the most a page holds
16
+ exports.MAX_LIMIT = 200;
17
+ // the values of a field a page holds when the caller names no limit
18
+ exports.VALUES_LIMIT = 50;
19
+ // A parameter of a list that is not right: the caller is answered 400 with the message.
20
+ class ListParamError extends Error {
21
+ }
22
+ exports.ListParamError = ListParamError;
23
+ // `limit` and `cursor`: undefined when the caller names no limit, and gets everything.
24
+ function parsePage(params, fallback) {
25
+ const limit = params.get('limit');
26
+ const cursor = params.get('cursor') ?? undefined;
27
+ if (limit === null) {
28
+ if (cursor !== undefined && fallback === undefined) {
29
+ throw new ListParamError('cursor: only with limit');
30
+ }
31
+ return fallback === undefined ? undefined : { limit: fallback, ...(cursor !== undefined ? { cursor } : {}) };
32
+ }
33
+ if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > exports.MAX_LIMIT) {
34
+ throw new ListParamError(`limit: a number from 1 to ${exports.MAX_LIMIT}`);
35
+ }
36
+ return { limit: Number(limit), ...(cursor !== undefined ? { cursor } : {}) };
37
+ }
38
+ exports.parsePage = parsePage;
39
+ function encode(value) {
40
+ return Buffer.from(JSON.stringify(value)).toString('base64url');
41
+ }
42
+ function decode(cursor) {
43
+ try {
44
+ return JSON.parse(Buffer.from(cursor, 'base64url').toString());
45
+ }
46
+ catch {
47
+ throw new ListParamError('cursor: not one this server answered');
48
+ }
49
+ }
50
+ const before = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
51
+ function newestFirst(items, keyOf) {
52
+ return [...items].sort((a, b) => {
53
+ const x = keyOf(a);
54
+ const y = keyOf(b);
55
+ return before(x, y) ? 1 : before(y, x) ? -1 : 0;
56
+ });
57
+ }
58
+ exports.newestFirst = newestFirst;
59
+ /**
60
+ * A page of a list ordered newest first, by the time `keyOf` gives (newestFirst, or the order
61
+ * it was kept in): the cursor names the last one answered, by its time and id, so what is
62
+ * added meanwhile does not repeat one. When the last one answered is gone, the page goes on
63
+ * with the ones older than it.
64
+ */
65
+ function pageByKey(items, page, keyOf) {
66
+ let start = 0;
67
+ if (page.cursor !== undefined) {
68
+ const after = decode(page.cursor);
69
+ if (!Array.isArray(after) || after.length !== 2 || !after.every((part) => typeof part === 'string')) {
70
+ throw new ListParamError('cursor: not one this server answered');
71
+ }
72
+ const [at, id] = after;
73
+ const last = items.findIndex((item) => keyOf(item)[1] === id);
74
+ start = last >= 0 ? last + 1 : items.findIndex((item) => keyOf(item)[0] < at);
75
+ if (start < 0) {
76
+ return { items: [] };
77
+ }
78
+ }
79
+ const answered = items.slice(start, start + page.limit);
80
+ const more = start + page.limit < items.length;
81
+ return { items: answered, ...(more ? { next: encode(keyOf(answered[answered.length - 1])) } : {}) };
82
+ }
83
+ exports.pageByKey = pageByKey;
84
+ // A page of a list in an order of its own, such as numbers sorted by a column: by position.
85
+ function pageByPosition(items, page) {
86
+ let start = 0;
87
+ if (page.cursor !== undefined) {
88
+ const at = decode(page.cursor);
89
+ if (typeof at !== 'object' || at === null || !Number.isSafeInteger(at.at)) {
90
+ throw new ListParamError('cursor: not one this server answered');
91
+ }
92
+ start = Math.max(0, at.at);
93
+ }
94
+ const end = start + page.limit;
95
+ return { items: items.slice(start, end), ...(end < items.length ? { next: encode({ at: end }) } : {}) };
96
+ }
97
+ exports.pageByPosition = pageByPosition;
98
+ // The answer of a page: the list under its name, and `next` while more remain.
99
+ function answerPage(name, page) {
100
+ return { [name]: page.items, ...(page.next ? { next: page.next } : {}) };
101
+ }
102
+ exports.answerPage = answerPage;
103
+ // `values`, `search`, `limit` and `cursor`: undefined when the caller asks for the list.
104
+ function parseValues(params, fields) {
105
+ const field = params.get('values');
106
+ if (field === null) {
107
+ return undefined;
108
+ }
109
+ if (!fields.includes(field)) {
110
+ throw new ListParamError(`values: one of ${fields.join(', ')}`);
111
+ }
112
+ const search = params.get('search')?.trim().slice(0, 200);
113
+ return {
114
+ field: field,
115
+ ...(search ? { search } : {}),
116
+ page: parsePage(params, exports.VALUES_LIMIT),
117
+ };
118
+ }
119
+ exports.parseValues = parseValues;
120
+ /**
121
+ * The values `of` gives the items, each with how many items have it: the most first, then by
122
+ * name, or in the order of `order`; narrowed by the search and paged by position.
123
+ */
124
+ function countValues(items, of, request, order) {
125
+ const counts = new Map();
126
+ for (const item of items) {
127
+ const seen = new Set();
128
+ for (const found of of(item)) {
129
+ const { value, name } = typeof found === 'string' ? { value: found, name: undefined } : found;
130
+ if (seen.has(value)) {
131
+ continue;
132
+ }
133
+ seen.add(value);
134
+ const counted = counts.get(value) ?? { value, count: 0, ...(name ? { name } : {}) };
135
+ counted.count++;
136
+ counts.set(value, counted);
137
+ }
138
+ }
139
+ const needle = request.search?.toLowerCase();
140
+ const values = [...counts.values()]
141
+ .filter((counted) => !needle || counted.value.toLowerCase().includes(needle) || (counted.name ?? '').toLowerCase().includes(needle))
142
+ .sort((a, b) => order ? order.indexOf(a.value) - order.indexOf(b.value) : b.count - a.count || a.value.localeCompare(b.value));
143
+ return pageByPosition(values, request.page);
144
+ }
145
+ exports.countValues = countValues;
146
+ // The values of a filter the caller names: the parameter repeated, `state=queued&state=running`.
147
+ function readList(params, name) {
148
+ const values = params
149
+ .getAll(name)
150
+ .map((value) => value.trim())
151
+ .filter(Boolean);
152
+ return values.length > 0 ? values : undefined;
153
+ }
154
+ exports.readList = readList;
155
+ // the text a list is searched for: `q`, at most 200 characters
156
+ function readText(params) {
157
+ const text = params.get('q')?.trim().slice(0, 200);
158
+ return text ? text : undefined;
159
+ }
160
+ exports.readText = readText;
161
+ // Whether any of the values has the text in it, in any case.
162
+ function hasText(values, text) {
163
+ const needle = text.toLowerCase();
164
+ return values.some((value) => !!value && value.toLowerCase().includes(needle));
165
+ }
166
+ exports.hasText = hasText;
167
+ //# sourceMappingURL=paging.js.map
@@ -19,6 +19,8 @@ const parse_error_1 = require("../schema/parse-error");
19
19
  const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
21
  const run_source_envs_1 = require("../environment/run-source-envs");
22
+ const prefetch_secrets_1 = require("../secrets/prefetch-secrets");
23
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
22
24
  class DefinitionError extends Error {
23
25
  }
24
26
  exports.DefinitionError = DefinitionError;
@@ -71,12 +73,31 @@ function checkGitSource(path, where, source, noRemote) {
71
73
  }
72
74
  }
73
75
  // What a build file may not name on a server: the places it would run or store things
74
- // are the operator's. The docker host, a Kubernetes cluster and a remote cache are
75
- // credentials of the machine, not of the build file, and a project file that could carry
76
- // them could send runs, or the cache, anywhere.
76
+ // are the operator's. The docker host and a Kubernetes cluster are credentials of the machine,
77
+ // not of the build file, and a project file that could carry them could send runs anywhere. A
78
+ // remote cache is named by the build file only as a registry, which the server reads, and writes
79
+ // with its own credential for it (cache.push, ADR-0010).
77
80
  // A file a server leaves out (`publish: false`) is not checked, and neither is a service
78
81
  // with `publish: false`: what is left out is never run there.
79
- function findHostProblems(files) {
82
+ // What a registry cache a build file names needs to be on a server: a reference that parses, over
83
+ // https (a localhost registry is http, so refused), on a host the operator allows. Null when it is.
84
+ function checkRegistry(repository, allowed) {
85
+ let reference;
86
+ try {
87
+ reference = (0, registry_reference_1.parseRegistryReference)(repository);
88
+ }
89
+ catch (e) {
90
+ return (0, log_1.getErrorMessage)(e);
91
+ }
92
+ if (reference.insecure) {
93
+ return 'a server keeps its own cache, a build file names no path, s3 bucket or insecure registry (localhost is http)';
94
+ }
95
+ if (!allowed.includes(reference.host)) {
96
+ return `registry ${reference.host} is not one of the registries this server reads (cache.registries: ${allowed.join(', ') || 'none'})`;
97
+ }
98
+ return null;
99
+ }
100
+ function findHostProblems(files, allowed) {
80
101
  const problems = [];
81
102
  for (const [path, content] of Object.entries(files)) {
82
103
  let document;
@@ -93,9 +114,20 @@ function findHostProblems(files) {
93
114
  problems.push(`${path}: environments pick a docker host or a Kubernetes cluster, which are the server's to choose, remove them`);
94
115
  }
95
116
  for (const [name, cache] of Object.entries(document.caches ?? {})) {
96
- if (cache?.backend?.type !== 'local' || cache.backend.path !== undefined) {
97
- problems.push(`${path}: caches.${name}: a server keeps its own cache, a build file names no backend or path`);
117
+ const backend = cache?.backend;
118
+ if (backend?.type === 'local' && backend.path === undefined) {
119
+ continue;
120
+ }
121
+ // a registry is read over https from a host the operator allows; the server writes it only
122
+ // as a trusted run (cache.push), so the build file names no credential
123
+ if (backend?.type === 'registry' && typeof backend.repository === 'string' && !backend.insecure) {
124
+ const problem = checkRegistry(backend.repository, allowed);
125
+ if (problem) {
126
+ problems.push(`${path}: caches.${name}: ${problem}`);
127
+ }
128
+ continue;
98
129
  }
130
+ problems.push(`${path}: caches.${name}: a server keeps its own cache, a build file names no path, s3 bucket or insecure registry`);
99
131
  }
100
132
  for (const [name, service] of Object.entries(document.services ?? {})) {
101
133
  if (service &&
@@ -167,6 +199,9 @@ function describeSecret(secret) {
167
199
  if (source.type === 'provider') {
168
200
  return { from: `${source.provider}:${source.ref}`, account: source.account, target };
169
201
  }
202
+ if (source.type === 'unavailable') {
203
+ return { from: source.from, account: null, target };
204
+ }
170
205
  return { from: source.type === 'env' ? `env:${source.name}` : `file:${source.path}`, account: null, target };
171
206
  }
172
207
  // What a server refuses to publish. A secret that reads a file or a variable of the
@@ -335,7 +370,14 @@ function toPlan(root, item) {
335
370
  const mounts = (0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)
336
371
  ? data.mounts.map((mount) => {
337
372
  const inside = insideBundle(root, data.cwd, mount.localPath);
338
- return `${inside.length > 0 ? inside[0] : mount.localPath}:${mount.containerPath}${mount.readOnly ? ':ro' : ''}`;
373
+ const readOnly = mount.readOnly ? ':ro' : '';
374
+ // a mount that names only its source (`- .`) lands at the same path in the container,
375
+ // which is in the directory the server read the bundle in, one of its own each time:
376
+ // such a mount is named as the build file names it
377
+ if (inside.length > 0 && mount.containerPath === (0, path_1.resolve)(data.cwd, mount.localPath)) {
378
+ return `${inside[0]}${readOnly}`;
379
+ }
380
+ return `${inside.length > 0 ? inside[0] : mount.localPath}:${mount.containerPath}${readOnly}`;
339
381
  })
340
382
  : [];
341
383
  const ports = 'ports' in data ? data.ports.map((port) => `${port.hostPort ?? ''}:${port.containerPort}`) : [];
@@ -416,13 +458,17 @@ async function planBundle(bundle, environment, options = {}) {
416
458
  : (0, path_1.relative)(directory, from.fileName), `${block}.${name}`, source, options.noRemote),
417
459
  });
418
460
  if (options.policy) {
419
- const problems = findHostProblems(publishedBundleFiles(bundle, directory, scope));
461
+ const problems = findHostProblems(publishedBundleFiles(bundle, directory, scope), options.policy.cacheRegistries ?? []);
420
462
  if (problems.length > 0) {
421
463
  throw new DefinitionError(problems.join('\n'));
422
464
  }
423
465
  }
424
466
  const context = await (0, reference_parser_1.parseReferences)(ctx, scope, inspected);
425
467
  const workTree = (0, work_scope_parser_1.getWorkContext)(context, options.scope ?? { environmentName: null }, inspected);
468
+ // the server's providers and accounts are the ones that count: a task it could never read
469
+ // a secret of is refused when it is published, and a run when it is planned (only the
470
+ // tasks and services of the run count then)
471
+ (0, prefetch_secrets_1.requireReadableSecrets)(workTree);
426
472
  const items = itemsOf(workTree);
427
473
  if (options.policy) {
428
474
  const policyProblems = findPolicyProblems(items, options.policy, directory);
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findReadableRun = exports.accountsOf = void 0;
4
+ const policy_1 = require("./policy");
5
+ const runs_1 = require("./runs");
6
+ // The accounts the caller uses: who approves a run on them follows and stops it.
7
+ function accountsOf(config, principal) {
8
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
9
+ return (account) => (0, policy_1.canUse)(grant, account);
10
+ }
11
+ exports.accountsOf = accountsOf;
12
+ /**
13
+ * The run of `id` the caller may read: one they own or decided about (on an account they use),
14
+ * or any run when an entitlement observes every run.
15
+ */
16
+ function findReadableRun(config, registry, principal, id) {
17
+ if (!runs_1.RUN_ID_PATTERN.test(id)) {
18
+ return undefined;
19
+ }
20
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
21
+ return registry.get(principal, id, accountsOf(config, principal)) ?? (grant.observe ? registry.peek(id) : undefined);
22
+ }
23
+ exports.findReadableRun = findReadableRun;
24
+ //# sourceMappingURL=run-access.js.map