hammerkit 2.1.0-next.9 → 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 (70) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/executer/runner-commands.js +36 -0
  10. package/dist/file/get-file-context.js +4 -7
  11. package/dist/harness/connect.js +12 -8
  12. package/dist/harness/reconnect.js +141 -0
  13. package/dist/harness/sandbox-client.js +242 -33
  14. package/dist/harness/service-tools.js +36 -3
  15. package/dist/kubernetes/cluster-state.js +48 -14
  16. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  17. package/dist/kubernetes/follow-pod-logs.js +8 -5
  18. package/dist/kubernetes/kept-claims.js +26 -5
  19. package/dist/kubernetes/resources.js +5 -1
  20. package/dist/kubernetes/sandbox-runner.js +526 -156
  21. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  22. package/dist/kubernetes/sync-changes.js +463 -0
  23. package/dist/kubernetes/volumes.js +23 -1
  24. package/dist/optimizer/get-work-cache-stats.js +7 -0
  25. package/dist/planner/work-item-status.js +12 -2
  26. package/dist/planner/work-runtime-aggregate.js +1 -0
  27. package/dist/planner/work-runtime-docker.js +9 -5
  28. package/dist/planner/work-runtime-kubernetes.js +277 -55
  29. package/dist/planner/work-runtime-local.js +8 -4
  30. package/dist/remote/annotations.js +29 -3
  31. package/dist/remote/bundle.js +6 -8
  32. package/dist/remote/collect-bundle.js +3 -2
  33. package/dist/remote/device-login.js +4 -1
  34. package/dist/remote/remote-commands.js +16 -7
  35. package/dist/remote/remote-work-commands.js +265 -72
  36. package/dist/remote/server-client.js +38 -40
  37. package/dist/server/artifacts-api.js +56 -0
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/endpoints.js +52 -32
  40. package/dist/server/executor.js +117 -30
  41. package/dist/server/http.js +4 -1
  42. package/dist/server/keep-artifacts.js +230 -0
  43. package/dist/server/kubernetes-backend.js +186 -59
  44. package/dist/server/kubernetes-sandbox-storage.js +83 -22
  45. package/dist/server/overview.js +67 -9
  46. package/dist/server/paging.js +167 -0
  47. package/dist/server/plan.js +8 -1
  48. package/dist/server/public-paths.js +52 -0
  49. package/dist/server/run-access.js +24 -0
  50. package/dist/server/run-artifacts.js +171 -0
  51. package/dist/server/run-logs.js +25 -1
  52. package/dist/server/run-request.js +63 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-worker.js +267 -33
  55. package/dist/server/runs.js +527 -99
  56. package/dist/server/sandbox-files.js +9 -8
  57. package/dist/server/sandbox-follow.js +54 -0
  58. package/dist/server/sandbox-storage.js +38 -1
  59. package/dist/server/sandbox-sync.js +392 -0
  60. package/dist/server/sandboxes-api.js +54 -8
  61. package/dist/server/sandboxes.js +19 -0
  62. package/dist/server/server-config.js +14 -0
  63. package/dist/server/server.js +189 -46
  64. package/dist/server/service-runs.js +41 -8
  65. package/dist/server/task-order.js +56 -0
  66. package/dist/utils/project-path.js +20 -0
  67. package/dist/utils/tar-files.js +52 -0
  68. package/dist/utils/tar.js +37 -1
  69. package/package.json +1 -1
  70. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -9,6 +9,7 @@ const git_checkout_1 = require("./git-checkout");
9
9
  const oauth_1 = require("./oauth");
10
10
  const runs_1 = require("./runs");
11
11
  const repo_1 = require("./repo");
12
+ const sandbox_files_1 = require("./sandbox-files");
12
13
  const sandbox_storage_1 = require("./sandbox-storage");
13
14
  // How long creating a sandbox or moving it to another commit may take
14
15
  const FETCH_TIMEOUT_MS = 10 * 60 * 1000;
