hammerkit 2.0.0-next.2 → 2.0.0-next.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/index-DRSwIRXd.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +31 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +35 -14
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +100 -13
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-retry.js +57 -0
  91. package/dist/server/run-source-environment.js +39 -0
  92. package/dist/server/run-worker.js +71 -9
  93. package/dist/server/runs.js +133 -7
  94. package/dist/server/sandbox-files.js +339 -55
  95. package/dist/server/sandbox-patch.js +43 -17
  96. package/dist/server/sandboxes.js +57 -23
  97. package/dist/server/server-config.js +28 -5
  98. package/dist/server/server.js +150 -20
  99. package/dist/server/service-runs.js +50 -5
  100. package/dist/server/sources.js +68 -11
  101. package/dist/server/timings.js +23 -3
  102. package/dist/utils/buffer-context.js +30 -20
  103. package/dist/utils/limit.js +30 -0
  104. package/dist/utils/line-splitter.js +52 -0
  105. package/dist/utils/read-lines.js +65 -0
  106. package/dist/utils/tar.js +51 -1
  107. package/dist/utils/units.js +36 -1
  108. package/dist/utils/web-links.js +34 -0
  109. package/package.json +1 -1
  110. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  111. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  112. package/dist/dashboard/favicon.svg +0 -1
@@ -1,10 +1,11 @@
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");
7
7
  const promises_1 = require("fs/promises");
8
+ const os_1 = require("os");
8
9
  const path_1 = require("path");
9
10
  const minimatch_1 = require("minimatch");
10
11
  const source_manifest_1 = require("../remote/source-manifest");
@@ -25,6 +26,21 @@ const SEARCH_COUNT = 20000;
25
26
  const SEARCH_TIMEOUT_MS = 60000;
26
27
  // the most a diff or patch of the changes may take
27
28
  exports.MAX_CHANGES_BYTES = 64 * 1024 * 1024;
