hammerkit 2.1.0 → 2.2.0-next.1

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 (97) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/docker/item-network.js +6 -5
  8. package/dist/docker/remove-orphaned-containers.js +5 -4
  9. package/dist/environment/replace-env-variables.js +8 -5
  10. package/dist/environment/run-source-envs.js +2 -1
  11. package/dist/executer/archive-task-entry.js +1 -1
  12. package/dist/executer/check-readiness.js +8 -4
  13. package/dist/executer/docker-healthcheck.js +73 -0
  14. package/dist/executer/docker-service.js +21 -15
  15. package/dist/executer/event-cache.js +5 -1
  16. package/dist/executer/runner-commands.js +36 -0
  17. package/dist/file/get-file-context.js +4 -7
  18. package/dist/harness/connect.js +12 -8
  19. package/dist/harness/reconnect.js +141 -0
  20. package/dist/harness/sandbox-client.js +241 -33
  21. package/dist/harness/service-tools.js +11 -2
  22. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  23. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  24. package/dist/kubernetes/follow-pod-logs.js +8 -5
  25. package/dist/kubernetes/kept-claims.js +38 -14
  26. package/dist/kubernetes/sandbox-runner.js +526 -156
  27. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  28. package/dist/kubernetes/sync-changes.js +463 -0
  29. package/dist/kubernetes/volumes.js +23 -1
  30. package/dist/network/healthcheck-request.js +38 -0
  31. package/dist/optimizer/get-work-cache-stats.js +7 -0
  32. package/dist/optimizer/work-task-cache-description.js +5 -3
  33. package/dist/planner/image-build.js +5 -0
  34. package/dist/planner/service-definition.js +2 -1
  35. package/dist/planner/utils/append-work-service.js +12 -4
  36. package/dist/planner/utils/dependency-outputs.js +7 -6
  37. package/dist/planner/validate.js +41 -0
  38. package/dist/planner/work-healthcheck.js +23 -2
  39. package/dist/planner/work-item-status.js +12 -2
  40. package/dist/planner/work-runtime-aggregate.js +1 -0
  41. package/dist/planner/work-runtime-docker.js +33 -6
  42. package/dist/planner/work-runtime-kubernetes.js +313 -70
  43. package/dist/planner/work-runtime-local.js +8 -4
  44. package/dist/planner/work-secret.js +33 -11
  45. package/dist/planner/work-service-id.js +30 -6
  46. package/dist/planner/work-service.js +2 -2
  47. package/dist/program.js +19 -1
  48. package/dist/remote/annotations.js +8 -2
  49. package/dist/remote/bundle.js +6 -8
  50. package/dist/remote/device-login.js +4 -1
  51. package/dist/remote/remote-commands.js +16 -7
  52. package/dist/remote/remote-status.js +1 -1
  53. package/dist/remote/remote-work-commands.js +220 -68
  54. package/dist/remote/server-client.js +38 -40
  55. package/dist/schema/build-file-base-task-schema.js +16 -1
  56. package/dist/schema/build-file-image-build-schema.js +5 -8
  57. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  58. package/dist/schema/reference-parser.js +108 -43
  59. package/dist/schema/work-scope-parser.js +8 -0
  60. package/dist/secrets/prefetch-secrets.js +20 -1
  61. package/dist/server/artifacts-api.js +56 -0
  62. package/dist/server/borrowed-quota.js +216 -0
  63. package/dist/server/capacity.js +18 -6
  64. package/dist/server/definitions-api.js +62 -8
  65. package/dist/server/executor.js +117 -30
  66. package/dist/server/http.js +4 -1
  67. package/dist/server/keep-artifacts.js +230 -0
  68. package/dist/server/kubernetes-backend.js +292 -79
  69. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  70. package/dist/server/overview.js +73 -9
  71. package/dist/server/paging.js +167 -0
  72. package/dist/server/plan.js +16 -1
  73. package/dist/server/run-access.js +24 -0
  74. package/dist/server/run-artifacts.js +171 -0
  75. package/dist/server/run-logs.js +25 -1
  76. package/dist/server/run-request.js +11 -0
  77. package/dist/server/run-source-environment.js +1 -1
  78. package/dist/server/run-worker.js +267 -33
  79. package/dist/server/runs.js +531 -105
  80. package/dist/server/sandbox-files-api.js +27 -12
  81. package/dist/server/sandbox-files.js +12 -10
  82. package/dist/server/sandbox-follow.js +54 -0
  83. package/dist/server/sandbox-pod.js +1 -1
  84. package/dist/server/sandbox-storage.js +38 -1
  85. package/dist/server/sandbox-sync.js +392 -0
  86. package/dist/server/sandboxes-api.js +116 -19
  87. package/dist/server/sandboxes.js +38 -3
  88. package/dist/server/server-config.js +73 -2
  89. package/dist/server/server.js +169 -38
  90. package/dist/server/task-order.js +56 -0
  91. package/dist/utils/project-path.js +20 -0
  92. package/dist/utils/tar-files.js +52 -0
  93. package/dist/utils/tar.js +37 -1
  94. package/package.json +1 -1
  95. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  96. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  97. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -6,8 +6,10 @@ const promises_1 = require("fs/promises");
