hammerkit 2.0.0-next.9 → 2.1.0-next.1

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 (93) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/kept-claims.js +12 -9
  37. package/dist/kubernetes/network-gate.js +74 -11
  38. package/dist/kubernetes/network-policy.js +32 -10
  39. package/dist/kubernetes/remove-stale-items.js +15 -2
  40. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  41. package/dist/kubernetes/sandbox-runner.js +3 -4
  42. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  43. package/dist/kubernetes/transfer-tools.js +66 -0
  44. package/dist/kubernetes/volumes.js +52 -10
  45. package/dist/optimizer/check-key.js +7 -0
  46. package/dist/optimizer/check-keys.js +19 -5
  47. package/dist/optimizer/get-work-cache-stats.js +19 -7
  48. package/dist/optimizer/work-task-cache-description.js +42 -8
  49. package/dist/planner/image-build.js +172 -0
  50. package/dist/planner/utils/append-work-dependencies.js +14 -1
  51. package/dist/planner/utils/append-work-service.js +1 -1
  52. package/dist/planner/utils/append-work-task.js +51 -1
  53. package/dist/planner/utils/assert-item-paths.js +6 -7
  54. package/dist/planner/utils/dependency-outputs.js +18 -0
  55. package/dist/planner/work-runtime-docker.js +48 -50
  56. package/dist/planner/work-runtime-kubernetes.js +1 -0
  57. package/dist/planner/work-runtime-local.js +3 -7
  58. package/dist/planner/work-secret.js +135 -13
  59. package/dist/planner/work-tree.js +10 -0
  60. package/dist/remote/collect-bundle.js +9 -1
  61. package/dist/remote/host-config.js +49 -3
  62. package/dist/remote/location.js +5 -5
  63. package/dist/remote/remote-commands.js +12 -14
  64. package/dist/remote/remote-status.js +1 -1
  65. package/dist/remote/remote-work-commands.js +20 -8
  66. package/dist/schema/build-file-image-build-schema.js +77 -0
  67. package/dist/schema/build-file-task-schema.js +9 -2
  68. package/dist/schema/reference-parser.js +10 -1
  69. package/dist/schema/work-scope-parser.js +16 -1
  70. package/dist/secrets/secret-catalog.js +8 -1
  71. package/dist/server/borrowed-quota.js +216 -0
  72. package/dist/server/capacity.js +18 -6
  73. package/dist/server/dashboard.js +8 -5
  74. package/dist/server/executor.js +58 -35
  75. package/dist/server/kubernetes-backend.js +143 -32
  76. package/dist/server/overview.js +20 -2
  77. package/dist/server/plan.js +31 -3
  78. package/dist/server/policy.js +14 -7
  79. package/dist/server/repo-access.js +4 -3
  80. package/dist/server/run-environment.js +5 -2
  81. package/dist/server/run-plan.js +18 -6
  82. package/dist/server/run-retry.js +57 -0
  83. package/dist/server/run-source-environment.js +39 -0
  84. package/dist/server/run-worker.js +38 -9
  85. package/dist/server/runs.js +63 -7
  86. package/dist/server/sandbox-files.js +232 -39
  87. package/dist/server/server-config.js +83 -6
  88. package/dist/server/server.js +107 -12
  89. package/dist/server/service-runs.js +42 -4
  90. package/dist/utils/line-splitter.js +52 -0
  91. package/dist/utils/tar.js +51 -1
  92. package/package.json +1 -1
  93. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -5,6 +5,7 @@ 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");
@@ -193,6 +194,8 @@ function fileType(stats) {
193
194
  * without following a link, and on Linux the opened file is checked to be the one in the
194
195
  * sandbox, in case a task swapped a directory for a link in between.
195
196
  */
197
+ // the ignore files ripgrep reads in the folders above the path it searches
198
+ const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
196
199
  class HostSandboxFiles {
197
200
  constructor(root, git,
198
201
  // the environment of ripgrep: the variables runs see
@@ -301,12 +304,17 @@ class HostSandboxFiles {
301
304
  }
302
305
  }
303
306
  // The opened file is the one in the sandbox: a task may have swapped a directory above it
304
- // for a link after the names were checked. Linux names the file a descriptor is open on;
305
- // 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.
306
311
  async mustBeInside(handle, absolute, path) {
307
312
  let actual;
308
313
  if (process.platform === 'linux') {
309
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
+ }
310
318
  }
311
319
  if (actual === undefined) {
312
320
  const [opened, named] = await Promise.all([handle.stat(), (0, promises_1.lstat)(absolute)]);
@@ -534,7 +542,13 @@ class HostSandboxFiles {
534
542
  else {
535
543
  args.push('--count-matches', '--null');
536
544
  }
537
- 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);
538
552
  const result = { output_mode: mode, total: 0, exact: true, truncated: false, cursor: null };
539
553
  const files = [];
540
554
  const matches = [];
@@ -549,8 +563,11 @@ class HostSandboxFiles {
549
563
  };
550
564
  // the JSON of ripgrep names paths with the separator of the system, whatever --path-separator says
551
565
  const clean = (file) => {
552
- const path = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
553
- 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;
554
571
  };
555
572
  const onRecord = (record) => {
556
573
  if (mode === 'files_with_matches') {
@@ -577,7 +594,16 @@ class HostSandboxFiles {
577
594
  ...(message.type === 'context' ? { context: true } : {}),
578
595
  })));
579
596
  };
580
- 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;
581
607
  if (code === 2 && total === 0 && !stopped) {
582
608
  throw new SandboxFileError(400, stderr.trim() || 'ripgrep failed');
583
609
  }
@@ -596,9 +622,93 @@ class HostSandboxFiles {
596
622
  }
597
623
  return result;
598
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
+ }
599
709
  // Runs ripgrep in the files and hands each record of its output to `onRecord`, which
