hammerkit 2.1.0-next.10 → 2.1.0-next.12

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 (41) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/file/get-file-context.js +4 -7
  10. package/dist/harness/sandbox-client.js +29 -2
  11. package/dist/kubernetes/cluster-state.js +48 -14
  12. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  13. package/dist/kubernetes/resources.js +5 -1
  14. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  15. package/dist/planner/work-runtime-aggregate.js +1 -0
  16. package/dist/planner/work-runtime-docker.js +9 -5
  17. package/dist/planner/work-runtime-kubernetes.js +6 -4
  18. package/dist/planner/work-runtime-local.js +8 -4
  19. package/dist/remote/annotations.js +29 -3
  20. package/dist/remote/bundle.js +6 -8
  21. package/dist/remote/collect-bundle.js +3 -2
  22. package/dist/remote/remote-work-commands.js +161 -8
  23. package/dist/server/artifacts-api.js +56 -0
  24. package/dist/server/definitions-api.js +62 -8
  25. package/dist/server/executor.js +17 -0
  26. package/dist/server/keep-artifacts.js +230 -0
  27. package/dist/server/overview.js +67 -9
  28. package/dist/server/paging.js +167 -0
  29. package/dist/server/run-access.js +24 -0
  30. package/dist/server/run-artifacts.js +171 -0
  31. package/dist/server/run-worker.js +29 -0
  32. package/dist/server/runs.js +8 -0
  33. package/dist/server/sandbox-files.js +2 -7
  34. package/dist/server/sandboxes-api.js +54 -8
  35. package/dist/server/server-config.js +14 -0
  36. package/dist/server/server.js +122 -27
  37. package/dist/server/task-order.js +56 -0
  38. package/dist/utils/project-path.js +20 -0
  39. package/dist/utils/tar.js +37 -1
  40. package/package.json +1 -1
  41. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -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;
@@ -14,6 +14,7 @@ const run_plan_1 = require("./run-plan");
14
14
  const work_network_1 = require("../planner/work-network");
15
15
  const execute_docker_1 = require("../executer/execute-docker");
16
16
  const run_source_environment_1 = require("./run-source-environment");
17
+ const run_artifacts_1 = require("./run-artifacts");
17
18
  // `.git` as a file system may read it: any case, and a name Windows reads without its
18
19
  // trailing dots and spaces, or by its short name