6
6
  const path_1 = require("path");
7
7
  const units_1 = require("../utils/units");
8
8
  const git_checkout_1 = require("./git-checkout");
9
+ const oauth_1 = require("./oauth");
9
10
  const runs_1 = require("./runs");
10
11
  const repo_1 = require("./repo");
12
+ const sandbox_files_1 = require("./sandbox-files");
11
13
  const sandbox_storage_1 = require("./sandbox-storage");
12
14
  // How long creating a sandbox or moving it to another commit may take
13
15
  const FETCH_TIMEOUT_MS = 10 * 60 * 1000;
@@ -22,7 +24,8 @@ class SandboxError extends Error {
22
24
  exports.SandboxError = SandboxError;
23
25
  /**
24
26
  * The sandboxes of a server: who owns which, the limits, and one change at a time per
25
- * sandbox. Everything is scoped to the owner: somebody else's sandbox is "not found".
27
+ * sandbox. Everything is scoped to the owner: somebody else's sandbox is "not found". Only
28
+ * `all` and `peek` show the sandboxes of everybody, for who may read them (`observe`).
26
29
  */
27
30
  class SandboxRegistry {
28
31
  constructor(options) {
@@ -38,6 +41,8 @@ class SandboxRegistry {
38
41
  // the measures of runs that are over, which a run's result does not wait for
39
42
  this.measuring = new Map();
40
43
  this.locks = new Map();
44
+ // what hears of the files of a sandbox changing: an edit, or a run that wrote to them
45
+ this.listeners = new Set();
41
46
  this.runs = { holder: () => undefined, stop: async () => undefined };
42
47
  this.now = options.now ?? Date.now;
43
48
  }
@@ -45,6 +50,16 @@ class SandboxRegistry {
45
50
  useRuns(runs) {
46
51
  this.runs = runs;
47
52
  }
53
+ // Calls `listener` with the id of a sandbox whose files may have changed: after each edit,
54
+ // and after each run that wrote to them (measure). It may come when nothing changed.
55
+ onChange(listener) {
56
+ this.listeners.add(listener);
57
+ }
58
+ changed(id) {
59
+ for (const listener of this.listeners) {
60
+ listener(id);
61
+ }
62
+ }
48
63
  get limits() {
49
64
  return this.options.limits;
50
65
  }
@@ -111,6 +126,18 @@ class SandboxRegistry {
111
126
  const sandbox = this.sandboxes.get(id);
112
127
  return sandbox && owns(owner, sandbox) && !this.deleting.has(id) ? copy(sandbox) : undefined;
113
128
  }
129
+ // The sandboxes of everybody, oldest first: what who observes sees.
130
+ all() {
131
+ return [...this.sandboxes.values()]
132
+ .filter((sandbox) => !this.deleting.has(sandbox.id))
133
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
134
+ .map(copy);
135
+ }
136
+ // A sandbox of anybody, for who observes: to read, never to change.
137
+ peek(id) {
138
+ const sandbox = this.sandboxes.get(id);
139
+ return sandbox && !this.deleting.has(id) ? copy(sandbox) : undefined;
140
+ }
114
141
  holder(id) {
115
142
  return this.runs.holder(id);
116
143
  }
@@ -188,9 +215,10 @@ class SandboxRegistry {
188
215
  }
189
216
  this.creating.set(id, { owner: { iss: owner.iss, sub: owner.sub }, bytes });
190
217
  const at = this.timestamp();
218
+ const name = (0, oauth_1.displayName)(owner);
191
219
  const sandbox = {
192
220
  id,
193
- owner: { iss: owner.iss, sub: owner.sub },
221
+ owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) },
194
222
  repo,
195
223
  ref,
196
224
  commit,
@@ -246,6 +274,10 @@ class SandboxRegistry {
246
274
  });
247
275
  }
248
276
  catch (e) {
277
+ // a file of the sandbox in the way of the ref, which a checkout would overwrite
278
+ if (e instanceof sandbox_files_1.SandboxFileError && e.status === 409) {
279
+ throw new SandboxError(409, repos.scrub(e, credentials.values).message);
280
+ }
249
281
  throw new SandboxError(502, repos.scrub(e, credentials.values).message);
250
282
  }
251
283
  sandbox.ref = ref;
@@ -440,6 +472,7 @@ class SandboxRegistry {
440
472
  sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
441
473
  sandbox.lastUsedAt = this.timestamp();
442
474
  await this.save(sandbox);
475
+ this.changed(id);
443
476
  return plan.files;
444
477
  });
445
478
  }
@@ -473,6 +506,7 @@ class SandboxRegistry {
473
506
  }
474
507
  sandbox.bytes = await this.options.storage.usage(keyOf(sandbox));
475
508
  await this.save(sandbox);
