hammerkit 2.0.0-next.1 → 2.0.0-next.11

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 (64) hide show
  1. package/dist/cache/explain.js +7 -5
  2. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  3. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  4. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  5. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  6. package/dist/dashboard/index.html +3 -3
  7. package/dist/dashboard/logo.png +0 -0
  8. package/dist/executer/docker-task.js +3 -0
  9. package/dist/executer/execute-work-task.js +3 -1
  10. package/dist/executer/local-task.js +3 -0
  11. package/dist/executer/scheduler/enqueue-next.js +6 -1
  12. package/dist/executer/scheduler/state-key.js +71 -34
  13. package/dist/executer/watch-loop.js +18 -5
  14. package/dist/file/get-file-context.js +5 -1
  15. package/dist/kubernetes/await-running-state.js +69 -5
  16. package/dist/kubernetes/claim-layout.js +10 -1
  17. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  18. package/dist/kubernetes/ensure-persistent-data.js +108 -20
  19. package/dist/kubernetes/follow-pod-logs.js +128 -29
  20. package/dist/kubernetes/kept-claims.js +16 -1
  21. package/dist/kubernetes/network-policy.js +4 -4
  22. package/dist/kubernetes/quota-wait.js +97 -0
  23. package/dist/kubernetes/restore-kubernetes-data.js +27 -4
  24. package/dist/kubernetes/store-kubernetes-data.js +13 -2
  25. package/dist/kubernetes/volumes.js +34 -7
  26. package/dist/optimizer/calculate-checksum.js +46 -3
  27. package/dist/optimizer/check-keys.js +4 -2
  28. package/dist/optimizer/get-work-cache-stats.js +36 -24
  29. package/dist/parser/read-build-file.js +8 -3
  30. package/dist/planner/utils/template-value.js +20 -4
  31. package/dist/planner/work-item-executions.js +27 -0
  32. package/dist/planner/work-runtime-kubernetes.js +69 -41
  33. package/dist/remote/host-config.js +1 -1
  34. package/dist/remote/remote-work-commands.js +14 -5
  35. package/dist/schema/schema-parser.js +46 -2
  36. package/dist/server/capacity.js +71 -41
  37. package/dist/server/dashboard.js +27 -9
  38. package/dist/server/endpoints.js +10 -1
  39. package/dist/server/executor.js +65 -34
  40. package/dist/server/kubernetes-backend.js +9 -3
  41. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  42. package/dist/server/oauth.js +16 -1
  43. package/dist/server/overview.js +80 -11
  44. package/dist/server/plan.js +16 -3
  45. package/dist/server/policy.js +9 -3
  46. package/dist/server/run-worker.js +47 -6
  47. package/dist/server/runs.js +74 -6
  48. package/dist/server/sandbox-files.js +107 -16
  49. package/dist/server/sandbox-patch.js +43 -17
  50. package/dist/server/sandboxes.js +57 -23
  51. package/dist/server/server-config.js +4 -1
  52. package/dist/server/server.js +45 -10
  53. package/dist/server/service-runs.js +8 -1
  54. package/dist/server/sources.js +68 -11
  55. package/dist/server/timings.js +23 -3
  56. package/dist/utils/buffer-context.js +30 -20
  57. package/dist/utils/limit.js +30 -0
  58. package/dist/utils/read-lines.js +65 -0
  59. package/dist/utils/units.js +36 -1
  60. package/dist/utils/web-links.js +34 -0
  61. package/package.json +1 -1
  62. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  63. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  64. package/dist/dashboard/favicon.svg +0 -1