19
20
  function isGitDirectory(segment) {
@@ -212,6 +213,17 @@ class HostExecutor {
212
213
  if (refused) {
213
214
  throw new Error(refused);
214
215
  }
216
+ // the outputs of a run are not handed out when anything reads a credential, or when the
217
+ // local tasks of this host could write them: then the run keeps none and says why
218
+ const wanted = context.artifacts && !run.up ? context.artifacts : undefined;
219
+ const noArtifacts = wanted ? this.artifactsRefusal(planned.plan) : null;
220
+ const artifacts = noArtifacts ? undefined : wanted;
221
+ if (wanted && noArtifacts) {
222
+ const manifest = { refused: noArtifacts, outputs: [], left: [] };
223
+ await (0, promises_1.mkdir)(wanted.directory, { recursive: true });
224
+ await (0, promises_1.writeFile)((0, path_1.join)(wanted.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
225
+ context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `keeps no outputs: ${noArtifacts}` });
226
+ }
215
227
  const abortCtrl = new AbortController();
216
228
  const abort = () => abortCtrl.abort();
217
229
  if (context.signal.aborted) {
@@ -346,6 +358,7 @@ class HostExecutor {
346
358
  volumeScope: volumeScope(run, this.options.directory),
347
359
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
360
  ...(context.durations ? { durations: context.durations } : {}),
361
+ ...(artifacts ? { artifacts } : {}),
349
362
  catalog: planning.environment.hosted?.catalog,
350
363
  ...(run.up
351
364
  ? {
@@ -380,6 +393,10 @@ class HostExecutor {
380
393
  }
381
394
  }
382
395
  }
396
+ // why a run keeps none of its outputs: a credential its tasks read, or local tasks on this host
397
+ artifactsRefusal(plan) {
398
+ return this.options.localTasksOnHost ? run_artifacts_1.LOCAL_TASKS_REFUSAL : (0, run_artifacts_1.refuseArtifacts)(plan);
399
+ }
383
400
  directoryOf(run) {
384
401
  for (let execution = 1;; execution++) {
385
402
  const root = (0, path_1.join)(this.options.directory, execution === 1 ? run.id : `${run.id}-${execution}`);
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keepArtifacts = exports.MAX_OUTPUT_ENTRIES = void 0;
4
+ const fs_1 = require("fs");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const stream_1 = require("stream");
8
+ const promises_2 = require("stream/promises");
9
+ const log_1 = require("../log");
10
+ const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
11
+ const work_task_1 = require("../planner/work-task");
12
+ const tar_1 = require("../utils/tar");
13
+ const units_1 = require("../utils/units");
14
+ const run_artifacts_1 = require("./run-artifacts");
15
+ // The most entries an output may have when it is unpacked: what the server packs again.
16
+ exports.MAX_OUTPUT_ENTRIES = 10000;
17
+ // Why the outputs of a task that came from the cache are not kept: a cache is shared by the
18
+ // runs of the server, and its key holds no value of a secret, so what an entry holds may be
19
+ // what a run that read a secret wrote, and this run may read none.
20
+ const CACHE_REASON = 'it came from the cache: the cache is shared by the runs of this server and its key holds no secret value, ' +
21
+ 'so what it holds may be what a run that read a secret wrote';
22
+ /**
23
+ * Keeps the outputs of the tasks of a run that the build file says to copy out (`export`),
24
+ * as a run on a dev machine copies them out of their containers: those of a task that
25
+ * completed, and those with `export: always` of one that failed too. Each goes through the
26
+ * runtime its task ran on, as `hammerkit store` takes it, and is kept as a gzipped tar of
27
+ * its paths in the project, so a download is laid out the same whatever ran it.
28
+ */
29
+ async function keepArtifacts(workTree, environment, options) {
30
+ const manifest = { outputs: [], left: [] };
31
+ const staging = (0, path_1.join)(options.directory, '.staging');
32
+ await (0, promises_1.mkdir)(staging, { recursive: true });
33
+ // a failed task aborts the run's controller, the archives still have to be made
34
+ const keeping = { ...environment, abortCtrl: new AbortController() };
35
+ let bytes = 0;
36
+ try {
37
+ const tasks = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].sort((a, b) => a.name.localeCompare(b.name));
38
+ for (const task of tasks) {
39
+ for (const generate of getKeptOutputs(task)) {
40
+ const path = toPosix((0, path_1.relative)(options.root, generate.path));
41
+ const file = `${manifest.outputs.length + manifest.left.length}.tgz`;
42
+ const target = (0, path_1.join)(options.directory, file);
43
+ if (options.cancelled()) {
44
+ manifest.left.push({ task: task.name, path, reason: 'the run was cancelled' });
45
+ continue;
46
+ }
47
+ if (isFromCache(task)) {
48
+ manifest.left.push({ task: task.name, path, reason: CACHE_REASON });
49
+ continue;
50
+ }
51
+ try {
52
+ const kept = await keepOutput(task, generate, keeping, {
53
+ staging,
54
+ target,
55
+ root: options.root,
56
+ maxBytes: options.maxBytes,
57
+ remaining: options.maxBytes - bytes,
58
+ });
59
+ if (kept === null) {
60
+ manifest.left.push({ task: task.name, path, reason: 'the task left nothing there' });
61
+ }
62
+ else {
63
+ bytes += kept;
64
+ manifest.outputs.push({ task: task.name, path, file, bytes: kept });
65
+ }
66
+ }
67
+ catch (e) {
68
+ await (0, promises_1.rm)(target, { force: true });
69
+ // what this module says of the limit is ours to say, what else went wrong is redacted
70
+ const reason = e instanceof Refused ? e.message : options.redact((0, log_1.getErrorMessage)(e)).slice(0, 500);
71
+ manifest.left.push({ task: task.name, path, reason });
72
+ }
73
+ }
74
+ }
75
+ }
76
+ finally {
77
+ await (0, promises_1.rm)(staging, { recursive: true, force: true });
78
+ }
79
+ await (0, promises_1.writeFile)((0, path_1.join)(options.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
80
+ return manifest;
81
+ }
82
+ exports.keepArtifacts = keepArtifacts;
83
+ // The outputs of a task a run may keep: what its build file exports, of a task that completed,
84
+ // and what it exports always of one that failed. What it inherits is its dependency's to keep.
85
+ // A task that was skipped, as nothing needed it, has none. Those of a task that came from the
86
+ // cache are candidates too, and are refused in keepArtifacts (isFromCache).
87
+ function getKeptOutputs(task) {
88
+ const state = task.state.current;
89
+ if ((0, work_task_1.isAggregateTask)(task.data)) {
90
+ return [];
91
+ }
92
+ const completed = state.type === 'completed' && !state.skipped;
93
+ const failed = state.type === 'crash' || state.type === 'error';
94
+ return task.data.generates.filter((generate) => !generate.inherited && (generate.exportAlways || (generate.export && completed)) && (completed || failed));
95
+ }
96
+ function isFromCache(task) {
97
+ const state = task.state.current;
98
+ return state.type === 'completed' && !!state.cached;
99
+ }
100
+ // A refusal of one output, with what the run may say of it.
101
+ class Refused extends Error {
102
+ }
103
+ function overBudget(maxBytes, detail) {
104
+ return `more than the ${(0, units_1.formatSize)(maxBytes)} a run keeps (runs.artifacts.maxBytes)${detail ? `, ${detail}` : ''}`;
105
+ }
106
+ /**
107
+ * What the archives of one output may still take: the rest of the run's budget. Past it a
108
+ * write is refused and the stream writing the archive stops there, so a task can not fill the
109
+ * disk of the server with an output that is refused in the end.
110
+ */
111
+ class Budget {
112
+ constructor(limit, reason) {
113
+ this.limit = limit;
114
+ this.reason = reason;
115
+ this.used = 0;
116
+ }
117
+ take(bytes) {
118
+ this.used += bytes;
119
+ if (this.used > this.limit) {
120
+ throw new Refused(this.reason);
121
+ }
122
+ }
123
+ // a stream that writes an archive, metered: what passes it counts
124
+ meter() {
125
+ return new stream_1.Transform({
126
+ transform: (chunk, _encoding, callback) => {
127
+ try {
128
+ this.take(chunk.length);
129
+ callback(null, chunk);
130
+ }
131
+ catch (e) {
132
+ callback(e);
133
+ }
134
+ },
135
+ });
136
+ }
137
+ // a file an archive is written to, metered at its writes: past the limit it is destroyed
138
+ count(file) {
139
+ const write = file.write.bind(file);
140
+ file.on('error', (error) => {
141
+ this.refusal ?? (this.refusal = error);
142
+ });
143
+ file.write = ((chunk, ...rest) => {
144
+ if (this.refusal) {
145
+ return false;
146
+ }
147
+ try {
148
+ this.take(Buffer.byteLength(chunk));
149
+ }
150
+ catch (e) {
151
+ file.destroy(e);
152
+ return false;
153
+ }
154
+ return write(chunk, ...rest);
155
+ });
156
+ return file;
157
+ }
158
+ // throws what refused a write, when a stream did not say it by itself
159
+ check() {
160
+ if (this.refusal) {
161
+ throw this.refusal;
162
+ }
163
+ }
164
+ }
165
+ // The environment with its writes of archives counted by the budget: the runtimes write their
166
+ // archives through `file`, so every byte an output is archived with is counted here.
167
+ function budgeted(environment, budget) {
168
+ const { file } = environment;
169
+ return {
170
+ ...environment,
171
+ file: {
172
+ ...file,
173
+ writeStream: (path, stream) => {
174
+ const metered = budget.meter();
175
+ // the source is stopped where the meter stops it; the error reaches the write through `metered`
176
+ (0, promises_2.pipeline)(stream, metered).catch(() => undefined);
177
+ return file.writeStream(path, metered);
178
+ },
179
+ createWriteStream: (path) => budget.count(file.createWriteStream(path)),
180
+ },
181
+ };
182
+ }
183
+ // The archive of one output as the runtime of its task makes it, made again with the paths
184
+ // in the project: the size of the new archive, or null when there is nothing.
185
+ async function keepOutput(task, generate, environment, options) {
186
+ const raw = (0, path_1.join)(options.staging, 'raw');
187
+ const tree = (0, path_1.join)(options.staging, 'tree');
188
+ await (0, promises_1.rm)(raw, { recursive: true, force: true });
189
+ await (0, promises_1.rm)(tree, { recursive: true, force: true });
190
+ await (0, promises_1.mkdir)(raw, { recursive: true });
191
+ const budget = new Budget(options.remaining, overBudget(options.maxBytes));
192
+ const [archive] = await task.runtime.archive(budgeted(environment, budget), raw, { only: [generate.path] });
193
+ budget.check();
194
+ if (!archive || !(0, fs_1.existsSync)(archive.filename)) {
195
+ return null;
196
+ }
197
+ await checkArchive(archive, options);
198
+ const into = (0, path_1.join)(tree, (0, path_1.relative)(options.root, archive.root));
199
+ if ((0, path_1.relative)(tree, into).startsWith('..') || (0, path_1.isAbsolute)((0, path_1.relative)(tree, into))) {
200
+ throw new Error(`${archive.root} is not in the project`);
201
+ }
202
+ await (0, promises_1.mkdir)(into, { recursive: true });
203
+ // only entries of the output, and no link out of it: whatever the task wrote there
204
+ await (0, tar_1.extractOutput)(archive.filename, into, toPosix((0, path_1.relative)(archive.root, generate.path)) || '.', true);
205
+ const path = (0, path_1.relative)(options.root, generate.path);
206
+ if (!(0, fs_1.existsSync)((0, path_1.join)(tree, path))) {
207
+ return null;
208
+ }
209
+ await (0, tar_1.packArchive)({ cwd: tree, file: options.target, gzip: true, portable: true }, [toPosix(path)]);
210
+ const packed = (await (0, promises_1.stat)(options.target)).size;
211
+ if (packed > options.remaining) {
212
+ throw new Refused(overBudget(options.maxBytes, `${(0, units_1.formatSize)(packed)} packed`));
213
+ }
214
+ return packed;
215
+ }
216
+ // What an archive holds once it is unpacked is measured before it is, so a few bytes packed
217
+ // from a huge file, or from many files, are refused before anything is written.
218
+ async function checkArchive(archive, options) {
219
+ const measured = await (0, tar_1.measureArchive)(archive.filename, { entries: exports.MAX_OUTPUT_ENTRIES, bytes: options.remaining });
220
+ if (measured.entries > exports.MAX_OUTPUT_ENTRIES) {
221
+ throw new Refused(`more than ${exports.MAX_OUTPUT_ENTRIES} files in it`);
222
+ }
223
+ if (measured.bytes > options.remaining) {
224
+ throw new Refused(overBudget(options.maxBytes, `${(0, units_1.formatSize)(measured.bytes)} unpacked`));
225
+ }
226
+ }
227
+ function toPosix(path) {
228
+ return path.split(path_1.sep).join(path_1.posix.sep);
229
+ }
230
+ //# sourceMappingURL=keep-artifacts.js.map
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.visibleCapacity = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.mayRetry = exports.runActions = exports.getViewer = exports.describeWait = void 0;
3
+ exports.visibleCapacity = exports.withoutField = exports.runValues = exports.runSource = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.STATES = exports.RUN_FIELDS = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.mayRetry = exports.runActions = exports.getViewer = exports.describeWait = void 0;
4
4
  const policy_1 = require("./policy");
5
5
  const runs_1 = require("./runs");
6
6
  const service_runs_1 = require("./service-runs");
7
7
  const repo_1 = require("./repo");
8
8
  const units_1 = require("../utils/units");
9
+ const paging_1 = require("./paging");
9
10
  var wait_reason_1 = require("./wait-reason");
10
11
  Object.defineProperty(exports, "describeWait", { enumerable: true, get: function () { return wait_reason_1.describeWait; } });
11
12
  function getViewer(config, principal) {
@@ -227,7 +228,9 @@ exports.getOverview = getOverview;
227
228
  function meter(runs, limit) {
228
229
  return { used: runs.length, ...(limit !== undefined ? { limit } : {}), runs: [...runs] };
229
230
  }
230
- const STATES = [
231
+ // what the filters of the runs page narrow by, and GET /v1/runs?values= answers the values of
232
+ exports.RUN_FIELDS = ['state', 'source', 'task'];
233
+ exports.STATES = [
231
234
  'awaiting-approval',
232
235
  'queued',
233
236
  'running',
@@ -238,7 +241,8 @@ const STATES = [
238
241
  'cancelled',
239
242
  'rejected',
240
243
  ];
241
- // `scope`, `state` (a comma separated list), `kind`, `id`, `sandbox`, `since` and `until` of GET /v1/runs.
244
+ // `scope`, `state` (a comma separated list, or repeated), `kind`, `id`, `sandbox`, `since`,
245
+ // `until`, `source` and `task` (each repeated for more than one) and `q` of GET /v1/runs.
242
246
  function parseRunFilter(params, grant, now = Date.now()) {
243
247
  const scope = params.get('scope') ?? 'mine';
244
248
  if (scope !== 'mine' && scope !== 'visible' && scope !== 'all') {
@@ -247,11 +251,14 @@ function parseRunFilter(params, grant, now = Date.now()) {
247
251
  if (scope === 'all' && !grant.observe) {
248
252
  throw new FilterRefused('scope all needs an entitlement with observe');
249
253
  }
250
- const state = params.get('state');
251
- const states = state
252
- ? state.split(',').map((value) => {
253
- if (!STATES.includes(value)) {
254
- throw new Error(`state: one or more of ${STATES.join(', ')}`);
254
+ const state = params
255
+ .getAll('state')
256
+ .flatMap((value) => value.split(','))
257
+ .filter(Boolean);
258
+ const states = state.length
259
+ ? state.map((value) => {
260
+ if (!exports.STATES.includes(value)) {
261
+ throw new Error(`state: one or more of ${exports.STATES.join(', ')}`);
255
262
  }
256
263
  return value;
257
264
  })
@@ -273,6 +280,9 @@ function parseRunFilter(params, grant, now = Date.now()) {
273
280
  if (since !== undefined && until !== undefined && until < since) {
274
281
  throw new Error('until: after since');
275
282
  }
283
+ const sources = (0, paging_1.readList)(params, 'source');
284
+ const tasks = (0, paging_1.readList)(params, 'task');
285
+ const text = (0, paging_1.readText)(params);
276
286
  return {
277
287
  scope,
278
288
  ...(states ? { states } : {}),
@@ -281,6 +291,9 @@ function parseRunFilter(params, grant, now = Date.now()) {
281
291
  ...(sandbox ? { sandbox } : {}),
282
292
  ...(since !== undefined ? { since } : {}),
283
293
  ...(until !== undefined ? { until } : {}),
294
+ ...(sources ? { sources } : {}),
295
+ ...(tasks ? { tasks } : {}),
296
+ ...(text ? { text } : {}),
284
297
  };
285
298
  }
286
299
  exports.parseRunFilter = parseRunFilter;
@@ -308,9 +321,54 @@ function filterRuns(runs, viewer, filter) {
308
321
  (!filter.states || filter.states.includes(run.state)) &&
309
322
  (!filter.kind || (filter.kind === 'services') === !!run.up) &&
310
323
  (filter.since === undefined || Date.parse(run.createdAt) >= filter.since) &&
311
- (filter.until === undefined || Date.parse(run.createdAt) <= filter.until));
324
+ (filter.until === undefined || Date.parse(run.createdAt) <= filter.until) &&
325
+ (!filter.sources || filter.sources.includes(runSource(run))) &&
326
+ (!filter.tasks || runWork(run).some((name) => filter.tasks?.includes(name))) &&
327
+ (!filter.text || (0, paging_1.hasText)(runText(viewer, run), filter.text)));
312
328
  }
313
329
  exports.filterRuns = filterRuns;
330
+ // where a run is from, as the source filter names it: its repository, or `upload`
331
+ function runSource(run) {
332
+ return run.source.type === 'upload' ? 'upload' : run.source.repo;
333
+ }
334
+ exports.runSource = runSource;
335
+ // the tasks a run runs, or the services it keeps up
336
+ function runWork(run) {
337
+ return [...run.tasks, ...(run.up?.services ?? [])];
338
+ }
339
+ // what of a run the text of a search is looked for in: what the list shows of it
340
+ function runText(viewer, run) {
341
+ return [
342
+ run.id,
343
+ run.owner.sub,
344
+ run.owner.name ?? viewer.nameOf?.(run.owner),
345
+ ...runWork(run),
346
+ run.up?.name,
347
+ run.source.type === 'upload' ? undefined : run.source.repo,
348
+ run.source.type === 'ref' ? run.source.ref : undefined,
349
+ ];
350
+ }
351
+ // The values a field of the runs has, as GET /v1/runs?values= answers them: the states in the
352
+ // order a run goes through them, the others the most used first.
353
+ function runValues(field) {
354
+ switch (field) {
355
+ case 'state':
356
+ return { of: (run) => [run.state], order: exports.STATES };
357
+ case 'source':
358
+ return { of: (run) => [runSource(run)] };
359
+ case 'task':
360
+ return { of: runWork };
361
+ }
362
+ }
363
+ exports.runValues = runValues;
364
+ // The filter without the one of a field: what the values of that field are counted over.
365
+ function withoutField(filter, field) {
366
+ const key = { state: 'states', source: 'sources', task: 'tasks' }[field];
367
+ const { [key]: dropped, ...rest } = filter;
368
+ void dropped;
369
+ return rest;
370
+ }
371
+ exports.withoutField = withoutField;
314
372
  // The machines and what the runs take, with whose the namespaces are where the caller may
315
373
  // know: their own, and every one with `observe`.
316
374
  function visibleCapacity(capacity, viewer) {
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * The pages of a list the API answers, and the values its filters can take.
4
+ *
5
+ * A list asked with `limit` answers that many at most, and `next` while more remain: the
6
+ * `cursor` that asks for the page after it. A cursor is opaque to callers. Without `limit` a
7
+ * list answers everything, as before lists were paged.
8
+ *
9
+ * A list asked with `values=<field>` answers the values that field has instead, each with how
10
+ * many of the list have it, narrowed by `search` and paged the same way: what a filter offers
11
+ * to choose from.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.hasText = exports.readText = exports.readList = exports.countValues = exports.parseValues = exports.answerPage = exports.pageByPosition = exports.pageByKey = exports.newestFirst = exports.parsePage = exports.ListParamError = exports.VALUES_LIMIT = exports.MAX_LIMIT = void 0;
15
+ // the most a page holds
16
+ exports.MAX_LIMIT = 200;
17
+ // the values of a field a page holds when the caller names no limit
18
+ exports.VALUES_LIMIT = 50;
19
+ // A parameter of a list that is not right: the caller is answered 400 with the message.
20
+ class ListParamError extends Error {
21
+ }
22
+ exports.ListParamError = ListParamError;
23
+ // `limit` and `cursor`: undefined when the caller names no limit, and gets everything.
24
+ function parsePage(params, fallback) {
25
+ const limit = params.get('limit');
26
+ const cursor = params.get('cursor') ?? undefined;
27
+ if (limit === null) {
28
+ if (cursor !== undefined && fallback === undefined) {
29
+ throw new ListParamError('cursor: only with limit');
30
+ }
31
+ return fallback === undefined ? undefined : { limit: fallback, ...(cursor !== undefined ? { cursor } : {}) };
32
+ }
33
+ if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > exports.MAX_LIMIT) {
34
+ throw new ListParamError(`limit: a number from 1 to ${exports.MAX_LIMIT}`);
35
+ }
36
+ return { limit: Number(limit), ...(cursor !== undefined ? { cursor } : {}) };
37
+ }
38
+ exports.parsePage = parsePage;
39
+ function encode(value) {
40
+ return Buffer.from(JSON.stringify(value)).toString('base64url');
41
+ }
42
+ function decode(cursor) {
43
+ try {
44
+ return JSON.parse(Buffer.from(cursor, 'base64url').toString());
45
+ }
46
+ catch {
47
+ throw new ListParamError('cursor: not one this server answered');
48
+ }
49
+ }
50
+ const before = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
51
+ function newestFirst(items, keyOf) {
52
+ return [...items].sort((a, b) => {
53
+ const x = keyOf(a);
54
+ const y = keyOf(b);
55
+ return before(x, y) ? 1 : before(y, x) ? -1 : 0;
56
+ });
57
+ }
58
+ exports.newestFirst = newestFirst;
59
+ /**
60
+ * A page of a list ordered newest first, by the time `keyOf` gives (newestFirst, or the order
61
+ * it was kept in): the cursor names the last one answered, by its time and id, so what is
62
+ * added meanwhile does not repeat one. When the last one answered is gone, the page goes on
63
+ * with the ones older than it.
64
+ */
65
+ function pageByKey(items, page, keyOf) {
66
+ let start = 0;
67
+ if (page.cursor !== undefined) {
68
+ const after = decode(page.cursor);
69
+ if (!Array.isArray(after) || after.length !== 2 || !after.every((part) => typeof part === 'string')) {
70
+ throw new ListParamError('cursor: not one this server answered');
71
+ }
72
+ const [at, id] = after;
73
+ const last = items.findIndex((item) => keyOf(item)[1] === id);
74
+ start = last >= 0 ? last + 1 : items.findIndex((item) => keyOf(item)[0] < at);
75
+ if (start < 0) {
76
+ return { items: [] };
77
+ }
78
+ }
79
+ const answered = items.slice(start, start + page.limit);
80
+ const more = start + page.limit < items.length;
81
+ return { items: answered, ...(more ? { next: encode(keyOf(answered[answered.length - 1])) } : {}) };
82
+ }
83
+ exports.pageByKey = pageByKey;
84
+ // A page of a list in an order of its own, such as numbers sorted by a column: by position.
85
+ function pageByPosition(items, page) {
86
+ let start = 0;
87
+ if (page.cursor !== undefined) {
88
+ const at = decode(page.cursor);
89
+ if (typeof at !== 'object' || at === null || !Number.isSafeInteger(at.at)) {
90
+ throw new ListParamError('cursor: not one this server answered');
91
+ }
92
+ start = Math.max(0, at.at);
93
+ }
94
+ const end = start + page.limit;
95
+ return { items: items.slice(start, end), ...(end < items.length ? { next: encode({ at: end }) } : {}) };
96
+ }
97
+ exports.pageByPosition = pageByPosition;
98
+ // The answer of a page: the list under its name, and `next` while more remain.
99
+ function answerPage(name, page) {
100
+ return { [name]: page.items, ...(page.next ? { next: page.next } : {}) };
101
+ }
102
+ exports.answerPage = answerPage;
103
+ // `values`, `search`, `limit` and `cursor`: undefined when the caller asks for the list.
104
+ function parseValues(params, fields) {
105
+ const field = params.get('values');
106
+ if (field === null) {
107
+ return undefined;
108
+ }
109
+ if (!fields.includes(field)) {
110
+ throw new ListParamError(`values: one of ${fields.join(', ')}`);
111
+ }
112
+ const search = params.get('search')?.trim().slice(0, 200);
113
+ return {
114
+ field: field,
115
+ ...(search ? { search } : {}),
116
+ page: parsePage(params, exports.VALUES_LIMIT),
117
+ };
118
+ }
119
+ exports.parseValues = parseValues;
120
+ /**
121
+ * The values `of` gives the items, each with how many items have it: the most first, then by
122
+ * name, or in the order of `order`; narrowed by the search and paged by position.
123
+ */
124
+ function countValues(items, of, request, order) {
125
+ const counts = new Map();
126
+ for (const item of items) {
127
+ const seen = new Set();
128
+ for (const found of of(item)) {
129
+ const { value, name } = typeof found === 'string' ? { value: found, name: undefined } : found;
130
+ if (seen.has(value)) {
131
+ continue;
132
+ }
133
+ seen.add(value);
134
+ const counted = counts.get(value) ?? { value, count: 0, ...(name ? { name } : {}) };
135
+ counted.count++;
136
+ counts.set(value, counted);
137
+ }
138
+ }
139
+ const needle = request.search?.toLowerCase();
140
+ const values = [...counts.values()]
141
+ .filter((counted) => !needle || counted.value.toLowerCase().includes(needle) || (counted.name ?? '').toLowerCase().includes(needle))
142
+ .sort((a, b) => order ? order.indexOf(a.value) - order.indexOf(b.value) : b.count - a.count || a.value.localeCompare(b.value));
143
+ return pageByPosition(values, request.page);
144
+ }
145
+ exports.countValues = countValues;
146
+ // The values of a filter the caller names: the parameter repeated, `state=queued&state=running`.
147
+ function readList(params, name) {
148
+ const values = params
149
+ .getAll(name)
150
+ .map((value) => value.trim())
151
+ .filter(Boolean);
152
+ return values.length > 0 ? values : undefined;
153
+ }
154
+ exports.readList = readList;
155
+ // the text a list is searched for: `q`, at most 200 characters
156
+ function readText(params) {
157
+ const text = params.get('q')?.trim().slice(0, 200);
158
+ return text ? text : undefined;
159
+ }
160
+ exports.readText = readText;
161
+ // Whether any of the values has the text in it, in any case.
162
+ function hasText(values, text) {
163
+ const needle = text.toLowerCase();
164
+ return values.some((value) => !!value && value.toLowerCase().includes(needle));
165
+ }
166
+ exports.hasText = hasText;
167
+ //# sourceMappingURL=paging.js.map