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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/file/get-file-context.js +4 -7
  10. package/dist/harness/sandbox-client.js +29 -2
  11. package/dist/kubernetes/cluster-state.js +48 -14
  12. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  13. package/dist/kubernetes/resources.js +5 -1
  14. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  15. package/dist/planner/work-runtime-aggregate.js +1 -0
  16. package/dist/planner/work-runtime-docker.js +9 -5
  17. package/dist/planner/work-runtime-kubernetes.js +6 -4
  18. package/dist/planner/work-runtime-local.js +8 -4
  19. package/dist/remote/annotations.js +29 -3
  20. package/dist/remote/bundle.js +6 -8
  21. package/dist/remote/collect-bundle.js +3 -2
  22. package/dist/remote/remote-work-commands.js +161 -8
  23. package/dist/server/artifacts-api.js +56 -0
  24. package/dist/server/definitions-api.js +62 -8
  25. package/dist/server/executor.js +17 -0
  26. package/dist/server/keep-artifacts.js +230 -0
  27. package/dist/server/overview.js +67 -9
  28. package/dist/server/paging.js +167 -0
  29. package/dist/server/run-access.js +24 -0
  30. package/dist/server/run-artifacts.js +171 -0
  31. package/dist/server/run-worker.js +29 -0
  32. package/dist/server/runs.js +8 -0
  33. package/dist/server/sandbox-files.js +2 -7
  34. package/dist/server/sandboxes-api.js +54 -8
  35. package/dist/server/server-config.js +14 -0
  36. package/dist/server/server.js +122 -27
  37. package/dist/server/task-order.js +56 -0
  38. package/dist/utils/project-path.js +20 -0
  39. package/dist/utils/tar.js +37 -1
  40. package/package.json +1 -1
  41. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -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
@@ -28,6 +28,8 @@ const service_rollouts_1 = require("../kubernetes/service-rollouts");
28
28
  const cluster_state_1 = require("../kubernetes/cluster-state");
29
29
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
30
30
  const check_keys_1 = require("../optimizer/check-keys");
31
+ const units_2 = require("../utils/units");
32
+ const keep_artifacts_1 = require("./keep-artifacts");
31
33
  // one log line of a task is cut here, the registry caps how many events a run keeps
32
34
  const MAX_LOG_TEXT = 8 * 1024;
33
35
  /**
@@ -82,6 +84,12 @@ exports.workerInputSchema = zod_1.z
82
84
  check: zod_1.z.boolean().optional(),
83
85
  // what its tasks took in past runs, in ms by name, so the longest chain starts first
84
86
  durations: zod_1.z.record(zod_1.z.number().nonnegative()).optional(),
87
+ // where the outputs the tasks export are kept for a download once the tasks ended, and
88
+ // what they may take together; left out for a run that keeps none (refuseArtifacts)
89
+ artifacts: zod_1.z
90
+ .object({ directory: zod_1.z.string().min(1), maxBytes: zod_1.z.number().int().positive() })
91
+ .strict()
92
+ .optional(),
85
93
  })
86
94
  .strict();
87
95
  // The ceiling of the run, combined here and not in the server: the lower of two allow lists
@@ -278,6 +286,9 @@ up) {
278
286
  try {
279
287
  const result = await execution.start();
280
288
  report();
289
+ if (input.artifacts && !input.up) {
290
+ await keepRunArtifacts(workTree, environment, input.artifacts, work, cancelled, emit, (text) => secrets.redact(text));
291
+ }
281
292
  // on a cluster the services stay in their Deployments once they are ready, until
282
293
  // the namespace of the run goes
283
294
  if (input.up && input.kubernetes && ready && result.success && !abortCtrl.signal.aborted) {
@@ -332,6 +343,24 @@ up) {
332
343
  }
333
344
  }
334
345
  exports.runTasks = runTasks;
346
+ // The outputs the tasks export, kept for a download whether the run failed or not: when a
347
+ // test failed its screenshots matter most. Into the log goes what was kept and what was not;
348
+ // a run ends as its tasks did, whatever happened to its outputs.
349
+ async function keepRunArtifacts(workTree, environment, artifacts, root, cancelled, emit, redact) {
350
+ const say = (stream, text) => emit({ type: 'log', task: 'hammerkit', stream, text: redact(text).slice(0, MAX_LOG_TEXT) });
351
+ try {
352
+ const kept = await (0, keep_artifacts_1.keepArtifacts)(workTree, environment, { ...artifacts, root, cancelled, redact });
353
+ for (const output of kept.outputs) {
354
+ say('stdout', `kept ${output.path} of ${output.task} for a download (${(0, units_2.formatSize)(output.bytes)})`);
355
+ }
356
+ for (const output of kept.left) {
357
+ say('stderr', `did not keep ${output.path} of ${output.task}: ${output.reason}`);
358
+ }
359
+ }
360
+ catch (e) {
361
+ say('stderr', `the outputs of the run could not be kept: ${(0, log_1.getErrorMessage)(e)}`);
362
+ }
363
+ }
335
364
  // What the cluster said of a run that failed, into its log: the server removes its pods
336
365
  // once it ended.
337
366
  async function reportClusterState(kubernetes, workTree, ownNamespace, emit, redact) {
@@ -901,6 +901,14 @@ class RunRegistry {
901
901
  emit: (event) => this.record(entry, event),
902
902
  signal: entry.abort.signal,
903
903
  ...(Object.keys(durations).length > 0 ? { durations } : {}),
904
+ ...(this.options.artifacts && !entry.run.up
905
+ ? {
906
+ artifacts: {
907
+ directory: this.options.artifacts.directoryOf(run.id),
908
+ maxBytes: this.options.artifacts.maxBytes,
909
+ },
910
+ }
911
+ : {}),
904
912
  ...(entry.run.up
905
913
  ? {
906
914
  up: (targets) => this.markUp(entry, targets),
@@ -4,6 +4,7 @@ exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = ex
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const fs_1 = require("fs");
7
+ const project_path_1 = require("../utils/project-path");
7
8
  const promises_1 = require("fs/promises");
8
9
  const os_1 = require("os");
9
10
  const path_1 = require("path");
@@ -54,13 +55,7 @@ exports.SandboxFileError = SandboxFileError;
54
55
  * deny list of uploads names (`.git/`, `.env`, keys).
55
56
  */
