hammerkit 2.1.0-next.2 → 2.1.0-next.21

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 (87) hide show
  1. package/build.schema.json +39 -18
  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/environment/replace-env-variables.js +8 -5
  8. package/dist/environment/run-source-envs.js +2 -1
  9. package/dist/executer/archive-task-entry.js +1 -1
  10. package/dist/executer/deadline.js +63 -10
  11. package/dist/executer/event-cache.js +5 -1
  12. package/dist/executer/execute-work-task.js +15 -3
  13. package/dist/executer/runner-commands.js +36 -0
  14. package/dist/file/get-file-context.js +4 -7
  15. package/dist/harness/connect.js +12 -8
  16. package/dist/harness/reconnect.js +141 -0
  17. package/dist/harness/sandbox-client.js +241 -33
  18. package/dist/harness/service-tools.js +11 -2
  19. package/dist/kubernetes/cluster-state.js +48 -14
  20. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  21. package/dist/kubernetes/follow-pod-logs.js +8 -5
  22. package/dist/kubernetes/kept-claims.js +26 -5
  23. package/dist/kubernetes/resources.js +5 -1
  24. package/dist/kubernetes/sandbox-runner.js +526 -156
  25. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  26. package/dist/kubernetes/sync-changes.js +463 -0
  27. package/dist/kubernetes/volumes.js +23 -1
  28. package/dist/optimizer/get-work-cache-stats.js +7 -0
  29. package/dist/optimizer/work-task-cache-description.js +3 -2
  30. package/dist/planner/image-build.js +5 -0
  31. package/dist/planner/utils/dependency-outputs.js +7 -6
  32. package/dist/planner/validate.js +41 -0
  33. package/dist/planner/work-item-status.js +12 -2
  34. package/dist/planner/work-runtime-aggregate.js +1 -0
  35. package/dist/planner/work-runtime-docker.js +33 -6
  36. package/dist/planner/work-runtime-kubernetes.js +313 -70
  37. package/dist/planner/work-runtime-local.js +8 -4
  38. package/dist/planner/work-secret.js +33 -11
  39. package/dist/planner/work-service-id.js +30 -6
  40. package/dist/program.js +19 -1
  41. package/dist/remote/annotations.js +37 -5
  42. package/dist/remote/bundle.js +6 -8
  43. package/dist/remote/collect-bundle.js +3 -2
  44. package/dist/remote/device-login.js +4 -1
  45. package/dist/remote/remote-commands.js +16 -7
  46. package/dist/remote/remote-work-commands.js +266 -75
  47. package/dist/remote/server-client.js +38 -40
  48. package/dist/schema/build-file-base-task-schema.js +16 -1
  49. package/dist/schema/build-file-image-build-schema.js +5 -8
  50. package/dist/schema/reference-parser.js +108 -43
  51. package/dist/schema/work-scope-parser.js +8 -0
  52. package/dist/secrets/prefetch-secrets.js +20 -1
  53. package/dist/server/artifacts-api.js +56 -0
  54. package/dist/server/definitions-api.js +62 -8
  55. package/dist/server/executor.js +117 -30
  56. package/dist/server/http.js +4 -1
  57. package/dist/server/keep-artifacts.js +230 -0
  58. package/dist/server/kubernetes-backend.js +186 -59
  59. package/dist/server/kubernetes-sandbox-storage.js +3 -2
  60. package/dist/server/overview.js +73 -9
  61. package/dist/server/paging.js +167 -0
  62. package/dist/server/plan.js +16 -1
  63. package/dist/server/run-access.js +24 -0
  64. package/dist/server/run-artifacts.js +171 -0
  65. package/dist/server/run-logs.js +25 -1
  66. package/dist/server/run-request.js +11 -0
  67. package/dist/server/run-source-environment.js +1 -1
  68. package/dist/server/run-worker.js +267 -33
  69. package/dist/server/runs.js +527 -99
  70. package/dist/server/sandbox-files-api.js +27 -12
  71. package/dist/server/sandbox-files.js +12 -10
  72. package/dist/server/sandbox-follow.js +54 -0
  73. package/dist/server/sandbox-pod.js +1 -1
  74. package/dist/server/sandbox-storage.js +38 -1
  75. package/dist/server/sandbox-sync.js +392 -0
  76. package/dist/server/sandboxes-api.js +116 -19
  77. package/dist/server/sandboxes.js +38 -3
  78. package/dist/server/server-config.js +14 -0
  79. package/dist/server/server.js +169 -38
  80. package/dist/server/task-order.js +56 -0
  81. package/dist/utils/project-path.js +20 -0
  82. package/dist/utils/tar-files.js +52 -0
  83. package/dist/utils/tar.js +37 -1
  84. package/package.json +1 -1
  85. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  86. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  87. 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 {
@@ -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;
@@ -351,6 +385,8 @@ function toRunResponse(run, queue, named = false, nameOf) {
351
385
  ...(queue ? { queue } : {}),
352
386
  };
353
387
  }
