hammerkit 2.1.0-next.11 → 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.
@@ -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);
@@ -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({}),
@@ -49,6 +49,9 @@ const get_cache_directory_1 = require("../optimizer/get-cache-directory");
49
49
  const path_1 = require("path");
50
50
  const checks_1 = require("./checks");
51
51
  const checks_api_1 = require("./checks-api");
52
+ const run_artifacts_1 = require("./run-artifacts");
53
+ const artifacts_api_1 = require("./artifacts-api");
54
+ const run_access_1 = require("./run-access");
52
55
  const overview_1 = require("./overview");
53
56
  const paging_1 = require("./paging");
54
57
  var discovery_2 = require("./discovery");
@@ -81,6 +84,8 @@ const HEARTBEAT_MS = 15000;
81
84
  const MAX_WAIT_MS = 50000;
82
85
  // how often checks older than `runs.checksKeep` are removed
83
86
  const CHECK_SWEEP_MS = 6 * 60 * 60 * 1000;
87
+ // how often the outputs of runs that are over their time are removed
88
+ const ARTIFACT_SWEEP_MS = 60 * 60 * 1000;
84
89
  // Server-sent events: `id` is the sequence number, so a client that lost the
85
90
  // connection continues with Last-Event-ID (or ?after=) and misses nothing.
86
91
  function streamEvents(registry, config, principal, id, req, res, url) {
@@ -91,7 +96,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
91
96
  if (event.type === 'state' && (0, runs_1.isFinal)(event.state)) {
92
97
  end();
93
98
  }
94
- }, accountsOf(config, principal));
99
+ }, (0, run_access_1.accountsOf)(config, principal));
95
100
  if (!watch) {
96
101
  (0, http_2.send)(res, 404, { error: 'not found' });
97
102
  return;
@@ -181,7 +186,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
181
186
  return true;
182
187
  }
183
188
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
184
- const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
189
+ const run = registry.cancel(principal, id, (0, run_access_1.accountsOf)(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
185
190
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
186
191
  run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
187
192
  }
@@ -236,9 +241,8 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
236
241
  (0, http_2.send)(res, 400, { error: e instanceof Error ? e.message : String(e) });
237
242
  return true;
238
243
  }
239
- // an entitlement with `observe` reads the log of every run
240
- const logs = registry.logs(principal, id, accountsOf(config, principal)) ??
241
- ((0, policy_1.getGrant)(config.entitlements, principal).observe ? registry.logsOf(id) : undefined);
244
+ // who may read the run reads its log, an entitlement with `observe` every run's
245
+ const logs = (0, run_access_1.findReadableRun)(config, registry, principal, id) ? registry.logsOf(id) : undefined;
242
246
  // with the tasks, services and the server's own lines (`hammerkit`) the log has
243
247
  logs
244
248
  ? (0, http_2.send)(res, 200, { ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated), names: logs.index.names() })
@@ -261,7 +265,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
261
265
  res.on('close', () => gone.abort());
262
266
  const viewer = (0, overview_1.getViewer)(config, principal);
263
267
  // an entitlement with `observe` reads every run as it is, without waiting
264
- const run = (await registry.wait(principal, id, wait, accountsOf(config, principal), gone.signal)) ??
268
+ const run = (await registry.wait(principal, id, wait, (0, run_access_1.accountsOf)(config, principal), gone.signal)) ??
265
269
  (viewer.grant.observe ? registry.peek(id) : undefined);
266
270
  if (!gone.signal.aborted) {
267
271
  const may = run && (0, overview_1.runActions)(viewer, run);
@@ -275,11 +279,6 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
275
279
  }
276
280
  return true;
277
281
  }