509
+ this.changed(id);
476
510
  });
477
511
  const settled = measure.catch(() => undefined);
478
512
  this.measuring.set(id, settled);
@@ -548,8 +582,9 @@ function owns(owner, sandbox) {
548
582
  const of = 'owner' in sandbox ? sandbox.owner : sandbox;
549
583
  return of.iss === owner.iss && of.sub === owner.sub;
550
584
  }
585
+ // what the storage keeps a sandbox by: its owner's identity, not the name they had
551
586
  function keyOf(sandbox) {
552
- return { id: sandbox.id, owner: sandbox.owner };
587
+ return { id: sandbox.id, owner: { iss: sandbox.owner.iss, sub: sandbox.owner.sub } };
553
588
  }
554
589
  function copy(sandbox) {
555
590
  return {
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.detectPlatform = exports.getSecretCatalog = exports.readServerConfig = exports.getServerAccounts = exports.getSandboxRuntimes = exports.serverConfigSchema = exports.sourceSchema = exports.entitlementSchema = exports.endpointGrantSchema = exports.endpointLevelSchema = exports.sandboxGrantSchema = exports.sandboxBranchTypeSchema = exports.buildsLevelSchema = exports.accountLevelSchema = exports.getMaxVolumeSize = exports.DEFAULT_MAX_VOLUME_SIZE = exports.DEFAULT_DENIED_EGRESS = exports.kubernetesPoolSchema = exports.accountSchema = exports.issuerSchema = exports.serverPlatformSchema = void 0;
3
+ exports.getMaxQuotaIssues = exports.detectPlatform = exports.getSecretCatalog = exports.readServerConfig = exports.getServerAccounts = exports.getSandboxRuntimes = exports.serverConfigSchema = exports.sourceSchema = exports.entitlementSchema = exports.endpointGrantSchema = exports.endpointLevelSchema = exports.sandboxGrantSchema = exports.sandboxBranchTypeSchema = exports.buildsLevelSchema = exports.accountLevelSchema = exports.getMaxVolumeSize = exports.DEFAULT_MAX_VOLUME_SIZE = exports.DEFAULT_DENIED_EGRESS = exports.kubernetesPoolSchema = exports.accountSchema = exports.issuerSchema = exports.serverPlatformSchema = void 0;
4
4
  const run_source_envs_1 = require("../environment/run-source-envs");
5
5
  const net_1 = require("net");
6
6
  const zod_1 = require("zod");
7
7
  const yaml_1 = require("yaml");
8
8
  const log_1 = require("../log");
9
9
  const units_1 = require("../utils/units");
10
+ const borrowed_quota_1 = require("./borrowed-quota");
10
11
  const version_1 = require("../version");
11
12
  const network_schema_1 = require("../schema/network-schema");
12
13
  const capabilities_schema_1 = require("../schema/capabilities-schema");
@@ -275,8 +276,12 @@ const kubernetesBackendSchema = zod_1.z
275
276
  })
276
277
  .strict())
277
278
  .default({}),
278
- // the ResourceQuota of every caller's namespace, such as `requests.cpu: '8'`
279
+ // the ResourceQuota of every caller's namespace, such as `requests.cpu: '8'`: what each
280
+ // caller is promised
279
281
  quota: zod_1.z.record(zod_1.z.union([zod_1.z.string().min(1), zod_1.z.number()]).transform(String)).optional(),
282
+ // how far the CPU and memory of a caller's quota rise above `quota` while the nodes of the
283
+ // pools have room no other caller is promised (see BorrowedQuotas); never when left out
284
+ maxQuota: zod_1.z.record(zod_1.z.union([zod_1.z.string().min(1), zod_1.z.number()]).transform(String)).optional(),
280
285
  // what a container without `resources` requests (a LimitRange), so it is
281
286
  // admitted under a quota that limits compute
282
287
  defaultResources: zod_1.z
@@ -576,6 +581,20 @@ exports.serverConfigSchema = zod_1.z
576
581
  .default({}),
577
582
  // how long a passed check stays for `remote verify` to find (see checks.ts)
578
583
  checksKeep: duration.default('30d'),
584
+ // the outputs the tasks of a run export (`export: true`, and `export: always` of a task
585
+ // that failed), kept for `remote artifacts`; none of a run in which anything reads a
586
+ // secret or a variable of the server (run-artifacts.ts)
587
+ artifacts: zod_1.z
588
+ .object({
589
+ // how long they stay after their run ended
590
+ keep: duration.default('1d'),
591
+ // what one run keeps, packed; an output that would take it over is left out
592
+ maxBytes: size.default('256Mi'),
593
+ // what all runs keep together; the oldest runs' go first
594
+ total: size.default('10Gi'),
595
+ })
596
+ .strict()
597
+ .default({}),
579
598
  })
580
599
  .strict()
581
600
  .default({}),
@@ -854,6 +873,13 @@ exports.serverConfigSchema = zod_1.z
854
873
  }
855
874
  }
856
875
  }
