hammerkit 2.1.0-next.2 → 2.1.0-next.20

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 +159 -30
  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,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
@@ -19,6 +19,7 @@ const parse_error_1 = require("../schema/parse-error");
19
19
  const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
21
  const run_source_envs_1 = require("../environment/run-source-envs");
22
+ const prefetch_secrets_1 = require("../secrets/prefetch-secrets");
22
23
  class DefinitionError extends Error {
23
24
  }
24
25
  exports.DefinitionError = DefinitionError;
@@ -167,6 +168,9 @@ function describeSecret(secret) {
167
168
  if (source.type === 'provider') {
168
169
  return { from: `${source.provider}:${source.ref}`, account: source.account, target };
169
170
  }
171
+ if (source.type === 'unavailable') {
172
+ return { from: source.from, account: null, target };
173
+ }
170
174
  return { from: source.type === 'env' ? `env:${source.name}` : `file:${source.path}`, account: null, target };
171
175
  }
172
176
  // What a server refuses to publish. A secret that reads a file or a variable of the
@@ -335,7 +339,14 @@ function toPlan(root, item) {
335
339
  const mounts = (0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)
336
340
  ? data.mounts.map((mount) => {
337
341
  const inside = insideBundle(root, data.cwd, mount.localPath);
338
- 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}`;
339
350
  })
340
351
  : [];
341
352
  const ports = 'ports' in data ? data.ports.map((port) => `${port.hostPort ?? ''}:${port.containerPort}`) : [];
@@ -423,6 +434,10 @@ async function planBundle(bundle, environment, options = {}) {
423
434
  }
424
435
  const context = await (0, reference_parser_1.parseReferences)(ctx, scope, inspected);
425
436
  const workTree = (0, work_scope_parser_1.getWorkContext)(context, options.scope ?? { environmentName: null }, inspected);
437
+ // the server's providers and accounts are the ones that count: a task it could never read
438
+ // a secret of is refused when it is published, and a run when it is planned (only the
439
+ // tasks and services of the run count then)
440
+ (0, prefetch_secrets_1.requireReadableSecrets)(workTree);
426
441
  const items = itemsOf(workTree);
427
442
  if (options.policy) {
428
443
  const policyProblems = findPolicyProblems(items, options.policy, directory);
@@ -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;
@@ -124,6 +124,9 @@ exports.runRequestSchema = zod_1.z
124
124
  .array(zod_1.z.object({ service: name, port: zod_1.z.number().int().min(1).max(65535) }).strict())
125
125
  .max(exports.MAX_ENDPOINTS)
126
126
  .default([]),
127
+ // the services that start again with the files of their sandbox after an edit of it; the
128
+ // others keep the files they started with (see ServiceRunSpec.restart)
129
+ restart: zod_1.z.array(name).max(20).optional(),
127
130
  })
128
131
  .strict()
129
132
  .refine((request) => request.services.length > 0 || request.tasks.length > 0 || (request.options.filter ?? []).length > 0, {
@@ -145,6 +148,14 @@ exports.runRequestSchema = zod_1.z
145
148
  request.sleepTtl === undefined &&
146
149
  request.name === undefined &&
147
150
  request.endpoints.length === 0), { message: 'ttl, sleepTtl, name and endpoints are for a run of services', path: ['services'] })
151
+ .refine((request) => (request.restart ?? []).every((service) => request.services.includes(service)), {
152
+ message: 'restart names services the run starts',
153
+ path: ['restart'],
154
+ })
155
+ .refine((request) => !request.restart?.length || request.source.type === 'sandbox', {
156
+ message: 'restart is for a service run from a sandbox, which changes with its files',
157
+ path: ['restart'],
158
+ })
148
159
  .refine((request) => new Set(request.endpoints.map((endpoint) => `${endpoint.service}:${endpoint.port}`)).size ===
149
160
  request.endpoints.length, { message: 'an endpoint is named twice', path: ['endpoints'] })
150
161
  .refine((request) => (request.options.args ?? []).length === 0 || request.tasks.length === 1, {
@@ -9,7 +9,7 @@ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
9
9
  // repository, and the branch or tag and the commit it was pinned to, or the repository and the
10
10
  // sandbox. None of them is a credential, so a task that reads them still takes arguments and
11
11
  // keeps its network (see PLAIN_SERVER_ENVS). A sandbox has no commit: its files may hold
12
- // changes. A run from an upload has none of them.
12
+ // changes. A run from an upload has none of them. Each is a name of RUN_SOURCE_ENVS.
13
13
  function runSourceEnvironment(source) {
14
14
  if (source.type === 'ref') {
15
15
  return {