hammerkit 2.1.0 → 2.2.0-next.2

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 (103) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cache/backends/registry/push-credentials.js +50 -0
  3. package/dist/cache/backends/registry/registry-client.js +41 -10
  4. package/dist/cache/backends/registry-cache-backend.js +6 -1
  5. package/dist/cache/cache-inventory.js +3 -0
  6. package/dist/cli.js +5 -0
  7. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  8. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  9. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/docker/item-network.js +6 -5
  12. package/dist/docker/remove-orphaned-containers.js +5 -4
  13. package/dist/environment/replace-env-variables.js +8 -5
  14. package/dist/environment/run-source-envs.js +2 -1
  15. package/dist/executer/archive-task-entry.js +1 -1
  16. package/dist/executer/check-readiness.js +8 -4
  17. package/dist/executer/docker-healthcheck.js +73 -0
  18. package/dist/executer/docker-service.js +21 -15
  19. package/dist/executer/event-cache.js +7 -1
  20. package/dist/executer/execute-work-task.js +8 -0
  21. package/dist/executer/runner-commands.js +36 -0
  22. package/dist/file/get-file-context.js +4 -7
  23. package/dist/harness/connect.js +12 -8
  24. package/dist/harness/reconnect.js +141 -0
  25. package/dist/harness/sandbox-client.js +241 -33
  26. package/dist/harness/service-tools.js +11 -2
  27. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  28. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  29. package/dist/kubernetes/follow-pod-logs.js +8 -5
  30. package/dist/kubernetes/kept-claims.js +38 -14
  31. package/dist/kubernetes/sandbox-runner.js +526 -156
  32. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  33. package/dist/kubernetes/sync-changes.js +463 -0
  34. package/dist/kubernetes/volumes.js +23 -1
  35. package/dist/network/healthcheck-request.js +38 -0
  36. package/dist/optimizer/get-work-cache-stats.js +7 -0
  37. package/dist/optimizer/work-task-cache-description.js +5 -3
  38. package/dist/planner/image-build.js +5 -0
  39. package/dist/planner/service-definition.js +2 -1
  40. package/dist/planner/utils/append-work-service.js +12 -4
  41. package/dist/planner/utils/dependency-outputs.js +7 -6
  42. package/dist/planner/validate.js +41 -0
  43. package/dist/planner/work-healthcheck.js +23 -2
  44. package/dist/planner/work-item-status.js +12 -2
  45. package/dist/planner/work-runtime-aggregate.js +1 -0
  46. package/dist/planner/work-runtime-docker.js +33 -6
  47. package/dist/planner/work-runtime-kubernetes.js +313 -70
  48. package/dist/planner/work-runtime-local.js +8 -4
  49. package/dist/planner/work-secret.js +33 -11
  50. package/dist/planner/work-service-id.js +30 -6
  51. package/dist/planner/work-service.js +2 -2
  52. package/dist/program.js +19 -1
  53. package/dist/remote/annotations.js +8 -2
  54. package/dist/remote/bundle.js +6 -8
  55. package/dist/remote/device-login.js +4 -1
  56. package/dist/remote/remote-commands.js +16 -7
  57. package/dist/remote/remote-status.js +1 -1
  58. package/dist/remote/remote-work-commands.js +220 -68
  59. package/dist/remote/server-client.js +38 -40
  60. package/dist/schema/build-file-base-task-schema.js +16 -1
  61. package/dist/schema/build-file-image-build-schema.js +5 -8
  62. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  63. package/dist/schema/reference-parser.js +108 -43
  64. package/dist/schema/work-scope-parser.js +8 -0
  65. package/dist/secrets/prefetch-secrets.js +20 -1
  66. package/dist/server/artifacts-api.js +56 -0
  67. package/dist/server/borrowed-quota.js +216 -0
  68. package/dist/server/cache-push.js +50 -0
  69. package/dist/server/capacity.js +18 -6
  70. package/dist/server/definitions-api.js +62 -8
  71. package/dist/server/executor.js +131 -31
  72. package/dist/server/http.js +4 -1
  73. package/dist/server/keep-artifacts.js +230 -0
  74. package/dist/server/kubernetes-backend.js +292 -79
  75. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  76. package/dist/server/overview.js +73 -9
  77. package/dist/server/paging.js +167 -0
  78. package/dist/server/plan.js +54 -8
  79. package/dist/server/run-access.js +24 -0
  80. package/dist/server/run-artifacts.js +171 -0
  81. package/dist/server/run-logs.js +25 -1
  82. package/dist/server/run-request.js +11 -0
  83. package/dist/server/run-source-environment.js +1 -1
  84. package/dist/server/run-worker.js +305 -40
  85. package/dist/server/runs.js +531 -105
  86. package/dist/server/sandbox-files-api.js +27 -12
  87. package/dist/server/sandbox-files.js +12 -10
  88. package/dist/server/sandbox-follow.js +54 -0
  89. package/dist/server/sandbox-pod.js +1 -1
  90. package/dist/server/sandbox-storage.js +38 -1
  91. package/dist/server/sandbox-sync.js +392 -0
  92. package/dist/server/sandboxes-api.js +116 -19
  93. package/dist/server/sandboxes.js +38 -3
  94. package/dist/server/server-config.js +133 -2
  95. package/dist/server/server.js +189 -39
  96. package/dist/server/task-order.js +56 -0
  97. package/dist/utils/project-path.js +20 -0
  98. package/dist/utils/tar-files.js +52 -0
  99. package/dist/utils/tar.js +37 -1
  100. package/package.json +1 -1
  101. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  102. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  103. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BorrowedQuotas = exports.readPoolRoom = exports.isPoolNode = exports.getBorrowedQuota = exports.getBorrowedResource = exports.BORROWED_RESOURCES = void 0;