56
57
  function checkPath(path) {
57
- if (path.length === 0 ||
58
- path.length > 4096 ||
59
- path.startsWith('/') ||
60
- path.includes('\\') ||
61
- path.includes('\0') ||
62
- /^[A-Za-z]:/.test(path) ||
63
- path.split('/').some((part) => part === '' || part === '.' || part === '..')) {
58
+ if (!(0, project_path_1.isRelativePath)(path, 4096)) {
64
59
  throw new SandboxFileError(400, `${JSON.stringify(path.slice(0, 200))} is not a path in the sandbox: relative, / between names, no . or ..`);
65
60
  }
66
61
  const denied = deniedPath(path);
@@ -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({
@@ -46,7 +47,10 @@ const pushSchema = zod_1.z
46
47
  *
47
48
  * POST /v1/sandboxes { repo, ref } fetch a branch into a new sandbox
48
49
  * GET /v1/sandboxes the caller's sandboxes, their limits and usage;
49
- * `?scope=all` everybody's, with `observe`
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)
50
54
  * GET /v1/sandboxes/<id> one sandbox
51
55
  * DELETE /v1/sandboxes/<id> cancel its runs and remove it
52
56
  * POST /v1/sandboxes/<id>/fetch { ref } move a sandbox without changes to a branch's commit
@@ -81,13 +85,15 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
81
85
  (0, http_1.send)(res, 403, { error: 'scope all needs an entitlement with observe' });
82
86
  return true;
83
87
  }
84
- const limits = sandboxes.limits;
85
- // the limits and the usage are the caller's, whichever sandboxes they list
86
- (0, http_1.send)(res, 200, {
87
- sandboxes: (scope === 'all' ? sandboxes.all() : sandboxes.list(principal)).map(show),
88
- limits: { count: limits.count, bytes: limits.bytes },
89
- used: sandboxes.usage(principal),
90
- });
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
+ }
91
97
  }
92
98
  else if (method === 'POST') {
93
99
  const body = parse(createSchema, await (0, http_1.readJson)(req));
@@ -264,4 +270,44 @@ function view(config, sandboxes, principal, sandbox) {
264
270
  run: run ?? null,
265
271
  };
266
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
+ });
312
+ }
267
313
  //# sourceMappingURL=sandboxes-api.js.map
@@ -581,6 +581,20 @@ exports.serverConfigSchema = zod_1.z
581
581
  .default({}),
582
582
  // how long a passed check stays for `remote verify` to find (see checks.ts)
583
583
  checksKeep: duration.default('30d'),
584
+ // the outputs the tasks of a run export (`export: true`, and `export: always` of a task
585
+ // that failed), kept for `remote artifacts`; none of a run in which anything reads a
586
+ // secret or a variable of the server (run-artifacts.ts)
587
+ artifacts: zod_1.z
588
+ .object({
589
+ // how long they stay after their run ended
590
+ keep: duration.default('1d'),
591
+ // what one run keeps, packed; an output that would take it over is left out
592
+ maxBytes: size.default('256Mi'),
593
+ // what all runs keep together; the oldest runs' go first
594
+ total: size.default('10Gi'),
595
+ })
596
+ .strict()
597
+ .default({}),
584
598
  })
585
599
  .strict()
586
600
  .default({}),