388
+ // where a page of runs ends: when the last run was created, and which it is
389
+ const runKey = (run) => [run.createdAt, run.id];
354
390
  function listRun(registry, definitions, viewer, run) {
355
391
  return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
356
392
  }
@@ -371,7 +407,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
371
407
  // an approval where they need one, never the owner's (run-retry.ts).
372
408
  async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
373
409
  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);
410
+ const run = (0, run_access_1.findReadableRun)(config, registry, principal, id);
375
411
  if (!run) {
376
412
  (0, http_2.send)(res, 404, { error: 'not found' });
377
413
  return;
@@ -447,6 +483,14 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
447
483
  (0, http_2.send)(res, 400, { error: 'sleepTtl: a service run from a sandbox does not sleep, start it from a branch' });
448
484
  return;
449
485
  }
486
+ // only a Kubernetes backend syncs the changed files of a sandbox into the services; a host
487
+ // runs them on the sandbox's own files, so a restart would do nothing there
488
+ if (request.restart?.length && config.backend.type !== 'kubernetes') {
489
+ (0, http_2.send)(res, 400, {
490
+ error: `restart: this server (backend ${config.backend.type}) has no file sync, a host's services run on the sandbox's files`,
491
+ });
492
+ return;
493
+ }
450
494
  const sleepTtlText = request.source.type === 'ref' ? request.sleepTtl ?? config.runs.up.sleepTtl : undefined;
451
495
  const sleepTtl = request.services.length > 0 && sleepTtlText ? (0, units_1.parseDuration)(sleepTtlText) : undefined;
452
496
  const argued = (request.options.args ?? []).length > 0 ? request.tasks[0] : undefined;
@@ -470,12 +514,6 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
470
514
  return;
471
515
  }
472
516
  }
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
517
  const sandbox = request.source.type === 'sandbox' ? sandboxes.registry.get(principal, request.source.id) : undefined;
480
518
  if (request.source.type === 'sandbox') {
481
519
  if (!sandbox) {
@@ -626,6 +664,7 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
626
664
  ...(sleepTtl ? { sleepTtl } : {}),
627
665
  name: serviceName,
628
666
  endpoints: (0, service_runs_1.toRunEndpoints)(request.endpoints, (0, service_runs_1.getEndpointHosts)(serviceName, principal, request.endpoints), endpointUrl),
667
+ ...(request.restart?.length ? { restart: request.restart } : {}),
629
668
  }
630
669
  : undefined;
631
670
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
@@ -692,7 +731,8 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
692
731
  }
