hammerkit 2.1.0-next.9 → 2.2.0-next.1

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 (70) 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/executer/runner-commands.js +36 -0
  10. package/dist/file/get-file-context.js +4 -7
  11. package/dist/harness/connect.js +12 -8
  12. package/dist/harness/reconnect.js +141 -0
  13. package/dist/harness/sandbox-client.js +242 -33
  14. package/dist/harness/service-tools.js +36 -3
  15. package/dist/kubernetes/cluster-state.js +48 -14
  16. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  17. package/dist/kubernetes/follow-pod-logs.js +8 -5
  18. package/dist/kubernetes/kept-claims.js +26 -5
  19. package/dist/kubernetes/resources.js +5 -1
  20. package/dist/kubernetes/sandbox-runner.js +526 -156
  21. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  22. package/dist/kubernetes/sync-changes.js +463 -0
  23. package/dist/kubernetes/volumes.js +23 -1
  24. package/dist/optimizer/get-work-cache-stats.js +7 -0
  25. package/dist/planner/work-item-status.js +12 -2
  26. package/dist/planner/work-runtime-aggregate.js +1 -0
  27. package/dist/planner/work-runtime-docker.js +9 -5
  28. package/dist/planner/work-runtime-kubernetes.js +277 -55
  29. package/dist/planner/work-runtime-local.js +8 -4
  30. package/dist/remote/annotations.js +29 -3
  31. package/dist/remote/bundle.js +6 -8
  32. package/dist/remote/collect-bundle.js +3 -2
  33. package/dist/remote/device-login.js +4 -1
  34. package/dist/remote/remote-commands.js +16 -7
  35. package/dist/remote/remote-work-commands.js +265 -72
  36. package/dist/remote/server-client.js +38 -40
  37. package/dist/server/artifacts-api.js +56 -0
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/endpoints.js +52 -32
  40. package/dist/server/executor.js +117 -30
  41. package/dist/server/http.js +4 -1
  42. package/dist/server/keep-artifacts.js +230 -0
  43. package/dist/server/kubernetes-backend.js +186 -59
  44. package/dist/server/kubernetes-sandbox-storage.js +83 -22
  45. package/dist/server/overview.js +67 -9
  46. package/dist/server/paging.js +167 -0
  47. package/dist/server/plan.js +8 -1
  48. package/dist/server/public-paths.js +52 -0
  49. package/dist/server/run-access.js +24 -0
  50. package/dist/server/run-artifacts.js +171 -0
  51. package/dist/server/run-logs.js +25 -1
  52. package/dist/server/run-request.js +63 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-worker.js +267 -33
  55. package/dist/server/runs.js +527 -99
  56. package/dist/server/sandbox-files.js +9 -8
  57. package/dist/server/sandbox-follow.js +54 -0
  58. package/dist/server/sandbox-storage.js +38 -1
  59. package/dist/server/sandbox-sync.js +392 -0
  60. package/dist/server/sandboxes-api.js +54 -8
  61. package/dist/server/sandboxes.js +19 -0
  62. package/dist/server/server-config.js +14 -0
  63. package/dist/server/server.js +189 -46
  64. package/dist/server/service-runs.js +41 -8
  65. package/dist/server/task-order.js +56 -0
  66. package/dist/utils/project-path.js +20 -0
  67. package/dist/utils/tar-files.js +52 -0
  68. package/dist/utils/tar.js +37 -1
  69. package/package.json +1 -1
  70. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -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