29
+ // What one batch of edits may hold in memory, the files it reads and the files it would
30
+ // write together: a batch over it is refused before it reads or makes more.
31
+ exports.MAX_EDIT_BATCH_BYTES = 256 * 1024 * 1024;
32
+ // What one batch may process: the text it decodes, scans and makes, read files counted
33
+ // each time an operation reads them. A batch over it is refused, as one that holds too much.
34
+ exports.MAX_EDIT_BATCH_WORK = 1024 * 1024 * 1024;
35
+ // What all batches being planned on this server may hold in memory together.
36
+ exports.MAX_EDIT_SERVER_BYTES = 512 * 1024 * 1024;
37
+ const SERVER_EDITS = { held: 0, max: exports.MAX_EDIT_SERVER_BYTES };
38
+ const DEFAULT_EDIT_LIMITS = {
39
+ bytes: exports.MAX_EDIT_BATCH_BYTES,
40
+ work: exports.MAX_EDIT_BATCH_WORK,
41
+ compared: sandbox_patch_1.MAX_COMPARED_LINES,
42
+ server: SERVER_EDITS,
43
+ };
28
44
  class SandboxFileError extends Error {
29
45
  constructor(status, message, details = {}) {
30
46
  super(message);
@@ -178,16 +194,21 @@ function fileType(stats) {
178
194
  * without following a link, and on Linux the opened file is checked to be the one in the
179
195
  * sandbox, in case a task swapped a directory for a link in between.
180
196
  */
197
+ // the ignore files ripgrep reads in the folders above the path it searches
198
+ const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
181
199
  class HostSandboxFiles {
182
200
  constructor(root, git,
183
201
  // the environment of ripgrep: the variables runs see
184
202
  env,
185
203
  // the most a diff or patch of the changes may take
186
- maxChangesBytes = exports.MAX_CHANGES_BYTES) {
204
+ maxChangesBytes = exports.MAX_CHANGES_BYTES,
205
+ // what one batch of edits may hold and process
206
+ editLimits = {}) {
187
207
  this.root = root;
188
208
  this.git = git;
189
209
  this.env = env;
190
210
  this.maxChangesBytes = maxChangesBytes;
211
+ this.editLimits = editLimits;
191
212
  }
192
213
  absolute(path) {
193
214
  return (0, path_1.join)(this.root, ...path.split('/'));
@@ -283,12 +304,17 @@ class HostSandboxFiles {
283
304
  }
284
305
  }
285
306
  // The opened file is the one in the sandbox: a task may have swapped a directory above it
286
- // for a link after the names were checked. Linux names the file a descriptor is open on;
287
- // elsewhere the path has to lead to the same file and to no link.
307
+ // for a link after the names were checked. Linux names the file a descriptor is open on,
308
+ // and a server that can't read that (no /proc) reads nothing: a check of the path would
309
+ // leave a moment for a swap. Elsewhere (a machine of a developer) the path has to lead to
310
+ // the same file and to no link.
288
311
  async mustBeInside(handle, absolute, path) {
289
312
  let actual;
290
313
  if (process.platform === 'linux') {
291
314
  actual = await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined);
315
+ if (actual === undefined) {
316
+ throw new SandboxFileError(503, `${path} can not be read: the server can not tell which file it opened, /proc/self/fd is not readable`);
317
+ }
292
318
  }
293
319
  if (actual === undefined) {
294
320
  const [opened, named] = await Promise.all([handle.stat(), (0, promises_1.lstat)(absolute)]);
@@ -516,7 +542,13 @@ class HostSandboxFiles {
516
542
  else {
517
543
  args.push('--count-matches', '--null');
518
544
  }
519
- args.push('--regexp', query.pattern, '--', path ?? '.');
545
+ // ripgrep follows a link in the path it is given, which a running task can swap in after
546
+ // the check above: it reads what was checked (see pin)
547
+ const target = await this.pin(path);
548
+ if (target.stdin) {
549
+ args.push('--with-filename');
550
+ }
551
+ args.push('--regexp', query.pattern, '--', target.arg);
520
552
  const result = { output_mode: mode, total: 0, exact: true, truncated: false, cursor: null };
521
553
  const files = [];
522
554
  const matches = [];
@@ -531,8 +563,11 @@ class HostSandboxFiles {
531
563
  };
532
564
  // the JSON of ripgrep names paths with the separator of the system, whatever --path-separator says
533
565
  const clean = (file) => {
534
- const path = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
535
- return path.startsWith('./') ? path.slice(2) : path;
566
+ if (target.stdin && file === '<stdin>') {
567
+ return path;
568
+ }
569
+ const name = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
570
+ return name.startsWith('./') ? name.slice(2) : name;
536
571
  };
537
572
  const onRecord = (record) => {
538
573
  if (mode === 'files_with_matches') {
@@ -559,7 +594,16 @@ class HostSandboxFiles {
559
594
  ...(message.type === 'context' ? { context: true } : {}),
560
595
  })));
561
596
  };
562
- const { code, stderr, stopped } = await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord);
597
+ let ran;
598
+ try {
599
+ ran = target.skip
600
+ ? { code: 1, stderr: '', stopped: false }
601
+ : await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord, target);
602
+ }
603
+ finally {
604
+ await target.release();
605
+ }
606
+ const { code, stderr, stopped } = ran;
563
607
  if (code === 2 && total === 0 && !stopped) {
564
608
  throw new SandboxFileError(400, stderr.trim() || 'ripgrep failed');
565
609
  }
@@ -578,9 +622,93 @@ class HostSandboxFiles {
578
622
  }
579
623
  return result;
580
624
  }
625
+ // What ripgrep searches for a `path` of a search, so that it reads what was checked when a
626
+ // task swaps a link into the path meanwhile (ripgrep follows the links of the path it is
627
+ // given, not those it finds below it). A file is read here, through the check of what was
628
+ // opened, and handed to ripgrep on stdin. A directory is opened here and checked the same
629
+ // way; ripgrep is given the same relative path in a folder of its own where it is a link
630
+ // to that open directory (on Linux, /proc/<pid>/fd/<n>), next to copies of the ignore
631
+ // files above it, so that globs, `.gitignore` and the paths it prints are what they were.
632
+ // Elsewhere (a machine of a developer) a directory is searched by its name.
633
+ async pin(path) {
634
+ const none = async () => undefined;
635
+ if (!path) {
636
+ return { arg: '.', cwd: this.root, release: none };
637
+ }
638
+ const found = await this.stat(path);
639
+ if (found?.type === 'file') {
640
+ const { handle, stat } = await this.open(path);
641
+ if (stat.size > exports.MAX_FILE_BYTES) {
642
+ // as ripgrep's --max-filesize leaves it out
643
+ await handle.close();
644
+ return { arg: '-', cwd: this.root, skip: true, release: none };
645
+ }
646
+ const stdin = handle.createReadStream();
647
+ return { arg: '-', cwd: this.root, stdin, release: async () => void stdin.destroy() };
648
+ }
649
+ if (process.platform !== 'linux') {
650
+ return { arg: path, cwd: this.root, release: none };
651
+ }
652
+ const absolute = this.absolute(path);
653
+ const handle = await (0, promises_1.open)(absolute, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | fs_1.constants.O_NOFOLLOW).catch((e) => {
654
+ if (e.code === 'ELOOP' || e.code === 'ENOTDIR') {
655
+ throw new SandboxFileError(409, `${path} changed while it was searched, search again`);
656
+ }
657
+ throw e;
658
+ });
659
+ let folder;
660
+ try {
661
+ await this.mustBeInside(handle, absolute, path);
662
+ folder = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-search-'));
663
+ const parts = path.split('/');
664
+ for (let depth = 0; depth < parts.length; depth++) {
665
+ const above = parts.slice(0, depth).join('/');
666
+ await (0, promises_1.mkdir)((0, path_1.join)(folder, ...parts.slice(0, depth)), { recursive: true });
667
+ for (const name of IGNORE_FILES) {
668
+ const file = above ? `${above}/${name}` : name;
669
+ const content = await this.ignoreFile(file);
670
+ if (content !== undefined) {
671
+ await (0, promises_1.writeFile)((0, path_1.join)(folder, ...parts.slice(0, depth), name), content);
672
+ }
673
+ }
674
+ }
675
+ await (0, promises_1.symlink)(`/proc/${process.pid}/fd/${handle.fd}`, (0, path_1.join)(folder, ...parts));
676
+ }
677
+ catch (e) {
678
+ await handle.close();
679
+ if (folder) {
680
+ await (0, promises_1.rm)(folder, { recursive: true, force: true });
681
+ }
682
+ throw e;
683
+ }
684
+ const pinned = folder;
685
+ return {
686
+ arg: path,
687
+ cwd: pinned,
688
+ release: async () => {
689
+ await (0, promises_1.rm)(pinned, { recursive: true, force: true });
690
+ await handle.close();
691
+ },
692
+ };
693
+ }
694
+ // An ignore file above the path of a search, read as any file is; none when there is none
695
+ // or it can not be read as a file
696
+ async ignoreFile(path) {
697
+ const found = await this.stat(path);
698
+ if (found?.type !== 'file' || found.size > exports.MAX_FILE_BYTES) {
699
+ return undefined;
700
+ }
701
+ const { handle, stat } = await this.open(path);
702
+ try {
703
+ return await readOpened(handle, stat.size);
704
+ }
705
+ finally {
706
+ await handle.close();
707
+ }
708
+ }
581
709
  // Runs ripgrep in the files and hands each record of its output to `onRecord`, which
582
710
  // answers whether to read on.
583
- ripgrep(args, separator, onRecord) {
711
+ ripgrep(args, separator, onRecord, target = { cwd: this.root }) {
584
712
  const env = {};
585
713
  for (const [key, value] of Object.entries(this.env)) {
586
714
  if (value !== undefined && !key.toUpperCase().startsWith('RIPGREP_')) {
@@ -589,11 +717,20 @@ class HostSandboxFiles {
589
717
  }
590
718
  return new Promise((resolve, reject) => {
591
719
  const child = (0, child_process_1.spawn)('rg', args, {
592
- cwd: this.root,
720
+ cwd: target.cwd,
593
721
  env,
594
- stdio: ['ignore', 'pipe', 'pipe'],
722
+ stdio: ['pipe', 'pipe', 'pipe'],
595
723
  signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
596
724
  });
725
+ // ripgrep stops reading when it is stopped or has seen enough
726
+ child.stdin.on('error', () => undefined);
727
+ if (target.stdin) {
728
+ target.stdin.on('error', () => child.stdin.destroy());
729
+ target.stdin.pipe(child.stdin);
730
+ }
731
+ else {
732
+ child.stdin.end();
733
+ }
597
734
  let stopped = false;
598
735
  let buffered = '';
599
736
  let stderr = '';
@@ -706,8 +843,21 @@ class HostSandboxFiles {
706
843
  });
707
844
  }
708
845
  async plan(ops) {
709
- const batch = new EditBatch(this);
846
+ const batch = new EditBatch(this, { ...DEFAULT_EDIT_LIMITS, ...this.editLimits });
847
+ try {
848
+ return await this.planBatch(batch, ops);
849
+ }
850
+ finally {
851
+ // the plan is written right after it is made, under the same lock of the sandbox
852
+ batch.release();
853
+ }
854
+ }
855
+ async planBatch(batch, ops) {
710
856
  for (const [index, op] of ops.entries()) {
857
+ if (index > 0) {
858
+ // the other requests of the server get their turn between two operations
859
+ await new Promise((resolve) => setImmediate(resolve));
860
+ }
711
861
  try {
712
862
  await batch.apply(op);
713
863
  }
@@ -766,50 +916,124 @@ class HostSandboxFiles {
766
916
  return state.content;
767
917
  }
768
918
  // Writes the changes: what a path held is moved aside first, and put back when a later
769
- // write fails.
919
+ // write fails. Each name is written in the directory above it, opened from the root name
920
+ // by name (see `folder`), so what a task swaps in meanwhile leads no write out of the files.
770
921
  async write(changes) {
771
922
  const backups = [];
772
923
  const written = [];
773
- // the directories above every path are still the ones the edits were planned in
774
- for (const [path] of changes) {
775
- await this.sameParents(path);
776
- }
924
+ const folders = new Map();
925
+ const folderOf = async (path, create) => {
926
+ const key = (0, path_1.dirname)(path);
927
+ let folder = folders.get(key);
928
+ if (!folder) {
929
+ folder = await this.folder(path, create);
930
+ folders.set(key, folder);
931
+ }
932
+ return folder;
933
+ };
777
934
  try {
778
- for (const [path, before] of changes) {
779
- if (before.kind === 'file' || before.kind === 'link') {
780
- const absolute = this.absolute(path);
781
- const backup = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`);
782
- await (0, promises_1.rename)(absolute, backup);
783
- backups.push([absolute, backup]);
935
+ // the directories above every path are still the ones the edits were planned in
936
+ for (const [path] of changes) {
937
+ await this.sameParents(path);
938
+ }
939
+ try {
940
+ for (const [path, before] of changes) {
941
+ if (before.kind === 'file' || before.kind === 'link') {
942
+ const folder = await folderOf(path, false);
943
+ const name = (0, path_1.basename)(path);
944
+ const backup = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`;
945
+ await (0, promises_1.rename)(folder.at(name), folder.at(backup));
946
+ backups.push([folder, name, backup]);
947
+ }
948
+ }
949
+ for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
950
+ if (after.kind !== 'file') {
951
+ continue;
952
+ }
953
+ const folder = await folderOf(path, true);
954
+ const name = (0, path_1.basename)(path);
955
+ const temporary = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`;
956
+ const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
957
+ const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
958
+ const flags = fs_1.constants.O_WRONLY | fs_1.constants.O_CREAT | fs_1.constants.O_EXCL | (fs_1.constants.O_NOFOLLOW ?? 0);
959
+ const handle = await (0, promises_1.open)(folder.at(temporary), flags, mode);
960
+ try {
961
+ await handle.writeFile(after.content ?? Buffer.alloc(0));
962
+ await handle.chmod(mode);
963
+ }
964
+ finally {
965
+ await handle.close();
966
+ }
967
+ await (0, promises_1.rename)(folder.at(temporary), folder.at(name));
968
+ written.push([folder, name]);
784
969
  }
785
970
  }
786
- for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
787
- if (after.kind !== 'file') {
788
- continue;
971
+ catch (e) {
972
+ for (const [folder, name] of written.reverse()) {
973
+ await (0, promises_1.rm)(folder.at(name), { force: true });
974
+ }
975
+ for (const [folder, name, backup] of backups.reverse()) {
976
+ await (0, promises_1.rename)(folder.at(backup), folder.at(name)).catch(() => undefined);
789
977
  }
978
+ throw e;
979
+ }
980
+ for (const [folder, , backup] of backups) {
981
+ await (0, promises_1.rm)(folder.at(backup), { force: true });
982
+ }
983
+ }
984
+ finally {
985
+ for (const folder of folders.values()) {
986
+ await folder.release();
987
+ }
988
+ }
989
+ }
990
+ // The directory above `path`, made where it is missing and `create` is set. On Linux it is
991
+ // opened from the root name by name, never through a link, and its names are reached
992
+ // through the open descriptor (/proc/self/fd/<n>/<name>): a directory a task swaps for a link
993
+ // after the checks leads no write out of the files. A server on Linux that can not read
994
+ // /proc writes nothing. Elsewhere (a machine of a developer) the names are checked on the way.
995
+ async folder(path, create) {
996
+ const parts = path.split('/').slice(0, -1);
997
+ if (process.platform !== 'linux') {
998
+ if (create) {
790
999
  await this.makeParents(path);
791
- const absolute = this.absolute(path);
792
- const temporary = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`);
793
- const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
794
- const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
795
- await (0, promises_1.writeFile)(temporary, after.content ?? Buffer.alloc(0), { flag: 'wx', mode });
796
- await (0, promises_1.chmod)(temporary, mode);
797
- await (0, promises_1.rename)(temporary, absolute);
798
- written.push(absolute);
799
1000
  }
1001
+ const absolute = (0, path_1.dirname)(this.absolute(path));
1002
+ return { at: (name) => (0, path_1.join)(absolute, name), release: async () => undefined };
800
1003
  }
801
- catch (e) {
802
- for (const absolute of written.reverse()) {
803
- await (0, promises_1.rm)(absolute, { force: true });
1004
+ let handle = await (0, promises_1.open)(this.root, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY);
1005
+ try {
1006
+ if ((await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined)) === undefined) {
1007
+ throw new SandboxFileError(503, `${path} can not be written: the server can not reach a directory it opened, /proc/self/fd is not readable`);
804
1008
  }
805
- for (const [absolute, backup] of backups.reverse()) {
806
- await (0, promises_1.rename)(backup, absolute).catch(() => undefined);
1009
+ const flags = fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | (fs_1.constants.O_NOFOLLOW ?? 0);
1010
+ for (const part of parts) {
1011
+ const at = `/proc/self/fd/${handle.fd}/${part}`;
1012
+ const next = await (0, promises_1.open)(at, flags).catch(async (e) => {
1013
+ if (create && isNotFound(e)) {
1014
+ await (0, promises_1.mkdir)(at).catch((made) => {
1015
+ if (made.code !== 'EEXIST') {
1016
+ throw made;
1017
+ }
1018
+ });
1019
+ return (0, promises_1.open)(at, flags);
1020
+ }
1021
+ throw e;
1022
+ });
1023
+ await handle.close();
1024
+ handle = next;
807
1025
  }
808
- throw e;
809
1026
  }
810
- for (const [, backup] of backups) {
811
- await (0, promises_1.rm)(backup, { force: true });
1027
+ catch (e) {
1028
+ await handle.close().catch(() => undefined);
1029
+ const code = e.code;
1030
+ if (code === 'ELOOP' || code === 'ENOTDIR' || code === 'ENOENT') {
1031
+ throw new SandboxFileError(409, `${parts.join('/')} is not a directory any more`);
1032
+ }
1033
+ throw e;
812
1034
  }
1035
+ const opened = handle;
1036
+ return { at: (name) => `/proc/self/fd/${opened.fd}/${name}`, release: () => opened.close() };
813
1037
  }
814
1038
  async sameParents(path) {
815
1039
  const parts = path.split('/');
@@ -841,13 +1065,57 @@ class HostSandboxFiles {
841
1065
  }
842
1066
  }
843
1067
  exports.HostSandboxFiles = HostSandboxFiles;
1068
+ function tooLarge(path, bytes) {
1069
+ if (bytes > exports.MAX_FILE_BYTES) {
1070
+ throw new SandboxFileError(413, `${path} would take ${bytes} bytes, more than ${exports.MAX_FILE_BYTES}`);
1071
+ }
1072
+ }
844
1073
  // The edits of one request, applied to what the files would hold after them, before any
845
1074
  // of it is written.
846
1075
  class EditBatch {
847
- constructor(files) {
1076
+ constructor(files, limits) {
848
1077
  this.files = files;
1078
+ this.limits = limits;
849
1079
  this.before = new Map();
850
1080
  this.after = new Map();
1081
+ // the bytes of the files read and made so far
1082
+ this.held = 0;
1083
+ // the bytes of text decoded, scanned and made so far
1084
+ this.worked = 0;
1085
+ this.budget = new sandbox_patch_1.PatchBudget(limits.compared);
1086
+ }
1087
+ hold(bytes) {
1088
+ if (this.held + bytes > this.limits.bytes) {
1089
+ throw new SandboxFileError(413, `the edits of this batch read and write more than ${this.limits.bytes} bytes, send them in smaller batches`);
1090
+ }
1091
+ const server = this.limits.server;
1092
+ if (bytes > 0 && server.held + bytes > server.max) {
1093
+ throw new SandboxFileError(503, 'the server is busy with other edits, send the batch again in a moment');
1094
+ }
1095
+ this.held += bytes;
1096
+ server.held += bytes;
1097
+ }
1098
+ free(bytes) {
1099
+ this.held -= bytes;
1100
+ this.limits.server.held -= bytes;
1101
+ }
1102
+ // What this batch holds no longer counts against the server.
1103
+ release() {
1104
+ this.limits.server.held -= this.held;
1105
+ this.held = 0;
1106
+ }
1107
+ work(bytes) {
1108
+ this.worked += bytes;
1109
+ if (this.worked > this.limits.work) {
1110
+ throw new SandboxFileError(413, `the edits of this batch process more than ${this.limits.work} bytes of text, send them in smaller batches`);
1111
+ }
1112
+ }
1113
+ // A file's content, counted once when it is read.
1114
+ async content(path, state) {
1115
+ if (!state.content) {
1116
+ this.hold(state.size);
1117
+ }
1118
+ return this.files.content(path, state);
851
1119
  }
852
1120
  async current(path) {
853
1121
  const changed = this.after.get(path);
@@ -862,7 +1130,9 @@ class EditBatch {
862
1130
  return original;
863
1131
  }
864
1132
  async text(path, state) {
865
- return decodeText(path, await this.files.content(path, state));
1133
+ const content = await this.content(path, state);
1134
+ this.work(content.length);
1135
+ return decodeText(path, content);
866
1136
  }
867
1137
  async file(path, verb) {
868
1138
  const state = await this.current(path);
@@ -882,7 +1152,7 @@ class EditBatch {
882
1152
  return;
883
1153
  }
884
1154
  const state = await this.current(path);
885
- const actual = state.kind === 'file' ? sha256(await this.files.content(path, state)) : undefined;
1155
+ const actual = state.kind === 'file' ? sha256(await this.content(path, state)) : undefined;
886
1156
  if (actual !== ifHash.toLowerCase()) {
887
1157
  throw new SandboxFileError(412, actual
888
1158
  ? `${path} changed since you read it (sha256 ${actual}), read it again`
@@ -911,9 +1181,11 @@ class EditBatch {
911
1181
  return state;
912
1182
  }
913
1183
  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
- }
1184
+ tooLarge(path, content.length);
1185
+ const replaced = this.after.get(path);
1186
+ // what an earlier edit of the batch made for the path is not kept
1187
+ this.free(replaced?.kind === 'file' ? replaced.content?.length ?? 0 : 0);
1188
+ this.hold(content.length);
917
1189
  this.after.set(path, { kind: 'file', size: content.length, exec, content });
918
1190
  }
919
1191
  async apply(op) {
@@ -931,17 +1203,28 @@ class EditBatch {
931
1203
  if (op.old_string === op.new_string) {
932
1204
  throw new SandboxFileError(422, 'old_string and new_string are the same, nothing would change');
933
1205
  }
1206
+ // the first places are kept to name their lines, the others counted
934
1207
  const at = [];
1208
+ let count = 0;
935
1209
  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);
1210
+ if (at.length < 10) {
1211
+ at.push(found);
1212
+ }
1213
+ count++;
937
1214
  }
938
- if (at.length === 0) {
1215
+ if (count === 0) {
939
1216
  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
1217
  }
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 });
1218
+ if (count > 1 && !op.replace_all) {
1219
+ const lines = at.map((offset) => text.slice(0, offset).split('\n').length);
1220
+ 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
1221
  }
1222
+ // the size of the result, before it is made
1223
+ const size = Buffer.byteLength(text, 'utf8') +
1224
+ count * (Buffer.byteLength(op.new_string, 'utf8') - Buffer.byteLength(op.old_string, 'utf8'));
1225
+ tooLarge(path, size);
1226
+ // the scan, and the result that is made
1227
+ this.work(text.length + size);
945
1228
  const replaced = op.replace_all
946
1229
  ? text.split(op.old_string).join(op.new_string)
947
1230
  : text.slice(0, at[0]) + op.new_string + text.slice(at[0] + op.old_string.length);
@@ -967,7 +1250,7 @@ class EditBatch {
967
1250
  else {
968
1251
  const to = checkPath(op.to);
969
1252
  const state = await this.file(path, 'move');
970
- const content = await this.files.content(path, state);
1253
+ const content = await this.content(path, state);
971
1254
  const target = await this.writable(to);
972
1255
  if (target.kind !== 'absent') {
973
1256
  throw new SandboxFileError(409, `${to} exists, delete it first`);
@@ -997,7 +1280,8 @@ class EditBatch {
997
1280
  throw new SandboxFileError(409, `${to} exists, the patch ${from ? 'moves a file onto' : 'adds'} it`);
998
1281
  }
999
1282
  }
1000
- const result = file.apply(content);
1283
+ const result = file.apply(content, this.budget);
1284
+ this.work(content.length + result.length);
1001
1285
  if (to === undefined) {
1002
1286
  if (from !== undefined && result !== '') {
1003
1287
  throw new sandbox_patch_1.PatchError(`${from}: the patch deletes it, but its lines are not what the file holds`);