4
+ const log_1 = require("../log");
5
+ const apply_1 = require("../kubernetes/apply");
6
+ const units_1 = require("../utils/units");
7
+ /**
8
+ * A caller's quota above its share (`backend.quota`), up to `backend.maxQuota`: the room of
9
+ * the nodes that no other caller is promised. While a run of a caller executes, the caller is
10
+ * promised its share; the room of the nodes of the pools beyond the shares of the callers with
11
+ * a run executing and the quotas of the service runs that are up is split evenly among those
12
+ * callers, each up to its `maxQuota`. A caller alone on the cluster gets all of it. The server
13
+ * works it out again when a run of a caller or a service run starts or ends, from nothing but
14
+ * which of them execute and what the nodes hold, so the same runs give the same quotas. It only
15
+ * lowers a quota and never evicts: the pods a caller runs above its new quota run on, and its
16
+ * next ones wait for room under the quota as they do under a full one.
17
+ */
18
+ // The keys of a quota a caller may borrow, by the resource of the nodes whose room they take.
19
+ // `cpu` and `memory` are `requests.cpu` and `requests.memory`, as Kubernetes reads them.
20
+ exports.BORROWED_RESOURCES = {
21
+ cpu: { requests: ['requests.cpu', 'cpu'], limits: ['limits.cpu'] },
22
+ memory: { requests: ['requests.memory', 'memory'], limits: ['limits.memory'] },
23
+ };
24
+ function getBorrowedResource(key) {
25
+ return Object.keys(exports.BORROWED_RESOURCES).find((resource) => {
26
+ const keys = [...exports.BORROWED_RESOURCES[resource].requests, ...exports.BORROWED_RESOURCES[resource].limits];
27
+ return keys.includes(key);
28
+ });
29
+ }
30
+ exports.getBorrowedResource = getBorrowedResource;
31
+ // The key of a quota that holds what the pods of a namespace request of `resource`
32
+ function requestsKey(quota, resource) {
33
+ return exports.BORROWED_RESOURCES[resource].requests.find((key) => quota[key] !== undefined);
34
+ }
35
+ /**
36
+ * The quota of each caller with a run executing: its share, and of each resource of
37
+ * `maxQuota` the part of the room `callers` share evenly beyond what is promised, up to
38
+ * `maxQuota`. Every key of a resource rises by the same part of the way from its share to its
39
+ * `maxQuota`, its limits as its requests. Without the room of the nodes, the share.
40
+ */
41
+ function getBorrowedQuota(options) {
42
+ const { quota, maxQuota } = options;
43
+ const borrowed = { ...quota };
44
+ const callers = Math.max(1, options.callers);
45
+ for (const resource of Object.keys(exports.BORROWED_RESOURCES)) {
46
+ const key = requestsKey(maxQuota, resource);
47
+ const room = options.room?.[resource];
48
+ if (!key || room === undefined) {
49
+ continue;
50
+ }
51
+ const share = (0, units_1.parseQuantity)(quota[key]) ?? 0;
52
+ const max = (0, units_1.parseQuantity)(maxQuota[key]) ?? share;
53
+ if (max <= share) {
54
+ continue;
55
+ }
56
+ const promised = callers * share +
57
+ options.serviceRuns.reduce((sum, up) => {
58
+ const of = requestsKey(up, resource);
59
+ return sum + (of ? (0, units_1.parseQuantity)(up[of]) ?? 0 : 0);
60
+ }, 0);
61
+ const part = Math.min(1, Math.max(0, (room - promised) / callers / (max - share)));
62
+ if (part === 0) {
63
+ continue;
64
+ }
65
+ for (const of of [...exports.BORROWED_RESOURCES[resource].requests, ...exports.BORROWED_RESOURCES[resource].limits]) {
66
+ if (maxQuota[of] === undefined) {
67
+ continue;
68
+ }
69
+ if (part === 1) {
70
+ borrowed[of] = maxQuota[of];
71
+ continue;
72
+ }
73
+ const from = (0, units_1.parseQuantity)(quota[of]) ?? 0;
74
+ const to = (0, units_1.parseQuantity)(maxQuota[of]) ?? from;
75
+ borrowed[of] = formatQuantity(resource, from + part * (to - from));
76
+ }
77
+ }
78
+ return borrowed;
79
+ }
80
+ exports.getBorrowedQuota = getBorrowedQuota;
81
+ // Down to a millicore and a MiB, so that a quota changes only with what it is worked out from
82
+ function formatQuantity(resource, amount) {
83
+ return resource === 'cpu' ? `${Math.floor(amount * 1000)}m` : `${Math.floor(amount / 2 ** 20)}Mi`;
84
+ }
85
+ // Whether a node is one of a pool's, where the pods of tasks and services go
86
+ function isPoolNode(node, pools) {
87
+ if (node.spec?.unschedulable) {
88
+ return false;
89
+ }
90
+ const labels = node.metadata?.labels ?? {};
91
+ return pools.some((pool) => labels['kubernetes.io/os'] === pool.platform.os &&
92
+ labels['kubernetes.io/arch'] === pool.platform.arch &&
93
+ Object.entries(pool.nodeSelector).every(([label, value]) => labels[label] === value));
94
+ }
95
+ exports.isPoolNode = isPoolNode;
96
+ // What the schedulable nodes of the pools hold together
97
+ async function readPoolRoom(instance, pools) {
98
+ const nodes = await instance.coreApi.listNode();
99
+ const room = { cpu: 0, memory: 0 };
100
+ for (const node of nodes.items.filter((candidate) => isPoolNode(candidate, pools))) {
101
+ room.cpu = (room.cpu ?? 0) + ((0, units_1.parseQuantity)(node.status?.allocatable?.cpu) ?? 0);
102
+ room.memory = (room.memory ?? 0) + ((0, units_1.parseQuantity)(node.status?.allocatable?.memory) ?? 0);
103
+ }
104
+ return room;
105
+ }
106
+ exports.readPoolRoom = readPoolRoom;
107
+ /**
108
+ * The quotas of the callers' namespaces while `backend.maxQuota` lets them borrow: which
109
+ * callers have a run executing and which service runs are up, and the quota last written to
110
+ * each namespace. Changes are worked out and written one at a time, in the order they came.
111
+ */
112
+ class BorrowedQuotas {
113
+ constructor(options) {
114
+ this.options = options;
115
+ // per caller namespace, its runs that execute
116
+ this.runs = new Map();
117
+ // per namespace of a service run that is up, its quota
118
+ this.serviceRuns = new Map();
119
+ // per caller namespace, the quota last written to it
120
+ this.written = new Map();
121
+ this.last = Promise.resolve();
122
+ }
123
+ // A run of the caller of `namespace` executes from now, until `leave`.
124
+ enter(namespace, run) {
125
+ const runs = this.runs.get(namespace) ?? new Set();
126
+ runs.add(run);
127
+ this.runs.set(namespace, runs);
128
+ }
129
+ // The run ended: the quotas are worked out again, the caller's back to its share once its
130
+ // last run ended.
131
+ leave(namespace, run) {
132
+ const runs = this.runs.get(namespace);
133
+ if (!runs?.delete(run)) {
134
+ return this.last;
135
+ }
136
+ if (runs.size === 0) {
137
+ this.runs.delete(namespace);
138
+ }
139
+ return this.apply();
140
+ }
141
+ // A service run is up, with the quota of its namespace, until `serviceRunEnded`.
142
+ serviceRun(namespace, quota) {
143
+ this.serviceRuns.set(namespace, quota ?? {});
144
+ return this.apply();
145
+ }
146
+ serviceRunEnded(namespace) {
147
+ if (!this.serviceRuns.delete(namespace)) {
148
+ return this.last;
149
+ }
150
+ return this.apply();
151
+ }
152
+ // The quotas as they are now, written where they changed; the quota of `own` (the namespace
153
+ // of a run that starts, which it is written into before its tasks run) also when it did
154
+ // not, since the server may have made the namespace since. Writing to `own` fails the call,
155
+ // writing to another caller's namespace is logged.
156
+ apply(own) {
157
+ const next = this.last.then(() => this.write(own));
158
+ this.last = next.catch(() => undefined);
159
+ return next;
160
+ }
161
+ async write(own) {
162
+ const room = await this.options.room().then((room) => {
163
+ this.roomProblem = undefined;
164
+ return room;
165
+ }, (e) => {
166
+ const problem = (0, log_1.getErrorMessage)(e);
167
+ if (problem !== this.roomProblem) {
168
+ this.roomProblem = problem;
169
+ this.options.log?.(`callers borrow no quota, the nodes could not be read: ${problem}`);
170
+ }
171
+ return undefined;
172
+ });
173
+ const callers = [...this.runs.keys()];
174
+ const borrowed = getBorrowedQuota({
175
+ quota: this.options.quota,
176
+ maxQuota: this.options.maxQuota,
177
+ callers: callers.length,
178
+ serviceRuns: [...this.serviceRuns.values()],
179
+ room,
180
+ });
181
+ // those that give back first, then those that borrow
182
+ const quotas = [
183
+ ...[...this.written.keys()]
184
+ .filter((namespace) => !this.runs.has(namespace))
185
+ .map((namespace) => [namespace, this.options.quota]),
186
+ ...callers.map((namespace) => [namespace, borrowed]),
187
+ ];
188
+ for (const [namespace, quota] of quotas) {
189
+ const text = JSON.stringify(quota);
190
+ if (namespace !== own && this.written.get(namespace) === text) {
191
+ continue;
192
+ }
193
+ try {
194
+ await this.options.write(namespace, quota);
195
+ this.written.set(namespace, text);
196
+ }
197
+ catch (e) {
198
+ if (namespace === own) {
199
+ throw e;
200
+ }
201
+ this.written.delete(namespace);
202
+ if ((0, apply_1.statusCodeOf)(e) !== 404) {
203
+ this.options.log?.(`the quota of ${namespace} could not be changed: ${(0, log_1.getErrorMessage)(e)}`);
204
+ }
205
+ }
206
+ }
207
+ // a caller back at its share needs nothing written until it borrows again
208
+ for (const namespace of [...this.written.keys()]) {
209
+ if (!this.runs.has(namespace)) {
210
+ this.written.delete(namespace);
211
+ }
212
+ }
213
+ }
214
+ }
215
+ exports.BorrowedQuotas = BorrowedQuotas;
216
+ //# sourceMappingURL=borrowed-quota.js.map
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cacheRegistriesOf = exports.cachePushOf = void 0;
4
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
5
+ const policy_1 = require("./policy");
6
+ const repo_1 = require("./repo");
7
+ // a ref may name a commit, which is no branch of the repository (see git-checkout.ts)
8
+ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
9
+ // Whether a run writes a registry cache, and with which credential (ADR-0010). Every run reads
10
+ // the caches of its build file; only a trusted run writes one, and the answer is null for all
11
+ // others, which fails closed:
12
+ // - a run from a git ref that resolved as a branch when the server pinned it (`branch`, so a tag
13
+ // that matches a branch pattern is not one), of a repository and branch `cache.push` lists
14
+ // - by a caller who may publish build files, who is trusted with what the cache then holds; a
15
+ // caller whose grant is gone is no longer one
16
+ // - with a password the server's environment holds for the rule's registry
17
+ //
18
+ // The build file takes no part in it: a run writes the registry of its own configuration only.
19
+ // `envs` is the server's own environment, not the one of a run, which holds the allowlist.
20
+ function cachePushOf(run, config, envs) {
21
+ const source = run.source;
22
+ if (source.type !== 'ref' || source.branch !== true || COMMIT.test(source.ref)) {
23
+ return null;
24
+ }
25
+ const grant = (0, policy_1.getGrant)(config.entitlements, {
26
+ iss: run.owner.iss,
27
+ sub: run.owner.sub,
28
+ groups: run.owner.groups ?? [],
29
+ claims: run.owner.claims ?? {},
30
+ });
31
+ if (!(0, policy_1.mayPublish)(grant)) {
32
+ return null;
33
+ }
34
+ // the first rule that covers the run decides, even when its password is missing
35
+ const rule = config.cache.push.find((entry) => (0, repo_1.matchesRepo)(entry.repo, source.repo) && (0, repo_1.matchesRef)(entry.refs, source.ref));
36
+ const password = rule ? envs[rule.registry.passwordEnv] : undefined;
37
+ if (!rule || !password) {
38
+ return null;
39
+ }
40
+ return { repository: rule.registry.repository, username: rule.registry.username, password };
41
+ }
42
+ exports.cachePushOf = cachePushOf;
43
+ // The registry hosts a server run may read its caches from: `cache.registries`, and the host of
44
+ // each `cache.push` rule, which the operator named already.
45
+ function cacheRegistriesOf(config) {
46
+ const hosts = config.cache.push.map((rule) => (0, registry_reference_1.parseRegistryReference)(rule.registry.repository).host);
47
+ return [...new Set([...config.cache.registries, ...hosts])];
48
+ }
49
+ exports.cacheRegistriesOf = cacheRegistriesOf;
50
+ //# sourceMappingURL=cache-push.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.KubernetesCapacity = exports.cachedCapacity = exports.parseQuantity = void 0;
3
+ exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.KubernetesCapacity = exports.getQuotaResources = exports.cachedCapacity = exports.parseQuantity = void 0;
4
4
  const os_1 = require("os");
