hammerkit 2.1.0-next.2 → 2.1.0-next.21

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 (87) hide show
  1. package/build.schema.json +39 -18
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/environment/replace-env-variables.js +8 -5
  8. package/dist/environment/run-source-envs.js +2 -1
  9. package/dist/executer/archive-task-entry.js +1 -1
  10. package/dist/executer/deadline.js +63 -10
  11. package/dist/executer/event-cache.js +5 -1
  12. package/dist/executer/execute-work-task.js +15 -3
  13. package/dist/executer/runner-commands.js +36 -0
  14. package/dist/file/get-file-context.js +4 -7
  15. package/dist/harness/connect.js +12 -8
  16. package/dist/harness/reconnect.js +141 -0
  17. package/dist/harness/sandbox-client.js +241 -33
  18. package/dist/harness/service-tools.js +11 -2
  19. package/dist/kubernetes/cluster-state.js +48 -14
  20. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  21. package/dist/kubernetes/follow-pod-logs.js +8 -5
  22. package/dist/kubernetes/kept-claims.js +26 -5
  23. package/dist/kubernetes/resources.js +5 -1
  24. package/dist/kubernetes/sandbox-runner.js +526 -156
  25. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  26. package/dist/kubernetes/sync-changes.js +463 -0
  27. package/dist/kubernetes/volumes.js +23 -1
  28. package/dist/optimizer/get-work-cache-stats.js +7 -0
  29. package/dist/optimizer/work-task-cache-description.js +3 -2
  30. package/dist/planner/image-build.js +5 -0
  31. package/dist/planner/utils/dependency-outputs.js +7 -6
  32. package/dist/planner/validate.js +41 -0
  33. package/dist/planner/work-item-status.js +12 -2
  34. package/dist/planner/work-runtime-aggregate.js +1 -0
  35. package/dist/planner/work-runtime-docker.js +33 -6
  36. package/dist/planner/work-runtime-kubernetes.js +313 -70
  37. package/dist/planner/work-runtime-local.js +8 -4
  38. package/dist/planner/work-secret.js +33 -11
  39. package/dist/planner/work-service-id.js +30 -6
  40. package/dist/program.js +19 -1
  41. package/dist/remote/annotations.js +37 -5
  42. package/dist/remote/bundle.js +6 -8
  43. package/dist/remote/collect-bundle.js +3 -2
  44. package/dist/remote/device-login.js +4 -1
  45. package/dist/remote/remote-commands.js +16 -7
  46. package/dist/remote/remote-work-commands.js +266 -75
  47. package/dist/remote/server-client.js +38 -40
  48. package/dist/schema/build-file-base-task-schema.js +16 -1
  49. package/dist/schema/build-file-image-build-schema.js +5 -8
  50. package/dist/schema/reference-parser.js +108 -43
  51. package/dist/schema/work-scope-parser.js +8 -0
  52. package/dist/secrets/prefetch-secrets.js +20 -1
  53. package/dist/server/artifacts-api.js +56 -0
  54. package/dist/server/definitions-api.js +62 -8
  55. package/dist/server/executor.js +117 -30
  56. package/dist/server/http.js +4 -1
  57. package/dist/server/keep-artifacts.js +230 -0
  58. package/dist/server/kubernetes-backend.js +186 -59
  59. package/dist/server/kubernetes-sandbox-storage.js +3 -2
  60. package/dist/server/overview.js +73 -9
  61. package/dist/server/paging.js +167 -0
  62. package/dist/server/plan.js +16 -1
  63. package/dist/server/run-access.js +24 -0
  64. package/dist/server/run-artifacts.js +171 -0
  65. package/dist/server/run-logs.js +25 -1
  66. package/dist/server/run-request.js +11 -0
  67. package/dist/server/run-source-environment.js +1 -1
  68. package/dist/server/run-worker.js +267 -33
  69. package/dist/server/runs.js +527 -99
  70. package/dist/server/sandbox-files-api.js +27 -12
  71. package/dist/server/sandbox-files.js +12 -10
  72. package/dist/server/sandbox-follow.js +54 -0
  73. package/dist/server/sandbox-pod.js +1 -1
  74. package/dist/server/sandbox-storage.js +38 -1
  75. package/dist/server/sandbox-sync.js +392 -0
  76. package/dist/server/sandboxes-api.js +116 -19
  77. package/dist/server/sandboxes.js +38 -3
  78. package/dist/server/server-config.js +14 -0
  79. package/dist/server/server.js +169 -38
  80. package/dist/server/task-order.js +56 -0
  81. package/dist/utils/project-path.js +20 -0
  82. package/dist/utils/tar-files.js +52 -0
  83. package/dist/utils/tar.js +37 -1
  84. package/package.json +1 -1
  85. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  86. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  87. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -0,0 +1,392 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SandboxSync = exports.unsafePath = exports.MAX_BATCH_FILES = exports.MAX_BATCH_BYTES = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const log_1 = require("../log");
