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
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serviceRollouts = exports.ServiceRollouts = void 0;
4
+ const apply_1 = require("./apply");
5
+ const log_1 = require("../log");
6
+ /**
7
+ * The Deployments an execution of a service run replaced or made (rollOut). A move whose
8
+ * services do not all get up leaves the run where it was: the execution puts every one of
9
+ * them back as it found it and removes the ones it made, so no service serves the commit the
10
+ * run did not get to, and nothing of it takes the quota of the namespace.
11
+ */
12
+ class ServiceRollouts {
13
+ constructor() {
14
+ this.rolled = new Map();
15
+ }
16
+ // before the Deployment is replaced or made; the first time counts
17
+ add(namespace, name, previous, restore) {
18
+ const key = `${namespace}/${name}`;
19
+ if (!this.rolled.has(key)) {
20
+ this.rolled.set(key, {
21
+ namespace,
22
+ name,
23
+ ...(previous?.spec ? { previous } : {}),
24
+ ...(restore ? { restore } : {}),
25
+ });
26
+ }
27
+ }
28
+ get size() {
29
+ return this.rolled.size;
30
+ }
31
+ async undo(instance, say) {
32
+ const rolled = [...this.rolled.values()];
33
+ this.rolled.clear();
34
+ for (const { namespace, name, previous, restore } of rolled) {
35
+ try {
36
+ if (previous?.spec && restore) {
37
+ say(`putting the files of ${name} back as they were`);
38
+ await restore();
39
+ }
40
+ if (previous?.spec) {
41
+ say(`putting ${name} back as it was`);
42
+ await (0, apply_1.replaceDeployment)(instance, {
43
+ kind: 'Deployment',
44
+ apiVersion: 'apps/v1',
45
+ metadata: {
46
+ namespace,
47
+ name,
48
+ labels: previous.metadata?.labels,
49
+ annotations: previous.metadata?.annotations,
50
+ },
51
+ spec: previous.spec,
52
+ });
53
+ }
54
+ else {
55
+ say(`removing ${name}, which it made`);
56
+ await instance.appsApi
57
+ .deleteNamespacedDeployment({ name, namespace, propagationPolicy: 'Background' })
58
+ .catch((e) => {
59
+ if ((0, apply_1.statusCodeOf)(e) !== 404) {
60
+ throw e;
61
+ }
62
+ });
63
+ }
64
+ }
65
+ catch (e) {
66
+ say(`${name} could not be put back: ${(0, log_1.getErrorMessage)(e)}`);
67
+ }
68
+ }
69
+ }
70
+ }
71
+ exports.ServiceRollouts = ServiceRollouts;
72
+ // the rollouts of this process: a worker executes one run
73
+ exports.serviceRollouts = new ServiceRollouts();
74
+ //# sourceMappingURL=service-rollouts.js.map
@@ -1,16 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.storeKubernetesData = void 0;
4
+ const path_1 = require("path");
4
5
  const log_1 = require("../log");
5
6
  const event_cache_1 = require("../executer/event-cache");
6
7
  const volumes_1 = require("./volumes");
7
8
  const ensure_persistent_data_1 = require("./ensure-persistent-data");