@@ -32,6 +32,9 @@ class SandboxRegistry {
32
32
  // bytes they take once they were measured
33
33
  this.creating = new Map();
34
34
  this.deleting = new Set();
35
+ // the bytes edits take while they are written, so edits of two sandboxes at once both
36
+ // count against their owner's limit and the server's
37
+ this.reserved = new Map();
35
38
  // the measures of runs that are over, which a run's result does not wait for
36
39
  this.measuring = new Map();
37
40
  this.locks = new Map();
@@ -114,9 +117,10 @@ class SandboxRegistry {
114
117
  usage(owner) {
115
118
  const mine = this.list(owner);
116
119
  const creating = [...this.creating.values()].filter((create) => owns(owner, create.owner));
120
+ const reserved = [...this.reserved.values()].filter((reservation) => owns(owner, reservation.owner));
117
121
  return {
118
122
  count: mine.length + creating.length,
119
- bytes: [...mine, ...creating].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
123
+ bytes: [...mine, ...creating, ...reserved].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
120
124
  };
121
125
  }
122
126
  // Waits for the measures of the owner's runs that are over, so their limits hold.
@@ -139,6 +143,9 @@ class SandboxRegistry {
139
143
  * caller's to decide (`decideSandbox`); this checks the limits.
140
144
  */
141
145
  async create(owner, repo, ref) {
146
+ return this.growing(owner, () => this.createGrowing(owner, repo, ref));
147
+ }
148
+ async createGrowing(owner, repo, ref) {
142
149
  const { limits, storage, repos } = this.options;
143
150
  await this.measured(owner);
144
151
  const usage = this.usage(owner);
@@ -211,28 +218,47 @@ class SandboxRegistry {
211
218
  if (!state.clean) {
212
219
  throw new SandboxError(409, `the sandbox ${id} has changes, a fetch would mix them with another commit`);
213
220
  }
214
- const { storage, repos } = this.options;
215
- const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
216
- await this.resolve(sandbox.repo, ref, signal);
217
- const credentials = await repos.credentials(sandbox.repo);
218
- try {
219
- sandbox.commit = await storage.fetch(keyOf(sandbox), {
220
- url: repos.url(sandbox.repo),
221
- ref,
222
- env: credentials.env,
223
- signal,
224
- });
225
- }
226
- catch (e) {
227
- throw new SandboxError(502, repos.scrub(e, credentials.values).message);
228
- }
229
- sandbox.ref = ref;
230
- sandbox.bytes = await storage.usage(keyOf(sandbox));
231
- sandbox.lastUsedAt = this.timestamp();
232
- await this.save(sandbox);
233
- return copy(sandbox);
221
+ // a fetch can make the sandbox larger: not while the owner or the server is full, and
222
+ // one create or fetch of an owner at a time, so fetches at once can not pass it together
223
+ return this.growing(owner, () => this.fetchGrowing(owner, sandbox, ref));
234
224
  });
235
225
  }
226
+ async fetchGrowing(owner, sandbox, ref) {
227
+ const { limits } = this.options;
228
+ await this.measured(owner);
229
+ const used = this.usage(owner).bytes;
230
+ if (used >= limits.bytes) {
231
+ throw new SandboxError(413, `your sandboxes take ${(0, units_1.formatSize)(used)}, your limit is ${(0, units_1.formatSize)(limits.bytes)}: delete one`);
232
+ }
233
+ if (this.total() >= limits.total) {
234
+ throw new SandboxError(507, 'the server has no room for a fetch');
235
+ }
236
+ const { storage, repos } = this.options;
237
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
238
+ await this.resolve(sandbox.repo, ref, signal);
239
+ const credentials = await repos.credentials(sandbox.repo);
240
+ try {
241
+ sandbox.commit = await storage.fetch(keyOf(sandbox), {
242
+ url: repos.url(sandbox.repo),
243
+ ref,
244
+ env: credentials.env,
245
+ signal,
246
+ });
247
+ }
248
+ catch (e) {
249
+ throw new SandboxError(502, repos.scrub(e, credentials.values).message);
250
+ }
251
+ sandbox.ref = ref;
252
+ sandbox.bytes = await storage.usage(keyOf(sandbox));
253
+ sandbox.lastUsedAt = this.timestamp();
254
+ await this.save(sandbox);
255
+ return copy(sandbox);
256
+ }
257
+ // One create or fetch of an owner at a time: what one adds is measured before the next
258
+ // checks the limit.
259
+ growing(owner, fn) {
260
+ return this.withLock(`owner:${JSON.stringify([owner.iss, owner.sub])}`, fn);
261
+ }
236
262
  /**
237
263
  * Commits the changes of a sandbox as its owner and pushes them to a branch the operator
238
264
  * allows (`sources[].push.branches`). The branch must not exist yet, or be one this
@@ -392,6 +418,7 @@ class SandboxRegistry {
392
418
  if (dryRun || plan.files.length === 0) {
393
419
  return plan.files;
394
420
  }
421
+ const reservation = Symbol(id);
395
422
  if (plan.bytes > 0) {
396
423
  const { limits } = this.options;
397
424
  const used = this.usage(owner).bytes;
@@ -401,8 +428,15 @@ class SandboxRegistry {
401
428
  if (this.total() + plan.bytes > limits.total) {
402
429
  throw new SandboxError(507, 'the server has no room for these edits');
403
430
  }
431
+ // taken before anything else can check: no await between the check and this
432
+ this.reserved.set(reservation, { owner: { iss: owner.iss, sub: owner.sub }, bytes: plan.bytes });
433
+ }
434
+ try {
435
+ await plan.commit();
436
+ }
437
+ finally {
438
+ this.reserved.delete(reservation);
404
439
  }
405
- await plan.commit();
406
440
  sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
407
441
  sandbox.lastUsedAt = this.timestamp();
408
442
  await this.save(sandbox);
@@ -483,7 +517,7 @@ class SandboxRegistry {
483
517
  }
484
518
  }
485
519
  total() {
486
- return [...this.sandboxes.values(), ...this.creating.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
520
+ return [...this.sandboxes.values(), ...this.creating.values(), ...this.reserved.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
487
521
  }
488
522
  withLock(id, fn) {
489
523
  const previous = this.locks.get(id) ?? Promise.resolve();
@@ -45,7 +45,10 @@ exports.issuerSchema = zod_1.z
45
45
  scope: zod_1.z.string().min(1).default('openid'),
46
46
  })
47
47
  .strict();
48
- const subjectSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), sub: zod_1.z.string().min(1) }).strict();
48
+ // `name`: how pages name a subject whose tokens name nobody, such as a service account's
49
+ const subjectSchema = zod_1.z
50
+ .object({ iss: zod_1.z.string().min(1), sub: zod_1.z.string().min(1), name: zod_1.z.string().trim().min(1).max(100).optional() })
51
+ .strict();
49
52
  const groupSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), name: zod_1.z.string().min(1) }).strict();
50
53
  const claimsSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), match: zod_1.z.record(zod_1.z.string()) }).strict();
51
54
  // Who: the person or client (`subject`), everyone in a group of an issuer
@@ -109,7 +109,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
109
109
  });
110
110
  }
111
111
  async function handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res, url) {
112
- const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend))?)?$/.exec(url.pathname);
112
+ const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend|wake))?)?$/.exec(url.pathname);
113
113
  if (!match) {
114
114
  return false;
115
115
  }
@@ -129,7 +129,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
129
129
  }
130
130
  const runs = filter.scope === 'mine' ? registry.list(principal) : registry.all();
131
131
  (0, http_2.send)(res, 200, {
132
- runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, viewer, run)),
132
+ runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, definitions, viewer, run)),
133
133
  });
134
134
  }
135
135
  else if (method === 'POST') {
@@ -148,7 +148,8 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
148
148
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
149
149
  return true;
150
150
  }
151
- const run = registry.cancel(principal, id, accountsOf(config, principal));
151
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
152
+ const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
152
153
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
153
154
  run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
154
155
  }
@@ -159,6 +160,28 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
159
160
  }
160
161
  await extendRun(config, registry, log, principal, id, req, res);
161
162
  }
163
+ else if (action === 'wake') {
164
+ if (method !== 'POST') {
165
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
166
+ return true;
167
+ }
168
+ // as a request to one of its endpoints would, with the same check of its owner
169
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
170
+ const result = registry.wake(principal, id, (run) => (0, service_runs_1.mayOpenEndpoints)(grant, run), (run) => refuseWake(config, repos, run));
171
+ log(`wake iss=${principal.iss} sub=${principal.sub} run=${id} result=${result.status}`);
172
+ if (result.status === 'not-found') {
173
+ (0, http_2.send)(res, 404, { error: 'not found' });
174
+ }
175
+ else if (result.status === 'not-asleep') {
176
+ (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that sleeps wakes` });
177
+ }
178
+ else if (result.status === 'refused') {
179
+ (0, http_2.send)(res, 409, { error: result.reason });
180
+ }
181
+ else {
182
+ (0, http_2.send)(res, 200, toRunResponse(result.run));
183
+ }
184
+ }
162
185
  else if (method !== 'GET') {
163
186
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
164
187
  }
@@ -205,7 +228,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
205
228
  const may = run && (0, overview_1.runActions)(viewer, run);
206
229
  run
207
230
  ? (0, http_2.send)(res, 200, {
208
- ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run)),
231
+ ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run), viewer.nameOf),
209
232
  ...(may ? { may } : {}),
210
233
  })
211
234
  : (0, http_2.send)(res, 404, { error: 'not found' });
@@ -299,18 +322,21 @@ function runsTheSame(run, next) {
299
322
  }
300
323
  exports.runsTheSame = runsTheSame;
301
324
  // A run whole, for its owner and who may read it; who is not its owner is told whose it is.
302
- function toRunResponse(run, queue, named = false) {
325
+ function toRunResponse(run, queue, named = false, nameOf) {
303
326
  const { owner, ...visible } = run;
327
+ const name = owner.name ?? nameOf?.(owner);
304
328
  return {
305
329
  ...visible,
306
- ...(named ? { owner: { iss: owner.iss, sub: owner.sub } } : {}),
330
+ ...(named ? { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } } : {}),
307
331
  results: run.results ?? {},
308
332
  ...(queue ? { queue } : {}),
309
333
  };
310
334
  }
311
- function listRun(registry, viewer, run) {
312
- return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run));
335
+ function listRun(registry, definitions, viewer, run) {
336
+ return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
313
337
  }
338
+ // where in its repository the build file of a version is
339
+ const entryOf = (definitions) => (definition) => definitions.find(definition)?.entry;
314
340
  async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res) {
315
341
  const parsed = run_request_1.runRequestSchema.safeParse(await (0, http_2.readJson)(req));
316
342
  if (!parsed.success) {
@@ -518,8 +544,11 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
518
544
  : undefined;
519
545
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
520
546
  const claimNames = new Set(config.entitlements.flatMap((entitlement) => Object.keys(entitlement.claims?.match ?? {})));
547
+ const name = (0, oauth_1.displayName)(principal);
521
548
  const owner = {
522
549
  ...principal,
550
+ // how the pages name them, which the claims kept no longer tell
551
+ ...(name ? { name } : {}),
523
552
  claims: Object.fromEntries(Object.entries(principal.claims).filter(([name]) => claimNames.has(name))),
524
553
  };
525
554
  // A service run of the caller of this name that runs the same build file, services and
@@ -671,7 +700,7 @@ async function handleApi(api, principal, req, res, url) {
671
700
  (0, http_2.send)(res, 403, { error: 'you are not entitled to anything on this server' });
672
701
  return;
673
702
  }
674
- (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer));
703
+ (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer, entryOf(definitions)));
675
704
  return;
676
705
  }
677
706
  if (path === '/v1/capacity' || path === '/v1/tasks') {
@@ -702,7 +731,13 @@ async function handleApi(api, principal, req, res, url) {
702
731
  return;
703
732
  }
704
733
  const runs = (0, overview_1.filterRuns)(registry.all(), viewer, filter).map((run) => (0, overview_1.toListedRun)(viewer, run));
705
- (0, http_2.send)(res, 200, { tasks: (0, timings_1.getTaskStats)(runs, Date.now()) });
734
+ const oldest = (0, timings_1.getOldestCounted)(runs);
735
+ // where in the repository the build file of the last run is, as its version says
736
+ const tasks = (0, timings_1.getTaskStats)(runs, Date.now()).map((stats) => {
737
+ const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
738
+ return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
739
+ });
740
+ (0, http_2.send)(res, 200, { tasks, ...(oldest ? { oldest } : {}) });
706
741
  return;
707
742
  }
708
743
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
3
+ exports.mayPublishEndpoints = exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const plan_1 = require("./plan");
6
6
  const policy_1 = require("./policy");
@@ -79,4 +79,11 @@ function mayOpenEndpoints(grant, run) {
79
79
  return repo !== null && (0, policy_1.endpointLevel)(grant, repo) !== null;
80
80
  }
81
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;
82
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
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTaskStats = exports.roughly = exports.ranMs = exports.waitedMs = void 0;
3
+ exports.getTaskStats = exports.getOldestCounted = exports.roughly = exports.ranMs = exports.waitedMs = void 0;
4
4
  const at = (iso) => (iso ? Date.parse(iso) : NaN);
5
5
  // How long a run waited in the queue for a place: from when it was queued (after its
6
6
  // approval, or when it woke) until it started, or until now while it waits.
@@ -64,9 +64,27 @@ function quantile(sorted, q) {
64
64
  }
65
65
  return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))];
66
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;
67
84
  /**
68
85
  * Per task and repository, newest first: how often it ran and how, what it took the last
69
- * time, and the median and 90th percentile of the times it executed. `runs` is newest first.
86
+ * time, the median and 90th percentile of the times it executed, and those times added up.
87
+ * `runs` is newest first.
70
88
  */
71
89
  function getTaskStats(runs, now) {
72
90
  const groups = new Map();
@@ -74,7 +92,7 @@ function getTaskStats(runs, now) {
74
92
  const repo = run.source.repo ?? 'an upload';
75
93
  const waited = waitedMs(run, now);
76
94
  for (const [task, timing] of Object.entries(run.timings ?? {})) {
77
- if (timing.status === 'running' || timing.status === 'skipped' || timing.status === 'cancelled') {
95
+ if (!counts(timing)) {
78
96
  continue;
79
97
  }
80
98
  const key = `${repo}\0${task}`;
@@ -92,6 +110,7 @@ function getTaskStats(runs, now) {
92
110
  status: timing.status,
93
111
  at: timing.finishedAt ?? run.finishedAt ?? run.createdAt,
94
112
  ...(timing.durationMs !== undefined ? { durationMs: timing.durationMs } : {}),
113
+ ...(run.definition ? { definition: run.definition } : {}),
95
114
  },
96
115
  },
97
116
  durations: [],
@@ -124,6 +143,7 @@ function getTaskStats(runs, now) {
124
143
  ...stats,
125
144
  ...(median !== undefined ? { medianMs: median } : {}),
126
145
  ...(p90 !== undefined ? { p90Ms: p90 } : {}),
146
+ ...(durations.length > 0 ? { totalMs: durations.reduce((sum, ms) => sum + ms, 0) } : {}),
127
147
  ...(wait !== undefined ? { medianWaitMs: wait } : {}),
128
148
  };
129
149
  });
@@ -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