hammerkit 2.0.0-next.8 → 2.0.0

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 (99) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/follow-pod-logs.js +5 -3
  37. package/dist/kubernetes/network-gate.js +74 -11
  38. package/dist/kubernetes/network-policy.js +32 -10
  39. package/dist/kubernetes/remove-stale-items.js +15 -2
  40. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  41. package/dist/kubernetes/sandbox-runner.js +3 -4
  42. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  43. package/dist/kubernetes/transfer-tools.js +66 -0
  44. package/dist/kubernetes/volumes.js +52 -10
  45. package/dist/optimizer/check-key.js +7 -0
  46. package/dist/optimizer/check-keys.js +19 -5
  47. package/dist/optimizer/get-work-cache-stats.js +19 -7
  48. package/dist/optimizer/work-task-cache-description.js +42 -8
  49. package/dist/parser/read-build-file.js +8 -3
  50. package/dist/planner/image-build.js +172 -0
  51. package/dist/planner/utils/append-work-dependencies.js +14 -1
  52. package/dist/planner/utils/append-work-service.js +1 -1
  53. package/dist/planner/utils/append-work-task.js +51 -1
  54. package/dist/planner/utils/assert-item-paths.js +6 -7
  55. package/dist/planner/utils/dependency-outputs.js +18 -0
  56. package/dist/planner/utils/template-value.js +20 -4
  57. package/dist/planner/work-runtime-docker.js +48 -50
  58. package/dist/planner/work-runtime-kubernetes.js +1 -0
  59. package/dist/planner/work-runtime-local.js +3 -7
  60. package/dist/planner/work-secret.js +135 -13
  61. package/dist/planner/work-tree.js +10 -0
  62. package/dist/remote/collect-bundle.js +9 -1
  63. package/dist/remote/host-config.js +49 -3
  64. package/dist/remote/location.js +5 -5
  65. package/dist/remote/remote-commands.js +12 -14
  66. package/dist/remote/remote-work-commands.js +20 -8
  67. package/dist/schema/build-file-image-build-schema.js +77 -0
  68. package/dist/schema/build-file-task-schema.js +9 -2
  69. package/dist/schema/reference-parser.js +10 -1
  70. package/dist/schema/schema-parser.js +46 -2
  71. package/dist/schema/work-scope-parser.js +16 -1
  72. package/dist/secrets/secret-catalog.js +8 -1
  73. package/dist/server/dashboard.js +8 -5
  74. package/dist/server/executor.js +58 -35
  75. package/dist/server/kubernetes-backend.js +29 -4
  76. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  77. package/dist/server/overview.js +20 -2
  78. package/dist/server/plan.js +31 -3
  79. package/dist/server/policy.js +14 -7
  80. package/dist/server/repo-access.js +4 -3
  81. package/dist/server/run-environment.js +5 -2
  82. package/dist/server/run-plan.js +18 -6
  83. package/dist/server/run-retry.js +57 -0
  84. package/dist/server/run-source-environment.js +39 -0
  85. package/dist/server/run-worker.js +38 -9
  86. package/dist/server/runs.js +59 -1
  87. package/dist/server/sandbox-files.js +339 -55
  88. package/dist/server/sandbox-patch.js +43 -17
  89. package/dist/server/sandboxes.js +57 -23
  90. package/dist/server/server-config.js +24 -4
  91. package/dist/server/server.js +107 -12
  92. package/dist/server/service-runs.js +42 -4
  93. package/dist/server/sources.js +68 -11
  94. package/dist/utils/buffer-context.js +30 -20
  95. package/dist/utils/line-splitter.js +52 -0
  96. package/dist/utils/read-lines.js +65 -0
  97. package/dist/utils/tar.js +51 -1
  98. package/package.json +1 -1
  99. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -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");
@@ -298,6 +299,15 @@ const kubernetesBackendSchema = zod_1.z
298
299
  // build file's environment does: hammerkit can't tell from the API, and without it a
299
300
  // task with a limited network fails rather than runs open
300
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(),
301
311
  // `runtimeClass` is a RuntimeClass of a sandbox, such as gvisor; the pods of tasks that
302
312
  // add capabilities run in it
303
313
  capabilities: zod_1.z.object({ allow: capabilitiesAllowSchema, runtimeClass: kubernetesNameSchema }).strict().optional(),
@@ -512,6 +522,15 @@ exports.serverConfigSchema = zod_1.z
512
522
  set: zod_1.z.record(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), zod_1.z.string()).default({}),
513
523
  })
514
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
+ })
515
534
  .default({}),
516
535
  // the most any task or service of a run reaches besides its needs: none, open
517
536
  // or { allow: [hosts] }. A version that asks for more is refused at publish.