876
+ for (const issue of getMaxQuotaIssues(backend.quota, backend.maxQuota)) {
877
+ ctx.addIssue({
878
+ code: zod_1.z.ZodIssueCode.custom,
879
+ path: ['backend', 'maxQuota', ...issue.path],
880
+ message: issue.message,
881
+ });
882
+ }
857
883
  if (backend.maxVolumeSize && (0, units_1.parseSize)(backend.volumeSize) > (0, units_1.parseSize)(backend.maxVolumeSize)) {
858
884
  ctx.addIssue({
859
885
  code: zod_1.z.ZodIssueCode.custom,
@@ -1071,4 +1097,49 @@ function detectPlatform() {
1071
1097
  return { os, arch };
1072
1098
  }
1073
1099
  exports.detectPlatform = detectPlatform;
1100
+ // What is wrong with `backend.maxQuota`: a key a caller may borrow (CPU and memory, see
1101
+ // BORROWED_RESOURCES) that `quota` has too, no less than there, and a limit only with the
1102
+ // requests of its resource, which say how much room the caller takes of the nodes.
1103
+ function getMaxQuotaIssues(quota, maxQuota) {
1104
+ if (!maxQuota) {
1105
+ return [];
1106
+ }
1107
+ if (!quota) {
1108
+ return [{ path: [], message: 'a caller borrows above backend.quota, which is not set' }];
1109
+ }
1110
+ const issues = [];
1111
+ for (const [key, value] of Object.entries(maxQuota)) {
1112
+ const resource = (0, borrowed_quota_1.getBorrowedResource)(key);
1113
+ if (!resource) {
1114
+ issues.push({
1115
+ path: [key],
1116
+ message: `${key} can't be borrowed, only ${Object.values(borrowed_quota_1.BORROWED_RESOURCES)
1117
+ .flatMap((keys) => [...keys.requests, ...keys.limits])
1118
+ .join(', ')}`,
1119
+ });
1120
+ continue;
1121
+ }
1122
+ if (quota[key] === undefined) {
1123
+ issues.push({ path: [key], message: `${key} is not in backend.quota, the share it rises from` });
1124
+ continue;
1125
+ }
1126
+ const max = (0, units_1.parseQuantity)(value);
1127
+ const share = (0, units_1.parseQuantity)(quota[key]);
1128
+ if (max === undefined) {
1129
+ issues.push({ path: [key], message: `expected a quantity such as 8, 500m or 16Gi` });
1130
+ }
1131
+ else if (share !== undefined && max < share) {
1132
+ issues.push({ path: [key], message: `${value} is less than ${quota[key]} of backend.quota` });
1133
+ }
1134
+ const requests = borrowed_quota_1.BORROWED_RESOURCES[resource].requests;
1135
+ if (!requests.includes(key) && !requests.some((other) => maxQuota[other] !== undefined)) {
1136
+ issues.push({
1137
+ path: [key],
1138
+ message: `${key} rises with the requests of ${resource}, add ${requests[0]} to backend.maxQuota`,
1139
+ });
1140
+ }
1141
+ }
1142
+ return issues;
1143
+ }
1144
+ exports.getMaxQuotaIssues = getMaxQuotaIssues;
1074
1145
  //# sourceMappingURL=server-config.js.map
@@ -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");
@@ -18,6 +19,7 @@ const executor_1 = require("./executor");
18
19
  const capacity_1 = require("./capacity");
19
20
  const execute_docker_1 = require("../executer/execute-docker");
20
21
  const timings_1 = require("./timings");
22
+ const task_order_1 = require("./task-order");
21
23
  const kubernetes_backend_1 = require("./kubernetes-backend");
22
24
  const run_plan_1 = require("./run-plan");
23
25
  const run_source_environment_1 = require("./run-source-environment");
@@ -34,6 +36,8 @@ const proposals_api_1 = require("./proposals-api");
34
36
  const proposals_1 = require("./proposals");
35
37
  const sources_1 = require("./sources");
36
38
  const sources_api_1 = require("./sources-api");
39
+ const sandbox_follow_1 = require("./sandbox-follow");
40
+ const sandbox_sync_1 = require("./sandbox-sync");
37
41
  const sandboxes_1 = require("./sandboxes");
38
42
  const sandbox_storage_1 = require("./sandbox-storage");
39
43
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
@@ -48,7 +52,11 @@ const get_cache_directory_1 = require("../optimizer/get-cache-directory");
48
52
  const path_1 = require("path");
49
53
  const checks_1 = require("./checks");
50
54
  const checks_api_1 = require("./checks-api");
55
+ const run_artifacts_1 = require("./run-artifacts");
56
+ const artifacts_api_1 = require("./artifacts-api");
57
+ const run_access_1 = require("./run-access");
51
58
  const overview_1 = require("./overview");
59
+ const paging_1 = require("./paging");
52
60
  var discovery_2 = require("./discovery");
53
61
  Object.defineProperty(exports, "DISCOVERY_PATH", { enumerable: true, get: function () { return discovery_2.DISCOVERY_PATH; } });
54
62
  Object.defineProperty(exports, "SERVER_PROTOCOL", { enumerable: true, get: function () { return discovery_2.SERVER_PROTOCOL; } });
@@ -79,6 +87,8 @@ const HEARTBEAT_MS = 15000;
79
87
  const MAX_WAIT_MS = 50000;
80
88
  // how often checks older than `runs.checksKeep` are removed
81
89
  const CHECK_SWEEP_MS = 6 * 60 * 60 * 1000;
90
+ // how often the outputs of runs that are over their time are removed
91
+ const ARTIFACT_SWEEP_MS = 60 * 60 * 1000;
82
92
  // Server-sent events: `id` is the sequence number, so a client that lost the
83
93
  // connection continues with Last-Event-ID (or ?after=) and misses nothing.
84
94
  function streamEvents(registry, config, principal, id, req, res, url) {
@@ -89,7 +99,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
89
99
  if (event.type === 'state' && (0, runs_1.isFinal)(event.state)) {
90
100
  end();
91
101
  }
92
- }, accountsOf(config, principal));
102
+ }, (0, run_access_1.accountsOf)(config, principal));
93
103
  if (!watch) {
94
104
  (0, http_2.send)(res, 404, { error: 'not found' });
95
105
  return;
@@ -122,18 +132,45 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
122
132
  if (method === 'GET') {
123
133
  // the results of each task are read one run at a time
124
134
  const viewer = (0, overview_1.getViewer)(config, principal);
125
- let filter;
135
+ let filter, page, values;
126
136
  try {
127
137
  filter = (0, overview_1.parseRunFilter)(url.searchParams, viewer.grant);
138
+ values = (0, paging_1.parseValues)(url.searchParams, overview_1.RUN_FIELDS);
139
+ page = values ? undefined : (0, paging_1.parsePage)(url.searchParams);
128
140
  }
129
141
  catch (e) {
130
142
  (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
131
143
  return true;
132
144
  }
133
145
  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
- });
146
+ const list = (run) => listRun(registry, definitions, viewer, run);
147
+ try {
148
+ if (values) {
149
+ // a value of the field is counted over the runs the other filters let through
150
+ const { of, order } = (0, overview_1.runValues)(values.field);
151
+ const counted = (0, paging_1.countValues)((0, overview_1.filterRuns)(runs, viewer, (0, overview_1.withoutField)(filter, values.field)), of, values, order);
152
+ (0, http_2.send)(res, 200, (0, paging_1.answerPage)('values', counted));
153
+ }
154
+ else if (page) {
155
+ // newest first, as the registry keeps them
156
+ const found = (0, overview_1.filterRuns)(runs, viewer, filter);
157
+ const oldest = found[found.length - 1]?.createdAt;
158
+ const answered = (0, paging_1.pageByKey)(found, page, runKey);
159
+ (0, http_2.send)(res, 200, {
160
+ ...(0, paging_1.answerPage)('runs', { ...answered, items: answered.items.map(list) }),
161
+ ...(oldest ? { oldest } : {}),
162
+ });
163
+ }
164
+ else {
165
+ (0, http_2.send)(res, 200, { runs: (0, overview_1.filterRuns)(runs, viewer, filter).map(list) });
166
+ }
167
+ }
168
+ catch (e) {
169
+ if (!(e instanceof paging_1.ListParamError)) {
170
+ throw e;
171
+ }
172
+ (0, http_2.send)(res, 400, { error: e.message });
173
+ }
137
174
  }