@@ -40,6 +41,8 @@ class SandboxRegistry {
40
41
  // the measures of runs that are over, which a run's result does not wait for
41
42
  this.measuring = new Map();
42
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();
43
46
  this.runs = { holder: () => undefined, stop: async () => undefined };
44
47
  this.now = options.now ?? Date.now;
45
48
  }
@@ -47,6 +50,16 @@ class SandboxRegistry {
47
50
  useRuns(runs) {
48
51
  this.runs = runs;
49
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
+ }
50
63
  get limits() {
51
64
  return this.options.limits;
52
65
  }
@@ -261,6 +274,10 @@ class SandboxRegistry {
261
274
  });
262
275
  }
263
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
+ }
264
281
  throw new SandboxError(502, repos.scrub(e, credentials.values).message);
265
282
  }
266
283
  sandbox.ref = ref;
@@ -455,6 +472,7 @@ class SandboxRegistry {
455
472
  sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
456
473
  sandbox.lastUsedAt = this.timestamp();
457
474
  await this.save(sandbox);
475
+ this.changed(id);
458
476
  return plan.files;
459
477
  });
460
478
  }
@@ -488,6 +506,7 @@ class SandboxRegistry {
488
506
  }
489
507
  sandbox.bytes = await this.options.storage.usage(keyOf(sandbox));
490
508
  await this.save(sandbox);
509
+ this.changed(id);
491
510
  });
492
511
  const settled = measure.catch(() => undefined);
493
512
  this.measuring.set(id, settled);
@@ -581,6 +581,20 @@ exports.serverConfigSchema = zod_1.z
581
581
  .default({}),
582
582
  // how long a passed check stays for `remote verify` to find (see checks.ts)
583
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({}),
584
598
  })
585
599
  .strict()
586
600
  .default({}),
@@ -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;
@@ -328,7 +362,13 @@ exports.refuseWake = refuseWake;
328
362
  function runsTheSame(run, next) {
329
363
  const sorted = (values) => JSON.stringify([...values].sort());
330
364
  const options = (value) => JSON.stringify(value ?? {}, Object.keys(value ?? {}).sort());
331
- const endpoints = (spec) => JSON.stringify(spec.endpoints.map((endpoint) => [endpoint.service, endpoint.port, endpoint.host]));
365
+ // the public paths are part of an endpoint: a run that opens other paths is not the same run
366
+ const endpoints = (spec) => JSON.stringify(spec.endpoints.map((endpoint) => [
367
+ endpoint.service,
368
+ endpoint.port,
369
+ endpoint.host,
370
+ sorted(endpoint.publicPaths ?? []),
371
+ ]));
332
372
  return (!!run.up &&
333
373
  run.source.type === 'ref' &&
334
374
  run.source.repo === next.source.repo &&
@@ -351,6 +391,8 @@ function toRunResponse(run, queue, named = false, nameOf) {
351
391
  ...(queue ? { queue } : {}),
352
392
  };
353
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];
354
396
  function listRun(registry, definitions, viewer, run) {
355
397
  return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
356
398
  }
@@ -371,7 +413,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
371
413
  // an approval where they need one, never the owner's (run-retry.ts).
372
414
  async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
373
415
  const viewer = (0, overview_1.getViewer)(config, principal);
374
- 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);
375
417
  if (!run) {
376
418
  (0, http_2.send)(res, 404, { error: 'not found' });
377
419
  return;
@@ -447,6 +489,14 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
447
489
  (0, http_2.send)(res, 400, { error: 'sleepTtl: a service run from a sandbox does not sleep, start it from a branch' });
448
490
  return;
449
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
+ }
450
500
  const sleepTtlText = request.source.type === 'ref' ? request.sleepTtl ?? config.runs.up.sleepTtl : undefined;
451
501
  const sleepTtl = request.services.length > 0 && sleepTtlText ? (0, units_1.parseDuration)(sleepTtlText) : undefined;
452
502
  const argued = (request.options.args ?? []).length > 0 ? request.tasks[0] : undefined;
@@ -470,12 +520,6 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
470
520
  return;
471
521
  }
472
522
  }
