hammerkit 2.0.0-next.2 → 2.0.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 (112) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/index-DRSwIRXd.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +31 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +35 -14
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +100 -13
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-retry.js +57 -0
  91. package/dist/server/run-source-environment.js +39 -0
  92. package/dist/server/run-worker.js +71 -9
  93. package/dist/server/runs.js +133 -7
  94. package/dist/server/sandbox-files.js +339 -55
  95. package/dist/server/sandbox-patch.js +43 -17
  96. package/dist/server/sandboxes.js +57 -23
  97. package/dist/server/server-config.js +28 -5
  98. package/dist/server/server.js +150 -20
  99. package/dist/server/service-runs.js +50 -5
  100. package/dist/server/sources.js +68 -11
  101. package/dist/server/timings.js +23 -3
  102. package/dist/utils/buffer-context.js +30 -20
  103. package/dist/utils/limit.js +30 -0
  104. package/dist/utils/line-splitter.js +52 -0
  105. package/dist/utils/read-lines.js +65 -0
  106. package/dist/utils/tar.js +51 -1
  107. package/dist/utils/units.js +36 -1
  108. package/dist/utils/web-links.js +34 -0
  109. package/package.json +1 -1
  110. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  111. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  112. package/dist/dashboard/favicon.svg +0 -1
@@ -6,7 +6,7 @@
6
6
  * file, and each file is changed in memory, so a batch of edits applies fully or not at all.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.MAX_COMPARED_LINES = exports.parsePatch = exports.PatchError = void 0;
9
+ exports.MAX_HUNK_LINE = exports.PatchBudget = exports.MAX_COMPARED_LINES = exports.parsePatch = exports.PatchError = void 0;
10
10
  class PatchError extends Error {
11
11
  }
12
12
  exports.PatchError = PatchError;
