hammerkit 2.0.0-next.1 → 2.0.0-next.11

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 (64) hide show
  1. package/dist/cache/explain.js +7 -5
  2. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  3. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  4. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  5. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  6. package/dist/dashboard/index.html +3 -3
  7. package/dist/dashboard/logo.png +0 -0
  8. package/dist/executer/docker-task.js +3 -0
  9. package/dist/executer/execute-work-task.js +3 -1
  10. package/dist/executer/local-task.js +3 -0
  11. package/dist/executer/scheduler/enqueue-next.js +6 -1
  12. package/dist/executer/scheduler/state-key.js +71 -34
  13. package/dist/executer/watch-loop.js +18 -5
  14. package/dist/file/get-file-context.js +5 -1
  15. package/dist/kubernetes/await-running-state.js +69 -5
  16. package/dist/kubernetes/claim-layout.js +10 -1
  17. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  18. package/dist/kubernetes/ensure-persistent-data.js +108 -20
  19. package/dist/kubernetes/follow-pod-logs.js +128 -29
  20. package/dist/kubernetes/kept-claims.js +16 -1
  21. package/dist/kubernetes/network-policy.js +4 -4
  22. package/dist/kubernetes/quota-wait.js +97 -0
  23. package/dist/kubernetes/restore-kubernetes-data.js +27 -4
  24. package/dist/kubernetes/store-kubernetes-data.js +13 -2
  25. package/dist/kubernetes/volumes.js +34 -7
  26. package/dist/optimizer/calculate-checksum.js +46 -3
  27. package/dist/optimizer/check-keys.js +4 -2
  28. package/dist/optimizer/get-work-cache-stats.js +36 -24
  29. package/dist/parser/read-build-file.js +8 -3
  30. package/dist/planner/utils/template-value.js +20 -4
  31. package/dist/planner/work-item-executions.js +27 -0
  32. package/dist/planner/work-runtime-kubernetes.js +69 -41
  33. package/dist/remote/host-config.js +1 -1
  34. package/dist/remote/remote-work-commands.js +14 -5
  35. package/dist/schema/schema-parser.js +46 -2
  36. package/dist/server/capacity.js +71 -41
  37. package/dist/server/dashboard.js +27 -9
  38. package/dist/server/endpoints.js +10 -1
  39. package/dist/server/executor.js +65 -34
  40. package/dist/server/kubernetes-backend.js +9 -3
  41. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  42. package/dist/server/oauth.js +16 -1
  43. package/dist/server/overview.js +80 -11
  44. package/dist/server/plan.js +16 -3
  45. package/dist/server/policy.js +9 -3
  46. package/dist/server/run-worker.js +47 -6
  47. package/dist/server/runs.js +74 -6
  48. package/dist/server/sandbox-files.js +107 -16
  49. package/dist/server/sandbox-patch.js +43 -17
  50. package/dist/server/sandboxes.js +57 -23
  51. package/dist/server/server-config.js +4 -1
  52. package/dist/server/server.js +45 -10
  53. package/dist/server/service-runs.js +8 -1
  54. package/dist/server/sources.js +68 -11
  55. package/dist/server/timings.js +23 -3
  56. package/dist/utils/buffer-context.js +30 -20
  57. package/dist/utils/limit.js +30 -0
  58. package/dist/utils/read-lines.js +65 -0
  59. package/dist/utils/units.js +36 -1
  60. package/dist/utils/web-links.js +34 -0
  61. package/package.json +1 -1
  62. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  63. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  64. package/dist/dashboard/favicon.svg +0 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.workerMain = exports.readInput = exports.taskCauses = exports.describeFailures = exports.runTasks = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
3
+ exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.runTasks = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const zod_1 = require("zod");
6
6
  const cli_1 = require("../cli");
@@ -10,6 +10,7 @@ const schema_parser_1 = require("../schema/schema-parser");
10
10
  const reference_parser_1 = require("../schema/reference-parser");
11
11
  const work_scope_parser_1 = require("../schema/work-scope-parser");
12
12
  const work_item_status_1 = require("../planner/work-item-status");
13
+ const work_item_executions_1 = require("../planner/work-item-executions");
13
14
  const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
14
15
  const assert_item_paths_1 = require("../planner/utils/assert-item-paths");
15
16
  const hosted_volumes_1 = require("../planner/utils/hosted-volumes");