473
- if (request.services.length > 0 && request.source.type === 'sandbox' && config.backend.type === 'kubernetes') {
474
- (0, http_2.send)(res, 400, {
475
- error: 'on a cluster a service run starts from a branch, push the sandbox and start it from there',
476
- });
477
- return;
478
- }
479
523
  const sandbox = request.source.type === 'sandbox' ? sandboxes.registry.get(principal, request.source.id) : undefined;
480
524
  if (request.source.type === 'sandbox') {
481
525
  if (!sandbox) {
@@ -513,6 +557,16 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
513
557
  return;
514
558
  }
515
559
  }
560
+ // a service run is named after its branch unless it says, and its endpoints after that
561
+ const serviceName = request.services.length > 0
562
+ ? request.name ??
563
+ (0, service_runs_1.getServiceRunName)(request.source.type === 'ref' ? request.source.ref : sandbox?.ref)
564
+ : '';
565
+ const misnamed = (0, service_runs_1.refusePublicPaths)(request, serviceName);
566
+ if (misnamed) {
567
+ (0, http_2.send)(res, 400, { error: misnamed });
568
+ return;
569
+ }
516
570
  // the accounts of a run are read from the files it is pinned to, with the engine
517
571
  const bundle = version.plan ? await definitions.files(version) : undefined;
518
572
  if (!version.plan || !bundle) {
@@ -537,7 +591,8 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
537
591
  return;
538
592
  }
539
593
  const refused = (0, run_plan_1.refuseArguments)(request, planned.plan, sandbox ? sandboxes.policy : planning.policy) ??