@@ -575,8 +594,9 @@ exports.serverConfigSchema = zod_1.z
575
594
  // the most open network a task or service of a run on a sandbox gets, written as
576
595
  // a task's `network`: only the services it needs by default
577
596
  network: network_schema_1.networkSchema.default('none'),
578
- // the variables of `runs.env.allow` an `env:` secret of a run on a sandbox may
579
- // 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
580
600
  env: zod_1.z
581
601
  .object({ allow: zod_1.z.array(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_()]*$/)).default([]) })
582
602
  .strict()
@@ -769,11 +789,11 @@ exports.serverConfigSchema = zod_1.z
769
789
  });
770
790
  }
771
791
  config.sandboxes.env.allow.forEach((name, index) => {
772
- if (!config.runs.env.allow.includes(name)) {
792
+ if (!config.runs.env.allow.includes(name) && !Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
773
793
  ctx.addIssue({
774
794
  code: zod_1.z.ZodIssueCode.custom,
775
795
  path: ['sandboxes', 'env', 'allow', index],
776
- 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`,
777
797
  });
778
798
  }
779
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|wake))?)?$/.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
  }
@@ -151,7 +154,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
151
154
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
152
155
  const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
153
156
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
154
- 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' });
155
158
  }
156
159
  else if (action === 'extend') {
157
160
  if (method !== 'POST') {
@@ -160,6 +163,13 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
160
163
  }
161
164
  await extendRun(config, registry, log, principal, id, req, res);
162
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
+ }
163
173
  else if (action === 'wake') {
164
174
  if (method !== 'POST') {
165
175
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
@@ -179,7 +189,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
179
189
  (0, http_2.send)(res, 409, { error: result.reason });
180
190
  }
181
191
  else {
182
- (0, http_2.send)(res, 200, toRunResponse(result.run));
192
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
183
193
  }
184
194
  }
185
195
  else if (method !== 'GET') {
@@ -267,9 +277,18 @@ async function extendRun(config, registry, log, principal, id, req, res) {
267
277
  (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that is up can be extended` });
268
278
  }
269
279
  else {
270
- (0, http_2.send)(res, 200, toRunResponse(result.run));
280
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
271
281
  }
272
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
+ }
273
292
  // Why the owner of a service run that sleeps may no longer run it, with the entitlements of
274
293
  // the moment: a wake is started by who opens an endpoint, but runs as the owner, as a new
275
294
  // run of theirs would.
@@ -344,7 +363,47 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
344
363
  (0, http_2.send)(res, 400, { error: `${issue.path.join('.') || 'request'}: ${issue.message}` });
345
364
  return;
346
365
  }
347
- 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) {
348
407
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
349
408
  // what the caller may not do is said plainly: they already know who they are
350
409
  if (!(0, policy_1.mayRun)(grant)) {
@@ -465,7 +524,13 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
465
524
  let planned;
466
525
  try {
467
526
  // a run on a sandbox may only use the runtimes of `sandboxes.runtimes`
468
- 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);
469
534
  }
470
535
  catch (e) {
471
536
  (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
@@ -509,7 +574,9 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
509
574
  try {
510
575
  const commit = await repos.resolve(request.source.repo, request.source.ref);
511
576
  if (request.source.commit && commit !== request.source.commit) {
512
- 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}`;
513
580
  log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
514
581
  (0, http_2.send)(res, 409, { error });
515
582
  return;
@@ -528,6 +595,25 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
528
595
  else if (request.source.type === 'upload') {
529
596
  source = request.source;
530
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
+ }
531
617
  // a service run is named after its branch unless it says, and its endpoints after that
532
618
  const serviceName = request.services.length > 0
533
619
  ? request.name ??
@@ -554,7 +640,8 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
554
640
  // A service run of the caller of this name that runs the same build file, services and
555
641
  // endpoints moves to the commit, in place of a new run that would replace it: it keeps its
556
642
  // id, its addresses and its volumes. A run that needs an approval is new as before.
557
- 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) {
558
645
  const named = registry.named(principal, up.name);
559
646
  if (named && runsTheSame(named, { definition: version.hash, accounts: planned.accounts, request, source, up })) {
560
647
  const from = (registry.logs(principal, named.id)?.index.size ?? 0) + 1;
@@ -579,6 +666,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
579
666
  source: runSource,
580
667
  options: request.options,
581
668
  ...(up ? { up } : {}),
669
+ ...(retryOf ? { retryOf: retryOf.id } : {}),
582
670
  }, approvals);
583
671
  try {
584
672
  // a sandbox is read and the run submitted while nothing else changes it: the run
@@ -597,7 +685,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
597
685
  ...(request.source.type === 'sandbox' && request.source.check ? { check: true } : {}),
598
686
  });
599
687
  });
600
- 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
601
689
  ? ` services=[${run.up.services.join(',')}] name=${run.up.name} endpoints=${run.up.endpoints.length}`
602
690
  : ''}${approvals.length > 0 ? ` approval=[${approvals.join(',')}]` : ''}`);
603
691
  (0, http_2.send)(res, 202, toRunResponse(run, (0, overview_1.queuePlace)(registry, (0, overview_1.getViewer)(config, principal), run)));
@@ -790,9 +878,14 @@ async function startServer(config, environment, options = {}) {
790
878
  },
791
879
  };
792
880
  const storage = config.storage.directory ?? (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'server');
793
- const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), planning.environment, {
794
- policy: planning.policy,
795
- });
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 });
796
889
  await definitions.load();