@@ -213,16 +214,25 @@ up) {
213
214
  // the files as they are before any task wrote to them, a second task's too: a first
214
215
  // one that formats or generates into src would key it by files no commit holds
215
216
  for (const { scope } of scopes) {
216
- for (const [task, { key }] of Object.entries(await (0, check_keys_1.getCheckKeys)(input.entry, environment, scope))) {
217
+ for (const [task, { key }] of Object.entries(await (0, check_keys_1.getCheckKeys)(input.entry, environment, scope, input.directory))) {
217
218
  emit({ type: 'key', task, key });
218
219
  }
219
220
  }
220
221
  }
222
+ // every scope is planned before any task runs: what the run executes is read from the
223
+ // published files as they were when it started, whatever a task does to its files
224
+ const planned = [];
221
225
  for (const { name, scope } of scopes) {
222
226
  const { ctx, scope: parsed } = await (0, schema_parser_1.createParseContext)(input.entry, environment, {
223
227
  directory: input.directory,
224
228
  });
225
- const workTree = (0, work_scope_parser_1.getWorkContext)(await (0, reference_parser_1.parseReferences)(ctx, parsed, environment), scope, environment);
229
+ planned.push({
230
+ name,
231
+ workTree: (0, work_scope_parser_1.getWorkContext)(await (0, reference_parser_1.parseReferences)(ctx, parsed, environment), scope, environment),
232
+ });
233
+ }
234
+ let started = false;
235
+ for (const { name, workTree } of planned) {
226
236
  await (0, assert_item_paths_1.assertWorkTreePathsWithinRoot)(workTree, work);
227
237
  if (input.volumeScope && !input.kubernetes) {
228
238
  (0, hosted_volumes_1.scopeServiceVolumes)(workTree, input.volumeScope);
@@ -234,6 +244,16 @@ up) {
234
244
  if (cli.tasks().length === 0 && (!input.up || cli.services().length === 0)) {
235
245
  throw new Error(`no tasks found for ${name}`);
236
246
  }
247
+ if (!started) {
248
+ // from the start of this process, which the executor started for the run
249
+ started = true;
250
+ emit({
251
+ type: 'phase',
252
+ phase: 'plan',
253
+ startedAt: new Date(performance.timeOrigin).toISOString(),
254
+ finishedAt: new Date().toISOString(),
255
+ });
256
+ }
237
257
  const execution = input.up
238
258
  ? cli.up({ ...execOptions, workers: cli.defaultWorkers(), daemon: false, wait: 'ready' })
239
259
  : cli.exec({ ...execOptions, workers: cli.defaultWorkers() });
@@ -392,6 +412,19 @@ function taskCauses(causes, redact) {
392
412
  : {};
393
413
  }
394
414
  exports.taskCauses = taskCauses;
415
+ // When the commands of a task that is over ran, as its runtime saw them.
416
+ function taskCommands(task) {
417
+ const executions = (0, work_item_executions_1.readExecutions)(task);
418
+ return executions.length
419
+ ? {
420
+ commands: executions.slice(0, runs_1.MAX_COMMANDS).map((e) => ({
421
+ startedAt: e.startedAt.toISOString(),
422
+ finishedAt: e.finishedAt.toISOString(),
423
+ })),
424
+ }
425
+ : {};
426
+ }
427
+ exports.taskCommands = taskCommands;
395
428
  // A task event when a task has moved on since the last look, with what its result needs
396
429
  // once it is over.
397
430
  function reportTasks(emit, workTree, seen,
@@ -414,17 +447,25 @@ redact) {
414
447
  state: status,
415
448
  ...(status === 'skipped' ? {} : { durationMs: state.duration }),
416
449
  ...taskCauses(state.missCauses, redact),
450
+ ...(status === 'succeeded' ? taskCommands(task.data) : {}),
417
451
  };
418
452
  }
419
453
  else if (state.type === 'crash') {
420
- event = { type: 'task', task: task.name, state: 'failed', exitCode: state.exitCode, ...since() };
454
+ event = {
455
+ type: 'task',
456
+ task: task.name,
457
+ state: 'failed',
458
+ exitCode: state.exitCode,
459
+ ...since(),
460
+ ...taskCommands(task.data),
461
+ };
421
462
  }
422
463
  else if (state.type === 'error') {
423
464
  const error = redact(state.errorMessage).slice(0, runs_1.MAX_TASK_ERROR);
424
- event = { type: 'task', task: task.name, state: 'failed', error, ...since() };
465
+ event = { type: 'task', task: task.name, state: 'failed', error, ...since(), ...taskCommands(task.data) };
425
466
  }
426
467
  else if (state.type === 'canceled') {
427
- event = { type: 'task', task: task.name, state: 'cancelled' };
468
+ event = { type: 'task', task: task.name, state: 'cancelled', ...taskCommands(task.data) };
428
469
  }
429
470
  if (event && before?.status !== event.state) {
430
471
  seen.set(task.name, { status: event.state, started });
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.unavailableExecutor = exports.RunRegistry = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.RunError = exports.isFinal = void 0;
3
+ exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.RunError = exports.RUN_PHASES = exports.isFinal = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ const oauth_1 = require("./oauth");
5
6
  const run_logs_1 = require("./run-logs");
6
7
  const units_1 = require("../utils/units");
7
8
  const FINAL_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
@@ -9,6 +10,11 @@ function isFinal(state) {
9
10
  return FINAL_STATES.includes(state);
10
11
  }
11
12
  exports.isFinal = isFinal;
13
+ // What an executor reports while it works. `seq` and `time` are added by the registry.
14
+ // The steps of a run before its tasks: `source` gets its files (a checkout of the commit, or
15
+ // those of the sandbox), `namespace` prepares its place on the cluster, `plan` starts the
16
+ // process of the run and reads its build files.
17
+ exports.RUN_PHASES = ['source', 'namespace', 'plan'];
12
18
  // The server can not take the run now; `status` is what the caller is told
13
19
  class RunError extends Error {
14
20
  constructor() {
@@ -60,6 +66,11 @@ const TAIL_LINE_LENGTH = 1000;
60
66
  // does not can still not make a result of any size.
61
67
  exports.MAX_CAUSES = 20;
62
68
  exports.MAX_TASK_ERROR = 2 * 1024;
69
+ // the command times a task result keeps
70
+ exports.MAX_COMMANDS = 50;
71
+ function isTimestamp(value) {
72
+ return typeof value === 'string' && value.length <= 40 && !Number.isNaN(Date.parse(value));
73
+ }
63
74
  function bounded(event) {
64
75
  const causes = event.causes;
65
76
  return {
@@ -73,12 +84,20 @@ function bounded(event) {
73
84
  }
74
85
  : {}),
75
86
  ...(event.error !== undefined ? { error: event.error.slice(0, exports.MAX_TASK_ERROR) } : {}),
87
+ ...(event.commands
88
+ ? {
89
+ commands: event.commands
90
+ .filter((c) => isTimestamp(c?.startedAt) && isTimestamp(c?.finishedAt))
91
+ .slice(0, exports.MAX_COMMANDS)
92
+ .map(({ startedAt, finishedAt }) => ({ startedAt, finishedAt })),
93
+ }
94
+ : {}),
76
95
  };
77
96
  }
78
97
  // what a task event weighs against the log limits of a run
79
98
  function taskEventSize(event) {
80
99
  const causes = (event.causes ?? []).reduce((sum, cause) => sum + Buffer.byteLength(cause) + 4, 0);
81
- return 64 + causes + Buffer.byteLength(event.error ?? '');
100
+ return 64 + causes + Buffer.byteLength(event.error ?? '') + (event.commands?.length ?? 0) * 64;
82
101
  }
83
102
  // Where runs are kept while the server is up. Everything is scoped to the
84
103
  // caller that submitted the run: the same id asked for by someone else is
@@ -94,6 +113,8 @@ class RunRegistry {
94
113
  this.waiters = new Set();
95
114
  // the moves of service runs that execute beside their services
96
115
  this.moving = new Set();
116
+ // the records of evicted runs still being removed from the store, waited for by close
117
+ this.removing = new Set();
97
118
  this.maxConcurrent = options.maxConcurrent ?? 4;
98
119
  this.keep = options.keep ?? 200;
99
120
  this.maxEvents = options.maxEvents ?? 5000;
@@ -192,12 +213,14 @@ class RunRegistry {
192
213
  this.checkUpLimits(owner, spec.up.name);
193
214
  this.checkHosts(owner, spec.up);
194
215
  }
216
+ const name = (0, oauth_1.displayName)(owner);
195
217
  const run = {
196
218
  ...spec,
197
219
  id: `run_${(0, crypto_1.randomBytes)(12).toString('base64url')}`,
198
220
  owner: {
199
221
  iss: owner.iss,
200
222
  sub: owner.sub,
223
+ ...(name ? { name } : {}),
201
224
  ...(spec.up?.sleepTtl ? { groups: [...(owner.groups ?? [])], claims: { ...(owner.claims ?? {}) } } : {}),
202
225
  },
203
226
  state: waiting ? 'awaiting-approval' : 'queued',
@@ -306,8 +329,10 @@ class RunRegistry {
306
329
  }
307
330
  // A queued run is cancelled at once; a running one when its executor stops. A service run
308
331
  // that is up stops its services, and says who stopped it.
309
- cancel(owner, id, canUse) {
310
- const entry = this.find(owner, id, canUse);
332
+ // Stops a run for its owner, who decides about it, and, a service run, whoever `mayStop` says.
333
+ cancel(owner, id, canUse, mayStop) {
334
+ const other = this.entries.get(id);
335
+ const entry = this.find(owner, id, canUse) ?? (other?.run.up && mayStop?.(this.copy(other.run)) ? other : undefined);
311
336
  if (!entry) {
312
337
  return undefined;
313
338
  }
@@ -336,6 +361,24 @@ class RunRegistry {
336
361
  this.expireLater(entry);
337
362
  return { status: 'ok', run: this.copy(entry.run) };
338
363
  }
364
+ /**
365
+ * Wakes a service run that sleeps, for its owner or who `mayOpen` it, as a request to its
366
+ * endpoints would (visit): with the same check of its owner (`mayWake`) and the same places.
367
+ * Answers why it did not wake when it could not.
368
+ */
369
+ wake(caller, id, mayOpen, mayWake) {
370
+ const entry = this.entries.get(id);
371
+ if (!entry?.run.up || !(this.owns(caller, entry) || mayOpen?.(this.copy(entry.run)))) {
372
+ return { status: 'not-found' };
373
+ }
374
+ if (entry.run.state !== 'asleep') {
375
+ return { status: 'not-asleep', state: entry.run.state };
376
+ }
377
+ const refused = this.visit(id, mayWake);
378
+ return refused
379
+ ? { status: 'refused', reason: refused, run: this.copy(entry.run) }
380
+ : { status: 'ok', run: this.copy(entry.run) };
381
+ }
339
382
  /**
340
383
  * The service run an endpoint host belongs to: the newest that is up, so one that replaces
341
384
  * a run of the same name takes its hosts over as soon as it is up; else the newest that
@@ -575,8 +618,10 @@ class RunRegistry {
575
618
  [...this.entries.values()].some((entry) => entry.run.state === 'running' || entry.run.state === 'up')) {
576
619
  await new Promise((resolve) => setTimeout(resolve, 10));
577
620
  }
578
- // the runs that were stopped are written down before the server is gone
621
+ // the runs that were stopped are written down before the server is gone, and the records
622
+ // of evicted runs are gone from the store
579
623
  await Promise.all([...this.entries.values()].map((entry) => entry.saving));
624
+ await Promise.all([...this.removing]);
580
625
  }
581
626
  find(owner, id, canUse) {
582
627
  const entry = this.entries.get(id);
@@ -612,6 +657,7 @@ class RunRegistry {
612
657
  accounts: [...run.accounts],
613
658
  ...(run.approvals ? { approvals: JSON.parse(JSON.stringify(run.approvals)) } : {}),
614
659
  ...(run.results ? { results: JSON.parse(JSON.stringify(run.results)) } : {}),
660
+ ...(run.phases ? { phases: run.phases.map((phase) => ({ ...phase })) } : {}),
615
661
  ...(run.moves ? { moves: run.moves.map((move) => ({ ...move })) } : {}),
616
662
  ...(run.moving ? { moving: { ...run.moving } } : {}),
617
663
  };
@@ -1424,6 +1470,10 @@ class RunRegistry {
1424
1470
  }
1425
1471
  return;
1426
1472
  }
1473
+ if (recorded.type === 'phase') {
1474
+ this.keepPhase(entry, recorded);
1475
+ return;
1476
+ }
1427
1477
  const event = recorded.type === 'task' ? bounded(recorded) : recorded;
1428
1478
  if (event.type === 'log') {
1429
1479
  this.keepTail(entry, event.task, event.text);
@@ -1446,6 +1496,19 @@ class RunRegistry {
1446
1496
  }
1447
1497
  this.push(entry, event);
1448
1498
  }
1499
+ // once each, from the executor: a phase it reports again (a service run that wakes) is the
1500
+ // newest
1501
+ keepPhase(entry, event) {
1502
+ if (!exports.RUN_PHASES.includes(event.phase) ||
1503
+ !isTimestamp(event.startedAt) ||
1504
+ !isTimestamp(event.finishedAt) ||
1505
+ Date.parse(event.finishedAt) < Date.parse(event.startedAt)) {
1506
+ return;
1507
+ }
1508
+ const phases = (entry.run.phases ?? []).filter((phase) => phase.phase !== event.phase);
1509
+ phases.push({ phase: event.phase, startedAt: event.startedAt, finishedAt: event.finishedAt });
1510
+ entry.run.phases = phases.sort((a, b) => exports.RUN_PHASES.indexOf(a.phase) - exports.RUN_PHASES.indexOf(b.phase));
1511
+ }
1449
1512
  keepTail(entry, task, text) {
1450
1513
  let tail = entry.tails.get(task);
1451
1514
  if (!tail) {
@@ -1487,6 +1550,7 @@ class RunRegistry {
1487
1550
  ...(event.durationMs !== undefined ? { durationMs: event.durationMs } : {}),
1488
1551
  ...(event.exitCode !== undefined ? { exitCode: event.exitCode } : {}),
1489
1552
  ...(event.error ? { error: event.error } : {}),
1553
+ ...(event.commands?.length ? { commands: event.commands } : {}),
1490
1554
  ...(event.state === 'cached'
1491
1555
  ? { cache: { hit: true } }
1492
1556
  : event.state === 'succeeded' || event.state === 'failed'
@@ -1524,7 +1588,11 @@ class RunRegistry {
1524
1588
  const finished = [...this.entries.values()].filter((entry) => FINAL_STATES.includes(entry.run.state));
1525
1589
  for (const entry of finished.slice(0, Math.max(0, finished.length - this.keep))) {
1526
1590
  this.entries.delete(entry.run.id);
1527
- void entry.saving.then(() => this.options.store?.remove(entry.run.id)).catch(() => undefined);
1591
+ const removal = entry.saving
1592
+ .then(() => this.options.store?.remove(entry.run.id))
1593
+ .catch(() => undefined)
1594
+ .finally(() => this.removing.delete(removal));
1595
+ this.removing.add(removal);
1528
1596
  }
1529
1597
  }
1530
1598
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.SandboxFileError = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
3
+ exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const fs_1 = require("fs");
@@ -25,6 +25,21 @@ const SEARCH_COUNT = 20000;
25
25
  const SEARCH_TIMEOUT_MS = 60000;
26
26
  // the most a diff or patch of the changes may take
27
27
  exports.MAX_CHANGES_BYTES = 64 * 1024 * 1024;
28
+ // What one batch of edits may hold in memory, the files it reads and the files it would
29
+ // write together: a batch over it is refused before it reads or makes more.
30
+ exports.MAX_EDIT_BATCH_BYTES = 256 * 1024 * 1024;
31
+ // What one batch may process: the text it decodes, scans and makes, read files counted
32
+ // each time an operation reads them. A batch over it is refused, as one that holds too much.
33
+ exports.MAX_EDIT_BATCH_WORK = 1024 * 1024 * 1024;
34
+ // What all batches being planned on this server may hold in memory together.
35
+ exports.MAX_EDIT_SERVER_BYTES = 512 * 1024 * 1024;
36
+ const SERVER_EDITS = { held: 0, max: exports.MAX_EDIT_SERVER_BYTES };
37
+ const DEFAULT_EDIT_LIMITS = {
38
+ bytes: exports.MAX_EDIT_BATCH_BYTES,
39
+ work: exports.MAX_EDIT_BATCH_WORK,
40
+ compared: sandbox_patch_1.MAX_COMPARED_LINES,
41
+ server: SERVER_EDITS,
42
+ };
28
43
  class SandboxFileError extends Error {
29
44
  constructor(status, message, details = {}) {
30
45
  super(message);
@@ -183,11 +198,14 @@ class HostSandboxFiles {
183
198
  // the environment of ripgrep: the variables runs see
184
199
  env,
185
200
  // the most a diff or patch of the changes may take
186
- maxChangesBytes = exports.MAX_CHANGES_BYTES) {
201
+ maxChangesBytes = exports.MAX_CHANGES_BYTES,
202
+ // what one batch of edits may hold and process
203
+ editLimits = {}) {
187
204
  this.root = root;
188
205
  this.git = git;
189
206
  this.env = env;
190
207
  this.maxChangesBytes = maxChangesBytes;
208
+ this.editLimits = editLimits;
191
209
  }
192
210
  absolute(path) {
193
211
  return (0, path_1.join)(this.root, ...path.split('/'));
@@ -706,8 +724,21 @@ class HostSandboxFiles {
706
724
  });
707
725
  }
708
726
  async plan(ops) {
709
- const batch = new EditBatch(this);
727
+ const batch = new EditBatch(this, { ...DEFAULT_EDIT_LIMITS, ...this.editLimits });
728
+ try {
729
+ return await this.planBatch(batch, ops);
730
+ }
731
+ finally {
732
+ // the plan is written right after it is made, under the same lock of the sandbox
733
+ batch.release();
734
+ }
735
+ }
736
+ async planBatch(batch, ops) {
710
737
  for (const [index, op] of ops.entries()) {
738
+ if (index > 0) {
739
+ // the other requests of the server get their turn between two operations
740
+ await new Promise((resolve) => setImmediate(resolve));
741
+ }
711
742
  try {
712
743
  await batch.apply(op);
713
744
  }
@@ -841,13 +872,57 @@ class HostSandboxFiles {
841
872
  }
842
873
  }
843
874
  exports.HostSandboxFiles = HostSandboxFiles;
875
+ function tooLarge(path, bytes) {
876
+ if (bytes > exports.MAX_FILE_BYTES) {
877
+ throw new SandboxFileError(413, `${path} would take ${bytes} bytes, more than ${exports.MAX_FILE_BYTES}`);
878
+ }
879
+ }
844
880
  // The edits of one request, applied to what the files would hold after them, before any
845
881
  // of it is written.
846
882
  class EditBatch {
847
- constructor(files) {
883
+ constructor(files, limits) {
848
884
  this.files = files;
885
+ this.limits = limits;
849
886
  this.before = new Map();
850
887
  this.after = new Map();
888
+ // the bytes of the files read and made so far
889
+ this.held = 0;
890
+ // the bytes of text decoded, scanned and made so far
891
+ this.worked = 0;
892
+ this.budget = new sandbox_patch_1.PatchBudget(limits.compared);
893
+ }
894
+ hold(bytes) {
895
+ if (this.held + bytes > this.limits.bytes) {
896
+ throw new SandboxFileError(413, `the edits of this batch read and write more than ${this.limits.bytes} bytes, send them in smaller batches`);
897
+ }
898
+ const server = this.limits.server;
899
+ if (bytes > 0 && server.held + bytes > server.max) {
900
+ throw new SandboxFileError(503, 'the server is busy with other edits, send the batch again in a moment');
901
+ }
902
+ this.held += bytes;
903
+ server.held += bytes;
904
+ }
905
+ free(bytes) {
906
+ this.held -= bytes;
907
+ this.limits.server.held -= bytes;
908
+ }
909
+ // What this batch holds no longer counts against the server.
910
+ release() {
911
+ this.limits.server.held -= this.held;
912
+ this.held = 0;
913
+ }
914
+ work(bytes) {
915
+ this.worked += bytes;
916
+ if (this.worked > this.limits.work) {
917
+ throw new SandboxFileError(413, `the edits of this batch process more than ${this.limits.work} bytes of text, send them in smaller batches`);
918
+ }
919
+ }
920
+ // A file's content, counted once when it is read.
921
+ async content(path, state) {
922
+ if (!state.content) {
923
+ this.hold(state.size);
924
+ }
925
+ return this.files.content(path, state);
851
926
  }
852
927
  async current(path) {
853
928
  const changed = this.after.get(path);
@@ -862,7 +937,9 @@ class EditBatch {
862
937
  return original;
863
938
  }
864
939
  async text(path, state) {
865
- return decodeText(path, await this.files.content(path, state));
940
+ const content = await this.content(path, state);
941
+ this.work(content.length);
942
+ return decodeText(path, content);
866
943
  }
867
944
  async file(path, verb) {
868
945
  const state = await this.current(path);
@@ -882,7 +959,7 @@ class EditBatch {
882
959
  return;
883
960
  }
884
961
  const state = await this.current(path);
885
- const actual = state.kind === 'file' ? sha256(await this.files.content(path, state)) : undefined;
962
+ const actual = state.kind === 'file' ? sha256(await this.content(path, state)) : undefined;
886
963
  if (actual !== ifHash.toLowerCase()) {
887
964
  throw new SandboxFileError(412, actual
888
965
  ? `${path} changed since you read it (sha256 ${actual}), read it again`
@@ -911,9 +988,11 @@ class EditBatch {
911
988
  return state;
912
989
  }
913
990
  set(path, content, exec) {
914
- if (content.length > exports.MAX_FILE_BYTES) {
915
- throw new SandboxFileError(413, `${path} would take ${content.length} bytes, more than ${exports.MAX_FILE_BYTES}`);
916
- }
991
+ tooLarge(path, content.length);
992
+ const replaced = this.after.get(path);
993
+ // what an earlier edit of the batch made for the path is not kept
994
+ this.free(replaced?.kind === 'file' ? replaced.content?.length ?? 0 : 0);
995
+ this.hold(content.length);
917
996
  this.after.set(path, { kind: 'file', size: content.length, exec, content });
918
997
  }
919
998
  async apply(op) {
@@ -931,17 +1010,28 @@ class EditBatch {
931
1010
  if (op.old_string === op.new_string) {
932
1011
  throw new SandboxFileError(422, 'old_string and new_string are the same, nothing would change');
933
1012
  }
1013
+ // the first places are kept to name their lines, the others counted
934
1014
  const at = [];
1015
+ let count = 0;
935
1016
  for (let found = text.indexOf(op.old_string); found >= 0; found = text.indexOf(op.old_string, found + op.old_string.length)) {
936
- at.push(found);
1017
+ if (at.length < 10) {
1018
+ at.push(found);
1019
+ }
1020
+ count++;
937
1021
  }
938
- if (at.length === 0) {
1022
+ if (count === 0) {
939
1023
  throw new SandboxFileError(422, `old_string is not in ${path}; it has to match the file exactly, whitespace and indentation included: read the file again`);
940
1024
  }
941
- if (at.length > 1 && !op.replace_all) {
942
- const lines = at.slice(0, 10).map((offset) => text.slice(0, offset).split('\n').length);
943
- throw new SandboxFileError(422, `old_string is ${at.length} times in ${path}, at lines ${lines.join(', ')}${at.length > 10 ? ', …' : ''}: add lines around it until it is there once, or set replace_all`, { lines });
1025
+ if (count > 1 && !op.replace_all) {
1026
+ const lines = at.map((offset) => text.slice(0, offset).split('\n').length);
1027
+ throw new SandboxFileError(422, `old_string is ${count} times in ${path}, at lines ${lines.join(', ')}${count > 10 ? ', …' : ''}: add lines around it until it is there once, or set replace_all`, { lines });
944
1028
  }
1029
+ // the size of the result, before it is made
1030
+ const size = Buffer.byteLength(text, 'utf8') +
1031
+ count * (Buffer.byteLength(op.new_string, 'utf8') - Buffer.byteLength(op.old_string, 'utf8'));
1032
+ tooLarge(path, size);
1033
+ // the scan, and the result that is made
1034
+ this.work(text.length + size);
945
1035
  const replaced = op.replace_all
946
1036
  ? text.split(op.old_string).join(op.new_string)
947
1037
  : text.slice(0, at[0]) + op.new_string + text.slice(at[0] + op.old_string.length);
@@ -967,7 +1057,7 @@ class EditBatch {
967
1057
  else {
968
1058
  const to = checkPath(op.to);
969
1059
  const state = await this.file(path, 'move');
970
- const content = await this.files.content(path, state);
1060
+ const content = await this.content(path, state);
971
1061
  const target = await this.writable(to);
972
1062
  if (target.kind !== 'absent') {
973
1063
  throw new SandboxFileError(409, `${to} exists, delete it first`);
@@ -997,7 +1087,8 @@ class EditBatch {
997
1087
  throw new SandboxFileError(409, `${to} exists, the patch ${from ? 'moves a file onto' : 'adds'} it`);
998
1088
  }
999
1089
  }
1000
- const result = file.apply(content);
1090
+ const result = file.apply(content, this.budget);
1091
+ this.work(content.length + result.length);
1001
1092
  if (to === undefined) {
1002
1093
  if (from !== undefined && result !== '') {
1003
1094
  throw new sandbox_patch_1.PatchError(`${from}: the patch deletes it, but its lines are not what the file holds`);
@@ -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) => {