6
+ const tar_files_1 = require("../utils/tar-files");
7
+ const sandbox_files_1 = require("./sandbox-files");
8
+ // the most bytes of files one part of a batch sends; a larger batch goes in several parts
9
+ exports.MAX_BATCH_BYTES = 16 * 1024 * 1024;
10
+ // the most files one part of a batch sends
11
+ exports.MAX_BATCH_FILES = 10000;
12
+ // how many files of a sandbox are read at once, while a batch is worked out
13
+ const READ_CONCURRENCY = 8;
14
+ // a file whose mtime is this recent may be written again in the same timestamp: it is read again
15
+ // on every sync, as git does with its index (the racy rule)
16
+ const RACY_MS = 2000;
17
+ // how long a run whose services failed to apply a batch waits before the full set is sent again:
18
+ // the first wait, doubled on each failure up to RETRY_MAX_MS
19
+ const RETRY_MIN_MS = 1000;
20
+ const RETRY_MAX_MS = 10000;
21
+ // what a path is in the services when it is gone
22
+ const ABSENT = 'absent';
23
+ /**
24
+ * Why a path of the sandbox can not be a path of a service's folder, or none. A name with a
25
+ * control character (a newline in particular), an absolute path, an empty segment, a trailing `/`
26
+ * or a `.` or `..` segment is refused: each of those can name the folder itself or one above it.
27
+ */
28
+ function unsafePath(path) {
29
+ if (path === '') {
30
+ return 'it is empty';
31
+ }
32
+ if ([...path].some((char) => char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f)) {
33
+ return 'it has a control character';
34
+ }
35
+ if (path.startsWith('/') || /^[A-Za-z]:/.test(path)) {
36
+ return 'it is not relative to the sandbox';
37
+ }
38
+ if (path.endsWith('/') || path.split('/').includes('')) {
39
+ return 'it has an empty segment or ends in /';
40
+ }
41
+ if (path.split('/').some((segment) => segment === '..' || segment === '.')) {
42
+ return 'it has a . or .. segment';
43
+ }
44
+ return undefined;
45
+ }
46
+ exports.unsafePath = unsafePath;
47
+ // whether a file with this mtime may still change without its mtime changing: an mtime that is
48
+ // recent, or one that is not a date, is read on every sync
49
+ function racy(modifiedAt) {
50
+ const time = Date.parse(modifiedAt);
51
+ return Number.isNaN(time) || Date.now() - time < RACY_MS;
52
+ }
53
+ // the mtime of a file as it is in the sandbox, for its entry of an archive
54
+ function mtimeOf(modifiedAt) {
55
+ const time = Date.parse(modifiedAt);
56
+ return Number.isNaN(time) ? new Date() : new Date(time);
57
+ }
58
+ /**
59
+ * The files of a batch in parts, each under the caps (MAX_BATCH_FILES, MAX_BATCH_BYTES), in the
60
+ * order they came. A file over the byte cap goes alone in its part: the parts are sent one after
61
+ * another, so each stays under the cap in memory.
62
+ */
63
+ function partition(writes) {
64
+ const parts = [];
65
+ let part = [];
66
+ let bytes = 0;
67
+ for (const write of writes) {
68
+ if (part.length > 0 && (part.length === exports.MAX_BATCH_FILES || bytes + write.size > exports.MAX_BATCH_BYTES)) {
69
+ parts.push(part);
70
+ part = [];
71
+ bytes = 0;
72
+ }
73
+ part.push(write);
74
+ bytes += write.size;
75
+ }
76
+ if (part.length > 0) {
77
+ parts.push(part);
78
+ }
79
+ return parts;
80
+ }
81
+ // the results of `fn` for `items`, with at most `limit` calls in flight
82
+ async function mapLimit(items, limit, fn) {
83
+ const results = new Array(items.length);
84
+ let next = 0;
85
+ const worker = async () => {
86
+ while (next < items.length) {
87
+ const index = next++;
88
+ results[index] = await fn(items[index]);
89
+ }
90
+ };
91
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
92
+ return results;
93
+ }
94
+ /**
95
+ * Keeps the services of the service runs on a sandbox in step with its files. Each change of the
96
+ * sandbox (batched by SandboxFollow) goes to each run that is up, as the files that changed since
97
+ * the services last got their files. Nothing else of the services is touched, and nothing is
98
+ * restarted here.
99
+ *
100
+ * The record of what the services have is kept in memory, per run: for each path, the stat and
101
+ * the hash of the file the services got, or ABSENT once its deletion went out. A file whose stat
102
+ * did not change, and whose mtime is not recent, is not read at all. A run without a record (the
103
+ * server started since it did) gets every file that differs from the commit once: "the full set"
104
+ * means exactly that. A run whose services failed to apply a batch loses its record, and the full
105
+ * set is sent again after a backoff.
106
+ */
107
+ class SandboxSync {
108
+ constructor(options) {
109
+ this.options = options;
110
+ // per run, what the services have of each path they got (see the class comment)
111
+ this.records = new Map();
112
+ // the sandbox of each run that was started here, for the retry of its failed batch
113
+ this.sandboxes = new Map();
114
+ // per run, the timer of its retry and how long the wait was
115
+ this.retries = new Map();
116
+ // the batches of each sandbox, one after another
117
+ this.queues = new Map();
118
+ // the batch of each sandbox that waits to start: it reads the files when it starts, so a
119
+ // change that comes meanwhile is in it too
120
+ this.waiting = new Map();
121
+ // per run, the lines already logged: a path that is refused says so once
122
+ this.logged = new Map();
123
+ }
124
+ /**
125
+ * A service run starts from a copy of the files now: what differs from the commit in the copy
126
+ * is what the services have from the start, and what a later change has to include.
127
+ */
128
+ async started(run) {
129
+ if (run.source.type !== 'sandbox') {
130
+ return;
131
+ }
132
+ this.sandboxes.set(run.id, run.source.id);
133
+ const files = this.options.files(run.owner, run.source.id);
134
+ const record = new Map();
135
+ const paths = (await this.changedPaths(files)).filter((path) => !unsafePath(path));
136
+ const looked = await mapLimit(paths, READ_CONCURRENCY, (path) => this.look(files, path, undefined, () => undefined));
137
+ for (const item of looked) {
138
+ if (item.kind === 'same') {
139
+ record.set(item.path, item.mark);
140
+ }
141
+ else if (item.kind === 'changed') {
142
+ record.set(item.path, item.mark);
143
+ }
144
+ else if (item.kind === 'gone') {
145
+ record.set(item.path, ABSENT);
146
+ }
147
+ }
148
+ this.records.set(run.id, record);
149
+ }
150
+ // A run that ended: nothing is synced for it any more, and its retry is stopped
151
+ async forget(run) {
152
+ this.records.delete(run);
153
+ this.sandboxes.delete(run);
154
+ this.logged.delete(run);
155
+ this.clearRetry(run);
156
+ }
157
+ /**
158
+ * The services of a run did not apply the last batch: its record goes, and the full set is sent
159
+ * again after a backoff (1 s, doubled on each failure up to 10 s).
160
+ */
161
+ failed(run) {
162
+ this.records.delete(run);
163
+ const sandbox = this.sandboxes.get(run);
164
+ if (sandbox === undefined) {
165
+ return;
166
+ }
167
+ const previous = this.retries.get(run);
168
+ const delay = previous ? Math.min(previous.delay * 2, RETRY_MAX_MS) : RETRY_MIN_MS;
169
+ if (previous) {
170
+ clearTimeout(previous.timer);
171
+ }
172
+ const timer = setTimeout(() => void this.follow(sandbox), delay);
173
+ timer.unref?.();
174
+ this.retries.set(run, { timer, delay });
175
+ }
176
+ // Stops the retries: nothing is sent after the server closes
177
+ close() {
178
+ for (const { timer } of this.retries.values()) {
179
+ clearTimeout(timer);
180
+ }
181
+ this.retries.clear();
182
+ }
183
+ clearRetry(run) {
184
+ const retry = this.retries.get(run);
185
+ if (retry) {
186
+ clearTimeout(retry.timer);
187
+ this.retries.delete(run);
188
+ }
189
+ }
190
+ // The batch of changes of a sandbox, after the ones before it. One that waits already has the
191
+ // newest files when it starts, so a second one is not queued behind it.
192
+ follow(sandbox) {
193
+ const waiting = this.waiting.get(sandbox);
194
+ if (waiting) {
195
+ return waiting;
196
+ }
197
+ const previous = this.queues.get(sandbox) ?? Promise.resolve();
198
+ const next = previous
199
+ .then(() => {
200
+ this.waiting.delete(sandbox);
201
+ return this.sync(sandbox);
202
+ })
203
+ .catch((e) => this.log(`sync sandbox ${sandbox}: ${(0, log_1.getErrorMessage)(e)}`));
204
+ this.waiting.set(sandbox, next);
205
+ this.queues.set(sandbox, next);
206
+ void next.then(() => {
207
+ if (this.queues.get(sandbox) === next) {
208
+ this.queues.delete(sandbox);
209
+ }
210
+ });
211
+ return next;
212
+ }
213
+ async sync(sandbox) {
214
+ const runs = this.options.upOn(sandbox);
215
+ if (runs.length === 0) {
216
+ return;
217
+ }
218
+ // the files of a sandbox are one owner's: a run of another owner would read them as theirs
219
+ const [{ owner }] = runs;
220
+ if (runs.some((run) => run.owner.iss !== owner.iss || run.owner.sub !== owner.sub)) {
221
+ throw new Error(`the service runs on ${sandbox} have more than one owner, their changes are not synced`);
222
+ }
223
+ const files = this.options.files(owner, sandbox);
224
+ const changed = await this.changedPaths(files);
225
+ for (const run of runs) {
226
+ await this.sendTo(run, sandbox, files, changed);
227
+ }
228
+ }
229
+ /**
230
+ * Sends the batch of one run: the paths that changed since the record of the run (or, without
231
+ * one, the paths that differ from the commit). A batch over the caps goes in parts, one after the
232
+ * other. The record moves on for each part the services took; a part they refuse is in the next
233
+ * batch.
234
+ */
235
+ async sendTo(run, sandbox, files, changed) {
236
+ const record = this.records.get(run.id) ?? new Map();
237
+ this.records.set(run.id, record);
238
+ const say = (line) => this.logOnce(run.id, line);
239
+ const candidates = [...new Set([...changed, ...record.keys()])].filter((path) => {
240
+ const problem = unsafePath(path);
241
+ if (problem) {
242
+ say(`skipped ${JSON.stringify(path)} of the sandbox: ${problem}`);
243
+ record.delete(path);
244
+ }
245
+ return !problem;
246
+ });
247
+ const writes = [];
248
+ const gone = [];
249
+ const looked = await mapLimit(candidates, READ_CONCURRENCY, (path) => this.look(files, path, record.get(path), say));
250
+ for (const item of looked) {
251
+ if (item.kind === 'refused') {
252
+ // not in the record: the next batch that has it sends it again
253
+ record.delete(item.path);
254
+ }
255
+ else if (item.kind === 'same') {
256
+ record.set(item.path, item.mark);
257
+ }
258
+ else if (item.kind === 'gone') {
259
+ gone.push(item.path);
260
+ }
261
+ else {
262
+ writes.push({ ...item.mark, path: item.path, content: item.content });
263
+ }
264
+ }
265
+ const parts = partition(writes);
266
+ if (parts.length > 1) {
267
+ say(`the changes of ${sandbox} are more than a batch takes, ${run.id} gets them in ${parts.length} parts`);
268
+ }
269
+ // the gone paths go with the first part; with no file written, they go alone
270
+ const batches = parts.length > 0 ? parts : [[]];
271
+ for (const [index, part] of batches.entries()) {
272
+ const removed = index === 0 ? gone : [];
273
+ if (part.length + removed.length === 0) {
274
+ continue;
275
+ }
276
+ const changes = {
277
+ archive: (0, tar_files_1.tarFiles)(part.map((write) => ({
278
+ path: write.path,
279
+ mode: write.exec ? 0o755 : 0o644,
280
+ content: write.content,
281
+ mtime: mtimeOf(write.modifiedAt),
282
+ }))),
283
+ written: part.map((write) => write.path),
284
+ deleted: removed,
285
+ restart: false,
286
+ };
287
+ if (!this.options.send(run.id, changes)) {
288
+ return;
289
+ }
290
+ for (const write of part) {
291
+ record.set(write.path, { size: write.size, modifiedAt: write.modifiedAt, exec: write.exec, hash: write.hash });
292
+ }
293
+ // a deletion stays in the record as ABSENT: git lists a deleted file until it is committed,
294
+ // and a deletion that is not recorded would be sent again on every sync
295
+ for (const path of removed) {
296
+ record.set(path, ABSENT);
297
+ }
298
+ // a batch went: the next failure starts the backoff again
299
+ this.clearRetry(run.id);
300
+ }
301
+ }
302
+ /**
303
+ * What a path of the sandbox is, against what the services have of it (`known`). A file whose
304
+ * size, mtime and exec bit are the ones the services have, and whose mtime is not racy, is the
305
+ * same without a read. Otherwise its content is read once and hashed, and the read is kept for
306
+ * the entry of the batch.
307
+ */
308
+ async look(files, path, known, say) {
309
+ let stat;
310
+ try {
311
+ stat = await files.stat(path);
312
+ }
313
+ catch (e) {
314
+ say(`skipped ${JSON.stringify(path)} of the sandbox: ${(0, log_1.getErrorMessage)(e)}`);
315
+ return { path, kind: 'refused' };
316
+ }
317
+ if (stat?.type !== 'file') {
318
+ return known === ABSENT ? { path, kind: 'same', mark: ABSENT } : { path, kind: 'gone' };
319
+ }
320
+ if (stat.size > sandbox_files_1.MAX_FILE_BYTES) {
321
+ say(`refused ${JSON.stringify(path)} of the sandbox: it is over ${sandbox_files_1.MAX_FILE_BYTES} bytes`);
322
+ return { path, kind: 'refused' };
323
+ }
324
+ if (known !== undefined &&
325
+ known !== ABSENT &&
326
+ known.size === stat.size &&
327
+ known.modifiedAt === stat.modifiedAt &&
328
+ known.exec === stat.exec &&
329
+ !racy(stat.modifiedAt)) {
330
+ return { path, kind: 'same', mark: known };
331
+ }
332
+ let read;
333
+ try {
334
+ read = await this.readOf(files, path);
335
+ }
336
+ catch (e) {
337
+ say(`skipped ${JSON.stringify(path)} of the sandbox: ${(0, log_1.getErrorMessage)(e)}`);
338
+ return { path, kind: 'refused' };
339
+ }
340
+ if (read === undefined || read.content.length > sandbox_files_1.MAX_FILE_BYTES) {
341
+ say(`refused ${JSON.stringify(path)} of the sandbox: it is over ${sandbox_files_1.MAX_FILE_BYTES} bytes`);
342
+ return { path, kind: 'refused' };
343
+ }
344
+ const mark = {
345
+ size: stat.size,
346
+ modifiedAt: stat.modifiedAt,
347
+ exec: stat.exec,
348
+ hash: read.sha256 ?? (0, crypto_1.createHash)('sha256').update(read.content).digest('hex'),
349
+ };
350
+ if (known !== undefined && known !== ABSENT && known.hash === mark.hash && known.exec === mark.exec) {
351
+ return { path, kind: 'same', mark };
352
+ }
353
+ return { path, kind: 'changed', mark, content: read.content };
354
+ }
355
+ // logs a line of a run once: a path that stays refused is not said again on every sync
356
+ logOnce(run, line) {
357
+ const lines = this.logged.get(run) ?? new Set();
358
+ this.logged.set(run, lines);
359
+ if (!lines.has(line)) {
360
+ lines.add(line);
361
+ this.log(line);
362
+ }
363
+ }
364
+ log(line) {
365
+ this.options.log?.(line);
366
+ }
367
+ /**
368
+ * The content of a file of the sandbox, read whole, with its hash when the files give one.
369
+ * Undefined for a file that is over the cap at open: its stream is destroyed, and nothing is
370
+ * read into memory.
371
+ */
372
+ async readOf(files, path) {
373
+ const raw = await files.raw(path);
374
+ if (raw.content) {
375
+ return { content: raw.content, sha256: raw.sha256 };
376
+ }
377
+ raw.stream?.destroy();
378
+ return undefined;
379
+ }
380
+ async changedPaths(files) {
381
+ const paths = new Set();
382
+ for (const change of await files.changes()) {
383
+ paths.add(change.path);
384
+ if (change.from) {
385
+ paths.add(change.from);
386
+ }
387
+ }
388
+ return [...paths];
389
+ }
390
+ }
391
+ exports.SandboxSync = SandboxSync;
392
+ //# sourceMappingURL=sandbox-sync.js.map
@@ -8,6 +8,7 @@ const repo_1 = require("./repo");
8
8
  const runs_1 = require("./runs");