278
- // The accounts the caller uses: who approves a run on them follows and stops it.
279
- function accountsOf(config, principal) {
280
- const grant = (0, policy_1.getGrant)(config.entitlements, principal);
281
- return (account) => (0, policy_1.canUse)(grant, account);
282
- }
283
282
  async function extendRun(config, registry, log, principal, id, req, res) {
284
283
  const body = (await (0, http_2.readJson)(req));
285
284
  let ttl;
@@ -402,7 +401,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
402
401
  // an approval where they need one, never the owner's (run-retry.ts).
403
402
  async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
404
403
  const viewer = (0, overview_1.getViewer)(config, principal);
405
- const run = registry.get(principal, id, accountsOf(config, principal)) ?? (viewer.grant.observe ? registry.peek(id) : undefined);
404
+ const run = (0, run_access_1.findReadableRun)(config, registry, principal, id);
406
405
  if (!run) {
407
406
  (0, http_2.send)(res, 404, { error: 'not found' });
408
407
  return;
@@ -792,7 +791,7 @@ async function handle(api, verifier, req, res) {
792
791
  * dashboard, which asks the same API for what its pages show (dashboard.ts).
793
792
  */
794
793
  async function handleApi(api, principal, req, res, url) {
795
- const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, capacity, log, } = api;
794
+ const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, artifacts, capacity, log, now, } = api;
796
795
  const path = url.pathname;
797
796
  if (await (0, accounts_api_1.handleAccounts)(config, log, principal, req, res, url)) {
798
797
  return;
@@ -806,6 +805,9 @@ async function handleApi(api, principal, req, res, url) {
806
805
  if (await (0, sandboxes_api_1.handleSandboxes)(config, sandboxes.registry, repos, log, principal, req, res, url)) {
807
806
  return;
808
807
  }
808
+ if (await (0, artifacts_api_1.handleArtifacts)(config, registry, artifacts, log, principal, req, res, url, now)) {
809
+ return;
810
+ }
809
811
  if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, (host) => gateway?.url(host) ?? host, log, principal, req, res, url)) {
810
812
  return;
811
813
  }
@@ -912,7 +914,8 @@ async function startServer(config, environment, options = {}) {
912
914
  const log = (line) => write(line.replace(/\p{Cc}/gu, '?').slice(0, 1000));
913
915
  if (config.runtimes.includes('local') && config.backend.type === 'host') {
914
916
  log('warning: the local runtime is allowed, local tasks run as the user of this server and read all it can read; ' +
915
- 'an account is then an approval class, not a credential boundary');
917
+ 'an account is then an approval class, not a credential boundary, and the server keeps no outputs of its runs ' +
918
+ '(remote artifacts)');
916
919
  }
917
920
  // build files are read, planned and run as the server's runs see the world: the
918
921
  // operator's accounts and the allowlisted environment, nothing of the server's own
@@ -992,6 +995,8 @@ async function startServer(config, environment, options = {}) {
992
995
  if (config.backend.type === 'host' || config.entitlements.some((entitlement) => entitlement.sandboxes?.length)) {
993
996
  await sandboxes.registry.load();
994
997
  }
998
+ // a local task of a host runs as the user of this server: what it can write is never served
999
+ const localTasksOnHost = config.backend.type === 'host' && config.runtimes.includes('local');
995
1000
  const executorOptions = {
996
1001
  definitions,
997
1002
  planning,
@@ -1000,6 +1005,7 @@ async function startServer(config, environment, options = {}) {
1000
1005
  cache: (0, path_1.join)(storage, 'cache'),
1001
1006
  worker: options.worker,
1002
1007
  sandboxes: { ...sandboxes, network: config.sandboxes.network },
1008
+ localTasksOnHost,
1003
1009
  ...(config.backend.type === 'host' && config.backend.capabilities
1004
1010
  ? { capabilityRuntime: config.backend.capabilities.runtime }
1005
1011
  : {}),
@@ -1020,6 +1026,11 @@ async function startServer(config, environment, options = {}) {
1020
1026
  void sweepChecks();
1021
1027
  const sweeping = setInterval(sweepChecks, CHECK_SWEEP_MS);
1022
1028
  sweeping.unref();
1029
+ const artifacts = new run_artifacts_1.ArtifactStore((0, path_1.join)(storage, 'artifacts'), {
1030
+ keep: (0, units_1.parseDuration)(config.runs.artifacts.keep),
1031
+ total: (0, units_1.parseSize)(config.runs.artifacts.total),
1032
+ localTasksOnHost,
1033
+ });
1023
1034
  const registry = new runs_1.RunRegistry({
1024
1035
  executor,
1025
1036
  maxConcurrent: config.runs.maxConcurrent,
@@ -1046,12 +1057,31 @@ async function startServer(config, environment, options = {}) {
1046
1057
  .then(() => log(`checks run=${run.id} passed=[${passed.map((record) => record.task).join(',')}]`))
1047
1058
  .catch((e) => log(`the checks of run ${run.id} were not kept: ${e instanceof Error ? e.message : e}`));
1048
1059
  }
1060
+ // what the run kept counts against the total of all runs from now
1061
+ void sweepArtifacts();
1062
+ },
1063
+ artifacts: {
1064
+ directoryOf: (id) => artifacts.directoryOf(id),
1065
+ maxBytes: (0, units_1.parseSize)(config.runs.artifacts.maxBytes),
1049
1066
  },
1050
1067
  log,
1051
1068
  });
1069
+ const now = options.now ?? Date.now;
1070
+ // what is over its time goes within the hour, what is over the total when a run ends
1071
+ const sweepArtifacts = () => artifacts
1072
+ .sweep((id) => registry.peek(id), now())
1073
+ .then((removed) => {
1074
+ if (removed.length > 0) {
1075
+ log(`removed the outputs of ${removed.length} runs: ${removed.join(', ')}`);
1076
+ }
1077
+ })
1078
+ .catch((e) => log(`the outputs of old runs could not be removed: ${e instanceof Error ? e.message : e}`));
1079
+ const sweepingArtifacts = setInterval(sweepArtifacts, ARTIFACT_SWEEP_MS);
1080
+ sweepingArtifacts.unref();
1052
1081
  // the executor hears which service runs sleep with their volumes kept, and removes what it
1053
1082
  // kept for any other (RunExecutor.restored)
1054
1083
  await registry.restore();
1084
+ void sweepArtifacts();
1055
1085
  const proposals = new proposals_1.ProposalRegistry({
1056
1086
  maxWaiting: config.approvals.maxWaiting,
1057
1087
  timeout: (0, units_1.parseDuration)(config.approvals.timeout),
@@ -1087,8 +1117,10 @@ async function startServer(config, environment, options = {}) {
1087
1117
  planning,
1088
1118
  repos,
1089
1119
  checks,
1120
+ artifacts,
1090
1121
  capacity,
1091
1122
  log,
1123
+ now,
1092
1124
  };
1093
1125
  await gateway?.load();
1094
1126
  sandboxes.registry.useRuns({
@@ -1188,6 +1220,7 @@ async function startServer(config, environment, options = {}) {
1188
1220
  },
1189
1221
  close: async () => {
1190
1222
  clearInterval(sweeping);
1223
+ clearInterval(sweepingArtifacts);
1191
1224
  proposals.close();
1192
1225
  await registry.close();
1193
1226
  await new Promise((resolve, reject) => {
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRelativePath = void 0;
4
+ /**
5
+ * A path relative to a root (of a project, a bundle, a sandbox), as the API and the CLI take
6
+ * it: at most `maxLength` characters, `/` between names, no `.` or `..` or empty name, no
7
+ * backslash, no NUL, nothing absolute (`/x`, `C:x`). The one rule every path an input names
8
+ * is checked by, so the places that check it can not drift apart.
9
+ */
10
+ function isRelativePath(path, maxLength) {
11
+ return (path.length > 0 &&
12
+ path.length <= maxLength &&
13
+ !path.startsWith('/') &&
14
+ !/^[A-Za-z]:/.test(path) &&
15
+ !path.includes('\\') &&
16
+ !path.includes('\0') &&
17
+ !path.split('/').some((part) => part === '' || part === '.' || part === '..'));
18
+ }
19
+ exports.isRelativePath = isRelativePath;
20
+ //# sourceMappingURL=project-path.js.map
package/dist/utils/tar.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.onlyBelow = exports.extractOutput = exports.packArchive = void 0;
3
+ exports.onlyBelow = exports.extractOutput = exports.measureArchive = exports.packArchive = void 0;
4
+ const fs_1 = require("fs");
4
5
  const tar_1 = require("tar");
5
6
  const path_1 = require("path");
6
7
  function packArchive(options, files) {
@@ -34,6 +35,41 @@ const NOT_PACKED = '\0';
34
35
  function isExact(key) {
35
36
  return key.split(':').every((part) => Number.isSafeInteger(Number(part)));
36
37
  }
38
+ // The entries of an archive and the bytes of their content, unpacked, measured before anything
39
+ // is extracted from it. Reading stops at the first entry that takes it past `limit`, so what
40
+ // is returned is then more than the limit, and the rest of the archive is not read.
41
+ function measureArchive(file, limit) {
42
+ return new Promise((resolve, reject) => {
43
+ const measured = { entries: 0, bytes: 0 };
44
+ let done = false;
45
+ const source = (0, fs_1.createReadStream)(file);
46
+ const parser = new tar_1.Parser({
47
+ onReadEntry: (entry) => {
48
+ if (done) {
49
+ entry.resume();
50
+ return;
51
+ }
52
+ measured.entries++;
53
+ measured.bytes += entry.size ?? 0;
54
+ entry.resume();
55
+ if (measured.entries > limit.entries || measured.bytes > limit.bytes) {
56
+ done = true;
57
+ source.unpipe(parser);
58
+ source.destroy();
59
+ resolve({ ...measured });
60
+ }
61
+ },
62
+ });
63
+ parser.on('end', () => {
64
+ done = true;
65
+ resolve({ ...measured });
66
+ });
67
+ parser.on('error', reject);
68
+ source.on('error', reject);
69
+ source.pipe(parser);
70
+ });
71
+ }
72
+ exports.measureArchive = measureArchive;
37
73
  // Extracts the archive of one output (a path relative to `cwd`) into `cwd`. An archive
38
74
  // comes from a cache another run, or whoever writes to the cache backend, filled, so only
39
75
  // entries of that output are taken: one beside it (another output, a source of the task, a
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.1.0-next.11",
4
+ "version": "2.1.0-next.12",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",