797
890
  const repos = new repo_access_1.RepoAccess(config, planning.environment, options.repos);
798
891
  const sandboxRuntimes = (0, server_config_1.getSandboxRuntimes)(config);
@@ -821,6 +914,8 @@ async function startServer(config, environment, options = {}) {
821
914
  ...planning.policy,
822
915
  envs: config.sandboxes.env.allow,
823
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,
824
919
  runtimes: sandboxRuntimes,
825
920
  capabilities: config.sandboxes.capabilities,
826
921
  capabilitiesFrom: 'sandboxes.capabilities',
@@ -38,7 +38,9 @@ function containerPorts(plan) {
38
38
  * Why the endpoints of a service run can't be published, or null. Each is a port its
39
39
  * service declares, of a service the run starts. Under a `runs.secretNetwork` below `open`
40
40
  * a service behind an endpoint may not read a secret or a credential of the server: a page
41
- * is a way out that no mask of the log covers.
41
+ * is a way out that no mask of the log covers. Nor may what it is made from or talks to: a
42
+ * task it depends on (its init task too) can leave a value in a file the service serves,
43
+ * and a service it needs can hand one over the connection it answers on.
42
44
  */
43
45
  function refuseEndpoints(request, plan, secretNetworkOpen) {
44
46
  for (const endpoint of request.endpoints) {
@@ -50,14 +52,50 @@ function refuseEndpoints(request, plan, secretNetworkOpen) {
50
52
  const ports = containerPorts(item);
51
53
  return `${endpoint.service} has no port ${endpoint.port}${ports.length > 0 ? `, its ports are ${ports.join(', ')}` : ', it declares none'}`;
52
54
  }
53
- const reads = (0, plan_1.getCredentialReads)(item);
54
- if (!secretNetworkOpen && reads.length > 0) {
55
- return `${endpoint.service} reads ${reads.join(', ')}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
55
+ if (secretNetworkOpen) {
56
+ continue;
57
+ }
58
+ for (const { name, path } of reachedFrom(endpoint.service, plan)) {
59
+ const reads = (0, plan_1.getCredentialReads)(plan[name]);
60
+ if (reads.length === 0) {
61
+ continue;
62
+ }
63
+ const what = reads.join(', ');
64
+ if (path.length === 0) {
65
+ return `${name} reads ${what}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
66
+ }
67
+ // the way from the service to what reads it: `web needs api, which needs vault`
68
+ const way = path.map((step, index) => `${index === 0 ? '' : ', which '}${step.relation} ${step.name}`).join('');
69
+ return (`${endpoint.service} ${way}, which reads ${what}: ` +
70
+ 'it can not be behind an endpoint on this server (runs.secretNetwork), a page could show it');
56
71
  }
57
72
  }
58
73
  return null;
59
74
  }
60
75
  exports.refuseEndpoints = refuseEndpoints;
76
+ function reachedFrom(service, plan) {
77
+ if (!plan[service]) {
78
+ return [];
79
+ }
80
+ const reached = [{ name: service, path: [] }];
81
+ const seen = new Set([service]);
82
+ for (let index = 0; index < reached.length; index++) {
83
+ const { name, path } = reached[index];
84
+ const item = plan[name];
85
+ const next = [
86
+ ...(item.init ? [{ relation: 'is initialized by', name: item.init }] : []),
87
+ ...(item.deps ?? []).map((dep) => ({ relation: 'depends on', name: dep })),
88
+ ...(item.needs ?? []).map((need) => ({ relation: 'needs', name: need })),
89
+ ];
90
+ for (const step of next) {
91
+ if (plan[step.name] && !seen.has(step.name)) {
92
+ seen.add(step.name);
93
+ reached.push({ name: step.name, path: [...path, step] });
94
+ }
95
+ }
96
+ }
97
+ return reached;
98
+ }
61
99
  function toRunEndpoints(endpoints, hosts, url) {
62
100
  return endpoints.map((endpoint, index) => ({
63
101
  service: endpoint.service,