8
- async function storeKubernetesData(work, kubernetes, instance, environment, path) {
9
- const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes);
10
- await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'read', async (name) => {
9
+ async function storeKubernetesData(work, kubernetes, instance, environment, path,
10
+ // the state the outputs are of: on a service run, they are in its folder (see
11
+ // getStateFilesDir)
12
+ stateKey) {
13
+ const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes, stateKey);
14
+ // a run stopped while the pod waits for room under the quota
15
+ const { signal } = environment.abortCtrl;
16
+ // an output that is a file is mounted as one: its archive holds it by its name, as on Docker
17
+ const files = new Set(work.data.type === 'container-task'
18
+ ? work.data.generates
19
+ .filter((generate) => generate.isFile && !generate.inherited)
20
+ .map((generate) => generate.path)
21
+ : []);
22
+ await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'read', signal, async (name) => {
11
23
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path)) {
12
24
  const writerStream = environment.file.createWriteStream(generatedArchive.filename);
13
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', ['tar', 'zcf', '-', '-C', generatedArchive.path, '.'], writerStream, process.stderr, null, false, (status) => {
25
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', files.has(generatedArchive.path)
26
+ ? ['tar', 'zcf', '-', '-C', path_1.posix.dirname(generatedArchive.path), path_1.posix.basename(generatedArchive.path)]
27
+ : ['tar', 'zcf', '-', '-C', generatedArchive.path, '.'], writerStream, process.stderr, null, false, (status) => {
14
28
  work.status.write('debug', `archive ${generatedArchive.path} of ${name}: ${status}`);
15
29
  writerStream.close();
16
30
  });
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSandboxAffinity = exports.SANDBOX_LABEL = exports.getWorkspacePodSpec = exports.appendVolume = exports.getKubernetesPersistence = exports.getVolumeName = void 0;
3
+ exports.getItemFilesDir = exports.isLiveService = exports.LIVE_FILES_DIR = exports.getStateFilesDir = exports.STATE_FILES_PREFIX = exports.getSandboxAffinity = exports.SANDBOX_LABEL = exports.getClaimMountLabel = exports.getClaimPodSpec = exports.getWorkspacePodSpec = exports.appendVolume = exports.getKubernetesPersistence = exports.getVolumeName = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
+ const crypto_1 = require("crypto");
6
7
  const kept_claims_1 = require("./kept-claims");
7
8
  const claim_layout_1 = require("./claim-layout");
8
9
  function getVolumeName(service, kubernetes) {
@@ -41,7 +42,15 @@ function appendWorkspaceMount(workspace, persistence, containerPath, localPath,
41
42
  });
42
43
  return true;
43
44
  }