540
- (0, service_runs_1.refuseEndpoints)(request, planned.plan, config.runs.secretNetwork === 'open');
594
+ (0, service_runs_1.refuseEndpoints)(request, planned.plan, config.runs.secretNetwork === 'open') ??
595
+ (0, service_runs_1.refusePublicSecrets)(request, planned.plan);
541
596
  if (refused) {
542
597
  log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${refused}`);
543
598
  (0, http_2.send)(res, 400, { error: refused });
@@ -614,18 +669,14 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
614
669
  }
615
670
  planned = pinned;
616
671
  }
617
- // a service run is named after its branch unless it says, and its endpoints after that
618
- const serviceName = request.services.length > 0
619
- ? request.name ??
620
- (0, service_runs_1.getServiceRunName)(request.source.type === 'ref' ? request.source.ref : sandbox?.ref)
621
- : '';
622
672
  const up = request.services.length > 0
623
673
  ? {
624
674
  services: request.services,
625
675
  ttl,
626
676
  ...(sleepTtl ? { sleepTtl } : {}),
627
677
  name: serviceName,
628
- endpoints: (0, service_runs_1.toRunEndpoints)(request.endpoints, (0, service_runs_1.getEndpointHosts)(serviceName, principal, request.endpoints), endpointUrl),
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 } : {}),
629
680
  }
630
681
  : undefined;
631
682
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
@@ -692,7 +743,8 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
692
743
  }
693
744
  catch (e) {
694
745
  if (e instanceof runs_1.RunError) {
695
- (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' } : {});
696
748
  return;
697
749
  }
698
750
  if (e instanceof sandboxes_1.SandboxError) {
@@ -761,7 +813,7 @@ async function handle(api, verifier, req, res) {
761
813
  * dashboard, which asks the same API for what its pages show (dashboard.ts).
762
814
  */
763
815
  async function handleApi(api, principal, req, res, url) {
764
- 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;
765
817
  const path = url.pathname;
766
818
  if (await (0, accounts_api_1.handleAccounts)(config, log, principal, req, res, url)) {
767
819
  return;
@@ -775,6 +827,9 @@ async function handleApi(api, principal, req, res, url) {
775
827
  if (await (0, sandboxes_api_1.handleSandboxes)(config, sandboxes.registry, repos, log, principal, req, res, url)) {
776
828
  return;
777
829
  }
830
+ if (await (0, artifacts_api_1.handleArtifacts)(config, registry, artifacts, log, principal, req, res, url, now)) {
831
+ return;
832
+ }
778
833
  if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, (host) => gateway?.url(host) ?? host, log, principal, req, res, url)) {
779
834
  return;
780
835
  }
@@ -810,22 +865,53 @@ async function handleApi(api, principal, req, res, url) {
810
865
  if (!params.has('scope')) {
811
866
  params.set('scope', 'visible');
812
867
  }
813
- 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);
814
872
  try {
815
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);
816
877
  }
817
878
  catch (e) {
818
879
  (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
819
880
  return;
820
881
  }
821
- const runs = (0, overview_1.filterRuns)(registry.all(), viewer, filter).map((run) => (0, overview_1.toListedRun)(viewer, run));
822
- const oldest = (0, timings_1.getOldestCounted)(runs);
823
- // where in the repository the build file of the last run is, as its version says
824
- const tasks = (0, timings_1.getTaskStats)(runs, Date.now()).map((stats) => {
825
- const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
826
- return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
827
- });
828
- (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
+ }
829
915
  return;
830
916
  }
831
917
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -850,7 +936,8 @@ async function startServer(config, environment, options = {}) {
850
936
  const log = (line) => write(line.replace(/\p{Cc}/gu, '?').slice(0, 1000));
851
937
  if (config.runtimes.includes('local') && config.backend.type === 'host') {
852
938
  log('warning: the local runtime is allowed, local tasks run as the user of this server and read all it can read; ' +
853
- '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)');
854
941
  }
855
942
  // build files are read, planned and run as the server's runs see the world: the
856
943
  // operator's accounts and the allowlisted environment, nothing of the server's own
@@ -930,6 +1017,18 @@ async function startServer(config, environment, options = {}) {
930
1017
  if (config.backend.type === 'host' || config.entitlements.some((entitlement) => entitlement.sandboxes?.length)) {
931
1018
  await sandboxes.registry.load();
932
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
+ });
933
1032
  const executorOptions = {
934
1033
  definitions,
935
1034
  planning,
@@ -937,7 +1036,14 @@ async function startServer(config, environment, options = {}) {
937
1036
  directory: (0, path_1.join)(storage, 'runs'),
938
1037
  cache: (0, path_1.join)(storage, 'cache'),
939
1038
  worker: options.worker,
940
- 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,
941
1047
  ...(config.backend.type === 'host' && config.backend.capabilities
942
1048
  ? { capabilityRuntime: config.backend.capabilities.runtime }
943
1049
  : {}),
@@ -958,6 +1064,11 @@ async function startServer(config, environment, options = {}) {
958
1064
  void sweepChecks();
959
1065
  const sweeping = setInterval(sweepChecks, CHECK_SWEEP_MS);
960
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
+ });
961
1072
  const registry = new runs_1.RunRegistry({
962
1073
  executor,
963
1074
  maxConcurrent: config.runs.maxConcurrent,
@@ -984,12 +1095,32 @@ async function startServer(config, environment, options = {}) {
984
1095
  .then(() => log(`checks run=${run.id} passed=[${passed.map((record) => record.task).join(',')}]`))
985
1096
  .catch((e) => log(`the checks of run ${run.id} were not kept: ${e instanceof Error ? e.message : e}`));
986
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),
987
1104
  },
988
1105
  log,
989
1106
  });
990
- // the executor hears which service runs sleep with their volumes kept, and removes what it
991
- // 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)
992
1122
  await registry.restore();
1123
+ void sweepArtifacts();
993
1124
  const proposals = new proposals_1.ProposalRegistry({
994
1125
  maxWaiting: config.approvals.maxWaiting,
995
1126
  timeout: (0, units_1.parseDuration)(config.approvals.timeout),
@@ -1025,14 +1156,23 @@ async function startServer(config, environment, options = {}) {
1025
1156
  planning,
1026
1157
  repos,
1027
1158
  checks,
1159
+ artifacts,
1028
1160
  capacity,
1029
1161
  log,
1162
+ now,
1030
1163
  };
1031
1164
  await gateway?.load();
1032
1165
  sandboxes.registry.useRuns({
1033
1166
  holder: (id) => registry.holder(id),
1034
1167
  stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
1035
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));
1036
1176
  const listener = (req, res) => {
1037
1177
  handle(api, verifier, req, res).catch((e) => {
1038
1178
  if (e instanceof http_2.HttpError) {
@@ -1126,7 +1266,10 @@ async function startServer(config, environment, options = {}) {
1126
1266
  },
1127
1267
  close: async () => {
1128
1268
  clearInterval(sweeping);
1269
+ clearInterval(sweepingArtifacts);
1129
1270
  proposals.close();
1271
+ follower.close();
1272
+ sandboxSync.close();
1130
1273
  await registry.close();
1131
1274
  await new Promise((resolve, reject) => {
1132
1275
  server.close((err) => (err ? reject(err) : resolve()));
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mayPublishEndpoints = exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
3
+ exports.mayPublishEndpoints = exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refusePublicPaths = exports.refusePublicSecrets = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const plan_1 = require("./plan");
6
6
  const policy_1 = require("./policy");
@@ -73,6 +73,28 @@ function refuseEndpoints(request, plan, secretNetworkOpen) {
73
73
  return null;
74
74
  }
75
75
  exports.refuseEndpoints = refuseEndpoints;
76
+ /**
77
+ * Why the public paths of a run can not be served, or null. A public path is open without a
78
+ * sign-in, so a service with one may not read a secret or a credential, directly or through
79
+ * what it is made from or needs, whatever `runs.secretNetwork` says: the way out refuseEndpoints
80
+ * allows for a signed-in page does not hold for a path anybody may request.
81
+ */
82
+ function refusePublicSecrets(request, plan) {
83
+ for (const { service } of request.publicPaths) {
84
+ for (const { name, path } of reachedFrom(service, plan)) {
85
+ const reads = (0, plan_1.getCredentialReads)(plan[name]);
86
+ if (reads.length === 0) {
87
+ continue;
88
+ }
89
+ // the way from the service to what reads it: `web needs api, which needs vault`
90
+ const way = path.map((step, index) => `${index === 0 ? '' : ', which '}${step.relation} ${step.name}`).join('');
91
+ const from = path.length === 0 ? `${service} reads` : `${service} ${way}, which reads`;
92
+ return `${from} ${reads.join(', ')}: it can not have public paths on this server, a path open without a sign-in could show it`;
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+ exports.refusePublicSecrets = refusePublicSecrets;
76
98
  function reachedFrom(service, plan) {
77
99
  if (!plan[service]) {
78
100
  return [];
@@ -96,13 +118,24 @@ function reachedFrom(service, plan) {
96
118
  }
97
119
  return reached;
98
120
  }
99
- function toRunEndpoints(endpoints, hosts, url) {
100
- return endpoints.map((endpoint, index) => ({
101
- service: endpoint.service,
102
- port: endpoint.port,
103
- host: hosts[index],
104
- url: url(hosts[index]),
105
- }));
121
+ // The public paths of a run must name the run they start: a run that gets another name than the
122
+ // one the paths were written for would publish them at endpoints the operator did not mean.
123
+ function refusePublicPaths(request, name) {
124
+ const other = request.publicPaths.find((entry) => entry.run !== name);
125
+ return other ? `the public paths name the run ${other.run}, but this run is ${name}` : null;
126
+ }
127
+ exports.refusePublicPaths = refusePublicPaths;
128
+ function toRunEndpoints(endpoints, hosts, url, publicPaths = []) {
129
+ return endpoints.map((endpoint, index) => {
130
+ const paths = publicPaths.find((entry) => entry.service === endpoint.service && entry.port === endpoint.port);
131
+ return {
132
+ service: endpoint.service,
133
+ port: endpoint.port,
134
+ host: hosts[index],
135
+ url: url(hosts[index]),
136
+ ...(paths ? { publicPaths: paths.paths } : {}),
137
+ };
138
+ });
106
139
  }
107
140
  exports.toRunEndpoints = toRunEndpoints;
108
141
  // The repository of a run's source, which the endpoints grants are written for.