693
732
  catch (e) {
694
733
  if (e instanceof runs_1.RunError) {
695
- (0, http_2.send)(res, e.status, { error: e.message });
734
+ // a proxy answers 503 too, also after the server took the request: this one is safe to send again
735
+ (0, http_2.send)(res, e.status, { error: e.message }, e instanceof runs_1.ShuttingDownError ? { [http_2.RETRY_HEADER]: 'safe' } : {});
696
736
  return;
697
737
  }
698
738
  if (e instanceof sandboxes_1.SandboxError) {
@@ -761,7 +801,7 @@ async function handle(api, verifier, req, res) {
761
801
  * dashboard, which asks the same API for what its pages show (dashboard.ts).
762
802
  */
763
803
  async function handleApi(api, principal, req, res, url) {
764
- const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, capacity, log, } = api;
804
+ const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, artifacts, capacity, log, now, } = api;
765
805
  const path = url.pathname;
766
806
  if (await (0, accounts_api_1.handleAccounts)(config, log, principal, req, res, url)) {
767
807
  return;
@@ -775,6 +815,9 @@ async function handleApi(api, principal, req, res, url) {
775
815
  if (await (0, sandboxes_api_1.handleSandboxes)(config, sandboxes.registry, repos, log, principal, req, res, url)) {
776
816
  return;
777
817
  }
818
+ if (await (0, artifacts_api_1.handleArtifacts)(config, registry, artifacts, log, principal, req, res, url, now)) {
819
+ return;
820
+ }
778
821
  if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, (host) => gateway?.url(host) ?? host, log, principal, req, res, url)) {
779
822
  return;
780
823
  }
@@ -810,22 +853,53 @@ async function handleApi(api, principal, req, res, url) {
810
853
  if (!params.has('scope')) {
811
854
  params.set('scope', 'visible');
812
855
  }
813
- let filter;
856
+ // the text is looked for in the tasks, not in the runs they ran in
857
+ params.delete('q');
858
+ let filter, page, values, order;
859
+ const text = (0, paging_1.readText)(url.searchParams);
814
860
  try {
815
861
  filter = (0, overview_1.parseRunFilter)(params, viewer.grant);
862
+ values = (0, paging_1.parseValues)(url.searchParams, task_order_1.TASK_FIELDS);
863
+ page = values ? undefined : (0, paging_1.parsePage)(url.searchParams);
864
+ order = (0, task_order_1.parseTaskOrder)(url.searchParams);
816
865
  }
817
866
  catch (e) {
818
867
  (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
819
868
  return;
820
869
  }
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 } : {}) });
870
+ const statsOf = (over) => {
871
+ const runs = (0, overview_1.filterRuns)(registry.all(), viewer, over).map((run) => (0, overview_1.toListedRun)(viewer, run));
872
+ // where in the repository the build file of the last run is, as its version says
873
+ const tasks = (0, timings_1.getTaskStats)(runs, Date.now())
874
+ .map((stats) => {
875
+ const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
876
+ return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
877
+ })
878
+ .filter((stats) => !text || (0, paging_1.hasText)([stats.repo, stats.task, stats.last.entry], text));
879
+ return { runs, tasks };
880
+ };
881
+ try {
882
+ if (values) {
883
+ const { sources, ...others } = filter;
884
+ void sources;
885
+ const counted = (0, paging_1.countValues)(statsOf(others).tasks, (stats) => [(0, task_order_1.taskSource)(stats)], values);
886
+ (0, http_2.send)(res, 200, (0, paging_1.answerPage)('values', counted));
887
+ return;
888
+ }
889
+ const { runs, tasks } = statsOf(filter);
890
+ const oldest = (0, timings_1.getOldestCounted)(runs);
891
+ const sorted = order ? (0, task_order_1.sortTasks)(tasks, order) : tasks;
892
+ (0, http_2.send)(res, 200, {
893
+ ...(page ? (0, paging_1.answerPage)('tasks', (0, paging_1.pageByPosition)(sorted, page)) : { tasks: sorted }),
894
+ ...(oldest ? { oldest } : {}),
895
+ });
896
+ }
897
+ catch (e) {
898
+ if (!(e instanceof paging_1.ListParamError)) {
899
+ throw e;
900
+ }
901
+ (0, http_2.send)(res, 400, { error: e.message });
902
+ }
829
903
  return;
830
904
  }
831
905
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -850,7 +924,8 @@ async function startServer(config, environment, options = {}) {
850
924
  const log = (line) => write(line.replace(/\p{Cc}/gu, '?').slice(0, 1000));
851
925
  if (config.runtimes.includes('local') && config.backend.type === 'host') {
852
926
  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');
927
+ 'an account is then an approval class, not a credential boundary, and the server keeps no outputs of its runs ' +
928
+ '(remote artifacts)');
854
929
  }
855
930
  // build files are read, planned and run as the server's runs see the world: the
856
931
  // operator's accounts and the allowlisted environment, nothing of the server's own
