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,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mayPublishEndpoints = exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const plan_1 = require("./plan");
6
+ const policy_1 = require("./policy");
7
+ const run_request_1 = require("./run-request");
8
+ // The name of a service run when the request names none: the branch it runs from, as a DNS
9
+ // label, so the runs of several branches stand side by side and each keeps its hosts.
10
+ function getServiceRunName(branch) {
11
+ const name = (branch ?? '')
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9-]+/g, '-')
14
+ .replace(/-+/g, '-')
15
+ .slice(0, 40)
16
+ .replace(/^-+|-+$/g, '');
17
+ return run_request_1.SERVICE_RUN_NAME_PATTERN.test(name) ? name : 'run';
18
+ }
19
+ exports.getServiceRunName = getServiceRunName;
20
+ /**
21
+ * The host labels of a run's endpoints: its name, the port and twelve hex digits of its
22
+ * owner (at most 40 + 5 + 2 + 12 and three dashes: a DNS label), so two callers with a branch of the same name get hosts of their own, and a run
23
+ * that replaces another of the same name takes over its hosts. Two endpoints on the same
24
+ * port (of two services) are told apart by their place.
25
+ */
26
+ function getEndpointHosts(name, owner, endpoints) {
27
+ const of = (0, crypto_1.createHash)('sha256').update(`${owner.iss}\0${owner.sub}`).digest('hex').slice(0, 12);
28
+ return endpoints.map((endpoint, index) => endpoints.findIndex((other) => other.port === endpoint.port) === index
29
+ ? `${name}-${endpoint.port}-${of}`
30
+ : `${name}-${endpoint.port}-${index}-${of}`);
31
+ }
32
+ exports.getEndpointHosts = getEndpointHosts;
33
+ // The container port of each `host:container` port of a planned service.
34
+ function containerPorts(plan) {
35
+ return plan.ports.map((port) => Number(port.split(':').pop()));
36
+ }
37
+ /**
38
+ * Why the endpoints of a service run can't be published, or null. Each is a port its
39
+ * service declares, of a service the run starts. Under a `runs.secretNetwork` below `open`
40
+ * a service behind an endpoint may not read a secret or a credential of the server: a page
41
+ * is a way out that no mask of the log covers.
42
+ */
43
+ function refuseEndpoints(request, plan, secretNetworkOpen) {
44
+ for (const endpoint of request.endpoints) {
45
+ const item = plan[endpoint.service];
46
+ if (!item || item.kind !== 'service') {
47
+ return `the endpoint ${endpoint.service}:${endpoint.port} names no service the run starts`;
48
+ }
49
+ if (!containerPorts(item).includes(endpoint.port)) {
50
+ const ports = containerPorts(item);
51
+ return `${endpoint.service} has no port ${endpoint.port}${ports.length > 0 ? `, its ports are ${ports.join(', ')}` : ', it declares none'}`;
52
+ }
53
+ const reads = (0, plan_1.getCredentialReads)(item);
54
+ if (!secretNetworkOpen && reads.length > 0) {
55
+ return `${endpoint.service} reads ${reads.join(', ')}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+ exports.refuseEndpoints = refuseEndpoints;
61
+ function toRunEndpoints(endpoints, hosts, url) {
62
+ return endpoints.map((endpoint, index) => ({
63
+ service: endpoint.service,
64
+ port: endpoint.port,
65
+ host: hosts[index],
66
+ url: url(hosts[index]),
67
+ }));
68
+ }
69
+ exports.toRunEndpoints = toRunEndpoints;
70
+ // The repository of a run's source, which the endpoints grants are written for.
71
+ function getRunRepo(run) {
72
+ return run.source.type === 'upload' ? null : run.source.repo;
73
+ }
74
+ exports.getRunRepo = getRunRepo;
75
+ // Who may open the endpoints of a service run, and extend it, besides its owner: those
76
+ // with an `open` or `publish` level for its repository.
77
+ function mayOpenEndpoints(grant, run) {
78
+ const repo = getRunRepo(run);
79
+ return repo !== null && (0, policy_1.endpointLevel)(grant, repo) !== null;
80
+ }
81
+ exports.mayOpenEndpoints = mayOpenEndpoints;
82
+ // Who may publish endpoints of the run's repository: they could bring up a run of their own
83
+ // there, so they may stop somebody else's (a preview left running), besides its owner.
84
+ function mayPublishEndpoints(grant, run) {
85
+ const repo = getRunRepo(run);
86
+ return repo !== null && (0, policy_1.endpointLevel)(grant, repo) === 'publish';
87
+ }
88
+ exports.mayPublishEndpoints = mayPublishEndpoints;
89
+ //# sourceMappingURL=service-runs.js.map
@@ -15,7 +15,11 @@ class SourceError extends Error {
15
15
  }
16
16
  }
17
17
  exports.SourceError = SourceError;
18
- exports.DEFAULT_SOURCE_LIMITS = { subjectBytes: 4 * 1024 * 1024 * 1024 };
18
+ exports.DEFAULT_SOURCE_LIMITS = {
19
+ subjectBytes: 4 * 1024 * 1024 * 1024,
20
+ subjectManifests: 1000,
21
+ subjectManifestBytes: 64 * 1024 * 1024,
22
+ };
19
23
  // The directory name of a caller: the issuer and subject, hashed.
20
24
  function subjectKey(principal) {
21
25
  return (0, crypto_1.createHash)('sha256')
@@ -35,11 +39,11 @@ exports.subjectKey = subjectKey;
35
39
  * what other people work on.
36
40
  */
37
41
  class SourceStore {
38
- constructor(directory, limits = exports.DEFAULT_SOURCE_LIMITS, now = Date.now) {
42
+ constructor(directory, limits = {}, now = Date.now) {
39
43
  this.directory = directory;
40
- this.limits = limits;
41
44
  this.now = now;
42
45
  this.subjects = new Map();
46
+ this.limits = { ...exports.DEFAULT_SOURCE_LIMITS, ...limits };
43
47
  }
44
48
  // Announces a tree. Answers what has to be sent to complete it.
45
49
  async announce(principal, manifest) {
@@ -70,9 +74,27 @@ class SourceStore {
70
74
  sizes.set(file.sha256, file.size);
71
75
  }
72
76
  const stored = { manifest, createdAt: new Date(this.now()).toISOString() };
73
- await (0, promises_1.mkdir)((0, path_1.join)(this.directory, key, 'manifests'), { recursive: true });
74
- await this.write((0, path_1.join)(this.directory, key, 'manifests', `${snapshot.slice('sha256:'.length)}.json`), stored);
77
+ const content = JSON.stringify(stored);
78
+ const bytes = Buffer.byteLength(content, 'utf8');
79
+ if (subject.manifests.size >= this.limits.subjectManifests) {
80
+ throw new SourceError(413, `the server keeps at most ${this.limits.subjectManifests} trees for you, delete one with DELETE /v1/sources/<snapshot>`);
81
+ }
82
+ const manifestBytes = [...subject.manifestBytes.values()].reduce((sum, size) => sum + size, 0);
83
+ if (manifestBytes + bytes > this.limits.subjectManifestBytes) {
84
+ throw new SourceError(413, `the server keeps at most ${this.limits.subjectManifestBytes} bytes of trees for you, delete one with DELETE /v1/sources/<snapshot>`);
85
+ }
86
+ // taken before the write, so announcements at once can not pass the limits together
75
87
  subject.manifests.set(snapshot, stored);
88
+ subject.manifestBytes.set(snapshot, bytes);
89
+ try {
90
+ await (0, promises_1.mkdir)((0, path_1.join)(this.directory, key, 'manifests'), { recursive: true });
91
+ await this.write((0, path_1.join)(this.directory, key, 'manifests', `${snapshot.slice('sha256:'.length)}.json`), content);
92
+ }
93
+ catch (e) {
94
+ subject.manifests.delete(snapshot);
95
+ subject.manifestBytes.delete(snapshot);
96
+ throw e;
97
+ }
76
98
  for (const [digest, size] of sizes) {
77
99
  subject.wanted.set(digest, size);
78
100
  }
@@ -91,14 +113,38 @@ class SourceStore {
91
113
  throw new SourceError(400, 'this file is not part of a tree you announced');
92
114
  }
93
115
  const target = this.blob(key, digest);
116
+ // the same file sent twice at once is received once: the second waits for the first
117
+ for (let pending = subject.sending.get(digest); pending; pending = subject.sending.get(digest)) {
118
+ await pending;
119
+ }
94
120
  if (await exists(target)) {
95
121
  body.resume();
96
122
  return 'exists';
97
123
  }
98
- if (subject.stored + size > this.limits.subjectBytes) {
124
+ // a send that came in while this one looked waits for this one
125
+ if (subject.sending.has(digest)) {
126
+ return this.put(principal, digest, body);
127
+ }
128
+ // files being received count too: uploads at once can not pass the limit together
129
+ if (subject.stored + subject.receiving + size > this.limits.subjectBytes) {
99
130
  body.resume();
100
131
  throw new SourceError(413, `the server keeps at most ${this.limits.subjectBytes} bytes of files for you`);
101
132
  }
133
+ subject.receiving += size;
134
+ const received = this.receive(subject, key, digest, size, target, body);
135
+ const settled = received.then(() => undefined, () => undefined);
136
+ subject.sending.set(digest, settled);
137
+ try {
138
+ return await received;
139
+ }
140
+ finally {
141
+ subject.receiving -= size;
142
+ if (subject.sending.get(digest) === settled) {
143
+ subject.sending.delete(digest);
144
+ }
145
+ }
146
+ }
147
+ async receive(subject, key, digest, size, target, body) {
102
148
  await (0, promises_1.mkdir)((0, path_1.join)(this.directory, key, 'blobs'), { recursive: true });
103
149
  const temporary = `${target}.${(0, crypto_2.randomBytes)(8).toString('hex')}.tmp`;
104
150
  const hash = (0, crypto_1.createHash)('sha256');
@@ -166,6 +212,7 @@ class SourceStore {
166
212
  if (!subject.manifests.delete(snapshot)) {
167
213
  return false;
168
214
  }
215
+ subject.manifestBytes.delete(snapshot);
169
216
  await (0, promises_1.rm)((0, path_1.join)(this.directory, key, 'manifests', `${snapshot.slice('sha256:'.length)}.json`), { force: true });
170
217
  const kept = new Map();
171
218
  for (const stored of subject.manifests.values()) {
@@ -202,9 +249,9 @@ class SourceStore {
202
249
  blob(key, digest) {
203
250
  return (0, path_1.join)(this.directory, key, 'blobs', digest);
204
251
  }
205
- async write(file, value) {
252
+ async write(file, content) {
206
253
  const temporary = `${file}.${(0, crypto_2.randomBytes)(8).toString('hex')}.tmp`;
207
- await (0, promises_1.writeFile)(temporary, JSON.stringify(value), { flag: 'wx' });
254
+ await (0, promises_1.writeFile)(temporary, content, { flag: 'wx' });
208
255
  await (0, promises_1.rename)(temporary, file);
209
256
  }
210
257
  // Reads what is kept for one caller the first time they are seen.
@@ -217,7 +264,14 @@ class SourceStore {
217
264
  return loaded;
218
265
  }
219
266
  async load(key) {
220
- const subject = { wanted: new Map(), stored: 0, manifests: new Map() };
267
+ const subject = {
268
+ wanted: new Map(),
269
+ stored: 0,
270
+ receiving: 0,
271
+ sending: new Map(),
272
+ manifests: new Map(),
273
+ manifestBytes: new Map(),
274
+ };
221
275
  const manifests = (0, path_1.join)(this.directory, key, 'manifests');
222
276
  let names = [];
223
277
  try {
@@ -227,8 +281,11 @@ class SourceStore {
227
281
  return subject;
228
282
  }
229
283
  for (const name of names.filter((n) => n.endsWith('.json'))) {
230
- const stored = JSON.parse(await (0, promises_1.readFile)((0, path_1.join)(manifests, name), 'utf8'));
231
- subject.manifests.set((0, source_manifest_1.hashSource)(stored.manifest), stored);
284
+ const content = await (0, promises_1.readFile)((0, path_1.join)(manifests, name), 'utf8');
285
+ const stored = JSON.parse(content);
286
+ const snapshot = (0, source_manifest_1.hashSource)(stored.manifest);
287
+ subject.manifests.set(snapshot, stored);
288
+ subject.manifestBytes.set(snapshot, Buffer.byteLength(content, 'utf8'));
232
289
  for (const file of stored.manifest.files) {
233
290
  subject.wanted.set(file.sha256, file.size);
234
291
  }
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTaskStats = exports.getOldestCounted = exports.roughly = exports.ranMs = exports.waitedMs = void 0;
4
+ const at = (iso) => (iso ? Date.parse(iso) : NaN);
5
+ // How long a run waited in the queue for a place: from when it was queued (after its
6
+ // approval, or when it woke) until it started, or until now while it waits.
7
+ function waitedMs(run, now) {
8
+ const queued = at(run.queuedAt);
9
+ if (!Number.isFinite(queued)) {
10
+ return undefined;
11
+ }
12
+ const started = at(run.startedAt);
13
+ if (Number.isFinite(started) && started >= queued) {
14
+ return started - queued;
15
+ }
16
+ if (run.state === 'queued') {
17
+ return Math.max(0, now - queued);
18
+ }
19
+ // it ended before it started: cancelled in the queue
20
+ const finished = at(run.finishedAt);
21
+ return Number.isFinite(finished) && finished >= queued ? finished - queued : undefined;
22
+ }
23
+ exports.waitedMs = waitedMs;
24
+ // How long a run ran: from its start to its end, or until now while it runs. A service run
25
+ // counts until its services were up.
26
+ function ranMs(run, now) {
27
+ const started = at(run.startedAt);
28
+ if (!Number.isFinite(started)) {
29
+ return undefined;
30
+ }
31
+ const up = at(run.upAt);
32
+ const finished = at(run.finishedAt);
33
+ const end = Number.isFinite(up) && up >= started ? up : Number.isFinite(finished) ? finished : now;
34
+ return Math.max(0, end - started);
35
+ }
36
+ exports.ranMs = ranMs;
37
+ // a span of time as a person reads it at a glance: 2d 3h, 7h 59m, 29m 5s, 12s, 340ms
38
+ function roughly(ms) {
39
+ if (ms < 1000) {
40
+ return `${Math.max(0, Math.round(ms))}ms`;
41
+ }
42
+ const seconds = Math.round(ms / 1000);
43
+ const [d, h, m, s] = [
44
+ Math.floor(seconds / 86400),
45
+ Math.floor(seconds / 3600) % 24,
46
+ Math.floor(seconds / 60) % 60,
47
+ seconds % 60,
48
+ ];
49
+ if (d > 0) {
50
+ return `${d}d ${h}h`;
51
+ }
52
+ if (h > 0) {
53
+ return `${h}h ${m}m`;
54
+ }
55
+ if (m > 0) {
56
+ return s > 0 && m < 10 ? `${m}m ${s}s` : `${m}m`;
57
+ }
58
+ return `${s}s`;
59
+ }
60
+ exports.roughly = roughly;
61
+ function quantile(sorted, q) {
62
+ if (sorted.length === 0) {
63
+ return undefined;
64
+ }
65
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))];
66
+ }
67
+ // a task that ran to its end or came from the cache; one that runs, was skipped or stopped says
68
+ // nothing about what it takes
69
+ const counts = (timing) => timing.status !== 'running' && timing.status !== 'skipped' && timing.status !== 'cancelled';
70
+ /**
71
+ * When the oldest run that getTaskStats counts was created: the start of what its numbers
72
+ * cover. Undefined when it counts none.
73
+ */
74
+ function getOldestCounted(runs) {
75
+ let oldest;
76
+ for (const run of runs) {
77
+ if (Object.values(run.timings ?? {}).some(counts) && (!oldest || Date.parse(run.createdAt) < Date.parse(oldest))) {
78
+ oldest = run.createdAt;
79
+ }
80
+ }
81
+ return oldest;
82
+ }
83
+ exports.getOldestCounted = getOldestCounted;
84
+ /**
85
+ * Per task and repository, newest first: how often it ran and how, what it took the last
86
+ * time, the median and 90th percentile of the times it executed, and those times added up.
87
+ * `runs` is newest first.
88
+ */
89
+ function getTaskStats(runs, now) {
90
+ const groups = new Map();
91
+ for (const run of runs) {
92
+ const repo = run.source.repo ?? 'an upload';
93
+ const waited = waitedMs(run, now);
94
+ for (const [task, timing] of Object.entries(run.timings ?? {})) {
95
+ if (!counts(timing)) {
96
+ continue;
97
+ }
98
+ const key = `${repo}\0${task}`;
99
+ let group = groups.get(key);
100
+ if (!group) {
101
+ group = {
102
+ stats: {
103
+ repo,
104
+ task,
105
+ runs: 0,
106
+ succeeded: 0,
107
+ failed: 0,
108
+ cached: 0,
109
+ last: {
110
+ status: timing.status,
111
+ at: timing.finishedAt ?? run.finishedAt ?? run.createdAt,
112
+ ...(timing.durationMs !== undefined ? { durationMs: timing.durationMs } : {}),
113
+ ...(run.definition ? { definition: run.definition } : {}),
114
+ },
115
+ },
116
+ durations: [],
117
+ waits: [],
118
+ };
119
+ groups.set(key, group);
120
+ }
121
+ const { stats } = group;
122
+ stats.runs++;
123
+ if (timing.status === 'cached') {
124
+ stats.cached++;
125
+ continue;
126
+ }
127
+ timing.status === 'succeeded' ? stats.succeeded++ : stats.failed++;
128
+ if (timing.durationMs !== undefined) {
129
+ group.durations.push(timing.durationMs);
130
+ }
131
+ if (waited !== undefined) {
132
+ group.waits.push(waited);
133
+ }
134
+ }
135
+ }
136
+ return [...groups.values()].map(({ stats, durations, waits }) => {
137
+ durations.sort((a, b) => a - b);
138
+ waits.sort((a, b) => a - b);
139
+ const median = quantile(durations, 0.5);
140
+ const p90 = quantile(durations, 0.9);
141
+ const wait = quantile(waits, 0.5);
142
+ return {
143
+ ...stats,
144
+ ...(median !== undefined ? { medianMs: median } : {}),
145
+ ...(p90 !== undefined ? { p90Ms: p90 } : {}),
146
+ ...(durations.length > 0 ? { totalMs: durations.reduce((sum, ms) => sum + ms, 0) } : {}),
147
+ ...(wait !== undefined ? { medianWaitMs: wait } : {}),
148
+ };
149
+ });
150
+ }
151
+ exports.getTaskStats = getTaskStats;
152
+ //# sourceMappingURL=timings.js.map
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.describeWait = void 0;
4
+ // What keeps a queued run from starting, in words: `mine` says whose limit it is, `keys`
5
+ // names the setting of the server that sets it.
6
+ function describeWait(reason, mine, keys = true) {
7
+ switch (reason.type) {
8
+ case 'own-limit':
9
+ return `${mine ? 'your' : 'its owner’s'} limit of running runs, ${reason.running} of ${reason.limit}${keys ? ' (runs.limits.running)' : ''}`;
10
+ case 'sandbox':
11
+ return reason.run ? `its sandbox runs ${reason.run}` : 'another run works on its sandbox';
12
+ case 'held':
13
+ return reason.run ? `${reason.run} holds what it needs` : 'another run holds what it needs';
14
+ case 'place':
15
+ return `no free place, ${reason.used} of ${reason.max} taken${keys ? ' (runs.maxConcurrent)' : ''}`;
16
+ case 'starting':
17
+ return 'starts now';
18
+ }
19
+ }
20
+ exports.describeWait = describeWait;
21
+ //# sourceMappingURL=wait-reason.js.map
@@ -1,42 +1,52 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BufferContext = void 0;
4
+ // The last `limit` entries of each id, and all of those in the order they came. An entry an id
5
+ // no longer keeps leaves both; the list of all of them drops what left now and then, so an
6
+ // entry costs the same however many ids there are.
4
7
  class BufferContext {
5
8
  constructor(limit) {
6
9
  this.limit = limit;
7
- this.scopedBuffer = {};
10
+ this.scopedBuffer = new Map();
8
11
  this.buffer = [];
12
+ this.dropped = 0;
9
13
  }
10
14
  add(id, data) {
11
- this.buffer.push(data);
12
- if (id in this.scopedBuffer) {
13
- const scopedBuffer = this.scopedBuffer[id];
14
- scopedBuffer.push(data);
15
- if (scopedBuffer.length > this.limit) {
16
- const removedBuffer = this.buffer.splice(0, 1)[0];
17
- const bufferIndex = this.buffer.indexOf(removedBuffer);
18
- if (bufferIndex >= 0) {
19
- this.buffer.splice(bufferIndex, 1);
20
- }
21
- }
15
+ const entry = { data, kept: true };
16
+ this.buffer.push(entry);
17
+ let scopedBuffer = this.scopedBuffer.get(id);
18
+ if (!scopedBuffer) {
19
+ scopedBuffer = [];
20
+ this.scopedBuffer.set(id, scopedBuffer);
22
21
  }
23
- else {
24
- this.scopedBuffer[id] = [data];
22
+ scopedBuffer.push(entry);
23
+ if (scopedBuffer.length > this.limit) {
24
+ const removed = scopedBuffer.shift();
25
+ removed.kept = false;
26
+ this.dropped++;
27
+ if (this.dropped * 2 > this.buffer.length) {
28
+ this.compact();
29
+ }
25
30
  }
26
31
  }
27
32
  current(id) {
28
- if (!(id in this.scopedBuffer)) {
33
+ const value = this.scopedBuffer.get(id);
34
+ if (!value || value.length === 0) {
29
35
  return null;
30
36
  }
31
- const value = this.scopedBuffer[id];
32
- return value[value.length - 1];
37
+ return value[value.length - 1].data;
33
38
  }
34
39
  get(id) {
35
40
  if (id) {
36
- return this.scopedBuffer[id] ?? [];
41
+ return (this.scopedBuffer.get(id) ?? []).map((entry) => entry.data);
37
42
  }
38
- else {
39
- return this.buffer;
43
+ this.compact();
44
+ return this.buffer.map((entry) => entry.data);
45
+ }
46
+ compact() {
47
+ if (this.dropped > 0) {
48
+ this.buffer = this.buffer.filter((entry) => entry.kept);
49
+ this.dropped = 0;
40
50
  }
41
51
  }
42
52
  }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLimit = void 0;
4
+ function createLimit(concurrency) {
5
+ let running = 0;
6
+ const waiting = [];
7
+ return async (fn) => {
8
+ if (running >= concurrency) {
9
+ await new Promise((resolve) => waiting.push(resolve));
10
+ }
11
+ else {
12
+ running++;
13
+ }
14
+ try {
15
+ return await fn();
16
+ }
17
+ finally {
18
+ const next = waiting.shift();
19
+ if (next) {
20
+ // the slot goes to the next one as it is
21
+ next();
22
+ }
23
+ else {
24
+ running--;
25
+ }
26
+ }
27
+ };
28
+ }
29
+ exports.createLimit = createLimit;
30
+ //# sourceMappingURL=limit.js.map
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readLines = void 0;
4
+ const string_decoder_1 = require("string_decoder");
5
+ /**
6
+ * Calls `onLine` with each line of `input` as readline does: a line ends at a line feed, a CR
7
+ * or both. It holds at most `maxChars` of a line: a longer line is cut there and says so, the
8
+ * rest of it up to the end of the line is passed over.
9
+ */
10
+ function readLines(input, maxChars, onLine) {
11
+ const decoder = new string_decoder_1.StringDecoder('utf8');
12
+ let pending = '';
13
+ let cut = false;
14
+ // the last line ended with a CR, so a line feed right after it ends no other line
15
+ let afterCr = false;
16
+ const emit = () => {
17
+ onLine(cut ? `${pending} … [cut at ${maxChars} characters]` : pending);
18
+ pending = '';
19
+ cut = false;
20
+ };
21
+ const take = (text) => {
22
+ let start = 0;
23
+ if (afterCr && text.length > 0) {
24
+ afterCr = false;
25
+ if (text[0] === '\n') {
26
+ start = 1;
27
+ }
28
+ }
29
+ const ends = /[\r\n]/g;
30
+ for (;;) {
31
+ ends.lastIndex = start;
32
+ const end = ends.exec(text);
33
+ if (!cut) {
34
+ pending += text.slice(start, end ? end.index : undefined);
35
+ if (pending.length > maxChars) {
36
+ pending = pending.slice(0, maxChars);
37
+ cut = true;
38
+ }
39
+ }
40
+ if (!end) {
41
+ return;
42
+ }
43
+ emit();
44
+ start = end.index + 1;
45
+ if (end[0] === '\r') {
46
+ if (start === text.length) {
47
+ afterCr = true;
48
+ return;
49
+ }
50
+ if (text[start] === '\n') {
51
+ start++;
52
+ }
53
+ }
54
+ }
55
+ };
56
+ input.on('data', (chunk) => take(typeof chunk === 'string' ? chunk : decoder.write(chunk)));
57
+ input.on('end', () => {
58
+ take(decoder.end());
59
+ if (pending.length > 0 || cut) {
60
+ emit();
61
+ }
62
+ });
63
+ }
64
+ exports.readLines = readLines;
65
+ //# sourceMappingURL=read-lines.js.map
package/dist/utils/tar.js CHANGED
@@ -3,7 +3,34 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.packArchive = void 0;
4
4
  const tar_1 = require("tar");
5
5
  function packArchive(options, files) {
6
- return (0, tar_1.create)({ ...options, jobs: 1 }, files);
6
+ return (0, tar_1.create)({ ...options, jobs: 1, linkCache: new ExactLinkCache() }, files);
7
7
  }
8
8
  exports.packArchive = packArchive;
9
+ // node-tar packs a file with more than one link as a link to the first file it packed with
10
+ // the same `dev:ino`. On Windows a file id has 64 bits, and Node gives it as a number, so
11
+ // ids above 2^53 are rounded and files of two link groups can get the same one. Packed as
12
+ // a link, a file would be restored with the other file's content. This cache leaves out the
13
+ // ids that may be rounded, so those files are packed in full.
14
+ //
15
+ // node-tar asks the cache in two places. A WriteEntry links to the path it gets only when
16
+ // that path is in the packed directory, and packs the file in full otherwise. The Pack treats
17
+ // a file it gets no path for as the first of its links, and takes a path for it that ends
18
+ // the archive a second time when the file is empty and the last one packed: an empty file
19
+ // whose other link is outside the packed directory, as in a pnpm node_modules, or any empty
20
+ // file with a rounded id. That throws "write after end" (a zlib stream error with gzip)
21
+ // where nothing can catch it. With one file read at a time that path is not needed, so the
22
+ // cache never answers with nothing: for a file it has no path for, it answers NOT_PACKED,
23
+ // which is in no directory.
24
+ class ExactLinkCache extends Map {
25
+ get(key) {
26
+ return super.get(key) || NOT_PACKED;
27
+ }
28
+ set(key, path) {
29
+ return isExact(key) ? super.set(key, path) : this;
30
+ }
31
+ }
32
+ const NOT_PACKED = '\0';
33
+ function isExact(key) {
34
+ return key.split(':').every((part) => Number.isSafeInteger(Number(part)));
35
+ }
9
36
  //# sourceMappingURL=tar.js.map
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isYes = exports.getTerminalPrompt = exports.terminalPrompt = void 0;
4
+ const readline_1 = require("readline");
5
+ /**
6
+ * Asks the person at the terminal one question and answers the line they typed, or
7
+ * undefined when the input ended or the signal stopped the command first (Ctrl-C).
8
+ * The terminal stays in its own line mode, so Ctrl-C is a signal as anywhere else.
9
+ */
10
+ function terminalPrompt(input, output, signal) {
11
+ return (question) => new Promise((resolve) => {
12
+ if (signal.aborted) {
13
+ resolve(undefined);
14
+ return;
15
+ }
16
+ const lines = (0, readline_1.createInterface)({ input, output, terminal: false });
17
+ let answer;
18
+ const stop = () => lines.close();
19
+ signal.addEventListener('abort', stop, { once: true });
20
+ lines.once('close', () => {
21
+ signal.removeEventListener('abort', stop);
22
+ if (answer === undefined) {
23
+ // what was asked ends on a line of its own
24
+ output.write('\n');
25
+ }
26
+ resolve(answer);
27
+ });
28
+ lines.question(question, (line) => {
29
+ answer = line;
30
+ lines.close();
31
+ });
32
+ });
33
+ }
34
+ exports.terminalPrompt = terminalPrompt;
35
+ /**
36
+ * The prompt of the CLI: only when somebody sits at a terminal to answer it, never in
37
+ * CI, where a question would wait until the job times out.
38
+ */
39
+ function getTerminalPrompt(processEnvs, signal, stdio = process) {
40
+ if (!stdio.stdin.isTTY || !stdio.stdout.isTTY || isSet(processEnvs.CI)) {
41
+ return undefined;
42
+ }
43
+ return terminalPrompt(stdio.stdin, stdio.stdout, signal);
44
+ }
45
+ exports.getTerminalPrompt = getTerminalPrompt;
46
+ function isSet(value) {
47
+ return value !== undefined && value !== '' && value !== '0' && value.toLowerCase() !== 'false';
48
+ }
49
+ function isYes(answer) {
50
+ return /^\s*y(es)?\s*$/i.test(answer ?? '');
51
+ }
52
+ exports.isYes = isYes;
53
+ //# sourceMappingURL=terminal-prompt.js.map