5
5
  const log_1 = require("../log");
6
6
  const apply_1 = require("../kubernetes/apply");
@@ -71,6 +71,16 @@ function briefly(e, what) {
71
71
  }
72
72
  return what === 'nodes' ? 'nodes not readable' : 'metrics not readable';
73
73
  }
74
+ // The CPU and memory pods may request under a quota, if it limits them
75
+ function getQuotaResources(hard) {
76
+ const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
77
+ const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
78
+ if (cpu === undefined && memory === undefined) {
79
+ return undefined;
80
+ }
81
+ return { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
82
+ }
83
+ exports.getQuotaResources = getQuotaResources;
74
84
  const ENDED = ['Succeeded', 'Failed'];
75
85
  // On Kubernetes: per namespace of the server, its pods' requests, its quota and its usage.
76
86
  class KubernetesCapacity {
@@ -162,11 +172,13 @@ class KubernetesCapacity {
162
172
  name: this.options.quotaName,
163
173
  namespace,
164
174
  });
165
- const hard = quota.spec?.hard ?? {};
166
- const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
167
- const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
168
- if (cpu !== undefined || memory !== undefined) {
169
- group.quota = { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
175
+ const resources = getQuotaResources(quota.spec?.hard ?? {});
176
+ if (resources) {
177
+ group.quota = resources;
178
+ const share = this.options.share;
179
+ if (kind === 'caller' && share && (share.cpu !== resources.cpu || share.memory !== resources.memory)) {
180
+ group.share = share;
181
+ }
170
182
  }
171
183
  }
172
184
  catch (e) {
@@ -9,6 +9,7 @@ const run_plan_1 = require("./run-plan");
9
9
  const oauth_1 = require("./oauth");
10
10
  const policy_1 = require("./policy");
11
11
  const proposals_1 = require("./proposals");
12
+ const paging_1 = require("./paging");
12
13
  // A bundle is JSON text with escapes, so the body may be somewhat larger than the files.
13
14
  const MAX_PUBLISH_BYTES = bundle_1.MAX_BUNDLE_BYTES * 2;
14
15
  /**
@@ -19,7 +20,11 @@ const MAX_PUBLISH_BYTES = bundle_1.MAX_BUNDLE_BYTES * 2;
19
20
  * Beside entry and files the body may carry
20
21
  * `annotations`, which are not part of the hash
21
22
  * GET /v1/definitions the versions, newest first; `?<key>=<value>`
22
- * keeps the ones with those annotations
23
+ * keeps the ones with those annotations (a key
24
+ * repeated, with any of its values), `q` the ones
25
+ * with the text; `limit` and `cursor` page them,
26
+ * `values=<key>` answers the values of an
27
+ * annotation (paging.ts)
23
28
  * GET /v1/definitions/<hash> one version, with `arguments`: per task null when
24
29
  * a run of it may pass arguments, else why not
25
30
  * GET /v1/definitions/<hash>/files its files
@@ -67,13 +72,15 @@ async function handleDefinitions(config, store, proposals, log, principal, req,
67
72
  return true;
68
73
  }
69
74
  if (hash === undefined) {
70
- const wanted = [...url.searchParams.entries()];
71
- (0, http_1.send)(res, 200, {
72
- definitions: store
73
- .list()
74
- .filter((version) => wanted.every(([key, value]) => version.annotations?.[key] === value))
75
- .map(toSummary),
76
- });
75
+ try {
76
+ listDefinitions(store, url.searchParams, res);
77
+ }
78
+ catch (e) {
79
+ if (!(e instanceof paging_1.ListParamError)) {
80
+ throw e;
81
+ }
82
+ (0, http_1.send)(res, 400, { error: e.message });
83
+ }
77
84
  return true;
78
85
  }
79
86
  const found = store.find(hash);
@@ -91,6 +98,53 @@ async function handleDefinitions(config, store, proposals, log, principal, req,
91
98
  return true;
92
99
  }
93
100
  exports.handleDefinitions = handleDefinitions;
101
+ // the parameters of the list that are not annotations to filter by
102
+ const LIST_PARAMS = ['q', 'limit', 'cursor', 'values', 'search'];
103
+ // GET /v1/definitions: the versions with the annotations and the text asked for, a page of
104
+ // them, or the values of an annotation.
105
+ function listDefinitions(store, params, res) {
106
+ const wanted = new Map();
107
+ for (const [key, value] of params) {
108
+ if (!LIST_PARAMS.includes(key)) {
109
+ wanted.set(key, [...(wanted.get(key) ?? []), value]);
110
+ }
111
+ }
112
+ const text = (0, paging_1.readText)(params);
113
+ // any annotation has values, those of a key no version has are none
114
+ const asked = params.get('values');
115
+ if (asked !== null && !bundle_1.ANNOTATION_KEY_PATTERN.test(asked)) {
116
+ throw new paging_1.ListParamError('values: the key of an annotation');
117
+ }
118
+ const values = asked !== null ? (0, paging_1.parseValues)(params, [asked]) : undefined;
119
+ const page = values ? undefined : (0, paging_1.parsePage)(params);
120
+ const found = (except) => store
121
+ .list()
122
+ .filter((version) => [...wanted].every(([key, accepted]) => key === except || accepted.includes(version.annotations?.[key] ?? '\0')) &&
123
+ (!text ||
124
+ (0, paging_1.hasText)([
125
+ version.hash,
126
+ version.entry,
127
+ version.publishedBy.sub,
128
+ ...Object.values(version.annotations ?? {}),
129
+ ...version.tasks,
130
+ ...version.services,
131
+ ], text)));
132
+ if (values) {
133
+ // the values an annotation has, counted over the versions the other filters let through
134
+ const key = values.field;
135
+ const counted = (0, paging_1.countValues)(found(key), (version) => (version.annotations?.[key] !== undefined ? [version.annotations[key]] : []), values);
136
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('values', counted));
137
+ return;
138
+ }
139
+ const listed = found();
140
+ if (!page) {
141
+ (0, http_1.send)(res, 200, { definitions: listed.map(toSummary) });
142
+ return;
143
+ }
144
+ const key = (version) => [version.publishedAt, version.hash];
145
+ const answered = (0, paging_1.pageByKey)((0, paging_1.newestFirst)(listed, key), page, key);
146
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('definitions', { ...answered, items: answered.items.map(toSummary) }));
147
+ }
94
148
  // What the list shows of a version: who published it and when, and what it runs as.
95
149
  function toSummary(version) {
96
150
  const { hash, entry, publishedAt, publishedBy, approvedBy, annotations, tasks, services, accounts, yanked } = version;