600
710
  // answers whether to read on.
601
- ripgrep(args, separator, onRecord) {
711
+ ripgrep(args, separator, onRecord, target = { cwd: this.root }) {
602
712
  const env = {};
603
713
  for (const [key, value] of Object.entries(this.env)) {
604
714
  if (value !== undefined && !key.toUpperCase().startsWith('RIPGREP_')) {
@@ -607,11 +717,20 @@ class HostSandboxFiles {
607
717
  }
608
718
  return new Promise((resolve, reject) => {
609
719
  const child = (0, child_process_1.spawn)('rg', args, {
610
- cwd: this.root,
720
+ cwd: target.cwd,
611
721
  env,
612
- stdio: ['ignore', 'pipe', 'pipe'],
722
+ stdio: ['pipe', 'pipe', 'pipe'],
613
723
  signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
614
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
+ }
615
734
  let stopped = false;
616
735
  let buffered = '';
617
736
  let stderr = '';
@@ -797,50 +916,124 @@ class HostSandboxFiles {
797
916
  return state.content;
798
917
  }
799
918
  // Writes the changes: what a path held is moved aside first, and put back when a later
800
- // 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.
801
921
  async write(changes) {
802
922
  const backups = [];
803
923
  const written = [];
804
- // the directories above every path are still the ones the edits were planned in
805
- for (const [path] of changes) {
806
- await this.sameParents(path);
807
- }
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
+ };
808
934
  try {
809
- for (const [path, before] of changes) {
810
- if (before.kind === 'file' || before.kind === 'link') {
811
- const absolute = this.absolute(path);
812
- const backup = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`);
813
- await (0, promises_1.rename)(absolute, backup);
814
- 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]);
815
969
  }
816
970
  }
817
- for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
818
- if (after.kind !== 'file') {
819
- continue;
971
+ catch (e) {
972
+ for (const [folder, name] of written.reverse()) {
973
+ await (0, promises_1.rm)(folder.at(name), { force: true });
820
974
  }
975
+ for (const [folder, name, backup] of backups.reverse()) {
976
+ await (0, promises_1.rename)(folder.at(backup), folder.at(name)).catch(() => undefined);
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) {
821
999
  await this.makeParents(path);
822
- const absolute = this.absolute(path);
823
- const temporary = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`);
824
- const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
825
- const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
826
- await (0, promises_1.writeFile)(temporary, after.content ?? Buffer.alloc(0), { flag: 'wx', mode });
827
- await (0, promises_1.chmod)(temporary, mode);
828
- await (0, promises_1.rename)(temporary, absolute);
829
- written.push(absolute);
830
1000
  }
1001
+ const absolute = (0, path_1.dirname)(this.absolute(path));
1002
+ return { at: (name) => (0, path_1.join)(absolute, name), release: async () => undefined };
831
1003
  }
832
- catch (e) {
833
- for (const absolute of written.reverse()) {
834
- 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`);
835
1008
  }
836
- for (const [absolute, backup] of backups.reverse()) {
837
- 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;
838
1025
  }
839
- throw e;
840
1026
  }
841
- for (const [, backup] of backups) {
842
- 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;
843
1034
  }
1035
+ const opened = handle;
1036
+ return { at: (name) => `/proc/self/fd/${opened.fd}/${name}`, release: () => opened.close() };
844
1037
  }
845
1038
  async sameParents(path) {
846
1039
  const parts = path.split('/');
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.detectPlatform = exports.getSecretCatalog = exports.readServerConfig = exports.getServerAccounts = exports.getSandboxRuntimes = exports.serverConfigSchema = exports.sourceSchema = exports.entitlementSchema = exports.endpointGrantSchema = exports.endpointLevelSchema = exports.sandboxGrantSchema = exports.sandboxBranchTypeSchema = exports.buildsLevelSchema = exports.accountLevelSchema = exports.getMaxVolumeSize = exports.DEFAULT_MAX_VOLUME_SIZE = exports.DEFAULT_DENIED_EGRESS = exports.kubernetesPoolSchema = exports.accountSchema = exports.issuerSchema = exports.serverPlatformSchema = void 0;
3
+ exports.getMaxQuotaIssues = exports.detectPlatform = exports.getSecretCatalog = exports.readServerConfig = exports.getServerAccounts = exports.getSandboxRuntimes = exports.serverConfigSchema = exports.sourceSchema = exports.entitlementSchema = exports.endpointGrantSchema = exports.endpointLevelSchema = exports.sandboxGrantSchema = exports.sandboxBranchTypeSchema = exports.buildsLevelSchema = exports.accountLevelSchema = exports.getMaxVolumeSize = exports.DEFAULT_MAX_VOLUME_SIZE = exports.DEFAULT_DENIED_EGRESS = exports.kubernetesPoolSchema = exports.accountSchema = exports.issuerSchema = exports.serverPlatformSchema = void 0;
4
+ const run_source_envs_1 = require("../environment/run-source-envs");
4
5
  const net_1 = require("net");
5
6
  const zod_1 = require("zod");
6
7
  const yaml_1 = require("yaml");
7
8
  const log_1 = require("../log");
8
9
  const units_1 = require("../utils/units");
10
+ const borrowed_quota_1 = require("./borrowed-quota");
9
11
  const version_1 = require("../version");
10
12
  const network_schema_1 = require("../schema/network-schema");
11
13
  const capabilities_schema_1 = require("../schema/capabilities-schema");
@@ -274,8 +276,12 @@ const kubernetesBackendSchema = zod_1.z
274
276
  })
275
277
  .strict())
276
278
  .default({}),
277
- // the ResourceQuota of every caller's namespace, such as `requests.cpu: '8'`
279
+ // the ResourceQuota of every caller's namespace, such as `requests.cpu: '8'`: what each
280
+ // caller is promised
278
281
  quota: zod_1.z.record(zod_1.z.union([zod_1.z.string().min(1), zod_1.z.number()]).transform(String)).optional(),
282
+ // how far the CPU and memory of a caller's quota rise above `quota` while the nodes of the
283
+ // pools have room no other caller is promised (see BorrowedQuotas); never when left out
284
+ maxQuota: zod_1.z.record(zod_1.z.union([zod_1.z.string().min(1), zod_1.z.number()]).transform(String)).optional(),
279
285
  // what a container without `resources` requests (a LimitRange), so it is
280
286
  // admitted under a quota that limits compute
281
287
  defaultResources: zod_1.z
@@ -298,6 +304,15 @@ const kubernetesBackendSchema = zod_1.z
298
304
  // build file's environment does: hammerkit can't tell from the API, and without it a
299
305
  // task with a limited network fails rather than runs open
300
306
  networkPolicy: zod_1.z.literal('enforced').optional(),
307
+ // what the pods with an open network wait to no longer reach before they start, under
308
+ // `networkPolicy: enforced`: an address and port `deniedEgress` covers that answers without
309
+ // the policy (the metadata endpoint by default), or `false` for no wait
310
+ openNetworkGate: zod_1.z
311
+ .union([
312
+ zod_1.z.literal(false),
313
+ zod_1.z.object({ host: zod_1.z.string().ip({ version: 'v4' }), port: zod_1.z.number().int().min(1).max(65535) }).strict(),
314
+ ])
315
+ .optional(),
301
316
  // `runtimeClass` is a RuntimeClass of a sandbox, such as gvisor; the pods of tasks that
302
317
  // add capabilities run in it
303
318
  capabilities: zod_1.z.object({ allow: capabilitiesAllowSchema, runtimeClass: kubernetesNameSchema }).strict().optional(),
@@ -512,6 +527,15 @@ exports.serverConfigSchema = zod_1.z
512
527
  set: zod_1.z.record(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), zod_1.z.string()).default({}),
513
528
  })
514
529
  .strict()
530
+ // what a run is from is the run's: an operator's value would pass for it
531
+ .superRefine((env, ctx) => {
532
+ for (const name of [...env.allow, ...Object.keys(env.set)].filter(run_source_envs_1.isRunSourceEnv)) {
533
+ ctx.addIssue({
534
+ code: zod_1.z.ZodIssueCode.custom,
535
+ message: `${name} is set by the server for each run, from what the run is from`,
536
+ });
537
+ }
538
+ })
515
539
  .default({}),
516
540
  // the most any task or service of a run reaches besides its needs: none, open
517
541
  // or { allow: [hosts] }. A version that asks for more is refused at publish.
@@ -575,8 +599,9 @@ exports.serverConfigSchema = zod_1.z
575
599
  // the most open network a task or service of a run on a sandbox gets, written as
576
600
  // a task's `network`: only the services it needs by default
577
601
  network: network_schema_1.networkSchema.default('none'),
578
- // the variables of `runs.env.allow` an `env:` secret of a run on a sandbox may
579
- // read: none by default, a sandbox holds code nobody reviewed
602
+ // the variables of runs (`runs.env.allow` and `runs.env.set`) an `env:` secret and the
603
+ // `envs` of a build file of a run on a sandbox may read, besides PATH, HOME and CI:
604
+ // none by default, a sandbox holds code nobody reviewed
580
605
  env: zod_1.z
581
606
  .object({ allow: zod_1.z.array(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_()]*$/)).default([]) })
582
607
  .strict()
@@ -769,11 +794,11 @@ exports.serverConfigSchema = zod_1.z
769
794
  });
770
795
  }
771
796
  config.sandboxes.env.allow.forEach((name, index) => {
772
- if (!config.runs.env.allow.includes(name)) {
797
+ if (!config.runs.env.allow.includes(name) && !Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
773
798
  ctx.addIssue({
774
799
  code: zod_1.z.ZodIssueCode.custom,
775
800
  path: ['sandboxes', 'env', 'allow', index],
776
- message: `${name} is not in runs.env.allow, no run can read it`,
801
+ message: `${name} is not in runs.env.allow or runs.env.set, no run can read it`,
777
802
  });
778
803
  }
779
804
  });
@@ -834,6 +859,13 @@ exports.serverConfigSchema = zod_1.z
834
859
  }
835
860
  }
836
861
  }
862
+ for (const issue of getMaxQuotaIssues(backend.quota, backend.maxQuota)) {
863
+ ctx.addIssue({
864
+ code: zod_1.z.ZodIssueCode.custom,
865
+ path: ['backend', 'maxQuota', ...issue.path],
866
+ message: issue.message,
867
+ });
868
+ }
837
869
  if (backend.maxVolumeSize && (0, units_1.parseSize)(backend.volumeSize) > (0, units_1.parseSize)(backend.maxVolumeSize)) {
838
870
  ctx.addIssue({
839
871
  code: zod_1.z.ZodIssueCode.custom,
@@ -1051,4 +1083,49 @@ function detectPlatform() {
1051
1083
  return { os, arch };
1052
1084
  }
1053
1085
  exports.detectPlatform = detectPlatform;
1086
+ // What is wrong with `backend.maxQuota`: a key a caller may borrow (CPU and memory, see
1087
+ // BORROWED_RESOURCES) that `quota` has too, no less than there, and a limit only with the
1088
+ // requests of its resource, which say how much room the caller takes of the nodes.
1089
+ function getMaxQuotaIssues(quota, maxQuota) {
1090
+ if (!maxQuota) {
1091
+ return [];
1092
+ }
1093
+ if (!quota) {
1094
+ return [{ path: [], message: 'a caller borrows above backend.quota, which is not set' }];
1095
+ }
1096
+ const issues = [];
1097
+ for (const [key, value] of Object.entries(maxQuota)) {
1098
+ const resource = (0, borrowed_quota_1.getBorrowedResource)(key);
1099
+ if (!resource) {
1100
+ issues.push({
1101
+ path: [key],
1102
+ message: `${key} can't be borrowed, only ${Object.values(borrowed_quota_1.BORROWED_RESOURCES)
1103
+ .flatMap((keys) => [...keys.requests, ...keys.limits])
1104
+ .join(', ')}`,
1105
+ });
1106
+ continue;
1107
+ }
1108
+ if (quota[key] === undefined) {
1109
+ issues.push({ path: [key], message: `${key} is not in backend.quota, the share it rises from` });
1110
+ continue;
1111
+ }
1112
+ const max = (0, units_1.parseQuantity)(value);
1113
+ const share = (0, units_1.parseQuantity)(quota[key]);
1114
+ if (max === undefined) {
1115
+ issues.push({ path: [key], message: `expected a quantity such as 8, 500m or 16Gi` });
1116
+ }
1117
+ else if (share !== undefined && max < share) {
1118
+ issues.push({ path: [key], message: `${value} is less than ${quota[key]} of backend.quota` });
1119
+ }
1120
+ const requests = borrowed_quota_1.BORROWED_RESOURCES[resource].requests;
1121
+ if (!requests.includes(key) && !requests.some((other) => maxQuota[other] !== undefined)) {
1122
+ issues.push({
1123
+ path: [key],
1124
+ message: `${key} rises with the requests of ${resource}, add ${requests[0]} to backend.maxQuota`,
1125
+ });
1126
+ }
1127
+ }
1128
+ return issues;
1129
+ }
1130
+ exports.getMaxQuotaIssues = getMaxQuotaIssues;
1054
1131
  //# sourceMappingURL=server-config.js.map