@@ -339,7 +339,14 @@ function toPlan(root, item) {
339
339
  const mounts = (0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)
340
340
  ? data.mounts.map((mount) => {
341
341
  const inside = insideBundle(root, data.cwd, mount.localPath);
342
- return `${inside.length > 0 ? inside[0] : mount.localPath}:${mount.containerPath}${mount.readOnly ? ':ro' : ''}`;
342
+ const readOnly = mount.readOnly ? ':ro' : '';
343
+ // a mount that names only its source (`- .`) lands at the same path in the container,
344
+ // which is in the directory the server read the bundle in, one of its own each time:
345
+ // such a mount is named as the build file names it
346
+ if (inside.length > 0 && mount.containerPath === (0, path_1.resolve)(data.cwd, mount.localPath)) {
347
+ return `${inside[0]}${readOnly}`;
348
+ }
349
+ return `${inside.length > 0 ? inside[0] : mount.localPath}:${mount.containerPath}${readOnly}`;
343
350
  })
344
351
  : [];
345
352
  const ports = 'ports' in data ? data.ports.map((port) => `${port.hostPort ?? ''}:${port.containerPort}`) : [];
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isPublicPath = exports.publicPathProblem = void 0;
4
+ // A segment of a path a public path or a request is made of: letters, digits and . _ ~ -
5
+ const SEGMENT = /^[A-Za-z0-9._~-]+$/;
6
+ const isDotSegment = (segment) => segment === '.' || segment === '..';
7
+ /**
8
+ * Why a configured public path (such as `/mcp` or `/.well-known`) can not be one, or null
9
+ * when it can. It is a path of plain segments with no `.` or `..`, and never the server's own.
10
+ */
11
+ function publicPathProblem(path) {
12
+ const segments = path.slice(1).split('/');
13
+ if (!path.startsWith('/') || segments.some((segment) => !SEGMENT.test(segment))) {
14
+ return 'expected a path like /mcp or /.well-known, with letters, digits, . _ ~ - and /';
15
+ }
16
+ if (segments.some(isDotSegment)) {
17
+ return 'a public path has no . or .. segment';
18
+ }
19
+ if (segments[0] === '.hammerkit') {
20
+ return "the server's own paths can not be public";
21
+ }
22
+ return null;
23
+ }
24
+ exports.publicPathProblem = publicPathProblem;
25
+ /**
26
+ * Whether a request for `target` (the request target, query included) is for one of the
27
+ * public paths of its endpoint, which is the path itself and everything below it, by
28
+ * segments: `/mcp` takes `/mcp/oauth/token`, not `/mcpx`. A target that is not in its plain
29
+ * form (an empty, dot, or escaped segment, a backslash, a `%`) is never public: such a path
30
+ * could read as another one to the app, so it needs the sign-in like any other.
31
+ */
32
+ function isPublicPath(publicPaths, target) {
33
+ if (!publicPaths?.length) {
34
+ return false;
35
+ }
36
+ const path = target.split('?')[0];
37
+ if (!path.startsWith('/')) {
38
+ return false;
39
+ }
40
+ const segments = path.slice(1).split('/');
41
+ // a trailing slash is an empty last segment, which a request may end with
42
+ const plain = segments.every((segment, index) => (segment !== '' || index === segments.length - 1) && (segment === '' || SEGMENT.test(segment)));
43
+ if (!plain || segments.some(isDotSegment)) {
44
+ return false;
45
+ }
46
+ return publicPaths.some((publicPath) => {
47
+ const wanted = publicPath.slice(1).split('/');
48
+ return segments.length >= wanted.length && wanted.every((segment, index) => segments[index] === segment);
49
+ });
50
+ }
51
+ exports.isPublicPath = isPublicPath;
52
+ //# sourceMappingURL=public-paths.js.map
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findReadableRun = exports.accountsOf = void 0;
4
+ const policy_1 = require("./policy");
5
+ const runs_1 = require("./runs");
6
+ // The accounts the caller uses: who approves a run on them follows and stops it.
7
+ function accountsOf(config, principal) {
8
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
9
+ return (account) => (0, policy_1.canUse)(grant, account);
10
+ }
11
+ exports.accountsOf = accountsOf;
12
+ /**
13
+ * The run of `id` the caller may read: one they own or decided about (on an account they use),
14
+ * or any run when an entitlement observes every run.
15
+ */
16
+ function findReadableRun(config, registry, principal, id) {
17
+ if (!runs_1.RUN_ID_PATTERN.test(id)) {
18
+ return undefined;
19
+ }
20
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
21
+ return registry.get(principal, id, accountsOf(config, principal)) ?? (grant.observe ? registry.peek(id) : undefined);
22
+ }
23
+ exports.findReadableRun = findReadableRun;
24
+ //# sourceMappingURL=run-access.js.map
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ArtifactStore = exports.refuseArtifacts = exports.LOCAL_TASKS_REFUSAL = exports.ARTIFACTS_MANIFEST = void 0;
4
+ const fs_1 = require("fs");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const units_1 = require("../utils/units");
8
+ const plan_1 = require("./plan");
9
+ // What the process of a run kept of the files its tasks generated, written as
10
+ // `artifacts.json` beside the archives once it is done: the server serves only what it lists.
11
+ exports.ARTIFACTS_MANIFEST = 'artifacts.json';
12
+ // Why a host that runs local tasks as the user of the server keeps no outputs: such a task
13
+ // could write the store of them (see server.ts and HostExecutorOptions.localTasksOnHost).
14
+ exports.LOCAL_TASKS_REFUSAL = 'this server runs local tasks as its own user, which could write the outputs it keeps: it keeps none';
15
+ /**
16
+ * Why a run keeps none of the files its tasks generated, or null when it keeps them. Its
17
+ * outputs are handed out as they are, never masked: a task or service of the run that reads
18
+ * a secret or a variable of the server (but the plain ones) can write it into a file, its
19
+ * own or one a task after it reads and copies (an `.npmrc`, a docker `config.json`), as it
20
+ * could print it past the masking with an argument (task-arguments FR-008). So any of them
21
+ * leaves the whole run without artifacts.
22
+ */
23
+ function refuseArtifacts(plan) {
24
+ for (const [name, item] of Object.entries(plan).sort(([a], [b]) => a.localeCompare(b))) {
25
+ const reads = (0, plan_1.getCredentialReads)(item);
26
+ if (reads.length > 0) {
27
+ return `${name} reads ${reads.join(', ')}: what it writes can reach the outputs of the run, which keeps none`;
28
+ }
29
+ }
30
+ return null;
31
+ }
32
+ exports.refuseArtifacts = refuseArtifacts;
33
+ // Run ids name the directories: nothing else is taken from the store's folder
34
+ const RUN_DIRECTORY = /^run_[A-Za-z0-9_-]+$/;
35
+ // where a run's process writes the archives before it moves them into place (keepArtifacts)
36
+ const STAGING = '.staging';
37
+ /**
38
+ * The outputs runs kept, a directory per run below `directory`, written by its process
39
+ * (keepArtifacts) or its executor. They stay `keep` from the end of their run, while the
40
+ * registry keeps the run, and the newest runs' only while all together take at most `total`.
41
+ * `localTasksOnHost`: a local task of this host runs as the user of the server and could write
42
+ * the store, so nothing in it is served, whatever it holds, and the store is emptied.
43
+ */
44
+ class ArtifactStore {
45
+ constructor(directory, options) {
46
+ this.directory = directory;
47
+ this.options = options;
48
+ }
49
+ directoryOf(id) {
50
+ if (!RUN_DIRECTORY.test(id)) {
51
+ throw new Error(`${id} is not a run id`);
52
+ }
53
+ return (0, path_1.join)(this.directory, id);
54
+ }
55
+ // A run that ended; who may read it was checked already.
56
+ async read(run, now) {
57
+ // nothing is read from the store here: a run that ended before planning has no manifest of its own
58
+ if (this.options.localTasksOnHost) {
59
+ return { outputs: [], left: [], reason: exports.LOCAL_TASKS_REFUSAL };
60
+ }
61
+ if (run.up) {
62
+ return { outputs: [], left: [], reason: 'a service run keeps no outputs' };
63
+ }
64
+ const manifest = await this.manifest(run, now);
65
+ if (!manifest) {
66
+ return {
67
+ outputs: [],
68
+ left: [],
69
+ reason: `the server has no outputs of the run: it keeps what tasks export (export: true, or always) for ${(0, units_1.formatDuration)(this.options.keep)}, and ${(0, units_1.formatSize)(this.options.total)} of all runs, the newest`,
70
+ };
71
+ }
72
+ return {
73
+ outputs: manifest.outputs.map((output, id) => ({
74
+ id,
75
+ task: output.task,
76
+ path: output.path,
77
+ bytes: output.bytes,
78
+ })),
79
+ left: manifest.left,
80
+ ...(manifest.refused ? { reason: manifest.refused } : { expiresAt: this.expiresAt(run).toISOString() }),
81
+ };
82
+ }
83
+ // The archive of one output: a gzipped tar of its paths in the project.
84
+ async open(run, id, now) {
85
+ if (this.options.localTasksOnHost) {
86
+ return undefined;
87
+ }
88
+ const output = (await this.manifest(run, now))?.outputs[id];
89
+ if (!output || !/^\d+\.tgz$/.test(output.file)) {
90
+ return undefined;
91
+ }
92
+ const file = (0, path_1.join)(this.directoryOf(run.id), output.file);
93
+ const bytes = (await (0, promises_1.stat)(file).catch(() => undefined))?.size;
94
+ return bytes === undefined ? undefined : { bytes, stream: () => (0, fs_1.createReadStream)(file), read: () => (0, promises_1.readFile)(file) };
95
+ }
96
+ /**
97
+ * Removes what is over its time, what runs the registry no longer has kept, and of the
98
+ * runs that ended the oldest while all of them take more than `total`. A run that has not
99
+ * ended may still write. What a run's process left in its staging folder after it ended (a
100
+ * crash while it kept the outputs) goes too. Answers the runs it removed the outputs of.
101
+ */
102
+ async sweep(lookup, now) {
103
+ const names = await (0, promises_1.readdir)(this.directory).catch(() => []);
104
+ if (this.options.localTasksOnHost) {
105
+ // nothing a run keeps is served here, so nothing is kept: whatever is in the store goes
106
+ for (const name of names) {
107
+ await (0, promises_1.rm)((0, path_1.join)(this.directory, name), { recursive: true, force: true });
108
+ }
109
+ return names.filter((name) => RUN_DIRECTORY.test(name));
110
+ }
111
+ const removed = [];
112
+ const ended = [];
113
+ for (const id of names.filter((name) => RUN_DIRECTORY.test(name))) {
114
+ const run = lookup(id);
115
+ if (run && !run.finishedAt) {
116
+ continue;
117
+ }
118
+ if (!run || this.expiresAt(run).getTime() <= now) {
119
+ await this.remove(id);
120
+ removed.push(id);
121
+ continue;
122
+ }
123
+ await (0, promises_1.rm)((0, path_1.join)(this.directoryOf(id), STAGING), { recursive: true, force: true });
124
+ // what the directory takes, as it is: a file the manifest does not name counts too
125
+ const bytes = await sizeOf(this.directoryOf(id));
126
+ ended.push({ id, finishedAt: Date.parse(run.finishedAt), bytes });
127
+ }
128
+ let total = ended.reduce((sum, run) => sum + run.bytes, 0);
129
+ for (const run of ended.sort((a, b) => a.finishedAt - b.finishedAt)) {
130
+ if (total <= this.options.total) {
131
+ break;
132
+ }
133
+ await this.remove(run.id);
134
+ removed.push(run.id);
135
+ total -= run.bytes;
136
+ }
137
+ return removed;
138
+ }
139
+ expiresAt(run) {
140
+ return new Date(Date.parse(run.finishedAt ?? '') + this.options.keep);
141
+ }
142
+ // what the run kept, while it is kept
143
+ async manifest(run, now) {
144
+ if (!run.finishedAt || this.expiresAt(run).getTime() <= now) {
145
+ return undefined;
146
+ }
147
+ return this.readManifest(run.id);
148
+ }
149
+ async readManifest(id) {
150
+ try {
151
+ return JSON.parse(await (0, promises_1.readFile)((0, path_1.join)(this.directoryOf(id), exports.ARTIFACTS_MANIFEST), 'utf8'));
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ }
157
+ async remove(id) {
158
+ await (0, promises_1.rm)(this.directoryOf(id), { recursive: true, force: true });
159
+ }
160
+ }
161
+ exports.ArtifactStore = ArtifactStore;
162
+ // The bytes of the files below a directory, each as it is on disk (a link counts as itself).
163
+ async function sizeOf(directory) {
164
+ let bytes = 0;
165
+ for (const entry of await (0, promises_1.readdir)(directory, { withFileTypes: true }).catch(() => [])) {
166
+ const path = (0, path_1.join)(directory, entry.name);
167
+ bytes += entry.isDirectory() ? await sizeOf(path) : (await (0, promises_1.lstat)(path).catch(() => undefined))?.size ?? 0;
168
+ }
169
+ return bytes;
170
+ }
171
+ //# sourceMappingURL=run-artifacts.js.map
@@ -113,6 +113,23 @@ class LogIndex {
113
113
  lines(task) {
114
114
  return this.taskLines.get(task) ?? [];
115
115
  }
116
+ // How many lines of the log, or of one task, the first `count` events hold
117
+ linesBefore(count, task) {
118
+ const lines = task !== undefined ? this.lines(task) : undefined;
119
+ let low = 0;
120
+ let high = lines ? lines.length : this.size;
121
+ // the lines are in the order of their events
122
+ while (low < high) {
123
+ const middle = (low + high) >> 1;
124
+ if (this.lineEvent[lines ? lines[middle] : middle] < count) {
125
+ low = middle + 1;
126
+ }
127
+ else {
128
+ high = middle;
129
+ }
130
+ }
131
+ return low;
132
+ }
116
133
  text(events, line) {
117
134
  const event = events[this.lineEvent[line]];
118
135
  return { task: event.task, stream: event.stream, text: event.text.slice(this.lineStart[line], this.lineEnd[line]) };
@@ -145,9 +162,15 @@ class LogIndex {
145
162
  }
146
163
  exports.LogIndex = LogIndex;
147
164
  // The lines of the log a query selects, see LogQuery.
148
- function readLogs(events, index, query, truncated) {
165
+ // `lostAfter`: Run.lostAfter
166
+ function readLogs(events, index, query, truncated, lostAfter) {
149
167
  const selected = query.task !== undefined ? index.lines(query.task) : undefined;
150
168
  const total = selected ? selected.length : index.size;
169
+ const lost = lostAfter !== undefined
170
+ ? index.linesBefore(lostAfter, query.task) + 1
171
+ : query.from !== undefined && query.from > total + 1
172
+ ? total + 1
173
+ : undefined;
151
174
  const at = (position) => (selected ? selected[position] : position);
152
175
  const hits = query.grep !== undefined ? index.matches(events, query.grep, query.ignoreCase) : undefined;
153
176
  const toLine = (position) => ({
@@ -215,6 +238,7 @@ function readLogs(events, index, query, truncated) {
215
238
  total,
216
239
  ...(next !== undefined ? { next } : {}),
217
240
  truncated,
241
+ ...(lost !== undefined ? { lost } : {}),
218
242
  };
219
243
  }
220
244
  exports.readLogs = readLogs;