138
175
  else if (method === 'POST') {
139
176
  await submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res);
@@ -152,7 +189,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
152
189
  return true;
153
190
  }
154
191
  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));
192
+ const run = registry.cancel(principal, id, (0, run_access_1.accountsOf)(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
156
193
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
157
194
  run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
158
195
  }
@@ -207,12 +244,14 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
207
244
  (0, http_2.send)(res, 400, { error: e instanceof Error ? e.message : String(e) });
208
245
  return true;
209
246
  }
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);
247
+ // who may read the run reads its log, an entitlement with `observe` every run's
248
+ const logs = (0, run_access_1.findReadableRun)(config, registry, principal, id) ? registry.logsOf(id) : undefined;
213
249
  // with the tasks, services and the server's own lines (`hammerkit`) the log has
214
250
  logs
215
- ? (0, http_2.send)(res, 200, { ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated), names: logs.index.names() })
251
+ ? (0, http_2.send)(res, 200, {
252
+ ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated, logs.lostAfter),
253
+ names: logs.index.names(),
254
+ })
216
255
  : (0, http_2.send)(res, 404, { error: 'not found' });
217
256
  }
218
257
  else {
@@ -232,7 +271,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
232
271
  res.on('close', () => gone.abort());
233
272
  const viewer = (0, overview_1.getViewer)(config, principal);
234
273
  // 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)) ??
274
+ const run = (await registry.wait(principal, id, wait, (0, run_access_1.accountsOf)(config, principal), gone.signal)) ??
236
275
  (viewer.grant.observe ? registry.peek(id) : undefined);
237
276
  if (!gone.signal.aborted) {
238
277
  const may = run && (0, overview_1.runActions)(viewer, run);
@@ -246,11 +285,6 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
246
285
  }
247
286
  return true;
248
287
  }
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
288
  async function extendRun(config, registry, log, principal, id, req, res) {
255
289
  const body = (await (0, http_2.readJson)(req));
256
290
  let ttl;
@@ -357,6 +391,8 @@ function toRunResponse(run, queue, named = false, nameOf) {
357
391
  ...(queue ? { queue } : {}),
358
392
  };
359
393
  }
