hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -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) => {
@@ -1,12 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.sandboxPodMain = exports.decodePodError = exports.encodeEditOps = exports.INCOMING_REF = exports.INCOMING = void 0;
4
+ const crypto_1 = require("crypto");
4
5
  const promises_1 = require("fs/promises");
5
6
  const path_1 = require("path");
6
7
  const url_1 = require("url");
7
8
  const git_checkout_1 = require("./git-checkout");
8
9
  const sandbox_files_1 = require("./sandbox-files");
9
10
  const sandbox_storage_1 = require("./sandbox-storage");
11
+ const tar_1 = require("../utils/tar");
10
12
  // On a cluster a sandbox is a claim, and what the server does with its files runs in a
11
13
  // short pod that mounts it (see KubernetesSandboxStorage): `hammerkit server-sandbox
12
14
  // <directory>` reads one request on its standard input, does it with the code of a host
@@ -91,6 +93,32 @@ async function answer(storage, directory, request, out) {
91
93
  }
92
94
  return send({ files: plan.files, bytes: plan.bytes });
93
95
  }
96
+ case 'archive': {
97
+ // written beside the sandbox on the claim, sent, and removed
98
+ const into = (0, path_1.join)(directory, `${request.id}-archive-${(0, crypto_1.randomBytes)(6).toString('hex')}`);
99
+ try {
100
+ await storage.exportTree(key, request.tree, into, AbortSignal.timeout(10 * 60000));
101
+ await write(out, JSON.stringify({ ok: true, result: null, stream: true }) + '\n');
102
+ const pack = (0, tar_1.packArchive)({ cwd: into, portable: true }, ['.']);
103
+ try {
104
+ for await (const chunk of pack) {
105
+ await write(out, chunk);
106
+ }
107
+ }
108
+ catch (e) {
109
+ throw new AnswerStarted(e instanceof Error ? e.message : String(e));
110
+ }
111
+ finally {
112
+ // a reader that went away (over its size limit) leaves the pack reading files
113
+ // that are removed next: what fails then is no answer of anybody's
114
+ pack.on('error', () => undefined);
115
+ }
116
+ return;
117
+ }
118
+ finally {
119
+ await (0, promises_1.rm)(into, { recursive: true, force: true });
120
+ }
121
+ }
94
122
  case 'raw': {
95
123
  const raw = await files().raw(request.path);
96
124
  const header = {
@@ -276,6 +276,29 @@ class HostSandboxStorage {
276
276
  // files change, and what it wrote to the git data is pruned again. Files a task made
277
277
  // unreadable are made readable first: git would leave them out and call the sandbox
278
278
  // clean.
279
+ async exportTree({ id }, tree, into, signal) {
280
+ if (!/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(tree)) {
281
+ throw new Error(`${JSON.stringify(tree.slice(0, 80))} is not a git tree`);
282
+ }
283
+ return this.withIndex(id, signal, async (run) => {
284
+ const now = (await run(['write-tree'], 'read')).trim();
285
+ if (now !== tree) {
286
+ throw new Error(`the files of the sandbox ${id} are ${now} now, not ${tree}`);
287
+ }
288
+ // an index of its own holds the tree alone, whatever the sandbox's index says of its
289
+ // entries; the files are written as git has them, through no filter of the server's
290
+ const index = (0, path_1.join)(this.root(id), `export-${(0, crypto_1.randomBytes)(6).toString('hex')}`);
291
+ await (0, promises_1.mkdir)(into, { recursive: true });
292
+ try {
293
+ const env = this.readEnv({ GIT_INDEX_FILE: index });
294
+ await this.git(id, ['read-tree', tree], env, signal, 'read');
295
+ await this.git(id, ['checkout-index', '--all', '--force', `--prefix=${(0, path_1.join)(into, '/')}`], env, signal, 'read');
296
+ }
297
+ finally {
298
+ await (0, promises_1.rm)(index, { force: true });
299
+ }
300
+ });
301
+ }
279
302
  async state({ id }, signal = AbortSignal.timeout(5 * 60 * 1000)) {
280
303
  return this.withIndex(id, signal, async (run) => {
281
304
  const tree = (await run(['write-tree'], 'read')).trim();
@@ -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);
@@ -412,6 +446,14 @@ class SandboxRegistry {
412
446
  async state(id, signal) {
413
447
  return this.options.storage.state(keyOf(this.existing(id)), signal);
414
448
  }
449
+ // The files of `tree`, which the sandbox's files must be now, written into `into`: what a
450
+ // check runs on.
451
+ async exportTree(id, tree, into, signal) {
452
+ const sandbox = this.existing(id);
453
+ sandbox.lastUsedAt = this.timestamp();
454
+ await this.save(sandbox);
455
+ await this.options.storage.exportTree(keyOf(sandbox), tree, into, signal);
456
+ }
415
457
  // What a run works on, `into` a directory of the run when the storage copies the files;
416
458
  // the run is the sandbox's use.
417
459
  async attach(id, into) {
@@ -475,7 +517,7 @@ class SandboxRegistry {
475
517
  }
476
518
  }
477
519
  total() {
478
- 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);
479
521
  }
480
522
  withLock(id, fn) {
481
523
  const previous = this.locks.get(id) ?? Promise.resolve();