buildrush 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +84 -2
- package/SECURITY.md +57 -0
- package/bin/buildrush.js +6 -0
- package/dist/src/adapters.d.ts +23 -0
- package/dist/src/adapters.js +187 -0
- package/dist/src/adapters.js.map +1 -0
- package/dist/src/affected.d.ts +28 -0
- package/dist/src/affected.js +59 -0
- package/dist/src/affected.js.map +1 -0
- package/dist/src/cache.d.ts +94 -0
- package/dist/src/cache.js +362 -0
- package/dist/src/cache.js.map +1 -0
- package/dist/src/cli.d.ts +33 -0
- package/dist/src/cli.js +684 -0
- package/dist/src/cli.js.map +1 -0
- package/dist/src/config.d.ts +84 -0
- package/dist/src/config.js +394 -0
- package/dist/src/config.js.map +1 -0
- package/dist/src/daemon/cli.d.ts +36 -0
- package/dist/src/daemon/cli.js +202 -0
- package/dist/src/daemon/cli.js.map +1 -0
- package/dist/src/daemon/client.d.ts +106 -0
- package/dist/src/daemon/client.js +267 -0
- package/dist/src/daemon/client.js.map +1 -0
- package/dist/src/daemon/ops.d.ts +66 -0
- package/dist/src/daemon/ops.js +47 -0
- package/dist/src/daemon/ops.js.map +1 -0
- package/dist/src/daemon/paths.d.ts +62 -0
- package/dist/src/daemon/paths.js +192 -0
- package/dist/src/daemon/paths.js.map +1 -0
- package/dist/src/daemon/protocol.d.ts +60 -0
- package/dist/src/daemon/protocol.js +62 -0
- package/dist/src/daemon/protocol.js.map +1 -0
- package/dist/src/daemon/server.d.ts +68 -0
- package/dist/src/daemon/server.js +441 -0
- package/dist/src/daemon/server.js.map +1 -0
- package/dist/src/detect.d.ts +12 -0
- package/dist/src/detect.js +68 -0
- package/dist/src/detect.js.map +1 -0
- package/dist/src/doctor.d.ts +6 -0
- package/dist/src/doctor.js +94 -0
- package/dist/src/doctor.js.map +1 -0
- package/dist/src/engine.d.ts +70 -0
- package/dist/src/engine.js +655 -0
- package/dist/src/engine.js.map +1 -0
- package/dist/src/fsindex.d.ts +37 -0
- package/dist/src/fsindex.js +128 -0
- package/dist/src/fsindex.js.map +1 -0
- package/dist/src/fswatch.d.ts +30 -0
- package/dist/src/fswatch.js +141 -0
- package/dist/src/fswatch.js.map +1 -0
- package/dist/src/graph.d.ts +77 -0
- package/dist/src/graph.js +486 -0
- package/dist/src/graph.js.map +1 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +9 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/project.d.ts +45 -0
- package/dist/src/project.js +138 -0
- package/dist/src/project.js.map +1 -0
- package/dist/src/runner.d.ts +36 -0
- package/dist/src/runner.js +174 -0
- package/dist/src/runner.js.map +1 -0
- package/dist/src/scheduler.d.ts +30 -0
- package/dist/src/scheduler.js +143 -0
- package/dist/src/scheduler.js.map +1 -0
- package/dist/src/testcache.d.ts +60 -0
- package/dist/src/testcache.js +93 -0
- package/dist/src/testcache.js.map +1 -0
- package/dist/src/util/fsx.d.ts +11 -0
- package/dist/src/util/fsx.js +61 -0
- package/dist/src/util/fsx.js.map +1 -0
- package/dist/src/util/glob.d.ts +19 -0
- package/dist/src/util/glob.js +193 -0
- package/dist/src/util/glob.js.map +1 -0
- package/dist/src/util/hash.d.ts +14 -0
- package/dist/src/util/hash.js +57 -0
- package/dist/src/util/hash.js.map +1 -0
- package/dist/src/util/paths.d.ts +17 -0
- package/dist/src/util/paths.js +67 -0
- package/dist/src/util/paths.js.map +1 -0
- package/dist/src/watch.d.ts +101 -0
- package/dist/src/watch.js +289 -0
- package/dist/src/watch.js.map +1 -0
- package/dist/src/workspaces.d.ts +118 -0
- package/dist/src/workspaces.js +590 -0
- package/dist/src/workspaces.js.map +1 -0
- package/package.json +47 -4
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { CacheCorruptError } from './cache.js';
|
|
4
|
+
import { ADAPTER_PACKAGE, diagnostics as adapterDiagnostics, toolVersion } from './adapters.js';
|
|
5
|
+
import { isSecretName, makeRedactor, resolveExecutable, runCommand } from './runner.js';
|
|
6
|
+
import { detectCycle, schedule } from './scheduler.js';
|
|
7
|
+
import { changedFilesFromGit, selectTests } from './affected.js';
|
|
8
|
+
import { selectPackages } from './workspaces.js';
|
|
9
|
+
import { canonical, hashFile, hmac256, mapLimit, sha256 } from './util/hash.js';
|
|
10
|
+
import { readJson, writeFileAtomic } from './util/fsx.js';
|
|
11
|
+
import { compileGlobs } from './util/glob.js';
|
|
12
|
+
import { baseDigest, computeKeys, storePath, TestResultStore } from './testcache.js';
|
|
13
|
+
import { assertNoSymlinkInPath, resolveInside, toPosix, UnsafePathError } from './util/paths.js';
|
|
14
|
+
const BASE_ENV = ['PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'TEMP', 'TMP', 'SystemRoot', 'SYSTEMROOT', 'COMSPEC', 'PATHEXT'];
|
|
15
|
+
const MAX_STORED_LOG = 1024 * 1024;
|
|
16
|
+
const binDigestMemo = new Map();
|
|
17
|
+
/** All tasks needed to run `names`, in dependency order. */
|
|
18
|
+
export function closure(project, names) {
|
|
19
|
+
const out = [];
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
const visit = (n) => {
|
|
22
|
+
if (seen.has(n))
|
|
23
|
+
return;
|
|
24
|
+
seen.add(n);
|
|
25
|
+
const t = project.config.tasks[n];
|
|
26
|
+
if (!t)
|
|
27
|
+
throw new Error(`unknown task ${JSON.stringify(n)} (known: ${Object.keys(project.config.tasks).join(', ')})`);
|
|
28
|
+
t.dependsOn.forEach(visit);
|
|
29
|
+
out.push(n);
|
|
30
|
+
};
|
|
31
|
+
names.forEach(visit);
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
/** Expand a task name that may also be a pipeline name. */
|
|
35
|
+
export function expandNames(project, names, keep) {
|
|
36
|
+
const out = [];
|
|
37
|
+
const push = (n) => {
|
|
38
|
+
// A per-package task name stands for all its instances (optionally filtered, e.g. by --affected).
|
|
39
|
+
const group = project.taskGroups[n];
|
|
40
|
+
if (group)
|
|
41
|
+
out.push(...(keep ? group.filter(keep) : group));
|
|
42
|
+
else
|
|
43
|
+
out.push(n);
|
|
44
|
+
};
|
|
45
|
+
for (const n of names) {
|
|
46
|
+
if (!project.taskGroups[n] && project.config.pipelines[n] && !project.config.tasks[n])
|
|
47
|
+
project.config.pipelines[n].forEach(push);
|
|
48
|
+
else
|
|
49
|
+
push(n);
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
export async function runTasks(project, requested, opts = {}) {
|
|
54
|
+
const started = Date.now();
|
|
55
|
+
const parentEnv = opts.env ?? process.env;
|
|
56
|
+
const { config, root, cache } = project;
|
|
57
|
+
// Workspaces + --affected: only packages whose files (or dependencies) changed get their tasks
|
|
58
|
+
// scheduled; the tasks they depend on are pulled in by closure() and normally come from the cache.
|
|
59
|
+
let packageSelection = null;
|
|
60
|
+
let changedEarly = null;
|
|
61
|
+
if (opts.affected && project.workspace && Object.keys(project.taskGroups).length) {
|
|
62
|
+
changedEarly = await changedFilesFromGit(root, opts.affected.since);
|
|
63
|
+
packageSelection = changedEarly.ok
|
|
64
|
+
? selectPackages(project.workspace, await project.graph(), await project.loadPreviousGraph(), changedEarly.files)
|
|
65
|
+
: (() => {
|
|
66
|
+
const names = project.workspace.packages.map((x) => x.name);
|
|
67
|
+
const reason = `${changedEarly.error}; cannot compute changes, selecting every package`;
|
|
68
|
+
return { mode: 'all', reason, affected: names, skipped: [], why: Object.fromEntries(names.map((n) => [n, reason])) };
|
|
69
|
+
})();
|
|
70
|
+
}
|
|
71
|
+
const inAffected = packageSelection ? new Set(packageSelection.affected) : null;
|
|
72
|
+
const order = closure(project, expandNames(project, requested, inAffected ? (id) => inAffected.has(config.tasks[id]?.package?.name ?? '') : undefined));
|
|
73
|
+
const cycle = detectCycle(order.map((id) => ({ id, deps: config.tasks[id].dependsOn })));
|
|
74
|
+
if (cycle)
|
|
75
|
+
throw new Error(`task dependency cycle: ${cycle.join(' -> ')}`);
|
|
76
|
+
const history = (await readJson(path.join(project.stateDir, 'history.json'))) ?? {};
|
|
77
|
+
const secretKey = await cache.secretKey();
|
|
78
|
+
// A task may only consume another task's outputs if it (transitively) depends on that task.
|
|
79
|
+
// Everything else's artifacts (and its own outputs) are never inputs, whatever the globs match.
|
|
80
|
+
const transitiveDeps = (n, acc = new Set()) => {
|
|
81
|
+
for (const d of config.tasks[n].dependsOn)
|
|
82
|
+
if (!acc.has(d)) {
|
|
83
|
+
acc.add(d);
|
|
84
|
+
transitiveDeps(d, acc);
|
|
85
|
+
}
|
|
86
|
+
return acc;
|
|
87
|
+
};
|
|
88
|
+
const foreignOutputs = new Map();
|
|
89
|
+
const isOutputOf = (name) => {
|
|
90
|
+
let m = foreignOutputs.get(name);
|
|
91
|
+
if (!m) {
|
|
92
|
+
const deps = transitiveDeps(name);
|
|
93
|
+
m = compileGlobs(Object.values(config.tasks).filter((x) => x.name === name || !deps.has(x.name)).flatMap((x) => x.outputs));
|
|
94
|
+
foreignOutputs.set(name, m);
|
|
95
|
+
}
|
|
96
|
+
return m;
|
|
97
|
+
};
|
|
98
|
+
// ---- affected-test selection (before scheduling) -------------------------------------------
|
|
99
|
+
let selection = null;
|
|
100
|
+
const extraArgs = new Map();
|
|
101
|
+
const skipReason = new Map();
|
|
102
|
+
if (opts.affected) {
|
|
103
|
+
const testTasks = order.filter((n) => config.tasks[n].kind === 'test' && config.tasks[n].affected);
|
|
104
|
+
if (testTasks.length) {
|
|
105
|
+
const graph = await project.graph();
|
|
106
|
+
const prev = await project.loadPreviousGraph();
|
|
107
|
+
const ch = changedEarly ?? (await changedFilesFromGit(root, opts.affected.since));
|
|
108
|
+
selection = ch.ok
|
|
109
|
+
? selectTests(graph, prev, ch.files)
|
|
110
|
+
: { mode: 'all', reason: `${ch.error}; cannot compute changes, running every test`, changed: [], selected: graph.testFiles(), skipped: [], chains: {} };
|
|
111
|
+
await project.saveGraph(graph);
|
|
112
|
+
for (const n of testTasks) {
|
|
113
|
+
if (selection.mode === 'all')
|
|
114
|
+
continue; // run the task's own full command
|
|
115
|
+
// A per-package test task only receives the selected tests that live in its package.
|
|
116
|
+
const pkgDir = config.tasks[n].package?.dir;
|
|
117
|
+
const mine = pkgDir ? selection.selected.filter((t) => t.startsWith(pkgDir + '/')) : selection.selected;
|
|
118
|
+
if (mine.length === 0)
|
|
119
|
+
skipReason.set(n, 'no tests are affected by the changes');
|
|
120
|
+
else {
|
|
121
|
+
const cwd = path.join(root, config.tasks[n].cwd);
|
|
122
|
+
extraArgs.set(n, mine.map((t) => toPosix(path.relative(cwd, path.join(root, t)))));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// ---- shared state --------------------------------------------------------------------------
|
|
128
|
+
let dirty = false;
|
|
129
|
+
let scanLock = Promise.resolve();
|
|
130
|
+
const lockedScan = () => {
|
|
131
|
+
const p = scanLock.then(() => project.index.scan());
|
|
132
|
+
scanLock = p.catch(() => undefined);
|
|
133
|
+
return p;
|
|
134
|
+
};
|
|
135
|
+
const ensureFresh = async () => {
|
|
136
|
+
if (dirty) {
|
|
137
|
+
dirty = false;
|
|
138
|
+
await lockedScan();
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const reports = new Map();
|
|
142
|
+
const fingerprints = new Map();
|
|
143
|
+
const stats = { hits: 0, misses: 0, restored: 0, stored: 0, savedMs: 0 };
|
|
144
|
+
const finish = (r) => {
|
|
145
|
+
reports.set(r.task, r);
|
|
146
|
+
opts.onTaskDone?.(r);
|
|
147
|
+
};
|
|
148
|
+
const blank = (task) => ({
|
|
149
|
+
task, state: 'pending', cache: 'n/a', reasons: [], notes: [], fingerprint: null, durationMs: 0,
|
|
150
|
+
restoredBytes: 0, storedBytes: 0, savedMsEstimate: 0, exitCode: null, log: '', diagnostics: [], testCache: null,
|
|
151
|
+
});
|
|
152
|
+
const exec = async (name, signal) => {
|
|
153
|
+
const declared = config.tasks[name];
|
|
154
|
+
// Adapter env prefixes (e.g. VITE_) expand to every matching variable that is actually set.
|
|
155
|
+
const t = {
|
|
156
|
+
...declared,
|
|
157
|
+
env: [...new Set([...declared.env, ...Object.keys(parentEnv).filter((k) => declared.envPrefixes.some((p) => k.startsWith(p)))])].sort(),
|
|
158
|
+
};
|
|
159
|
+
const rep = blank(name);
|
|
160
|
+
const t0 = Date.now();
|
|
161
|
+
try {
|
|
162
|
+
if (skipReason.has(name)) {
|
|
163
|
+
rep.state = 'skipped';
|
|
164
|
+
rep.notes.push(skipReason.get(name));
|
|
165
|
+
finish(rep);
|
|
166
|
+
return 'skipped';
|
|
167
|
+
}
|
|
168
|
+
await ensureFresh();
|
|
169
|
+
const taskCwd = t.cwd === '.' ? root : resolveInside(root, t.cwd);
|
|
170
|
+
const env = buildEnv(t, parentEnv);
|
|
171
|
+
const exe = resolveExecutable(t.command[0], taskCwd, root, env.PATH ?? '');
|
|
172
|
+
if (!exe) {
|
|
173
|
+
rep.state = 'failed';
|
|
174
|
+
rep.exitCode = 127;
|
|
175
|
+
rep.notes.push(`executable ${JSON.stringify(t.command[0])} not found (searched node_modules/.bin and PATH)`);
|
|
176
|
+
finish(rep);
|
|
177
|
+
return 'failed';
|
|
178
|
+
}
|
|
179
|
+
let args = extraArgs.get(name) ?? [];
|
|
180
|
+
const inputs = resolveInputs(project, t, isOutputOf(name));
|
|
181
|
+
const components = await buildComponents(project, t, args, inputs, exe, fingerprints, secretKey, parentEnv);
|
|
182
|
+
if (t.adapter)
|
|
183
|
+
components.toolchain[t.adapter] = await toolVersion(root, taskCwd, ADAPTER_PACKAGE[t.adapter]);
|
|
184
|
+
let fp = sha256(canonical(components));
|
|
185
|
+
rep.fingerprint = fp;
|
|
186
|
+
fingerprints.set(name, fp);
|
|
187
|
+
const prev = await readJson(taskStatePath(project, name));
|
|
188
|
+
const cacheOn = t.cache && !opts.noCache;
|
|
189
|
+
if (!cacheOn) {
|
|
190
|
+
rep.cache = 'disabled';
|
|
191
|
+
rep.reasons.push(!t.cache ? 'caching disabled for this task (cache: false)' : 'caching disabled by --no-cache');
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
const rec = await cache.lookup(fp);
|
|
195
|
+
if (rec) {
|
|
196
|
+
try {
|
|
197
|
+
const r0 = Date.now();
|
|
198
|
+
const restored = await cache.restore(rec, root);
|
|
199
|
+
await removeStale(root, prev?.outputs ?? [], rec.outputs.map((o) => o.path));
|
|
200
|
+
await cache.touch(fp);
|
|
201
|
+
rep.state = 'cached';
|
|
202
|
+
rep.cache = 'hit';
|
|
203
|
+
rep.restoredBytes = restored.bytes;
|
|
204
|
+
rep.savedMsEstimate = rec.durationMs;
|
|
205
|
+
rep.durationMs = Date.now() - r0;
|
|
206
|
+
rep.notes.push(`restored ${restored.files} file(s) in ${rep.durationMs}ms`);
|
|
207
|
+
if (rec.logDigest)
|
|
208
|
+
rep.log = (await cache.readBlob(rec.logDigest))?.toString('utf8') ?? '';
|
|
209
|
+
stats.hits++;
|
|
210
|
+
stats.restored += restored.bytes;
|
|
211
|
+
stats.savedMs += rec.durationMs;
|
|
212
|
+
if (restored.files)
|
|
213
|
+
dirty = true;
|
|
214
|
+
await saveTaskState(project, name, { fingerprint: fp, components, outputs: rec.outputs.map((o) => o.path), at: Date.now() });
|
|
215
|
+
finish(rep);
|
|
216
|
+
return 'cached';
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
if (!(e instanceof CacheCorruptError || e instanceof UnsafePathError))
|
|
220
|
+
throw e;
|
|
221
|
+
rep.reasons.push(`cache entry unusable (${e.message}); entry discarded`);
|
|
222
|
+
await cache.deleteEntry(fp);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
rep.cache = 'miss';
|
|
226
|
+
if (rep.reasons.length === 0)
|
|
227
|
+
rep.reasons.push(...explainMiss(prev?.components ?? null, components));
|
|
228
|
+
stats.misses++;
|
|
229
|
+
}
|
|
230
|
+
// ---- per-test-file result caching (opt-in) -------------------------------------------
|
|
231
|
+
let plan = null;
|
|
232
|
+
if (cacheOn && t.testCache && t.kind === 'test') {
|
|
233
|
+
plan = await planTestCache(project, t, taskCwd, components, extraArgs.has(name) ? args : null);
|
|
234
|
+
if (plan) {
|
|
235
|
+
rep.testCache = { skipped: plan.skipped, ran: plan.ran, recorded: 0 };
|
|
236
|
+
if (plan.run.length === 0) {
|
|
237
|
+
rep.state = 'cached';
|
|
238
|
+
rep.cache = 'hit';
|
|
239
|
+
rep.durationMs = 0;
|
|
240
|
+
rep.savedMsEstimate = plan.savedMs;
|
|
241
|
+
rep.notes.push(`testCache: all ${plan.skipped.length} test file(s) unchanged since a passing run; nothing executed`);
|
|
242
|
+
stats.misses--;
|
|
243
|
+
stats.hits++;
|
|
244
|
+
stats.savedMs += plan.savedMs;
|
|
245
|
+
finish(rep);
|
|
246
|
+
return 'cached';
|
|
247
|
+
}
|
|
248
|
+
rep.notes.push(`testCache: skipped ${plan.skipped.length} of ${plan.skipped.length + plan.run.length} test file(s) (unchanged since a passing run); running ${plan.run.length}`);
|
|
249
|
+
args = plan.run.map((r) => toPosix(path.relative(taskCwd, path.join(root, r))));
|
|
250
|
+
components.args = args;
|
|
251
|
+
fp = sha256(canonical(components));
|
|
252
|
+
rep.fingerprint = fp;
|
|
253
|
+
fingerprints.set(name, fp);
|
|
254
|
+
}
|
|
255
|
+
else
|
|
256
|
+
rep.notes.push('testCache: no cacheable test files found for this task; running normally');
|
|
257
|
+
}
|
|
258
|
+
// ---- execute -------------------------------------------------------------------------
|
|
259
|
+
const redact = makeRedactor(env);
|
|
260
|
+
const res = await runCommand({
|
|
261
|
+
file: exe,
|
|
262
|
+
args: [...t.command.slice(1), ...args],
|
|
263
|
+
cwd: taskCwd,
|
|
264
|
+
env,
|
|
265
|
+
signal,
|
|
266
|
+
timeoutMs: t.timeoutMs,
|
|
267
|
+
redact,
|
|
268
|
+
});
|
|
269
|
+
rep.durationMs = res.durationMs;
|
|
270
|
+
rep.exitCode = res.exitCode;
|
|
271
|
+
rep.log = res.log;
|
|
272
|
+
if (res.exitCode !== 0)
|
|
273
|
+
rep.diagnostics = adapterDiagnostics(t.adapter, res.log);
|
|
274
|
+
if (res.spawnError)
|
|
275
|
+
rep.notes.push(`failed to start: ${res.spawnError}`);
|
|
276
|
+
if (res.timedOut)
|
|
277
|
+
rep.notes.push(`timed out after ${t.timeoutMs}ms`);
|
|
278
|
+
if (res.cancelled) {
|
|
279
|
+
rep.state = 'cancelled';
|
|
280
|
+
finish(rep);
|
|
281
|
+
return 'failed';
|
|
282
|
+
}
|
|
283
|
+
if (res.exitCode !== 0) {
|
|
284
|
+
rep.state = 'failed';
|
|
285
|
+
if (res.signal)
|
|
286
|
+
rep.notes.push(`terminated by ${res.signal}`);
|
|
287
|
+
finish(rep);
|
|
288
|
+
return 'failed';
|
|
289
|
+
}
|
|
290
|
+
// ---- success: validate outputs and inputs, then commit atomically -----------------------
|
|
291
|
+
dirty = true;
|
|
292
|
+
rep.state = 'succeeded';
|
|
293
|
+
history[name] = res.durationMs;
|
|
294
|
+
if (plan) {
|
|
295
|
+
rep.testCache.recorded = await recordPasses(project, plan, lockedScan, rep.notes, res.durationMs);
|
|
296
|
+
}
|
|
297
|
+
const cacheable = cacheOn;
|
|
298
|
+
let manifest = null;
|
|
299
|
+
if (t.outputs.length) {
|
|
300
|
+
const found = await captureOutputs(root, t.outputs);
|
|
301
|
+
if (found.problems.length) {
|
|
302
|
+
rep.cache = 'uncacheable';
|
|
303
|
+
rep.notes.push(...found.problems);
|
|
304
|
+
}
|
|
305
|
+
else
|
|
306
|
+
manifest = found.entries;
|
|
307
|
+
}
|
|
308
|
+
else
|
|
309
|
+
manifest = [];
|
|
310
|
+
if (cacheable && manifest) {
|
|
311
|
+
await lockedScan();
|
|
312
|
+
dirty = false;
|
|
313
|
+
const after = resolveInputs(project, t, isOutputOf(name));
|
|
314
|
+
const changed = diffInputs(components.inputs, after.map((p) => [p, project.index.files.get(p).digest]));
|
|
315
|
+
if (changed.length) {
|
|
316
|
+
rep.cache = 'uncacheable';
|
|
317
|
+
rep.notes.push(`inputs changed during execution (${changed.slice(0, 3).join(', ')}${changed.length > 3 ? ', ...' : ''}); result not cached`);
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
const logData = Buffer.from(res.log.length > MAX_STORED_LOG ? res.log.slice(-MAX_STORED_LOG) : res.log);
|
|
321
|
+
const logDigest = await cache.putBlobData(logData);
|
|
322
|
+
const record = {
|
|
323
|
+
v: 1, key: fp, task: name, createdAt: Date.now(), durationMs: res.durationMs,
|
|
324
|
+
outputs: manifest, logDigest, components,
|
|
325
|
+
};
|
|
326
|
+
const stored = await cache.store(record, root);
|
|
327
|
+
rep.storedBytes = stored.bytes;
|
|
328
|
+
stats.stored += stored.bytes;
|
|
329
|
+
await saveTaskState(project, name, { fingerprint: fp, components, outputs: manifest.map((o) => o.path), at: Date.now() });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
finish(rep);
|
|
333
|
+
return 'succeeded';
|
|
334
|
+
}
|
|
335
|
+
catch (e) {
|
|
336
|
+
rep.state = 'failed';
|
|
337
|
+
rep.notes.push(`internal error: ${e.message}`);
|
|
338
|
+
rep.durationMs ||= Date.now() - t0;
|
|
339
|
+
finish(rep);
|
|
340
|
+
return 'failed';
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const states = await schedule(order.map((id) => ({
|
|
344
|
+
id,
|
|
345
|
+
deps: config.tasks[id].dependsOn,
|
|
346
|
+
weight: config.tasks[id].cpu,
|
|
347
|
+
estimateMs: history[id] ?? 1000,
|
|
348
|
+
})), exec, { capacity: opts.concurrency ?? config.concurrency, signal: opts.signal, bail: opts.bail });
|
|
349
|
+
for (const id of order) {
|
|
350
|
+
if (!reports.has(id)) {
|
|
351
|
+
const r = blank(id);
|
|
352
|
+
r.state = states.get(id);
|
|
353
|
+
if (r.state === 'skipped')
|
|
354
|
+
r.notes.push('a dependency did not succeed');
|
|
355
|
+
if (r.state === 'cancelled')
|
|
356
|
+
r.notes.push('cancelled before start');
|
|
357
|
+
finish(r);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
await project.index.save();
|
|
361
|
+
await writeFileAtomic(path.join(project.stateDir, 'history.json'), JSON.stringify(history));
|
|
362
|
+
await bumpStats(project, stats);
|
|
363
|
+
if (project.config.cache.maxSizeMB > 0)
|
|
364
|
+
await cache.gc(project.config.cache.maxSizeMB * 1024 * 1024);
|
|
365
|
+
const tasks = order.map((id) => reports.get(id));
|
|
366
|
+
return {
|
|
367
|
+
ok: tasks.every((r) => ['succeeded', 'cached', 'skipped'].includes(r.state) && !(r.state === 'skipped' && r.notes.includes('a dependency did not succeed'))),
|
|
368
|
+
cancelled: tasks.some((r) => r.state === 'cancelled'),
|
|
369
|
+
durationMs: Date.now() - started,
|
|
370
|
+
tasks,
|
|
371
|
+
selection,
|
|
372
|
+
packages: packageSelection,
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
// ---------------------------------------------------------------------------------------------
|
|
376
|
+
export function buildEnv(t, parent) {
|
|
377
|
+
const env = {};
|
|
378
|
+
for (const k of BASE_ENV)
|
|
379
|
+
if (parent[k] !== undefined)
|
|
380
|
+
env[k] = parent[k];
|
|
381
|
+
// Pin sources of nondeterminism unless the task explicitly declares them as inputs.
|
|
382
|
+
env.TZ = 'UTC';
|
|
383
|
+
env.LANG = 'C.UTF-8';
|
|
384
|
+
env.NO_COLOR = '1';
|
|
385
|
+
env.FORCE_COLOR = '0';
|
|
386
|
+
env.CI = parent.CI ?? '';
|
|
387
|
+
if (env.CI === '')
|
|
388
|
+
delete env.CI;
|
|
389
|
+
for (const k of [...t.env, ...t.passEnv])
|
|
390
|
+
if (parent[k] !== undefined)
|
|
391
|
+
env[k] = parent[k];
|
|
392
|
+
for (const k of Object.keys(env))
|
|
393
|
+
if (k.startsWith('BUILDRUSH_'))
|
|
394
|
+
delete env[k]; // never leak internals
|
|
395
|
+
return env;
|
|
396
|
+
}
|
|
397
|
+
/** Decide which test files can be skipped. Returns null when the task has no usable test files. */
|
|
398
|
+
async function planTestCache(project, t, taskCwd, components, selectedArgs) {
|
|
399
|
+
const { root } = project;
|
|
400
|
+
const graph = await project.graph({ fresh: true });
|
|
401
|
+
const cwdRel = toPosix(path.relative(root, taskCwd));
|
|
402
|
+
const inCwd = (p) => cwdRel === '' || p.startsWith(cwdRel + '/');
|
|
403
|
+
let candidates;
|
|
404
|
+
if (selectedArgs) {
|
|
405
|
+
candidates = selectedArgs.map((a) => toPosix(path.relative(root, path.resolve(taskCwd, a))));
|
|
406
|
+
if (candidates.some((c) => !inCwd(c)))
|
|
407
|
+
return null; // cannot address tests outside cwd by relative argument safely
|
|
408
|
+
}
|
|
409
|
+
else
|
|
410
|
+
candidates = graph.testFiles().filter(inCwd);
|
|
411
|
+
if (candidates.length === 0)
|
|
412
|
+
return null;
|
|
413
|
+
const base = { task: t.name, command: components.command, cwd: components.cwd, env: components.env, toolchain: components.toolchain };
|
|
414
|
+
const keys = computeKeys(graph, project.index.files, candidates, baseDigest(base, project.index.files));
|
|
415
|
+
const store = new TestResultStore(storePath(project.stateDir, t.name));
|
|
416
|
+
await store.load();
|
|
417
|
+
const plan = { keys, base, store, skipped: [], ran: [], run: [], savedMs: 0 };
|
|
418
|
+
for (const c of candidates) {
|
|
419
|
+
const k = keys.get(c);
|
|
420
|
+
const hit = k.key ? store.has(k.key) : null;
|
|
421
|
+
if (hit) {
|
|
422
|
+
plan.skipped.push({ test: c, reason: `unchanged since passing run at ${new Date(hit.at).toISOString()} (file, imports, config, env and toolchain identical)` });
|
|
423
|
+
plan.savedMs += hit.durationMs;
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
plan.run.push(c);
|
|
427
|
+
plan.ran.push({ test: c, reason: k.key === null ? `always runs: ${k.reason}` : store.knowsTest(c) ? 'file, an import, config, env or toolchain changed since last passing run' : 'no recorded passing run' });
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return plan;
|
|
431
|
+
}
|
|
432
|
+
/** Record passes only for files whose inputs are provably unchanged since the run started. */
|
|
433
|
+
async function recordPasses(project, plan, rescan, notes, durationMs) {
|
|
434
|
+
await rescan();
|
|
435
|
+
const graph = await project.graph({ fresh: true });
|
|
436
|
+
const after = computeKeys(graph, project.index.files, plan.run, baseDigest(plan.base, project.index.files));
|
|
437
|
+
const per = Math.round(durationMs / Math.max(1, plan.run.length));
|
|
438
|
+
const moved = [];
|
|
439
|
+
let n = 0;
|
|
440
|
+
for (const test of plan.run) {
|
|
441
|
+
const before = plan.keys.get(test).key;
|
|
442
|
+
if (!before)
|
|
443
|
+
continue;
|
|
444
|
+
if (after.get(test)?.key !== before)
|
|
445
|
+
moved.push(test);
|
|
446
|
+
else {
|
|
447
|
+
plan.store.add(before, { test, at: Date.now(), durationMs: per });
|
|
448
|
+
n++;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (moved.length)
|
|
452
|
+
notes.push(`testCache: inputs changed during execution for ${moved.slice(0, 3).join(', ')}${moved.length > 3 ? ', ...' : ''}; those results not recorded`);
|
|
453
|
+
await plan.store.save();
|
|
454
|
+
return n;
|
|
455
|
+
}
|
|
456
|
+
function resolveInputs(project, t, isExcludedOutput) {
|
|
457
|
+
const all = [...project.index.files.keys()];
|
|
458
|
+
if (t.inputs === null)
|
|
459
|
+
return all.filter((f) => !isExcludedOutput(f));
|
|
460
|
+
const match = compileGlobs(t.inputs);
|
|
461
|
+
return all.filter((f) => match(f) && !isExcludedOutput(f));
|
|
462
|
+
}
|
|
463
|
+
async function buildComponents(project, t, args, inputs, exe, fingerprints, secretKey, parentEnv) {
|
|
464
|
+
const env = {};
|
|
465
|
+
for (const name of [...t.env].sort()) {
|
|
466
|
+
const v = parentEnv[name];
|
|
467
|
+
env[name] = v === undefined ? null : isSecretName(name) ? 'hmac:' + hmac256(secretKey, `${name}=${v}`) : sha256(`${name}=${v}`);
|
|
468
|
+
}
|
|
469
|
+
const inputDigests = {};
|
|
470
|
+
for (const p of inputs)
|
|
471
|
+
inputDigests[p] = project.index.files.get(p).digest;
|
|
472
|
+
const deps = {};
|
|
473
|
+
for (const d of [...t.dependsOn].sort()) {
|
|
474
|
+
const fp = fingerprints.get(d);
|
|
475
|
+
if (fp)
|
|
476
|
+
deps[d] = fp;
|
|
477
|
+
}
|
|
478
|
+
return {
|
|
479
|
+
schema: 1,
|
|
480
|
+
task: t.name,
|
|
481
|
+
command: t.command,
|
|
482
|
+
cwd: t.cwd,
|
|
483
|
+
env,
|
|
484
|
+
toolchain: {
|
|
485
|
+
node: process.version,
|
|
486
|
+
platform: process.platform,
|
|
487
|
+
arch: process.arch,
|
|
488
|
+
executable: await executableDigest(exe),
|
|
489
|
+
},
|
|
490
|
+
inputs: inputDigests,
|
|
491
|
+
deps,
|
|
492
|
+
outputs: [...t.outputs].sort(),
|
|
493
|
+
args,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
async function executableDigest(exe) {
|
|
497
|
+
let real = exe;
|
|
498
|
+
try {
|
|
499
|
+
real = await fs.realpath(exe);
|
|
500
|
+
}
|
|
501
|
+
catch { /* keep */ }
|
|
502
|
+
if (real === process.execPath)
|
|
503
|
+
return `node:${process.version}`;
|
|
504
|
+
const st = await fs.stat(real);
|
|
505
|
+
// Keyed by file identity too, so a long-lived process (the daemon) notices a replaced binary.
|
|
506
|
+
const memoKey = `${real}|${st.size}|${st.mtimeMs}|${st.ino}`;
|
|
507
|
+
const memo = binDigestMemo.get(memoKey);
|
|
508
|
+
if (memo)
|
|
509
|
+
return memo;
|
|
510
|
+
const d = st.size > 64 * 1024 * 1024 ? `meta:${st.size}:${Math.floor(st.mtimeMs)}` : await hashFile(real);
|
|
511
|
+
binDigestMemo.set(memoKey, d);
|
|
512
|
+
return d;
|
|
513
|
+
}
|
|
514
|
+
function diffInputs(before, after) {
|
|
515
|
+
const out = [];
|
|
516
|
+
const seen = new Set();
|
|
517
|
+
for (const [p, d] of after) {
|
|
518
|
+
seen.add(p);
|
|
519
|
+
if (!(p in before))
|
|
520
|
+
out.push(`+${p}`);
|
|
521
|
+
else if (before[p] !== d)
|
|
522
|
+
out.push(`~${p}`);
|
|
523
|
+
}
|
|
524
|
+
for (const p of Object.keys(before))
|
|
525
|
+
if (!seen.has(p))
|
|
526
|
+
out.push(`-${p}`);
|
|
527
|
+
return out;
|
|
528
|
+
}
|
|
529
|
+
/** Human-readable reasons a task could not be served from the cache. */
|
|
530
|
+
export function explainMiss(prev, cur) {
|
|
531
|
+
if (!prev)
|
|
532
|
+
return ['no previous successful run recorded for this task'];
|
|
533
|
+
const out = [];
|
|
534
|
+
if (canonical(prev.command) !== canonical(cur.command))
|
|
535
|
+
out.push('command changed');
|
|
536
|
+
if (canonical(prev.args) !== canonical(cur.args))
|
|
537
|
+
out.push('selected arguments changed (different test selection)');
|
|
538
|
+
if (prev.cwd !== cur.cwd)
|
|
539
|
+
out.push('working directory changed');
|
|
540
|
+
if (canonical(prev.outputs) !== canonical(cur.outputs))
|
|
541
|
+
out.push('declared outputs changed');
|
|
542
|
+
for (const k of new Set([...Object.keys(prev.env), ...Object.keys(cur.env)])) {
|
|
543
|
+
if (prev.env[k] !== cur.env[k])
|
|
544
|
+
out.push(`environment variable ${k} changed`);
|
|
545
|
+
}
|
|
546
|
+
for (const k of new Set([...Object.keys(prev.toolchain), ...Object.keys(cur.toolchain)])) {
|
|
547
|
+
if (prev.toolchain[k] !== cur.toolchain[k])
|
|
548
|
+
out.push(`toolchain ${k} changed`);
|
|
549
|
+
}
|
|
550
|
+
const changes = diffInputs(prev.inputs, Object.entries(cur.inputs));
|
|
551
|
+
const label = (c) => (c[0] === '+' ? `input added: ${c.slice(1)}` : c[0] === '-' ? `input removed: ${c.slice(1)}` : `input changed: ${c.slice(1)}`);
|
|
552
|
+
changes.slice(0, 5).forEach((c) => out.push(label(c)));
|
|
553
|
+
if (changes.length > 5)
|
|
554
|
+
out.push(`...and ${changes.length - 5} more input change(s)`);
|
|
555
|
+
for (const k of new Set([...Object.keys(prev.deps), ...Object.keys(cur.deps)])) {
|
|
556
|
+
if (prev.deps[k] !== cur.deps[k])
|
|
557
|
+
out.push(`dependency task "${k}" has a different fingerprint`);
|
|
558
|
+
}
|
|
559
|
+
if (out.length === 0)
|
|
560
|
+
out.push('cache entry missing (evicted, cleaned, or never stored)');
|
|
561
|
+
return out;
|
|
562
|
+
}
|
|
563
|
+
async function captureOutputs(root, patterns) {
|
|
564
|
+
const problems = [];
|
|
565
|
+
const entries = [];
|
|
566
|
+
const seen = new Set();
|
|
567
|
+
for (const pattern of patterns) {
|
|
568
|
+
const match = compileGlobs([pattern]);
|
|
569
|
+
const segs = pattern.replace(/^\.\//, '').split('/');
|
|
570
|
+
const stat = [];
|
|
571
|
+
for (const s of segs.slice(0, -1)) {
|
|
572
|
+
if (/[*?{]/.test(s))
|
|
573
|
+
break;
|
|
574
|
+
stat.push(s);
|
|
575
|
+
}
|
|
576
|
+
const baseRel = stat.join('/');
|
|
577
|
+
const found = [];
|
|
578
|
+
const walk = async (rel) => {
|
|
579
|
+
const abs = rel ? path.join(root, rel) : root;
|
|
580
|
+
let ents;
|
|
581
|
+
try {
|
|
582
|
+
ents = await fs.readdir(abs, { withFileTypes: true });
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
for (const e of ents) {
|
|
588
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
589
|
+
if (e.isSymbolicLink()) {
|
|
590
|
+
if (match(r))
|
|
591
|
+
problems.push(`output ${r} is a symlink; symlinked outputs are never cached`);
|
|
592
|
+
}
|
|
593
|
+
else if (e.isDirectory()) {
|
|
594
|
+
if (e.name !== '.git' && e.name !== '.buildrush' && (e.name !== 'node_modules' || baseRel.includes('node_modules')))
|
|
595
|
+
await walk(r);
|
|
596
|
+
}
|
|
597
|
+
else if (e.isFile() && match(r))
|
|
598
|
+
found.push(r);
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
await walk(baseRel);
|
|
602
|
+
if (found.length === 0)
|
|
603
|
+
problems.push(`declared output ${JSON.stringify(pattern)} matched no files; result not cached`);
|
|
604
|
+
for (const f of found) {
|
|
605
|
+
if (seen.has(f))
|
|
606
|
+
continue;
|
|
607
|
+
seen.add(f);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const files = [...seen].sort();
|
|
611
|
+
const hashed = await mapLimit(files, 16, async (rel) => {
|
|
612
|
+
const abs = resolveInside(root, rel);
|
|
613
|
+
const st = await fs.lstat(abs);
|
|
614
|
+
return { path: rel, digest: await hashFile(abs), size: st.size, mode: st.mode & 0o777 };
|
|
615
|
+
});
|
|
616
|
+
entries.push(...hashed);
|
|
617
|
+
return { entries, problems };
|
|
618
|
+
}
|
|
619
|
+
async function removeStale(root, previous, current) {
|
|
620
|
+
const keep = new Set(current);
|
|
621
|
+
for (const rel of previous) {
|
|
622
|
+
if (keep.has(rel))
|
|
623
|
+
continue;
|
|
624
|
+
try {
|
|
625
|
+
await assertNoSymlinkInPath(root, rel);
|
|
626
|
+
await fs.rm(resolveInside(root, rel), { force: true });
|
|
627
|
+
}
|
|
628
|
+
catch { /* unsafe or already gone: leave it */ }
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
function taskStatePath(project, name) {
|
|
632
|
+
return path.join(project.stateDir, 'tasks', encodeURIComponent(name) + '.json');
|
|
633
|
+
}
|
|
634
|
+
async function saveTaskState(project, name, s) {
|
|
635
|
+
await writeFileAtomic(taskStatePath(project, name), JSON.stringify(s));
|
|
636
|
+
}
|
|
637
|
+
export async function loadTaskState(project, name) {
|
|
638
|
+
return readJson(taskStatePath(project, name));
|
|
639
|
+
}
|
|
640
|
+
export async function readStats(project) {
|
|
641
|
+
return ((await readJson(path.join(project.stateDir, 'stats.json'))) ?? {
|
|
642
|
+
hits: 0, misses: 0, bytesRestored: 0, bytesStored: 0, estimatedSavedMs: 0,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
async function bumpStats(project, s) {
|
|
646
|
+
const cur = await readStats(project);
|
|
647
|
+
await writeFileAtomic(path.join(project.stateDir, 'stats.json'), JSON.stringify({
|
|
648
|
+
hits: cur.hits + s.hits,
|
|
649
|
+
misses: cur.misses + s.misses,
|
|
650
|
+
bytesRestored: cur.bytesRestored + s.restored,
|
|
651
|
+
bytesStored: cur.bytesStored + s.stored,
|
|
652
|
+
estimatedSavedMs: cur.estimatedSavedMs + s.savedMs,
|
|
653
|
+
}));
|
|
654
|
+
}
|
|
655
|
+
//# sourceMappingURL=engine.js.map
|