394
+ // where a page of runs ends: when the last run was created, and which it is
395
+ const runKey = (run) => [run.createdAt, run.id];
360
396
  function listRun(registry, definitions, viewer, run) {
361
397
  return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
362
398
  }
@@ -377,7 +413,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
377
413
  // an approval where they need one, never the owner's (run-retry.ts).
378
414
  async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
379
415
  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);
416
+ const run = (0, run_access_1.findReadableRun)(config, registry, principal, id);
381
417
  if (!run) {
382
418
  (0, http_2.send)(res, 404, { error: 'not found' });
383
419
  return;
@@ -453,6 +489,14 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
453
489
  (0, http_2.send)(res, 400, { error: 'sleepTtl: a service run from a sandbox does not sleep, start it from a branch' });
454
490
  return;
455
491
  }
492
+ // only a Kubernetes backend syncs the changed files of a sandbox into the services; a host
493
+ // runs them on the sandbox's own files, so a restart would do nothing there
494
+ if (request.restart?.length && config.backend.type !== 'kubernetes') {
495
+ (0, http_2.send)(res, 400, {
496
+ error: `restart: this server (backend ${config.backend.type}) has no file sync, a host's services run on the sandbox's files`,
497
+ });
498
+ return;
499
+ }
456
500
  const sleepTtlText = request.source.type === 'ref' ? request.sleepTtl ?? config.runs.up.sleepTtl : undefined;
457
501
  const sleepTtl = request.services.length > 0 && sleepTtlText ? (0, units_1.parseDuration)(sleepTtlText) : undefined;
458
502
  const argued = (request.options.args ?? []).length > 0 ? request.tasks[0] : undefined;
@@ -476,12 +520,6 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
476
520
  return;
477
521
  }
478
522
  }
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
523
  const sandbox = request.source.type === 'sandbox' ? sandboxes.registry.get(principal, request.source.id) : undefined;
486
524
  if (request.source.type === 'sandbox') {
487
525
  if (!sandbox) {
@@ -638,6 +676,7 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
638
676
  ...(sleepTtl ? { sleepTtl } : {}),
639
677
  name: serviceName,
640
678
  endpoints: (0, service_runs_1.toRunEndpoints)(request.endpoints, (0, service_runs_1.getEndpointHosts)(serviceName, principal, request.endpoints), endpointUrl, request.publicPaths),
679
+ ...(request.restart?.length ? { restart: request.restart } : {}),
641
680
  }
642
681
  : undefined;
643
682
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
@@ -704,7 +743,8 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
704
743
  }