@@ -930,6 +1005,18 @@ async function startServer(config, environment, options = {}) {
930
1005
  if (config.backend.type === 'host' || config.entitlements.some((entitlement) => entitlement.sandboxes?.length)) {
931
1006
  await sandboxes.registry.load();
932
1007
  }
1008
+ // a local task of a host runs as the user of this server: what it can write is never served
1009
+ const localTasksOnHost = config.backend.type === 'host' && config.runtimes.includes('local');
1010
+ // a service run from a sandbox on a cluster gets the changed files of the sandbox into its
1011
+ // services, batched (SandboxFollow), as the files that changed since the services last got theirs
1012
+ // the folder a server before the direct sync staged the changes in is no longer used
1013
+ await (0, promises_1.rm)((0, path_1.join)(storage, 'sandboxes', 'sync'), { recursive: true, force: true });
1014
+ const sandboxSync = new sandbox_sync_1.SandboxSync({
1015
+ files: (owner, id) => sandboxes.registry.files(owner, id),
1016
+ upOn: (id) => registry.upOn(id),
1017
+ send: (run, changes) => registry.syncFiles(run, changes),
1018
+ log,
1019
+ });
933
1020
  const executorOptions = {
934
1021
  definitions,
935
1022
  planning,
@@ -937,7 +1024,14 @@ async function startServer(config, environment, options = {}) {
937
1024
  directory: (0, path_1.join)(storage, 'runs'),
938
1025
  cache: (0, path_1.join)(storage, 'cache'),
939
1026
  worker: options.worker,
940
- sandboxes: { ...sandboxes, network: config.sandboxes.network },
1027
+ sandboxes: {
1028
+ ...sandboxes,
1029
+ network: config.sandboxes.network,
1030
+ started: async (run) => sandboxSync.started(run),
1031
+ ended: async (run) => sandboxSync.forget(run.id),
1032
+ syncFailed: (runId) => sandboxSync.failed(runId),
1033
+ },
1034
+ localTasksOnHost,
941
1035
  ...(config.backend.type === 'host' && config.backend.capabilities
942
1036
  ? { capabilityRuntime: config.backend.capabilities.runtime }
943
1037
  : {}),
@@ -958,6 +1052,11 @@ async function startServer(config, environment, options = {}) {
958
1052
  void sweepChecks();
959
1053
  const sweeping = setInterval(sweepChecks, CHECK_SWEEP_MS);
960
1054
  sweeping.unref();
1055
+ const artifacts = new run_artifacts_1.ArtifactStore((0, path_1.join)(storage, 'artifacts'), {
1056
+ keep: (0, units_1.parseDuration)(config.runs.artifacts.keep),
1057
+ total: (0, units_1.parseSize)(config.runs.artifacts.total),
1058
+ localTasksOnHost,
1059
+ });
961
1060
  const registry = new runs_1.RunRegistry({
962
1061
  executor,
963
1062
  maxConcurrent: config.runs.maxConcurrent,
@@ -984,12 +1083,32 @@ async function startServer(config, environment, options = {}) {
984
1083
  .then(() => log(`checks run=${run.id} passed=[${passed.map((record) => record.task).join(',')}]`))
985
1084
  .catch((e) => log(`the checks of run ${run.id} were not kept: ${e instanceof Error ? e.message : e}`));
986
1085
  }
1086
+ // what the run kept counts against the total of all runs from now
1087
+ void sweepArtifacts();
1088
+ },
1089
+ artifacts: {
1090
+ directoryOf: (id) => artifacts.directoryOf(id),
1091
+ maxBytes: (0, units_1.parseSize)(config.runs.artifacts.maxBytes),
987
1092
  },
988
1093
  log,
989
1094
  });
990
- // the executor hears which service runs sleep with their volumes kept, and removes what it
991
- // kept for any other (RunExecutor.restored)
1095
+ const now = options.now ?? Date.now;
1096
+ // what is over its time goes within the hour, what is over the total when a run ends
1097
+ const sweepArtifacts = () => artifacts
1098
+ .sweep((id) => registry.peek(id), now())
1099
+ .then((removed) => {
1100
+ if (removed.length > 0) {
1101
+ log(`removed the outputs of ${removed.length} runs: ${removed.join(', ')}`);
1102
+ }
1103
+ })
1104
+ .catch((e) => log(`the outputs of old runs could not be removed: ${e instanceof Error ? e.message : e}`));
1105
+ const sweepingArtifacts = setInterval(sweepArtifacts, ARTIFACT_SWEEP_MS);
1106
+ sweepingArtifacts.unref();
1107
+ // the runs the server before stopped resume, and the executor hears which service runs sleep
1108
+ // with their volumes kept and which runs resume, and removes what it kept for any other
1109
+ // (RunExecutor.restored)
992
1110
  await registry.restore();
1111
+ void sweepArtifacts();
993
1112
  const proposals = new proposals_1.ProposalRegistry({
994
1113
  maxWaiting: config.approvals.maxWaiting,
995
1114
  timeout: (0, units_1.parseDuration)(config.approvals.timeout),
@@ -1025,14 +1144,23 @@ async function startServer(config, environment, options = {}) {
1025
1144
  planning,
1026
1145
  repos,
1027
1146
  checks,
1147
+ artifacts,
1028
1148
  capacity,
1029
1149
  log,
1150
+ now,
1030
1151
  };
1031
1152
  await gateway?.load();
1032
1153
  sandboxes.registry.useRuns({
1033
1154
  holder: (id) => registry.holder(id),
1034
1155
  stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
1035
1156
  });
1157
+ // A service run from a sandbox follows the files of the sandbox: a burst of edits or runs that
1158
+ // wrote is synced once, when the sandbox has been quiet for a moment (SandboxFollow)
1159
+ const follower = new sandbox_follow_1.SandboxFollow({
1160
+ follow: (id) => sandboxSync.follow(id),
1161
+ log: (line) => log(`follow ${line}`),
1162
+ });
1163
+ sandboxes.registry.onChange((id) => follower.changed(id));
1036
1164
  const listener = (req, res) => {
1037
1165
  handle(api, verifier, req, res).catch((e) => {
1038
1166
  if (e instanceof http_2.HttpError) {
@@ -1126,7 +1254,10 @@ async function startServer(config, environment, options = {}) {
1126
1254
  },
1127
1255
  close: async () => {
1128
1256
  clearInterval(sweeping);
1257
+ clearInterval(sweepingArtifacts);
1129
1258
  proposals.close();
1259
+ follower.close();
1260
+ sandboxSync.close();
1130
1261
  await registry.close();
1131
1262
  await new Promise((resolve, reject) => {
1132
1263
  server.close((err) => (err ? reject(err) : resolve()));
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sortTasks = exports.parseTaskOrder = exports.taskSource = exports.TASK_FIELDS = void 0;
4
+ const paging_1 = require("./paging");
5
+ // what GET /v1/tasks?values= answers the values of: where the tasks ran from
6
+ exports.TASK_FIELDS = ['source'];
7
+ // where the runs of a task are from, as the source filter of the runs names it
8
+ function taskSource(stats) {
9
+ return stats.repo === 'an upload' ? 'upload' : stats.repo;
10
+ }
11
+ exports.taskSource = taskSource;
12
+ // of its runs, how many came from the cache, and how many ended well (cached passed before)
13
+ const rate = (part, stats) => (stats.runs ? part / stats.runs : undefined);
14
+ // what `sort` of GET /v1/tasks orders by: the columns of the Tasks page
15
+ const SORT_BY = {
16
+ task: (stats) => stats.task,
17
+ last: (stats) => Date.parse(stats.last.at),
18
+ runs: (stats) => stats.runs,
19
+ cache: (stats) => rate(stats.cached, stats),
20
+ success: (stats) => rate(stats.runs - stats.failed, stats),
21
+ median: (stats) => stats.medianMs,
22
+ p90: (stats) => stats.p90Ms,
23
+ total: (stats) => stats.totalMs,
24
+ };
25
+ // `sort` and `order` (asc or desc, desc when left out): undefined when the caller names no sort.
26
+ function parseTaskOrder(params) {
27
+ const sort = params.get('sort');
28
+ if (sort === null) {
29
+ return undefined;
30
+ }
31
+ if (!(sort in SORT_BY)) {
32
+ throw new paging_1.ListParamError(`sort: one of ${Object.keys(SORT_BY).join(', ')}`);
33
+ }
34
+ const order = params.get('order') ?? 'desc';
35
+ if (order !== 'asc' && order !== 'desc') {
36
+ throw new paging_1.ListParamError('order: asc or desc');
37
+ }
38
+ return { sort, order };
39
+ }
40
+ exports.parseTaskOrder = parseTaskOrder;
41
+ // The tasks in that order, those without a value last, and by repository and name when equal.
42
+ function sortTasks(tasks, { sort, order }) {
43
+ const value = SORT_BY[sort];
44
+ return [...tasks].sort((a, b) => {
45
+ const x = value(a);
46
+ const y = value(b);
47
+ if (x === undefined || y === undefined) {
48
+ return x === y ? tie(a, b) : x === undefined ? 1 : -1;
49
+ }
50
+ const compared = typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y));
51
+ return (order === 'asc' ? compared : -compared) || tie(a, b);
52
+ });
53
+ }
54
+ exports.sortTasks = sortTasks;
55
+ const tie = (a, b) => a.repo.localeCompare(b.repo) || a.task.localeCompare(b.task);
56
+ //# sourceMappingURL=task-order.js.map
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRelativePath = void 0;
4
+ /**
5
+ * A path relative to a root (of a project, a bundle, a sandbox), as the API and the CLI take
6
+ * it: at most `maxLength` characters, `/` between names, no `.` or `..` or empty name, no
7
+ * backslash, no NUL, nothing absolute (`/x`, `C:x`). The one rule every path an input names
8
+ * is checked by, so the places that check it can not drift apart.
9
+ */
10
+ function isRelativePath(path, maxLength) {
11
+ return (path.length > 0 &&
12
+ path.length <= maxLength &&
13
+ !path.startsWith('/') &&
14
+ !/^[A-Za-z]:/.test(path) &&
15
+ !path.includes('\\') &&
16
+ !path.includes('\0') &&
17
+ !path.split('/').some((part) => part === '' || part === '.' || part === '..'));
18
+ }
19
+ exports.isRelativePath = isRelativePath;
20
+ //# sourceMappingURL=project-path.js.map