44
- async function getKubernetesPersistence(work, kubernetes) {
45
+ async function getKubernetesPersistence(work, kubernetes,
46
+ // the state the work runs at, on a service run (see getStateFilesDir); what it inherits is
47
+ // at the state its own work item completed at
48
+ stateKey) {
49
+ const dirOf = (item) => kubernetes.server?.serviceRun ? getItemFilesDir(item, item === work ? stateKey : undefined) : undefined;
50
+ const own = dirOf(work);
51
+ // a service that watches its files mounts them from the folder they are synced into, and
52
+ // takes them into the folder of their state (see syncLiveFiles)
53
+ const mounted = own && isLiveService(work, kubernetes) ? exports.LIVE_FILES_DIR : own;
45
54
  const persistence = {
46
55
  volumes: [],
47
56
  sizes: {},
@@ -50,6 +59,7 @@ async function getKubernetesPersistence(work, kubernetes) {
50
59
  sources: [],
51
60
  mounts: [],
52
61
  initCommands: [],
62
+ files: [],
53
63
  };
54
64
  const workspace = kubernetes.server?.workspace;
55
65
  for (const mount of work.data.mounts) {
@@ -57,34 +67,67 @@ async function getKubernetesPersistence(work, kubernetes) {
57
67
  appendWorkspaceMount(workspace, persistence, mount.containerPath, mount.localPath, mount.isFile, mount.readOnly)) {
58
68
  continue;
59
69
  }
60
- appendVolume(work, persistence, mount.containerPath, mount.localPath, mount.isFile, true, kubernetes);
70
+ appendVolume(work, persistence, mount.containerPath, mount.localPath, mount.isFile, true, kubernetes, mounted, own);
61
71
  }
72
+ // its deps' src too, uploaded into its own claim: a container task sees them as it does on
73
+ // docker (a tsc -b of a project that references another reads the other's tsconfig)
62
74
  for (const src of work.data.src) {
63
- if (src.inherited) {
64
- continue;
65
- }
66
75
  if (workspace &&
67
76
  appendWorkspaceMount(workspace, persistence, src.absolutePath, src.absolutePath, src.isFile, false)) {
68
77
  continue;
69
78
  }
70
- appendVolume(work, persistence, src.absolutePath, src.absolutePath, src.isFile, true, kubernetes); // TODO matcher
79
+ appendVolume(work, persistence, src.absolutePath, src.absolutePath, src.isFile, true, kubernetes, mounted, own, src.inherited ? (0, claim_layout_1.getInheritedSourceSubPath)(work, src.absolutePath) : undefined); // TODO matcher
71
80
  }
72
81
  if (work.data.type === 'container-task') {
73
82
  for (const generate of work.data.generates) {
74
- appendVolume(generate.inherited ?? work, persistence, generate.path, null, false, !!generate.inherited, kubernetes);
83
+ const subPath = appendVolume(generate.inherited ?? work, persistence, generate.path, null, generate.isFile, !!generate.inherited, kubernetes, dirOf(generate.inherited ?? work));
84
+ if (generate.isFile && !generate.inherited) {
85
+ persistence.files.push(subPath);
86
+ }
75
87
  }
88
+ persistence.files.push(...getNestedMountPlaces(persistence, getVolumeName(work, kubernetes)));
76
89
  }
77
90
  else {
78
91
  for (const volume of work.data.volumes) {
79
- appendVolume(volume.inherited ?? work, persistence, volume.containerPath, null, false, !!volume.inherited || volume.readOnly, kubernetes);
92
+ appendVolume(volume.inherited ?? work, persistence, volume.containerPath, null, false, !!volume.inherited || volume.readOnly, kubernetes,
93
+ // the data of a service stays where it is, the outputs of its deps are by their state
94
+ volume.inherited ? dirOf(volume.inherited) : undefined);
80
95
  }
81
96
  }
82
97
  return persistence;
83
98
  }
84
99
  exports.getKubernetesPersistence = getKubernetesPersistence;
85
- function appendVolume(sourceWork, persistence, containerPath, localPath, isFile, readOnly, kubernetes) {
100
+ // The places in the claim `claim` of the paths mounted inside a folder that is mounted read
101
+ // only from it: an output of a task inside a folder of its src (pkg/coverage/lcov.info with a
102
+ // src pkg). The container runtime makes the place of a mount where it isn't there, which it
103
+ // can't in a folder mounted read only, and the pod fails to start (exit 128). Each is in the
104
+ // claim's folder of the read-only path, a folder ending in `/`, or a file.
105
+ function getNestedMountPlaces(persistence, claim) {
106
+ const own = persistence.mounts.filter((m) => !m.workspace);
107
+ const folders = own.filter((m) => m.mount.name === claim && m.mount.readOnly && m.cwd === m.mount.mountPath && m.mount.subPath);
108
+ const places = [];
109
+ for (const mount of own) {
110
+ const parent = folders
111
+ .filter((folder) => folder !== mount && mount.mount.mountPath.startsWith(`${folder.mount.mountPath}/`))
112
+ .sort((a, b) => b.mount.mountPath.length - a.mount.mountPath.length)[0];
113
+ if (!parent) {
114
+ continue;
115
+ }
116
+ const place = `${parent.mount.subPath}/${mount.mount.mountPath.slice(parent.mount.mountPath.length + 1)}`;
117
+ places.push(mount.cwd === mount.mount.mountPath ? `${place}/` : place);
118
+ }
119
+ return places;
120
+ }
121
+ function appendVolume(sourceWork, persistence, containerPath, localPath, isFile, readOnly, kubernetes,
122
+ // the folder of the state of `sourceWork` the path is in, see getStateFilesDir
123
+ stateDir,
124
+ // the folder its upload goes to, when it is not the one the path is mounted from (a
125
+ // service that watches its files, see syncLiveFiles)
126
+ uploadDir = stateDir,
127
+ // where it goes in the claim, when not where getClaimSubPath puts it
128
+ claimPath = (0, claim_layout_1.getClaimSubPath)(sourceWork, containerPath)) {
86
129
  const volumeName = getVolumeName(sourceWork, kubernetes);
87
- const subPath = (0, claim_layout_1.getClaimSubPath)(sourceWork, containerPath);
130
+ const subPath = (stateDir ? `${stateDir}/` : '') + claimPath;
88
131
  const existVolume = persistence.volumes.some((v) => v.name === volumeName);
89
132
  if (!existVolume) {
90
133
  persistence.volumes.push({
@@ -113,10 +156,11 @@ function appendVolume(sourceWork, persistence, containerPath, localPath, isFile,
113
156
  localPath: localPath,
114
157
  matcher: () => true, // TODO
115
158
  containerPath,
116
- subPath,
159
+ subPath: (uploadDir ? `${uploadDir}/` : '') + claimPath,
117
160
  stateKey: '', // TODO
118
161
  });
119
162
  }
163
+ return subPath;
120
164
  }
121
165
  exports.appendVolume = appendVolume;
122
166
  /**
@@ -128,6 +172,9 @@ exports.appendVolume = appendVolume;
128
172
  */
129
173
  function getWorkspacePodSpec(kubernetes, persistence, task) {
130
174
  const workspace = kubernetes.server?.workspace;
175
+ if (kubernetes.server?.serviceRun && !workspace) {
176
+ return getClaimPodSpec(persistence.volumes ?? []);
177
+ }
131
178
  if (!workspace || persistence.workspace.length === 0) {
132
179
  return { labels: {} };
133
180
  }
@@ -141,6 +188,41 @@ function getWorkspacePodSpec(kubernetes, persistence, task) {
141
188
  };
142
189
  }
143
190
  exports.getWorkspacePodSpec = getWorkspacePodSpec;
191
+ /**
192
+ * A pod of a service run that mounts claims: labelled by each of them, and made to go where a
193
+ * pod runs that mounts all of them. A run that moves to another commit starts a new pod of a
194
+ * service, a Job of a changed task or an upload while the pods of the commit before still
195
+ * mount the same claims, which a cloud disk attaches to one node at a time: a pod on another
196
+ * node would wait for the disk until its deadline. Required, as one term: while no pod mounts
197
+ * all of them (the first one, or after the run slept), the scheduler lets the pod go anywhere,
198
+ * because it matches the term itself, so a Deployment that keeps the term is never held back
199
+ * by it. Mounting all of them is what holds the disks on one node.
200
+ */
201
+ function getClaimPodSpec(volumes) {
202
+ const keys = [
203
+ ...new Set(volumes.flatMap((volume) => volume.persistentVolumeClaim ? [getClaimMountLabel(volume.persistentVolumeClaim.claimName)] : [])),
204
+ ].sort();
205
+ if (keys.length === 0) {
206
+ return { labels: {} };
207
+ }
208
+ const labels = Object.fromEntries(keys.map((key) => [key, 'mounted']));
209
+ return {
210
+ labels,
211
+ affinity: {
212
+ podAffinity: {
213
+ requiredDuringSchedulingIgnoredDuringExecution: [
214
+ { labelSelector: { matchLabels: labels }, topologyKey: 'kubernetes.io/hostname' },
215
+ ],
216
+ },
217
+ },
218
+ };
219
+ }
220
+ exports.getClaimPodSpec = getClaimPodSpec;
221
+ // a claim name is longer than a label name may be: its hash
222
+ function getClaimMountLabel(claimName) {
223
+ return `claim.hammerkit.dev/${(0, crypto_1.createHash)('sha256').update(claimName).digest('hex').slice(0, 16)}`;
224
+ }
225
+ exports.getClaimMountLabel = getClaimMountLabel;
144
226
  // the label of the pods that mount the claim of a sandbox
145
227
  exports.SANDBOX_LABEL = 'hammerkit.dev/sandbox';
146
228
  function getSandboxAffinity(label) {
@@ -153,4 +235,34 @@ function getSandboxAffinity(label) {
153
235
  };
154
236
  }
155
237
  exports.getSandboxAffinity = getSandboxAffinity;
238
+ // The folder of a service run's claim that holds the files of one state of a work item: the
239
+ // src and mounts it uploads, and the outputs of a task. A run that moves to another commit
240
+ // uploads and builds the files of the new state into a folder of their own, so the pods of
241
+ // the commit before keep the files and outputs they started with until the new ones are up,
242
+ // and a Deployment that is put back finds them again. The volumes of a service hold its data,
243
+ // which stays where it is.
244
+ exports.STATE_FILES_PREFIX = '.hammerkit-files-';
245
+ function getStateFilesDir(stateKey) {
246
+ return `${exports.STATE_FILES_PREFIX}${(0, crypto_1.createHash)('sha256').update(stateKey).digest('hex').slice(0, 16)}`;
247
+ }
248
+ exports.getStateFilesDir = getStateFilesDir;
249
+ // The folder of the claim of a service of a service run that watches its own files
250
+ // (`continuous`), which its pod mounts its `src` and `mounts` from. The files of each state
251
+ // are uploaded into the folder of that state, and synced into this one from there: the pod
252
+ // stays, and the service sees the files of the new commit (syncLiveFiles).
253
+ exports.LIVE_FILES_DIR = `${exports.STATE_FILES_PREFIX}live`;
254
+ function isLiveService(work, kubernetes) {
255
+ return (!!kubernetes.server?.serviceRun &&
256
+ !kubernetes.server.workspace &&
257
+ work.data.type === 'container-service' &&
258
+ work.data.continuous === true);
259
+ }
260
+ exports.isLiveService = isLiveService;
261
+ // The folder of the state of `item`: `stateKey`, or the one it completed at in this run
262
+ function getItemFilesDir(item, stateKey) {
263
+ const key = stateKey ??
264
+ item.state?.current.stateKey;
265
+ return key ? getStateFilesDir(key) : undefined;
266
+ }
267
+ exports.getItemFilesDir = getItemFilesDir;
156
268
  //# sourceMappingURL=volumes.js.map
package/dist/main.js CHANGED
@@ -8,6 +8,7 @@ const redact_1 = require("./utils/redact");
8
8
  const empty_writable_1 = require("./utils/empty-writable");
9
9
  const run_program_1 = require("./run-program");
10
10
  const abort_on_signals_1 = require("./utils/abort-on-signals");
11
+ const terminal_prompt_1 = require("./utils/terminal-prompt");
11
12
  const abortCtrl = new AbortController();
12
13
  (0, abort_on_signals_1.abortOnSignals)(process, abortCtrl);
13
14
  let settled = false;
@@ -32,6 +33,7 @@ const secrets = (0, redact_1.createSecretRegistry)();
32
33
  stdout: process.stdout,
33
34
  stderr: process.stderr,
34
35
  stdoutColumns: process.stdout.columns,
36
+ prompt: (0, terminal_prompt_1.getTerminalPrompt)(process.env, abortCtrl.signal),
35
37
  }, process.argv, false).then(() => {
36
38
  settled = true;
37
39
  }, () => {
@@ -1,16 +1,60 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateChecksum = void 0;
3
+ exports.calculateChecksum = exports.racyWindow = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ // The checksums a process computed, by the file context and path: every task of a run hashes
6
+ // the sources of the tasks it depends on too, so most files are asked for many times
7
+ const known = new WeakMap();
8
+ // A file written again soon after it was hashed, with the same size, keeps its times on a
9
+ // file system whose timestamps are coarser than that: a checksum of a file changed within
10
+ // the window before it was hashed is not kept. Whole seconds are taken for a file system
11
+ // that has no more (FAT, ext3, HFS+), else the window is short.
12
+ function racyWindow(stats) {
13
+ return stats.lastModified % 1000 === 0 && stats.identity.changed % 1000 === 0 ? 2000 : 50;
14
+ }
15
+ exports.racyWindow = racyWindow;
5
16
  // Hashes the raw bytes: decoding to text first would map every invalid UTF-8
6
17
  // sequence to U+FFFD, so two different binary files could share a checksum.
7
- // For UTF-8 text the result is unchanged.
8
- async function calculateChecksum(environment, path) {
9
- const hash = (0, crypto_1.createHash)('sha1');
18
+ // For UTF-8 text the result is unchanged. sha256, which nobody can make two files share:
19
+ // a cache hit is also what a verified check counts (check-key.ts).
20
+ //
21
+ // With the `stats` of the file, the checksum is reused while the file stays the same file:
22
+ // the same modification and change time, size and inode. A write changes its times, a
23
+ // replacement (a checkout, a rename over it) its inode.
24
+ async function calculateChecksum(environment, path, stats) {
25
+ const identity = stats?.identity;
26
+ if (!identity) {
27
+ return hashFile(environment, path);
28
+ }
29
+ let files = known.get(environment.file);
30
+ if (!files) {
31
+ files = new Map();
32
+ known.set(environment.file, files);
33
+ }
34
+ const cached = files.get(path);
35
+ if (cached &&
36
+ cached.lastModified === stats.lastModified &&
37
+ cached.size === identity.size &&
38
+ cached.changed === identity.changed &&
39
+ cached.inode === identity.inode) {
40
+ return cached.checksum;
41
+ }
42
+ const hashedAt = Date.now();
43
+ const checksum = await hashFile(environment, path);
44
+ if (hashedAt - Math.max(stats.lastModified, identity.changed) > racyWindow({ ...stats, identity })) {
45
+ files.set(path, { lastModified: stats.lastModified, ...identity, checksum });
46
+ }
47
+ else {
48
+ files.delete(path);
49
+ }
50
+ return checksum;
51
+ }
52
+ exports.calculateChecksum = calculateChecksum;
53
+ async function hashFile(environment, path) {
54
+ const hash = (0, crypto_1.createHash)('sha256');
10
55
  for await (const chunk of environment.file.readStream(path)) {
11
56
  hash.update(chunk);
12
57
  }
13
58
  return hash.digest('hex');
14
59
  }
15
- exports.calculateChecksum = calculateChecksum;
16
60
  //# sourceMappingURL=calculate-checksum.js.map
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCheckKey = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const state_key_1 = require("../executer/scheduler/state-key");
6
+ const get_work_cache_stats_1 = require("./get-work-cache-stats");
7
+ const work_task_cache_description_1 = require("./work-task-cache-description");
8
+ /**
9
+ * What a passed check is recorded under, and what `remote verify` looks it up by: the
10
+ * inputs of the task's cache key, so a cached result counts for the same key it was
11
+ * stored under. Its definition (the services it needs included), the files of its `src`,
12
+ * the keys of its dependencies, and the sources of the services it needs and of the tasks
13
+ * they depend on.
14
+ *
15
+ * It is computed on a checkout before anything ran in it, on both ends, so it also covers
16
+ * the files a commit holds where a dependency generates (the cache leaves those out, as
17
+ * they change once the dependency ran), and it leaves out `.git`, which is no file of a
18
+ * commit. Two checkouts of the same files give the same key wherever they are.
19
+ * Null for a task that can not be proven up to date (no `src` of its own, or none that
20
+ * matches a file, here or in a dependency): its result says nothing about any files.
21
+ */
22
+ async function getCheckKey(item, environment, memo = new Map(), path = new Set()) {
23
+ return memoized(memo, path, `task\0${item.id()}`, (inner) => computeCheckKey(item, environment, memo, inner));
24
+ }
25
+ exports.getCheckKey = getCheckKey;
26
+ async function computeCheckKey(item, environment, memo, path) {
27
+ const { stats, unmatched } = await (0, get_work_cache_stats_1.getWorkItemCheckoutStats)(item, environment);
28
+ if (!(0, state_key_1.isOwnProvable)(item, unmatched)) {
29
+ return null;
30
+ }
31
+ const inputs = await getInputKeys(item, environment, memo, path);
32
+ if (inputs === null) {
33
+ return null;
34
+ }
35
+ return hash({ task: (0, work_task_cache_description_1.getWorkTaskCacheDescription)(item), files: commitFiles(stats), ...inputs });
36
+ }
37
+ // The sources of a needed service, with the keys of what it depends on and needs; its
38
+ // definition is in the description of the task that needs it.
39
+ function getNeedKey(item, environment, memo, path) {
40
+ return memoized(memo, path, `need\0${item.name}`, async (inner) => {
41
+ const inputs = await getInputKeys(item, environment, memo, inner);
42
+ if (inputs === null) {
43
+ return null;
44
+ }
45
+ return hash({ files: commitFiles(await (0, get_work_cache_stats_1.getWorkCacheStats)(item.data, environment)), ...inputs });
46
+ });
47
+ }
48
+ async function getInputKeys(item, environment, memo, path) {
49
+ const deps = [];
50
+ for (const dep of item.deps) {
51
+ const key = await getCheckKey(dep, environment, memo, path);
52
+ if (key === null) {
53
+ return null;
54
+ }
55
+ deps.push(key);
56
+ }
57
+ const needs = [];
58
+ for (const need of item.needs) {
59
+ const key = await getNeedKey(need.service, environment, memo, path);
60
+ if (key === null) {
61
+ return null;
62
+ }
63
+ needs.push(`${need.name}=${key}`);
64
+ }
65
+ return { deps: deps.sort(), needs: needs.sort() };
66
+ }
67
+ // a commit never holds `.git`: what a checkout keeps there differs between a CI job's clone,
68
+ // the server's fetch and a sandbox's copy, which has none
69
+ function commitFiles(stats) {
70
+ return Object.keys(stats.files)
71
+ .filter((path) => !path.split('/').includes('.git'))
72
+ .sort()
73
+ .map((path) => [path, stats.files[path].checksum]);
74
+ }
75
+ function hash(value) {
76
+ return (0, crypto_1.createHash)('sha256').update(JSON.stringify(value)).digest('hex');
77
+ }
78
+ // `path` holds the keys being computed on the way here: one coming back is a loop (services
79
+ // that need each other), which can not be proven and fails to plan anyway. Waiting on its
80
+ // pending promise would never end. The keys are computed one after another, so every pending
81
+ // promise in the memo is on the path.
82
+ function memoized(memo, path, key, compute) {
83
+ if (path.has(key)) {
84
+ return Promise.resolve(null);
85
+ }
86
+ const known = memo.get(key);
87
+ if (known) {
88
+ return known;
89
+ }
90
+ const computed = compute(new Set([...path, key]));
91
+ memo.set(key, computed);
92
+ return computed;
93
+ }
94
+ //# sourceMappingURL=check-key.js.map
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCheckKeys = void 0;
4
+ const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
5
+ const reference_parser_1 = require("../schema/reference-parser");
6
+ const schema_parser_1 = require("../schema/schema-parser");
7
+ const work_scope_parser_1 = require("../schema/work-scope-parser");
8
+ const log_1 = require("../log");
9
+ const check_key_1 = require("./check-key");
10
+ /**
11
+ * The check keys of the tasks of a scope, as both ends compute them: the process of a run on
12
+ * the server before it executes anything, and `remote verify` in a CI job's checkout. So the
13
+ * build file is read the same way on both, as a server reads it (no `.env`, links are files)
14
+ * but placed nowhere: where a server runs a task (a pool, its tool image, the arch of its
15
+ * nodes) is the server's, and a result counts for the server it passed on. The secrets'
16
+ * providers and accounts are the server's too, and no part of a key, so any is taken here.
17
+ */
18
+ async function getCheckKeys(entry, environment, scope,
19
+ // on a server: the build files are read from the published files and work on the source
20
+ directory) {
21
+ const keyed = { ...environment, hosted: { catalog: anyCatalog(), localTasksInContainers: true } };
22
+ const { ctx, scope: parsed } = await (0, schema_parser_1.createParseContext)(entry, keyed, { directory });
23
+ const workTree = (0, work_scope_parser_1.getWorkContext)(await (0, reference_parser_1.parseReferences)(ctx, parsed, keyed), scope, keyed);
24
+ const memo = new Map();
25
+ const keys = {};
26
+ for (const task of (0, plan_work_tasks_1.iterateWorkTasks)(workTree)) {
27
+ try {
28
+ const key = await (0, check_key_1.getCheckKey)(task, keyed, memo);
29
+ keys[task.name] = key
30
+ ? { key }
31
+ : {
32
+ key: null,
33
+ reason: 'it, or a task it or a service it needs depends on, declares no src that matches a file',
34
+ };
35
+ }
36
+ catch (e) {
37
+ // a secret whose value is part of the key (`cache: true`) is not known here
38
+ keys[task.name] = { key: null, reason: (0, log_1.getErrorMessage)(e) };
39
+ }
40
+ }
41
+ return keys;
42
+ }
43
+ exports.getCheckKeys = getCheckKeys;
44
+ // Every provider and account name resolves, to a definition nothing runs.
45
+ function anyCatalog() {
46
+ const provider = (name) => ({
47
+ name,
48
+ type: 'command',
49
+ command: [],
50
+ env: {},
51
+ timeoutMs: 0,
52
+ declaredIn: 'the server',
53
+ });
54
+ const account = (name) => ({
55
+ name,
56
+ default: false,
57
+ providers: new Proxy({}, { get: () => ({ env: {} }) }),
58
+ declaredIn: 'the server',
59
+ });
60
+ return {
61
+ providers: new Proxy({}, { get: (_target, name) => (typeof name === 'string' ? provider(name) : undefined) }),
62
+ accounts: new Proxy({}, { get: (_target, name) => (typeof name === 'string' ? account(name) : undefined) }),
63
+ explicitAccounts: true,
64
+ };
65
+ }
66
+ //# sourceMappingURL=check-keys.js.map