705
744
  catch (e) {
706
745
  if (e instanceof runs_1.RunError) {
707
- (0, http_2.send)(res, e.status, { error: e.message });
746
+ // a proxy answers 503 too, also after the server took the request: this one is safe to send again
747
+ (0, http_2.send)(res, e.status, { error: e.message }, e instanceof runs_1.ShuttingDownError ? { [http_2.RETRY_HEADER]: 'safe' } : {});
708
748
  return;
709
749
  }
710
750
  if (e instanceof sandboxes_1.SandboxError) {
@@ -773,7 +813,7 @@ async function handle(api, verifier, req, res) {
773
813
  * dashboard, which asks the same API for what its pages show (dashboard.ts).
774
814
  */
775
815
  async function handleApi(api, principal, req, res, url) {
776
- const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, capacity, log, } = api;
816
+ const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, artifacts, capacity, log, now, } = api;
777
817
  const path = url.pathname;
778
818
  if (await (0, accounts_api_1.handleAccounts)(config, log, principal, req, res, url)) {
779
819
  return;
@@ -787,6 +827,9 @@ async function handleApi(api, principal, req, res, url) {
787
827
  if (await (0, sandboxes_api_1.handleSandboxes)(config, sandboxes.registry, repos, log, principal, req, res, url)) {
788
828
  return;
789
829
  }
830
+ if (await (0, artifacts_api_1.handleArtifacts)(config, registry, artifacts, log, principal, req, res, url, now)) {
831
+ return;
832
+ }
790
833
  if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, (host) => gateway?.url(host) ?? host, log, principal, req, res, url)) {
791
834
  return;
792
835
  }
@@ -822,22 +865,53 @@ async function handleApi(api, principal, req, res, url) {
822
865
  if (!params.has('scope')) {
823
866
  params.set('scope', 'visible');
824
867
  }
825
- let filter;
868
+ // the text is looked for in the tasks, not in the runs they ran in
869
+ params.delete('q');
870
+ let filter, page, values, order;
871
+ const text = (0, paging_1.readText)(url.searchParams);
826
872
  try {
827
873
  filter = (0, overview_1.parseRunFilter)(params, viewer.grant);
874
+ values = (0, paging_1.parseValues)(url.searchParams, task_order_1.TASK_FIELDS);
875
+ page = values ? undefined : (0, paging_1.parsePage)(url.searchParams);
876
+ order = (0, task_order_1.parseTaskOrder)(url.searchParams);
828
877
  }
829
878
  catch (e) {
830
879
  (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
831
880
  return;
832
881
  }
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 } : {}) });
882
+ const statsOf = (over) => {
883
+ const runs = (0, overview_1.filterRuns)(registry.all(), viewer, over).map((run) => (0, overview_1.toListedRun)(viewer, run));
884
+ // where in the repository the build file of the last run is, as its version says
885
+ const tasks = (0, timings_1.getTaskStats)(runs, Date.now())
886
+ .map((stats) => {
887
+ const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
888
+ return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
889
+ })
890
+ .filter((stats) => !text || (0, paging_1.hasText)([stats.repo, stats.task, stats.last.entry], text));
891
+ return { runs, tasks };
892
+ };
893
+ try {
894
+ if (values) {
895
+ const { sources, ...others } = filter;
896
+ void sources;
897
+ const counted = (0, paging_1.countValues)(statsOf(others).tasks, (stats) => [(0, task_order_1.taskSource)(stats)], values);
898
+ (0, http_2.send)(res, 200, (0, paging_1.answerPage)('values', counted));
899
+ return;
900
+ }
901
+ const { runs, tasks } = statsOf(filter);
902
+ const oldest = (0, timings_1.getOldestCounted)(runs);
903
+ const sorted = order ? (0, task_order_1.sortTasks)(tasks, order) : tasks;
904
+ (0, http_2.send)(res, 200, {
905
+ ...(page ? (0, paging_1.answerPage)('tasks', (0, paging_1.pageByPosition)(sorted, page)) : { tasks: sorted }),
906
+ ...(oldest ? { oldest } : {}),
907
+ });
908
+ }
909
+ catch (e) {
910
+ if (!(e instanceof paging_1.ListParamError)) {
911
+ throw e;
912
+ }
913
+ (0, http_2.send)(res, 400, { error: e.message });
914
+ }
841
915
  return;
842
916
  }
843
917
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -862,7 +936,8 @@ async function startServer(config, environment, options = {}) {
862
936
  const log = (line) => write(line.replace(/\p{Cc}/gu, '?').slice(0, 1000));
863
937
  if (config.runtimes.includes('local') && config.backend.type === 'host') {
864
938
  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');
939
+ 'an account is then an approval class, not a credential boundary, and the server keeps no outputs of its runs ' +
940
+ '(remote artifacts)');
866
941
  }
867
942
  // build files are read, planned and run as the server's runs see the world: the
868
943
  // operator's accounts and the allowlisted environment, nothing of the server's own