9
9
  const sandbox_files_api_1 = require("./sandbox-files-api");
10
10
  const sandboxes_1 = require("./sandboxes");
11
+ const paging_1 = require("./paging");
11
12
  const refSchema = zod_1.z.string().min(1).max(200);
12
13
  const createSchema = zod_1.z
13
14
  .object({
@@ -45,7 +46,11 @@ const pushSchema = zod_1.z
45
46
  * The sandboxes of a caller: checkouts on the server that runs work on.
46
47
  *
47
48
  * POST /v1/sandboxes { repo, ref } fetch a branch into a new sandbox
48
- * GET /v1/sandboxes the caller's sandboxes, their limits and usage
49
+ * GET /v1/sandboxes the caller's sandboxes, their limits and usage;
50
+ * `?scope=all` everybody's, with `observe`; `owner`,
51
+ * `repo` and `ref` narrow them, `limit` and `cursor`
52
+ * page them the last used first, `values=<field>`
53
+ * answers the values of a filter (paging.ts)
49
54
  * GET /v1/sandboxes/<id> one sandbox
50
55
  * DELETE /v1/sandboxes/<id> cancel its runs and remove it
51
56
  * POST /v1/sandboxes/<id>/fetch { ref } move a sandbox without changes to a branch's commit
@@ -53,7 +58,10 @@ const pushSchema = zod_1.z
53
58
  * ... /v1/sandboxes/<id>/tree, files/<path>, search, edits, changes: its files, see
54
59
  * `handleSandboxFiles`
55
60
  *
56
- * A sandbox is its owner's: anybody else gets `404`.
61
+ * A sandbox is its owner's: anybody else gets `404`. Who observes (`observe` on an
62
+ * entitlement) may read every sandbox, as they read every run: list them, and get one, its
63
+ * tree, files, search and changes. Everything that changes a sandbox or runs on it stays
64
+ * its owner's, and is `404` to them too.
57
65
  */
58
66
  async function handleSandboxes(config, sandboxes, repos, log, principal, req, res, url) {
59
67
  const match = /^\/v1\/sandboxes(?:\/([^/]+)(?:\/(fetch|push|tree|search|edits|changes)|\/(files)\/(.+))?)?$/.exec(url.pathname);
@@ -64,15 +72,28 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
64
72
  const action = named ?? files;
65
73
  const method = req.method;
66
74
  const who = `iss=${principal.iss} sub=${principal.sub}`;
75
+ const show = (sandbox) => view(config, sandboxes, principal, sandbox);
67
76
  try {
68
77
  if (!id) {
69
78
  if (method === 'GET') {
70
- const limits = sandboxes.limits;
71
- (0, http_1.send)(res, 200, {
72
- sandboxes: sandboxes.list(principal).map((sandbox) => view(sandboxes, sandbox)),
73
- limits: { count: limits.count, bytes: limits.bytes },
74
- used: sandboxes.usage(principal),
75
- });
79
+ const scope = url.searchParams.get('scope') ?? 'mine';
80
+ if (scope !== 'mine' && scope !== 'all') {
81
+ (0, http_1.send)(res, 400, { error: 'scope: mine or all' });
82
+ return true;
83
+ }
84
+ if (scope === 'all' && !(0, policy_1.getGrant)(config.entitlements, principal).observe) {
85
+ (0, http_1.send)(res, 403, { error: 'scope all needs an entitlement with observe' });
86
+ return true;
87
+ }
88
+ try {
89
+ listSandboxes(config, sandboxes, principal, scope, url.searchParams, res, show);
90
+ }
91
+ catch (e) {
92
+ if (!(e instanceof paging_1.ListParamError)) {
93
+ throw e;
94
+ }
95
+ (0, http_1.send)(res, 400, { error: e.message });
96
+ }
76
97
  }
77
98
  else if (method === 'POST') {
78
99
  const body = parse(createSchema, await (0, http_1.readJson)(req));
@@ -84,21 +105,29 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
84
105
  }
85
106
  const sandbox = await sandboxes.create(principal, body.repo, body.ref);
86
107
  log(`sandbox create ${sandbox.id} ${who} repo=${sandbox.repo} commit=${sandbox.commit} bytes=${sandbox.bytes}`);
87
- (0, http_1.send)(res, 201, view(sandboxes, sandbox));
108
+ (0, http_1.send)(res, 201, show(sandbox));
88
109
  }
89
110
  else {
90
111
  (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET, POST' });
91
112
  }
92
113
  return true;
93
114
  }
94
- const sandbox = runs_1.SANDBOX_ID_PATTERN.test(id) ? sandboxes.get(principal, id) : undefined;
115
+ const known = runs_1.SANDBOX_ID_PATTERN.test(id);
116
+ const own = known ? sandboxes.get(principal, id) : undefined;
117
+ const observes = (0, policy_1.getGrant)(config.entitlements, principal).observe;
118
+ const reading = isRead(action, method);
119
+ // who observes reads the sandbox of anybody; a change is for its owner, and else not found
120
+ const sandbox = own ?? (known && observes && reading ? sandboxes.peek(id) : undefined);
95
121
  if (!sandbox) {
96
122
  (0, http_1.send)(res, 404, { error: 'not found' });
97
123
  return true;
98
124
  }
99
125
  if (action && action !== 'fetch' && action !== 'push') {
100
- // the caller may have lost the repository, or the sandbox's branch, since they created it
101
- const refused = (0, policy_1.decideSandbox)((0, policy_1.getGrant)(config.entitlements, principal), sandbox.repo, sandbox.ref, (repo) => repos.readable(repo));
126
+ // the owner may have lost the repository, or the sandbox's branch, since they created
127
+ // it; who observes reads it all the same
128
+ const refused = own && !(observes && reading)
129
+ ? (0, policy_1.decideSandbox)((0, policy_1.getGrant)(config.entitlements, principal), sandbox.repo, sandbox.ref, (repo) => repos.readable(repo))
130
+ : undefined;
102
131
  if (refused) {
103
132
  log(`refuse sandbox ${action} ${id} ${who}: ${refused.error}`);
104
133
  (0, http_1.send)(res, refused.status, { error: refused.error });
@@ -133,15 +162,15 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
133
162
  if ('branch' in body) {
134
163
  const pushed = await sandboxes.push(principal, id, body.branch, { ...author(principal), message: body.message }, (0, policy_1.sandboxPushBranches)(grant, sandbox.repo));
135
164
  log(`sandbox push ${id} ${who} branch=${body.branch} commit=${pushed.commit}`);
136
- (0, http_1.send)(res, 200, { branch: body.branch, commit: pushed.commit, sandbox: view(sandboxes, pushed) });
165
+ (0, http_1.send)(res, 200, { branch: body.branch, commit: pushed.commit, sandbox: show(pushed) });
137
166
  return true;
138
167
  }
139
168
  const fetched = await sandboxes.fetch(principal, id, body.ref);
140
169
  log(`sandbox fetch ${id} ${who} ref=${body.ref} commit=${fetched.commit}`);
141
- (0, http_1.send)(res, 200, view(sandboxes, fetched));
170
+ (0, http_1.send)(res, 200, show(fetched));
142
171
  }
143
172
  else if (method === 'GET') {
144
- (0, http_1.send)(res, 200, view(sandboxes, sandbox));
173
+ (0, http_1.send)(res, 200, show(sandbox));
145
174
  }
146
175
  else if (method === 'DELETE') {
147
176
  // a caller who lost the entitlement can still delete what they keep
@@ -206,11 +235,79 @@ function author(principal) {
206
235
  return { name, email: `${local}@${host}` };
207
236
  }
208
237
  exports.author = author;
209
- // What the owner sees: everything but the owner, and the run that holds it.
210
- function view(sandboxes, sandbox) {
238
+ /**
239
+ * Whether a request only reads a sandbox, which who observes may: the sandbox, its tree, a
240
+ * file, a search and its changes. Edits, a write of a file, a fetch, a push and a delete
241
+ * change it.
242
+ */
243
+ function isRead(action, method) {
244
+ switch (action) {
245
+ case undefined:
246
+ return method === 'GET';
247
+ case 'tree':
248
+ case 'changes':
249
+ return method === 'GET';
250
+ case 'files':
251
+ return method === 'GET' || method === 'HEAD';
252
+ case 'search':
253
+ // ripgrep's query is a body
254
+ return method === 'POST';
255
+ default:
256
+ return false;
257
+ }
258
+ }
259
+ // A sandbox as the caller sees it, and the run that holds it: their own without its owner,
260
+ // one of somebody else (who observes) with whose it is, as a run of somebody else names it.
261
+ function view(config, sandboxes, principal, sandbox) {
211
262
  const { owner, ...visible } = sandbox;
212
- void owner;
213
263
  const run = sandboxes.holder(sandbox.id);
214
- return { ...visible, busy: run !== undefined, run: run ?? null };
264
+ const mine = owner.iss === principal.iss && owner.sub === principal.sub;
265
+ const name = owner.name ?? (0, policy_1.subjectName)(config.entitlements, owner);
266
+ return {
267
+ ...visible,
268
+ ...(mine ? {} : { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } }),
269
+ busy: run !== undefined,
270
+ run: run ?? null,
271
+ };
272
+ }
273
+ // what the sandboxes page narrows by, and GET /v1/sandboxes?values= answers the values of
274
+ const SANDBOX_FIELDS = ['owner', 'repo', 'ref'];
275
+ function parseSandboxFilter(params) {
276
+ return Object.fromEntries(SANDBOX_FIELDS.map((field) => [field, (0, paging_1.readList)(params, field)]).filter(([, values]) => values));
277
+ }
278
+ function filterSandboxes(sandboxes, filter) {
279
+ return sandboxes.filter((sandbox) => (!filter.owner || filter.owner.includes(sandbox.owner.sub)) &&
280
+ (!filter.repo || filter.repo.includes(sandbox.repo)) &&
281
+ (!filter.ref || filter.ref.includes(sandbox.ref)));
282
+ }
283
+ // the last used first, as the sandboxes page shows them
284
+ const sandboxKey = (sandbox) => [sandbox.lastUsedAt, sandbox.id];
285
+ function pageOfSandboxes(sandboxes, page, show) {
286
+ const answered = (0, paging_1.pageByKey)((0, paging_1.newestFirst)(sandboxes, sandboxKey), page, sandboxKey);
287
+ return { ...answered, items: answered.items.map(show) };
288
+ }
289
+ // GET /v1/sandboxes: the sandboxes of the scope that the filters let through, a page of them,
290
+ // or the values of a filter.
291
+ function listSandboxes(config, sandboxes, principal, scope, params, res, show) {
292
+ const filter = parseSandboxFilter(params);
293
+ const values = (0, paging_1.parseValues)(params, SANDBOX_FIELDS);
294
+ const page = values ? undefined : (0, paging_1.parsePage)(params);
295
+ const listed = scope === 'all' ? sandboxes.all() : sandboxes.list(principal);
296
+ const nameOf = (owner) => owner.name ?? (0, policy_1.subjectName)(config.entitlements, owner);
297
+ if (values) {
298
+ // a value of the field is counted over the sandboxes the other filters let through
299
+ const { field } = values;
300
+ const counted = (0, paging_1.countValues)(filterSandboxes(listed, { ...filter, [field]: undefined }), (sandbox) => [field === 'owner' ? { value: sandbox.owner.sub, name: nameOf(sandbox.owner) } : sandbox[field]], values);
301
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('values', counted));
302
+ return;
303
+ }
304
+ const found = filterSandboxes(listed, filter);
305
+ const limits = sandboxes.limits;
306
+ // the limits and the usage are the caller's, whichever sandboxes they list
307
+ (0, http_1.send)(res, 200, {
308
+ ...(page ? (0, paging_1.answerPage)('sandboxes', pageOfSandboxes(found, page, show)) : { sandboxes: found.map(show) }),
309
+ limits: { count: limits.count, bytes: limits.bytes },
310
+ used: sandboxes.usage(principal),
311
+ });
215
312
  }
216
313
  //# sourceMappingURL=sandboxes-api.js.map