@@ -57,16 +57,25 @@ function splice(file, at, block) {
57
57
  function oldSide(block) {
58
58
  return block.filter((line) => line.kind !== '+').map((line) => line.text);
59
59
  }
60
- // Lines one file's patch may compare to place its hunks. A hunk that is nowhere in a large
61
- // file would otherwise be compared with every place in it, its whole length at each.
60
+ // Lines the patches of one batch may compare to place their hunks. A hunk that is nowhere in
61
+ // a large file would otherwise be compared with every place in it, its whole length at each.
62
62
  exports.MAX_COMPARED_LINES = 20000000;
63
- let compared = 0;
64
- function startComparing() {
65
- compared = 0;
63
+ // The comparisons the patches of one batch made so far.
64
+ class PatchBudget {
65
+ constructor(max = exports.MAX_COMPARED_LINES) {
66
+ this.max = max;
67
+ this.compared = 0;
68
+ }
69
+ }
70
+ exports.PatchBudget = PatchBudget;
71
+ // the budget of the patch being applied: applying one is synchronous, so only one is
72
+ let current = new PatchBudget();
73
+ function startComparing(budget) {
74
+ current = budget ?? new PatchBudget();
66
75
  }
67
76
  function compare(path) {
68
- if (++compared > exports.MAX_COMPARED_LINES) {
69
- throw new PatchError(`${path}: the patch's lines were compared with the file ${exports.MAX_COMPARED_LINES} times without finding their place; give its hunks more lines of context or the line numbers of the file as it is`);
77
+ if (++current.compared > current.max) {
78
+ throw new PatchError(`${path}: the patches of this batch were compared with the files ${current.max} times without finding their place; give their hunks more lines of context or the line numbers of the files as they are`);
70
79
  }
71
80
  }
72
81
  function matchesAt(path, lines, at, wanted, same = (a, b) => stripCr(a) === stripCr(b)) {
@@ -176,14 +185,15 @@ function parseHunks(lines, start, path) {
176
185
  break;
177
186
  }
178
187
  const hunk = {
179
- oldStart: Number(header[1]),
180
- oldLength: header[2] === undefined ? 1 : Number(header[2]),
188
+ oldStart: lineNumber(header[1], path, hunks.length),
189
+ oldLength: header[2] === undefined ? 1 : lineNumber(header[2], path, hunks.length),
181
190
  lines: [],
182
191
  oldNoNewline: false,
183
192
  newNoNewline: false,
184
193
  };
194
+ lineNumber(header[3], path, hunks.length);
185
195
  let oldLeft = hunk.oldLength;
186
- let newLeft = header[4] === undefined ? 1 : Number(header[4]);
196
+ let newLeft = header[4] === undefined ? 1 : lineNumber(header[4], path, hunks.length);
187
197
  i++;
188
198
  while (oldLeft > 0 || newLeft > 0) {
189
199
  if (i >= lines.length) {
@@ -220,12 +230,22 @@ function parseHunks(lines, start, path) {
220
230
  }
221
231
  return [hunks, i];
222
232
  }
233
+ // The largest line number or line count a hunk header may name. A file an edit reads has
234
+ // at most MAX_FILE_BYTES, so no file has more lines than that.
235
+ exports.MAX_HUNK_LINE = 1000000000;
236
+ function lineNumber(digits, path, index) {
237
+ const value = Number(digits);
238
+ if (!Number.isSafeInteger(value) || value > exports.MAX_HUNK_LINE) {
239
+ throw new PatchError(`${path}: hunk ${index + 1} names line ${digits.length > 20 ? `${digits.slice(0, 20)}…` : digits}, more than a file has`);
240
+ }
241
+ return value;
242
+ }
223
243
  function filePatch(header, hunks) {
224
244
  const path = header.to ?? header.from ?? '';
225
245
  return {
226
246
  ...header,
227
- apply(content) {
228
- startComparing();
247
+ apply(content, budget) {
248
+ startComparing(budget);
229
249
  const file = splitLines(content);
230
250
  let delta = 0;
231
251
  let cursor = 0;
@@ -255,8 +275,14 @@ function nominal(hunk) {
255
275
  }
256
276
  // The match closest to `expected` at or after `from`, the way git apply moves a hunk
257
277
  // whose lines moved.
258
- function findNear(path, lines, wanted, expected, from) {
278
+ function findNear(path, lines, wanted, wantedAt, from) {
259
279
  const last = lines.length - wanted.length;
280
+ if (last < from) {
281
+ return -1;
282
+ }
283
+ // a line number past the end of the file looks from the end: every place it could be is
284
+ // between `from` and `last`, so the search never walks past them
285
+ const expected = Math.min(Math.max(wantedAt, from), last);
260
286
  for (let distance = 0; expected - distance >= from || expected + distance <= last; distance++) {
261
287
  if (expected - distance >= from && matchesAt(path, lines, expected - distance, wanted)) {
262
288
  return expected - distance;
@@ -414,7 +440,7 @@ function parseApplyPatch(text) {
414
440
  }
415
441
  chunks[chunks.length - 1].lines.push({ kind, text: current.slice(1) });
416
442
  }
417
- files.push({ from: path, to, apply: (content) => applyChunks(path, content, chunks) });
443
+ files.push({ from: path, to, apply: (content, budget) => applyChunks(path, content, chunks, budget) });
418
444
  }
419
445
  else {
420
446
  throw new PatchError(`"${line.slice(0, 80)}" is not an apply_patch line: expected *** Add File:, *** Update File:, *** Delete File: or *** End Patch`);
@@ -430,8 +456,8 @@ const trailing = (a, b) => a.trimEnd() === b.trimEnd();
430
456
  const trimmed = (a, b) => a.trim() === b.trim();
431
457
  // The way apply_patch finds its lines: after the chunk before it, exactly, then with
432
458
  // trailing and then all surrounding whitespace ignored.
433
- function applyChunks(path, content, chunks) {
434
- startComparing();
459
+ function applyChunks(path, content, chunks, budget) {
460
+ startComparing(budget);
435
461
  const file = splitLines(content);
436
462
  let cursor = 0;
437
463
  chunks.forEach((chunk, index) => {
@@ -32,6 +32,9 @@ class SandboxRegistry {
32
32
  // bytes they take once they were measured
33
33
  this.creating = new Map();
34
34
  this.deleting = new Set();
35
+ // the bytes edits take while they are written, so edits of two sandboxes at once both
36
+ // count against their owner's limit and the server's
37
+ this.reserved = new Map();
35
38
  // the measures of runs that are over, which a run's result does not wait for
36
39
  this.measuring = new Map();
37
40
  this.locks = new Map();
@@ -114,9 +117,10 @@ class SandboxRegistry {
114
117
  usage(owner) {
115
118
  const mine = this.list(owner);
116
119
  const creating = [...this.creating.values()].filter((create) => owns(owner, create.owner));
120
+ const reserved = [...this.reserved.values()].filter((reservation) => owns(owner, reservation.owner));
117
121
  return {
118
122
  count: mine.length + creating.length,
119
- bytes: [...mine, ...creating].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
123
+ bytes: [...mine, ...creating, ...reserved].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
120
124
  };
121
125
  }
122
126
  // Waits for the measures of the owner's runs that are over, so their limits hold.
@@ -139,6 +143,9 @@ class SandboxRegistry {
139
143
  * caller's to decide (`decideSandbox`); this checks the limits.
140
144
  */
141
145
  async create(owner, repo, ref) {
146
+ return this.growing(owner, () => this.createGrowing(owner, repo, ref));
147
+ }
148
+ async createGrowing(owner, repo, ref) {
142
149
  const { limits, storage, repos } = this.options;
143
150
  await this.measured(owner);
144
151
  const usage = this.usage(owner);
@@ -211,28 +218,47 @@ class SandboxRegistry {
211
218
  if (!state.clean) {
212
219
  throw new SandboxError(409, `the sandbox ${id} has changes, a fetch would mix them with another commit`);
213
220
  }
214
- const { storage, repos } = this.options;
215
- const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
216
- await this.resolve(sandbox.repo, ref, signal);
217
- const credentials = await repos.credentials(sandbox.repo);
218
- try {
219
- sandbox.commit = await storage.fetch(keyOf(sandbox), {
220
- url: repos.url(sandbox.repo),
221
- ref,
222
- env: credentials.env,
223
- signal,
224
- });
225
- }
226
- catch (e) {
227
- throw new SandboxError(502, repos.scrub(e, credentials.values).message);
228
- }
229
- sandbox.ref = ref;
230
- sandbox.bytes = await storage.usage(keyOf(sandbox));
231
- sandbox.lastUsedAt = this.timestamp();
232
- await this.save(sandbox);
233
- return copy(sandbox);
221
+ // a fetch can make the sandbox larger: not while the owner or the server is full, and
222
+ // one create or fetch of an owner at a time, so fetches at once can not pass it together
223
+ return this.growing(owner, () => this.fetchGrowing(owner, sandbox, ref));
234
224
  });
235
225
  }
226
+ async fetchGrowing(owner, sandbox, ref) {
227
+ const { limits } = this.options;
228
+ await this.measured(owner);
229
+ const used = this.usage(owner).bytes;
230
+ if (used >= limits.bytes) {
231
+ throw new SandboxError(413, `your sandboxes take ${(0, units_1.formatSize)(used)}, your limit is ${(0, units_1.formatSize)(limits.bytes)}: delete one`);
232
+ }
233
+ if (this.total() >= limits.total) {
234
+ throw new SandboxError(507, 'the server has no room for a fetch');
235
+ }
236
+ const { storage, repos } = this.options;
237
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
238
+ await this.resolve(sandbox.repo, ref, signal);
239
+ const credentials = await repos.credentials(sandbox.repo);
240
+ try {
241
+ sandbox.commit = await storage.fetch(keyOf(sandbox), {
242
+ url: repos.url(sandbox.repo),
243
+ ref,
244
+ env: credentials.env,
245
+ signal,
246
+ });
247
+ }
248
+ catch (e) {
249
+ throw new SandboxError(502, repos.scrub(e, credentials.values).message);
250
+ }
251
+ sandbox.ref = ref;
252
+ sandbox.bytes = await storage.usage(keyOf(sandbox));
253
+ sandbox.lastUsedAt = this.timestamp();
254
+ await this.save(sandbox);
255
+ return copy(sandbox);
256
+ }
257
+ // One create or fetch of an owner at a time: what one adds is measured before the next
258
+ // checks the limit.
259
+ growing(owner, fn) {
260
+ return this.withLock(`owner:${JSON.stringify([owner.iss, owner.sub])}`, fn);
261
+ }
236
262
  /**
237
263
  * Commits the changes of a sandbox as its owner and pushes them to a branch the operator
238
264
  * allows (`sources[].push.branches`). The branch must not exist yet, or be one this
@@ -392,6 +418,7 @@ class SandboxRegistry {
392
418
  if (dryRun || plan.files.length === 0) {
393
419
  return plan.files;
394
420
  }
421
+ const reservation = Symbol(id);
395
422
  if (plan.bytes > 0) {
396
423
  const { limits } = this.options;
397
424
  const used = this.usage(owner).bytes;
@@ -401,8 +428,15 @@ class SandboxRegistry {
401
428
  if (this.total() + plan.bytes > limits.total) {
402
429
  throw new SandboxError(507, 'the server has no room for these edits');
403
430
  }
431
+ // taken before anything else can check: no await between the check and this
432
+ this.reserved.set(reservation, { owner: { iss: owner.iss, sub: owner.sub }, bytes: plan.bytes });
433
+ }
434
+ try {
435
+ await plan.commit();
436
+ }
437
+ finally {
438
+ this.reserved.delete(reservation);
404
439
  }
405
- await plan.commit();
406
440
  sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
407
441
  sandbox.lastUsedAt = this.timestamp();
408
442
  await this.save(sandbox);
@@ -483,7 +517,7 @@ class SandboxRegistry {
483
517
  }
484
518
  }
485
519
  total() {
486
- return [...this.sandboxes.values(), ...this.creating.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
520
+ return [...this.sandboxes.values(), ...this.creating.values(), ...this.reserved.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
487
521
  }
488
522
  withLock(id, fn) {
489
523
  const previous = this.locks.get(id) ?? Promise.resolve();
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
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;
4
+ const run_source_envs_1 = require("../environment/run-source-envs");
4
5
  const net_1 = require("net");
5
6
  const zod_1 = require("zod");
6
7
  const yaml_1 = require("yaml");
@@ -45,7 +46,10 @@ exports.issuerSchema = zod_1.z
45
46
  scope: zod_1.z.string().min(1).default('openid'),
46
47
  })
47
48
  .strict();
48
- const subjectSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), sub: zod_1.z.string().min(1) }).strict();
49
+ // `name`: how pages name a subject whose tokens name nobody, such as a service account's
50
+ const subjectSchema = zod_1.z
51
+ .object({ iss: zod_1.z.string().min(1), sub: zod_1.z.string().min(1), name: zod_1.z.string().trim().min(1).max(100).optional() })
52
+ .strict();
49
53
  const groupSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), name: zod_1.z.string().min(1) }).strict();
50
54
  const claimsSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), match: zod_1.z.record(zod_1.z.string()) }).strict();
51
55
  // Who: the person or client (`subject`), everyone in a group of an issuer
@@ -295,6 +299,15 @@ const kubernetesBackendSchema = zod_1.z
295
299
  // build file's environment does: hammerkit can't tell from the API, and without it a
296
300
  // task with a limited network fails rather than runs open
297
301
  networkPolicy: zod_1.z.literal('enforced').optional(),
302
+ // what the pods with an open network wait to no longer reach before they start, under
303
+ // `networkPolicy: enforced`: an address and port `deniedEgress` covers that answers without
304
+ // the policy (the metadata endpoint by default), or `false` for no wait
305
+ openNetworkGate: zod_1.z
306
+ .union([
307
+ zod_1.z.literal(false),
308
+ zod_1.z.object({ host: zod_1.z.string().ip({ version: 'v4' }), port: zod_1.z.number().int().min(1).max(65535) }).strict(),
309
+ ])
310
+ .optional(),
298
311
  // `runtimeClass` is a RuntimeClass of a sandbox, such as gvisor; the pods of tasks that
299
312
  // add capabilities run in it
300
313
  capabilities: zod_1.z.object({ allow: capabilitiesAllowSchema, runtimeClass: kubernetesNameSchema }).strict().optional(),
@@ -509,6 +522,15 @@ exports.serverConfigSchema = zod_1.z
509
522
  set: zod_1.z.record(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), zod_1.z.string()).default({}),
510
523
  })
511
524
  .strict()
525
+ // what a run is from is the run's: an operator's value would pass for it
526
+ .superRefine((env, ctx) => {
527
+ for (const name of [...env.allow, ...Object.keys(env.set)].filter(run_source_envs_1.isRunSourceEnv)) {
528
+ ctx.addIssue({
529
+ code: zod_1.z.ZodIssueCode.custom,
530
+ message: `${name} is set by the server for each run, from what the run is from`,
531
+ });
532
+ }
533
+ })
512
534
  .default({}),
513
535
  // the most any task or service of a run reaches besides its needs: none, open
514
536
  // or { allow: [hosts] }. A version that asks for more is refused at publish.
@@ -572,8 +594,9 @@ exports.serverConfigSchema = zod_1.z
572
594
  // the most open network a task or service of a run on a sandbox gets, written as
573
595
  // a task's `network`: only the services it needs by default
574
596
  network: network_schema_1.networkSchema.default('none'),
575
- // the variables of `runs.env.allow` an `env:` secret of a run on a sandbox may
576
- // read: none by default, a sandbox holds code nobody reviewed
597
+ // the variables of runs (`runs.env.allow` and `runs.env.set`) an `env:` secret and the
598
+ // `envs` of a build file of a run on a sandbox may read, besides PATH, HOME and CI:
599
+ // none by default, a sandbox holds code nobody reviewed
577
600
  env: zod_1.z
578
601
  .object({ allow: zod_1.z.array(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_()]*$/)).default([]) })
579
602
  .strict()
@@ -766,11 +789,11 @@ exports.serverConfigSchema = zod_1.z
766
789
  });
767
790
  }
768
791
  config.sandboxes.env.allow.forEach((name, index) => {
769
- if (!config.runs.env.allow.includes(name)) {
792
+ if (!config.runs.env.allow.includes(name) && !Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
770
793
  ctx.addIssue({
771
794
  code: zod_1.z.ZodIssueCode.custom,
772
795
  path: ['sandboxes', 'env', 'allow', index],
773
- message: `${name} is not in runs.env.allow, no run can read it`,
796
+ message: `${name} is not in runs.env.allow or runs.env.set, no run can read it`,
774
797
  });
775
798
  }
776
799
  });
@@ -20,10 +20,12 @@ const execute_docker_1 = require("../executer/execute-docker");
20
20
  const timings_1 = require("./timings");
21
21
  const kubernetes_backend_1 = require("./kubernetes-backend");
22
22
  const run_plan_1 = require("./run-plan");
23
+ const run_source_environment_1 = require("./run-source-environment");
23
24
  const work_network_1 = require("../planner/work-network");
24
25
  const run_environment_1 = require("./run-environment");
25
26
  const accounts_api_1 = require("./accounts-api");
26
27
  const run_request_1 = require("./run-request");
28
+ const run_retry_1 = require("./run-retry");
27
29
  const http_2 = require("./http");
28
30
  const definitions_1 = require("./definitions");
29
31
  const definitions_api_1 = require("./definitions-api");
@@ -37,6 +39,7 @@ const sandbox_storage_1 = require("./sandbox-storage");
37
39
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
38
40
  const sandbox_docker_1 = require("./sandbox-docker");
39
41
  const sandboxes_api_1 = require("./sandboxes-api");
42
+ const plan_1 = require("./plan");
40
43
  const endpoints_1 = require("./endpoints");
41
44
  const service_runs_1 = require("./service-runs");
42
45
  const units_1 = require("../utils/units");
@@ -109,7 +112,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
109
112
  });
110
113
  }
111
114
  async function handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res, url) {
112
- const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend))?)?$/.exec(url.pathname);
115
+ const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend|wake|retry))?)?$/.exec(url.pathname);
113
116
  if (!match) {
114
117
  return false;
115
118
  }
@@ -129,7 +132,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
129
132
  }
130
133
  const runs = filter.scope === 'mine' ? registry.list(principal) : registry.all();
131
134
  (0, http_2.send)(res, 200, {
132
- runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, viewer, run)),
135
+ runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, definitions, viewer, run)),
133
136
  });
134
137
  }
135
138
  else if (method === 'POST') {
@@ -148,9 +151,10 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
148
151
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
149
152
  return true;
150
153
  }
151
- const run = registry.cancel(principal, id, accountsOf(config, principal));
154
+ 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));
152
156
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
153
- run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
157
+ run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
154
158
  }
155
159
  else if (action === 'extend') {
156
160
  if (method !== 'POST') {
@@ -159,6 +163,35 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
159
163
  }
160
164
  await extendRun(config, registry, log, principal, id, req, res);
161
165
  }
166
+ else if (action === 'retry') {
167
+ if (method !== 'POST') {
168
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
169
+ return true;
170
+ }
171
+ await retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res);
172
+ }
173
+ else if (action === 'wake') {
174
+ if (method !== 'POST') {
175
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
176
+ return true;
177
+ }
178
+ // as a request to one of its endpoints would, with the same check of its owner
179
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
180
+ const result = registry.wake(principal, id, (run) => (0, service_runs_1.mayOpenEndpoints)(grant, run), (run) => refuseWake(config, repos, run));
181
+ log(`wake iss=${principal.iss} sub=${principal.sub} run=${id} result=${result.status}`);
182
+ if (result.status === 'not-found') {
183
+ (0, http_2.send)(res, 404, { error: 'not found' });
184
+ }
185
+ else if (result.status === 'not-asleep') {
186
+ (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that sleeps wakes` });
187
+ }
188
+ else if (result.status === 'refused') {
189
+ (0, http_2.send)(res, 409, { error: result.reason });
190
+ }
191
+ else {
192
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
193
+ }
194
+ }
162
195
  else if (method !== 'GET') {
163
196
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
164
197
  }
@@ -205,7 +238,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
205
238
  const may = run && (0, overview_1.runActions)(viewer, run);
206
239
  run
207
240
  ? (0, http_2.send)(res, 200, {
208
- ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run)),
241
+ ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run), viewer.nameOf),
209
242
  ...(may ? { may } : {}),
210
243
  })
211
244
  : (0, http_2.send)(res, 404, { error: 'not found' });
@@ -244,9 +277,18 @@ async function extendRun(config, registry, log, principal, id, req, res) {
244
277
  (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that is up can be extended` });
245
278
  }
246
279
  else {
247
- (0, http_2.send)(res, 200, toRunResponse(result.run));
280
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
248
281
  }
249
282
  }
283
+ // What a stop, an extend or a wake answers: the run whole for who may read it (its owner, who
284
+ // decides about it, `observe`), else what the list shows of it. Who may only open or publish
285
+ // endpoints of its repository is told how it stands, not its arguments, plan or log.
286
+ function answerRun(config, principal, run) {
287
+ const viewer = (0, overview_1.getViewer)(config, principal);
288
+ return (0, overview_1.mayRead)(viewer, run)
289
+ ? toRunResponse(run, undefined, !(0, overview_1.owns)(viewer, run), viewer.nameOf)
290
+ : (0, overview_1.toListedRun)(viewer, run);
291
+ }
250
292
  // Why the owner of a service run that sleeps may no longer run it, with the entitlements of
251
293
  // the moment: a wake is started by who opens an endpoint, but runs as the owner, as a new
252
294
  // run of theirs would.
@@ -299,18 +341,21 @@ function runsTheSame(run, next) {
299
341
  }
300
342
  exports.runsTheSame = runsTheSame;
301
343
  // A run whole, for its owner and who may read it; who is not its owner is told whose it is.
302
- function toRunResponse(run, queue, named = false) {
344
+ function toRunResponse(run, queue, named = false, nameOf) {
303
345
  const { owner, ...visible } = run;
346
+ const name = owner.name ?? nameOf?.(owner);
304
347
  return {
305
348
  ...visible,
306
- ...(named ? { owner: { iss: owner.iss, sub: owner.sub } } : {}),
349
+ ...(named ? { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } } : {}),
307
350
  results: run.results ?? {},
308
351
  ...(queue ? { queue } : {}),
309
352
  };
310
353
  }
311
- function listRun(registry, viewer, run) {
312
- return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run));
354
+ function listRun(registry, definitions, viewer, run) {
355
+ return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
313
356
  }
357
+ // where in its repository the build file of a version is
358
+ const entryOf = (definitions) => (definition) => definitions.find(definition)?.entry;
314
359
  async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res) {
315
360
  const parsed = run_request_1.runRequestSchema.safeParse(await (0, http_2.readJson)(req));
316
361
  if (!parsed.success) {
@@ -318,7 +363,47 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
318
363
  (0, http_2.send)(res, 400, { error: `${issue.path.join('.') || 'request'}: ${issue.message}` });
319
364
  return;
320
365
  }
321
- const request = parsed.data;
366
+ await startRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, parsed.data, res);
367
+ }
368
+ // POST /v1/runs/<id>/retry: the run again, as a new run of the caller's. Who may read the run
369
+ // whole may retry it (what it runs again, its arguments too, is what they read), and it is
370
+ // decided as a run they started themselves would be: their entitlements, their accounts and
371
+ // an approval where they need one, never the owner's (run-retry.ts).
372
+ async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
373
+ 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);
375
+ if (!run) {
376
+ (0, http_2.send)(res, 404, { error: 'not found' });
377
+ return;
378
+ }
379
+ const retry = (0, run_retry_1.getRetryRequest)(run, (0, overview_1.owns)(viewer, run));
380
+ log(`retry run ${id} iss=${principal.iss} sub=${principal.sub}${'error' in retry ? ` refused: ${retry.error}` : ''}`);
381
+ if ('error' in retry) {
382
+ (0, http_2.send)(res, 409, { error: retry.error });
383
+ return;
384
+ }
385
+ // what the run had stays up as long, at most as long as the server allows now
386
+ const { request } = retry;
387
+ if (request.ttl && (0, units_1.parseDuration)(request.ttl) > (0, units_1.parseDuration)(config.runs.up.maxTtl)) {
388
+ request.ttl = config.runs.up.maxTtl;
389
+ }
390
+ // a new service run replaces one of the caller's of the same name, with its volumes: a click
391
+ // on a run that ended must not take down the one they have now
392
+ const name = request.name;
393
+ const live = name
394
+ ? registry.list(principal).find((other) => other.up?.name === name && !(0, runs_1.isFinal)(other.state))
395
+ : undefined;
396
+ if (live) {
397
+ log(`retry run ${id} iss=${principal.iss} sub=${principal.sub} refused: ${name} is ${live.state} as ${live.id}`);
398
+ (0, http_2.send)(res, 409, {
399
+ error: `your service run ${name} is ${live.state} as ${live.id}, a retry would replace it: stop it first`,
400
+ });
401
+ return;
402
+ }
403
+ await startRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, request, res, run);
404
+ }
405
+ // A run, from what `POST /v1/runs` takes or from a run it retries (`retryOf`).
406
+ async function startRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, request, res, retryOf) {
322
407
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
323
408
  // what the caller may not do is said plainly: they already know who they are
324
409
  if (!(0, policy_1.mayRun)(grant)) {
@@ -439,7 +524,13 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
439
524
  let planned;
440
525
  try {
441
526
  // a run on a sandbox may only use the runtimes of `sandboxes.runtimes`
442
- planned = await (0, run_plan_1.planRun)(bundle, request, planning.environment, sandbox ? sandboxes.policy : planning.policy);
527
+ // with what the run is from, as its tasks read it; the commit of a ref follows below
528
+ const from = request.source.type === 'ref'
529
+ ? { type: 'ref', repo: request.source.repo, ref: request.source.ref }
530
+ : sandbox
531
+ ? { type: 'sandbox', id: sandbox.id, repo: sandbox.repo }
532
+ : { type: 'upload' };
533
+ planned = await (0, run_plan_1.planRun)(bundle, request, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, from), sandbox ? sandboxes.policy : planning.policy);
443
534
  }
444
535
  catch (e) {
445
536
  (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
@@ -483,7 +574,9 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
483
574
  try {
484
575
  const commit = await repos.resolve(request.source.repo, request.source.ref);
485
576
  if (request.source.commit && commit !== request.source.commit) {
486
- const error = `${request.source.ref} is at ${commit} now, not at ${request.source.commit}`;
577
+ const error = retryOf
578
+ ? `${request.source.ref} moved to ${commit} since ${retryOf.id} ran ${request.source.commit}, start a new run from ${request.source.ref}`
579
+ : `${request.source.ref} is at ${commit} now, not at ${request.source.commit}`;
487
580
  log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
488
581
  (0, http_2.send)(res, 409, { error });
489
582
  return;
@@ -502,6 +595,25 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
502
595
  else if (request.source.type === 'upload') {
503
596
  source = request.source;
504
597
  }
598
+ if (source?.type === 'ref') {
599
+ // what the approver reads is what the tasks see, the commit included; who may run it was
600
+ // decided without it and can't change with it
601
+ let pinned;
602
+ try {
603
+ pinned = await (0, run_plan_1.planRun)(bundle, request, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, source), planning.policy);
604
+ }
605
+ catch (e) {
606
+ (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
607
+ return;
608
+ }
609
+ if (pinned.accounts.join(',') !== planned.accounts.join(',')) {
610
+ const error = `the accounts of the run change with its commit (${pinned.accounts.join(', ')})`;
611
+ log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
612
+ (0, http_2.send)(res, 400, { error });
613
+ return;
614
+ }
615
+ planned = pinned;
616
+ }
505
617
  // a service run is named after its branch unless it says, and its endpoints after that
506
618
  const serviceName = request.services.length > 0
507
619
  ? request.name ??
@@ -518,14 +630,18 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
518
630
  : undefined;
519
631
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
520
632
  const claimNames = new Set(config.entitlements.flatMap((entitlement) => Object.keys(entitlement.claims?.match ?? {})));
633
+ const name = (0, oauth_1.displayName)(principal);
521
634
  const owner = {
522
635
  ...principal,
636
+ // how the pages name them, which the claims kept no longer tell
637
+ ...(name ? { name } : {}),
523
638
  claims: Object.fromEntries(Object.entries(principal.claims).filter(([name]) => claimNames.has(name))),
524
639
  };
525
640
  // A service run of the caller of this name that runs the same build file, services and
526
641
  // endpoints moves to the commit, in place of a new run that would replace it: it keeps its
527
642
  // id, its addresses and its volumes. A run that needs an approval is new as before.
528
- if (up && source?.type === 'ref' && approvals.length === 0) {
643
+ // A retry is always a new run, which replaces a run of the same name as a new one would.
644
+ if (up && source?.type === 'ref' && approvals.length === 0 && !retryOf) {
529
645
  const named = registry.named(principal, up.name);
530
646
  if (named && runsTheSame(named, { definition: version.hash, accounts: planned.accounts, request, source, up })) {
531
647
  const from = (registry.logs(principal, named.id)?.index.size ?? 0) + 1;
@@ -550,6 +666,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
550
666
  source: runSource,
551
667
  options: request.options,
552
668
  ...(up ? { up } : {}),
669
+ ...(retryOf ? { retryOf: retryOf.id } : {}),
553
670
  }, approvals);
554
671
  try {
555
672
  // a sandbox is read and the run submitted while nothing else changes it: the run
@@ -568,7 +685,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
568
685
  ...(request.source.type === 'sandbox' && request.source.check ? { check: true } : {}),
569
686
  });
570
687
  });
571
- log(`run ${run.id} iss=${principal.iss} sub=${principal.sub} accounts=[${planned.accounts.join(',')}] source=${run.source.type}${run.source.type === 'sandbox' ? ` sandbox=${run.source.id}${run.source.check ? ' check' : ''}` : ''} tasks=${run.tasks.length}${run.up
688
+ log(`run ${run.id}${retryOf ? ` retry=${retryOf.id}` : ''} iss=${principal.iss} sub=${principal.sub} accounts=[${planned.accounts.join(',')}] source=${run.source.type}${run.source.type === 'sandbox' ? ` sandbox=${run.source.id}${run.source.check ? ' check' : ''}` : ''} tasks=${run.tasks.length}${run.up
572
689
  ? ` services=[${run.up.services.join(',')}] name=${run.up.name} endpoints=${run.up.endpoints.length}`
573
690
  : ''}${approvals.length > 0 ? ` approval=[${approvals.join(',')}]` : ''}`);
574
691
  (0, http_2.send)(res, 202, toRunResponse(run, (0, overview_1.queuePlace)(registry, (0, overview_1.getViewer)(config, principal), run)));
@@ -671,7 +788,7 @@ async function handleApi(api, principal, req, res, url) {
671
788
  (0, http_2.send)(res, 403, { error: 'you are not entitled to anything on this server' });
672
789
  return;
673
790
  }
674
- (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer));
791
+ (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer, entryOf(definitions)));
675
792
  return;
676
793
  }
677
794
  if (path === '/v1/capacity' || path === '/v1/tasks') {
@@ -702,7 +819,13 @@ async function handleApi(api, principal, req, res, url) {
702
819
  return;
703
820
  }
704
821
  const runs = (0, overview_1.filterRuns)(registry.all(), viewer, filter).map((run) => (0, overview_1.toListedRun)(viewer, run));
705
- (0, http_2.send)(res, 200, { tasks: (0, timings_1.getTaskStats)(runs, Date.now()) });
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 } : {}) });
706
829
  return;
707
830
  }
708
831
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -755,9 +878,14 @@ async function startServer(config, environment, options = {}) {
755
878
  },
756
879
  };
757
880
  const storage = config.storage.directory ?? (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'server');
758
- const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), planning.environment, {
759
- policy: planning.policy,
760
- });
881
+ // a build file nobody ran yet is read with the names of the variables, not their values
882
+ const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), {
883
+ ...planning.environment,
884
+ hosted: {
885
+ ...planning.environment.hosted,
886
+ buildFileEnvs: (0, plan_1.withSymbolicValues)(planning.environment.processEnvs),
887
+ },
888
+ }, { policy: planning.policy });
761
889
  await definitions.load();
762
890
  const repos = new repo_access_1.RepoAccess(config, planning.environment, options.repos);
763
891
  const sandboxRuntimes = (0, server_config_1.getSandboxRuntimes)(config);
@@ -786,6 +914,8 @@ async function startServer(config, environment, options = {}) {
786
914
  ...planning.policy,
787
915
  envs: config.sandboxes.env.allow,
788
916
  envsFrom: 'sandboxes.env.allow',
917
+ // and what its build files read of the run's variables, `$NAME` in its `envs`
918
+ readableEnvs: config.sandboxes.env.allow,
789
919
  runtimes: sandboxRuntimes,
790
920
  capabilities: config.sandboxes.capabilities,
791
921
  capabilitiesFrom: 'sandboxes.capabilities',