@@ -942,6 +1017,18 @@ async function startServer(config, environment, options = {}) {
942
1017
  if (config.backend.type === 'host' || config.entitlements.some((entitlement) => entitlement.sandboxes?.length)) {
943
1018
  await sandboxes.registry.load();
944
1019
  }
1020
+ // a local task of a host runs as the user of this server: what it can write is never served
1021
+ const localTasksOnHost = config.backend.type === 'host' && config.runtimes.includes('local');
1022
+ // a service run from a sandbox on a cluster gets the changed files of the sandbox into its
1023
+ // services, batched (SandboxFollow), as the files that changed since the services last got theirs
1024
+ // the folder a server before the direct sync staged the changes in is no longer used
1025
+ await (0, promises_1.rm)((0, path_1.join)(storage, 'sandboxes', 'sync'), { recursive: true, force: true });
1026
+ const sandboxSync = new sandbox_sync_1.SandboxSync({
1027
+ files: (owner, id) => sandboxes.registry.files(owner, id),
1028
+ upOn: (id) => registry.upOn(id),
1029
+ send: (run, changes) => registry.syncFiles(run, changes),
1030
+ log,
1031
+ });
945
1032
  const executorOptions = {
946
1033
  definitions,
947
1034
  planning,
@@ -949,7 +1036,14 @@ async function startServer(config, environment, options = {}) {
949
1036
  directory: (0, path_1.join)(storage, 'runs'),
950
1037
  cache: (0, path_1.join)(storage, 'cache'),
951
1038
  worker: options.worker,
952
- sandboxes: { ...sandboxes, network: config.sandboxes.network },
1039
+ sandboxes: {
1040
+ ...sandboxes,
1041
+ network: config.sandboxes.network,
1042
+ started: async (run) => sandboxSync.started(run),
1043
+ ended: async (run) => sandboxSync.forget(run.id),
1044
+ syncFailed: (runId) => sandboxSync.failed(runId),
1045
+ },
1046
+ localTasksOnHost,
953
1047
  ...(config.backend.type === 'host' && config.backend.capabilities
954
1048
  ? { capabilityRuntime: config.backend.capabilities.runtime }
955
1049
  : {}),
@@ -970,6 +1064,11 @@ async function startServer(config, environment, options = {}) {
970
1064
  void sweepChecks();
971
1065
  const sweeping = setInterval(sweepChecks, CHECK_SWEEP_MS);
972
1066
  sweeping.unref();
1067
+ const artifacts = new run_artifacts_1.ArtifactStore((0, path_1.join)(storage, 'artifacts'), {
1068
+ keep: (0, units_1.parseDuration)(config.runs.artifacts.keep),
1069
+ total: (0, units_1.parseSize)(config.runs.artifacts.total),
1070
+ localTasksOnHost,
1071
+ });
973
1072
  const registry = new runs_1.RunRegistry({
974
1073
  executor,
975
1074
  maxConcurrent: config.runs.maxConcurrent,
@@ -996,12 +1095,32 @@ async function startServer(config, environment, options = {}) {
996
1095
  .then(() => log(`checks run=${run.id} passed=[${passed.map((record) => record.task).join(',')}]`))
997
1096
  .catch((e) => log(`the checks of run ${run.id} were not kept: ${e instanceof Error ? e.message : e}`));
998
1097
  }
1098
+ // what the run kept counts against the total of all runs from now
1099
+ void sweepArtifacts();
1100
+ },
1101
+ artifacts: {
1102
+ directoryOf: (id) => artifacts.directoryOf(id),
1103
+ maxBytes: (0, units_1.parseSize)(config.runs.artifacts.maxBytes),
999
1104
  },
1000
1105
  log,
1001
1106
  });
1002
- // the executor hears which service runs sleep with their volumes kept, and removes what it
1003
- // kept for any other (RunExecutor.restored)
1107
+ const now = options.now ?? Date.now;
1108
+ // what is over its time goes within the hour, what is over the total when a run ends
1109
+ const sweepArtifacts = () => artifacts
1110
+ .sweep((id) => registry.peek(id), now())
1111
+ .then((removed) => {
1112
+ if (removed.length > 0) {
1113
+ log(`removed the outputs of ${removed.length} runs: ${removed.join(', ')}`);
1114
+ }
1115
+ })
1116
+ .catch((e) => log(`the outputs of old runs could not be removed: ${e instanceof Error ? e.message : e}`));
1117
+ const sweepingArtifacts = setInterval(sweepArtifacts, ARTIFACT_SWEEP_MS);
1118
+ sweepingArtifacts.unref();
1119
+ // the runs the server before stopped resume, and the executor hears which service runs sleep
1120
+ // with their volumes kept and which runs resume, and removes what it kept for any other
1121
+ // (RunExecutor.restored)
1004
1122
  await registry.restore();
1123
+ void sweepArtifacts();
1005
1124
  const proposals = new proposals_1.ProposalRegistry({
1006
1125
  maxWaiting: config.approvals.maxWaiting,
1007
1126
  timeout: (0, units_1.parseDuration)(config.approvals.timeout),
@@ -1037,14 +1156,23 @@ async function startServer(config, environment, options = {}) {
1037
1156
  planning,
1038
1157
  repos,
1039
1158
  checks,
1159
+ artifacts,
1040
1160
  capacity,
1041
1161
  log,
1162
+ now,
1042
1163
  };
1043
1164
  await gateway?.load();
1044
1165
  sandboxes.registry.useRuns({
1045
1166
  holder: (id) => registry.holder(id),
1046
1167
  stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
1047
1168
  });
1169
+ // A service run from a sandbox follows the files of the sandbox: a burst of edits or runs that
1170
+ // wrote is synced once, when the sandbox has been quiet for a moment (SandboxFollow)
1171
+ const follower = new sandbox_follow_1.SandboxFollow({
1172
+ follow: (id) => sandboxSync.follow(id),
1173
+ log: (line) => log(`follow ${line}`),
1174
+ });
1175
+ sandboxes.registry.onChange((id) => follower.changed(id));
1048
1176
  const listener = (req, res) => {
1049
1177
  handle(api, verifier, req, res).catch((e) => {
1050
1178
  if (e instanceof http_2.HttpError) {
@@ -1138,7 +1266,10 @@ async function startServer(config, environment, options = {}) {
1138
1266
  },
1139
1267
  close: async () => {
1140
1268
  clearInterval(sweeping);
1269
+ clearInterval(sweepingArtifacts);
1141
1270
  proposals.close();
1271
+ follower.close();
1272
+ sandboxSync.close();
1142
1273
  await registry.close();
1143
1274
  await new Promise((resolve, reject) => {
1144
1275
  server.close((err) => (err ? reject(err) : resolve()));