@smoothbricks/nx-plugin 0.4.25 → 0.4.26

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 (54) hide show
  1. package/README.md +144 -41
  2. package/dist/bin/smoo-nx-exec.js +3 -14
  3. package/dist/cargo-closure-input.d.ts +13 -15
  4. package/dist/cargo-closure-input.d.ts.map +1 -1
  5. package/dist/cargo-closure-input.js +29 -37
  6. package/dist/cargo-source-hash.d.ts +12 -7
  7. package/dist/cargo-source-hash.d.ts.map +1 -1
  8. package/dist/cargo-source-hash.js +416 -32
  9. package/dist/cargo-workspace.d.ts +7 -7
  10. package/dist/cargo-workspace.js +8 -8
  11. package/dist/ensure-built.d.ts +6 -0
  12. package/dist/ensure-built.d.ts.map +1 -1
  13. package/dist/ensure-built.js +79 -6
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +69 -96
  16. package/dist/managed-assets.d.ts +6 -0
  17. package/dist/managed-assets.d.ts.map +1 -1
  18. package/dist/manifest-hash.d.ts.map +1 -1
  19. package/dist/manifest-hash.js +6 -2
  20. package/dist/workspace-manifest.d.ts +0 -1
  21. package/dist/workspace-manifest.d.ts.map +1 -1
  22. package/managed/raw/envrc +6 -1
  23. package/managed/raw/tooling/direnv/developer-links.ts +43 -11
  24. package/managed/raw/tooling/direnv/devenv.smoo.nix +1 -0
  25. package/managed/raw/tooling/direnv/inherited-devenv.ts +69 -19
  26. package/managed/raw/tooling/direnv/setup-environment.ts +79 -2
  27. package/nextest.toml +3 -37
  28. package/package.json +2 -2
  29. package/src/__tests__/counted-cargo-process.ts +286 -0
  30. package/src/__tests__/counted-cargo.ts +711 -0
  31. package/src/__tests__/fixture-cargo-home.ts +36 -0
  32. package/src/__tests__/fixture-nx-env.ts +93 -3
  33. package/src/bin/smoo-nx-exec.ts +3 -14
  34. package/src/bounded-test-policy.test.ts +0 -1
  35. package/src/cargo-closure-input.test.ts +313 -15
  36. package/src/cargo-closure-input.ts +42 -50
  37. package/src/cargo-resolve-cache.test.ts +975 -0
  38. package/src/cargo-source-hash.test.ts +17 -3
  39. package/src/cargo-source-hash.ts +447 -37
  40. package/src/cargo-workspace.ts +8 -8
  41. package/src/ensure-built.test.ts +122 -20
  42. package/src/ensure-built.ts +82 -5
  43. package/src/index.test.ts +203 -107
  44. package/src/index.ts +86 -115
  45. package/src/managed-assets.ts +12 -0
  46. package/src/manifest-hash.ts +7 -2
  47. package/src/nextest-partitions.test.ts +150 -0
  48. package/src/nx-cache-bound.test.ts +114 -0
  49. package/src/nx-resident-graph-workers.test.ts +121 -0
  50. package/src/nx-store-resolution.test.ts +98 -0
  51. package/src/task-history-namespace.test.ts +183 -0
  52. package/src/workspace-manifest.ts +0 -1
  53. package/test-timings.json +30 -28
  54. package/src/__tests__/in-process-nx-index.ts +0 -9
@@ -0,0 +1,975 @@
1
+ import { expect, it } from 'bun:test';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { appendFile, mkdir, mkdtemp, readFile, realpath, rm, symlink, utimes, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { delimiter, dirname, join } from 'node:path';
6
+
7
+ import type { CreateNodesResultV2 } from 'nx/src/devkit-exports.js';
8
+ import { resetWorkspaceContext } from 'nx/src/utils/workspace-context.js';
9
+ import {
10
+ type CannedCargo,
11
+ type CountedCargo,
12
+ cannedCargo,
13
+ countedCargo,
14
+ expectCargoMetadataError,
15
+ expectGraphRefusal,
16
+ guardEvent,
17
+ rejectionOf,
18
+ waitForCargoJoins,
19
+ withEnvironment,
20
+ } from './__tests__/counted-cargo.js';
21
+ import { useFixtureCargoHome } from './__tests__/fixture-cargo-home.js';
22
+ import { CARGO_CLOSURE_INPUT } from './cargo-closure-input.js';
23
+ import { type CargoResolve, readCargoResolve } from './cargo-source-hash.js';
24
+ import { createNodesV2 } from './index.js';
25
+
26
+ useFixtureCargoHome();
27
+
28
+ /*
29
+ * What Cargo resolution costs, measured by the one number that matters: how many `cargo metadata`
30
+ * children were actually started. A `cargo` ahead of the real one on PATH reports each child's life
31
+ * to the fixture as it happens (`__tests__/counted-cargo.ts`); no assertion here reads a clock, and
32
+ * nothing here waits for one: every wait advances on a child's report, a process's output or exit,
33
+ * or a sharer joining an in-flight resolution. Only the outer hang guards keep time, and they report
34
+ * what was still open instead of advancing anything.
35
+ *
36
+ * These regressions exercise the content-keyed cache through `readCargoResolve`, project-graph
37
+ * inference and the hash command. Join readiness comes from the resolution's diagnostics channel;
38
+ * child counts and process-lifetime evidence come from the fixture's control connections.
39
+ *
40
+ * Every fixture is a temporary directory of its own, with its own Nx workspace-data directory (where
41
+ * the cache is kept), deleted with the fixture.
42
+ */
43
+
44
+ const sourceModule = join(import.meta.dir, 'cargo-source-hash.ts');
45
+ const cliModule = join(import.meta.dir, 'bin', 'smoo-nx-cargo-hash.ts');
46
+ const repositoryRoot = join(import.meta.dir, '../../..');
47
+
48
+ const spawned = async (cargo: CountedCargo): Promise<number> => (await cargo.runs()).spawned;
49
+
50
+ async function put(root: string, path: string, text: string): Promise<void> {
51
+ const file = join(root, path);
52
+ await mkdir(dirname(file), { recursive: true });
53
+ await writeFile(file, text);
54
+ }
55
+
56
+ /** Rewrite `path` as an editor that changed nothing would: the same bytes, a later mtime. */
57
+ async function touch(root: string, path: string): Promise<void> {
58
+ const file = join(root, path);
59
+ await writeFile(file, await readFile(file));
60
+ const later = new Date(Date.now() + 10_000);
61
+ await utimes(file, later, later);
62
+ }
63
+
64
+ /** Whether `pid` names a process right now: one syscall, never a wait. */
65
+ function alive(pid: number): boolean {
66
+ try {
67
+ process.kill(pid, 0);
68
+ return true;
69
+ } catch (error) {
70
+ if (error instanceof Error && 'code' in error && error.code === 'ESRCH') return false;
71
+ throw error;
72
+ }
73
+ }
74
+
75
+ /** How a subprocess ended, with everything it printed. */
76
+ interface Ended {
77
+ readonly exitCode: number | null;
78
+ readonly signalCode: NodeJS.Signals | null;
79
+ readonly stdout: string;
80
+ readonly stderr: string;
81
+ }
82
+
83
+ /**
84
+ * A subprocess whose stdout and stderr are read from the moment it starts, so a full pipe never
85
+ * stalls it and every failure message can say what it printed.
86
+ */
87
+ interface Drained {
88
+ readonly pid: number;
89
+ kill(signal: NodeJS.Signals): void;
90
+ /** Settles when stdout has printed `line` as a whole line; rejects if stdout ends first. */
91
+ printed(line: string): Promise<void>;
92
+ /** Settles once the process has exited and both of its streams have ended. */
93
+ readonly ended: Promise<Ended>;
94
+ /** The command, whether it is still running, and what it has printed so far. */
95
+ describe(): string;
96
+ }
97
+
98
+ async function drain(stream: ReadableStream<Uint8Array>, append: (text: string) => void): Promise<void> {
99
+ const decoder = new TextDecoder();
100
+ const reader = stream.getReader();
101
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
102
+ append(decoder.decode(chunk.value, { stream: true }));
103
+ }
104
+ append(decoder.decode());
105
+ }
106
+
107
+ function spawnDrained(command: readonly string[], cwd: string, environment: Readonly<Record<string, string>>): Drained {
108
+ const proc = Bun.spawn([...command], {
109
+ cwd,
110
+ env: { ...process.env, ...environment },
111
+ stdin: 'ignore',
112
+ stdout: 'pipe',
113
+ stderr: 'pipe',
114
+ });
115
+ let stdout = '';
116
+ let stderr = '';
117
+ let stdoutEnded = false;
118
+ const waiting = new Set<{ readonly line: string; resolve(): void; reject(error: Error): void }>();
119
+ const describe = (): string => {
120
+ const state =
121
+ proc.signalCode !== null
122
+ ? `killed by ${proc.signalCode}`
123
+ : proc.exitCode !== null
124
+ ? `exited ${proc.exitCode}`
125
+ : 'running';
126
+ return `${command.join(' ')} (pid ${proc.pid}, ${state})\nstdout: ${JSON.stringify(stdout)}\nstderr: ${JSON.stringify(stderr)}`;
127
+ };
128
+ const notify = (): void => {
129
+ const lines = new Set(stdout.split('\n').slice(0, -1));
130
+ for (const waiter of waiting) {
131
+ if (lines.has(waiter.line)) waiter.resolve();
132
+ else if (stdoutEnded) waiter.reject(new Error(`stdout ended before printing ${waiter.line}: ${describe()}`));
133
+ else continue;
134
+ waiting.delete(waiter);
135
+ }
136
+ };
137
+ const out = drain(proc.stdout, (text) => {
138
+ stdout += text;
139
+ notify();
140
+ }).finally(() => {
141
+ stdoutEnded = true;
142
+ notify();
143
+ });
144
+ const err = drain(proc.stderr, (text) => {
145
+ stderr += text;
146
+ });
147
+ return {
148
+ pid: proc.pid,
149
+ kill: (signal) => proc.kill(signal),
150
+ printed: (line) =>
151
+ new Promise<void>((resolve, reject) => {
152
+ waiting.add({ line, resolve, reject });
153
+ notify();
154
+ }),
155
+ ended: Promise.all([out, err, proc.exited]).then(
156
+ (): Ended => ({ exitCode: proc.exitCode, signalCode: proc.signalCode, stdout, stderr }),
157
+ ),
158
+ describe,
159
+ };
160
+ }
161
+
162
+ function summarize(resolved: CargoResolve) {
163
+ return {
164
+ root: resolved.root,
165
+ members: [...resolved.members],
166
+ local: resolved.local,
167
+ edges: resolved.edges === null ? null : [...resolved.edges],
168
+ };
169
+ }
170
+
171
+ /* ---- The cache's own behavior, against a Cargo that answers whatever the test says ---- */
172
+
173
+ const WORKSPACE_MANIFEST = '[workspace]\nmembers = ["crates/leaf"]\nresolver = "2"\n';
174
+ const WORKSPACE_FILES: Readonly<Record<string, string>> = {
175
+ 'Cargo.toml': WORKSPACE_MANIFEST,
176
+ 'Cargo.lock': '# fixture lock\nversion = 3\n',
177
+ 'crates/leaf/Cargo.toml': '[package]\nname = "leaf"\nversion = "0.1.0"\nedition = "2021"\n',
178
+ 'crates/leaf/src/lib.rs': 'pub fn leaf() -> u8 { 1 }\n',
179
+ 'README.md': '# fixture\n',
180
+ };
181
+
182
+ /** A package outside the Nx workspace that the member depends on by path: Cargo's answer names it, so its manifest is an input. */
183
+ const EXTERNAL_MANIFEST = '[package]\nname = "external"\nversion = "0.1.0"\nedition = "2021"\n[workspace]\n';
184
+ const EXTERNAL_SOURCE = 'pub fn external() -> u8 { 10 }\n';
185
+
186
+ /**
187
+ * What `cargo metadata` prints for the fixture when the workspace's one member is called `name`:
188
+ * it depends on the package outside the workspace, which Cargo reports as a local package too.
189
+ */
190
+ function metadataNamed(root: string, name: string) {
191
+ const workspace = join(root, 'workspace');
192
+ return {
193
+ packages: [
194
+ {
195
+ id: name,
196
+ source: null,
197
+ manifest_path: join(workspace, 'crates/leaf/Cargo.toml'),
198
+ targets: [{ src_path: join(workspace, 'crates/leaf/src/lib.rs') }],
199
+ },
200
+ {
201
+ id: 'external',
202
+ source: null,
203
+ manifest_path: join(root, 'external/Cargo.toml'),
204
+ targets: [{ src_path: join(root, 'external/src/lib.rs') }],
205
+ },
206
+ ],
207
+ resolve: {
208
+ nodes: [
209
+ { id: name, deps: [{ pkg: 'external' }] },
210
+ { id: 'external', deps: [] },
211
+ ],
212
+ },
213
+ workspace_members: [name],
214
+ workspace_root: workspace,
215
+ };
216
+ }
217
+
218
+ /** A process that has never resolved anything: it says on stdout that it is about to ask, asks, and prints the answer. */
219
+ const RESOLVE_WORKER = [
220
+ `import { readCargoResolve } from ${JSON.stringify(sourceModule)};`,
221
+ 'const [manifest, cwd] = process.argv.slice(2);',
222
+ "process.stdout.write('ready\\n');",
223
+ 'const resolved = await readCargoResolve(manifest, cwd);',
224
+ 'process.stdout.write(',
225
+ ' JSON.stringify({',
226
+ ' root: resolved.root,',
227
+ ' members: [...resolved.members],',
228
+ ' local: resolved.local,',
229
+ ' edges: resolved.edges === null ? null : [...resolved.edges],',
230
+ " }) + '\\n',",
231
+ ');',
232
+ '',
233
+ ].join('\n');
234
+
235
+ interface CannedWorkspace {
236
+ readonly root: string;
237
+ readonly workspace: string;
238
+ readonly manifest: string;
239
+ readonly cargo: CannedCargo;
240
+ /** What a process under test needs in its environment; this process already has it. */
241
+ readonly environment: Readonly<Record<string, string>>;
242
+ /** What Cargo says from now on: the workspace has one member, called `name`. */
243
+ answer(name: string): Promise<void>;
244
+ /** The members `readCargoResolve` reports for the workspace now. */
245
+ members(): Promise<string[]>;
246
+ }
247
+
248
+ /** `body` over a temporary Cargo workspace and the canned Cargo the module under test will find first. */
249
+ async function withCannedWorkspace(body: (fixture: CannedWorkspace) => Promise<void>): Promise<void> {
250
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-resolve-cache-')));
251
+ try {
252
+ const workspace = join(root, 'workspace');
253
+ for (const [path, text] of Object.entries(WORKSPACE_FILES)) await put(workspace, path, text);
254
+ await put(root, 'external/Cargo.toml', EXTERNAL_MANIFEST);
255
+ await put(root, 'external/src/lib.rs', EXTERNAL_SOURCE);
256
+ await put(root, 'resolve-worker.ts', RESOLVE_WORKER);
257
+ const cargo = await cannedCargo(root);
258
+ try {
259
+ const manifest = join(workspace, 'Cargo.toml');
260
+ const environment = { ...cargo.environment, CARGO_HOME: join(root, 'cargo-home') };
261
+ await withEnvironment(environment, () =>
262
+ body({
263
+ root,
264
+ workspace,
265
+ manifest,
266
+ cargo,
267
+ environment,
268
+ answer: (name) => cargo.answerWith(metadataNamed(root, name)),
269
+ members: async () => [...(await readCargoResolve(manifest, workspace)).members],
270
+ }),
271
+ );
272
+ } finally {
273
+ await cargo.release();
274
+ }
275
+ } finally {
276
+ await rm(root, { recursive: true, force: true });
277
+ }
278
+ }
279
+
280
+ /**
281
+ * `readCargoResolve` in a fresh process: a second Nx worker, or the next `nx` run. `ready` settles when
282
+ * the process has said it is about to ask; `result` is the answer it printed once it exited cleanly.
283
+ * Both are held to the fixture's hang guard, which reports what the process printed.
284
+ */
285
+ function freshResolver({ root, workspace, manifest, environment }: CannedWorkspace, name: string) {
286
+ const worker = spawnDrained(
287
+ [process.execPath, join(root, 'resolve-worker.ts'), manifest, workspace],
288
+ workspace,
289
+ environment,
290
+ );
291
+ const result = guardEvent(worker.ended, `fresh resolver ${name} to exit`, () => worker.describe()).then(
292
+ (ended): unknown => {
293
+ expect(ended.exitCode, worker.describe()).toBe(0);
294
+ const [announced, ...rest] = ended.stdout.trimEnd().split('\n');
295
+ expect(announced, worker.describe()).toBe('ready');
296
+ const answer = rest.at(-1);
297
+ if (answer === undefined) throw new Error(`fresh resolver ${name} printed no answer: ${worker.describe()}`);
298
+ const resolved: unknown = JSON.parse(answer);
299
+ return resolved;
300
+ },
301
+ );
302
+ return {
303
+ ready: () =>
304
+ guardEvent(worker.printed('ready'), `fresh resolver ${name} to say it is about to ask`, () => worker.describe()),
305
+ result,
306
+ };
307
+ }
308
+
309
+ it('concurrent resolutions of one Cargo workspace share one cargo child, and an unchanged workspace never runs Cargo again', async () => {
310
+ await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
311
+ await answer('before');
312
+ // The child holds its answer, after it read the workspace, until each of the other fifteen calls
313
+ // has joined its flight, so every call below arrives while it is pending.
314
+ await cargo.beforeAnswer.close();
315
+ const joins = waitForCargoJoins(manifest, 15);
316
+ let results: CargoResolve[];
317
+ try {
318
+ const calls = Promise.all(Array.from({ length: 16 }, () => readCargoResolve(manifest, workspace)));
319
+ await joins.joined;
320
+ await cargo.beforeAnswer.open();
321
+ results = await calls;
322
+ } finally {
323
+ joins.dispose();
324
+ }
325
+ expect(await spawned(cargo)).toBe(1);
326
+ expect(new Set(results).size).toBe(1);
327
+ for (const result of results) expect([...result.members]).toEqual(['before']);
328
+
329
+ // Nothing Cargo's answer depends on has changed, so Cargo, which would
330
+ // answer differently now, is not asked.
331
+ await answer('after');
332
+ expect(await members()).toEqual(['before']);
333
+ expect(await spawned(cargo)).toBe(1);
334
+
335
+ // A manifest edit is what changes the answer; it costs one child.
336
+ await appendFile(manifest, '# edited\n');
337
+ expect(await members()).toEqual(['after']);
338
+ expect(await members()).toEqual(['after']);
339
+ expect(await spawned(cargo)).toBe(2);
340
+ });
341
+ }, 20_000);
342
+
343
+ it("a failed resolution rejects every sharer with a CargoMetadataError carrying Cargo's stderr, and is not kept for the next call", async () => {
344
+ await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
345
+ await cargo.failWith('fake cargo: resolution failed\n');
346
+ // The child that fails holds its refusal until the second call has joined its flight.
347
+ await cargo.beforeAnswer.close();
348
+ const joins = waitForCargoJoins(manifest, 1);
349
+ let failures: unknown[];
350
+ try {
351
+ const refused = Promise.all(
352
+ [readCargoResolve(manifest, workspace), readCargoResolve(manifest, workspace)].map(rejectionOf),
353
+ );
354
+ await joins.joined;
355
+ await cargo.beforeAnswer.open();
356
+ failures = await refused;
357
+ } finally {
358
+ joins.dispose();
359
+ }
360
+ for (const failure of failures) {
361
+ expect(expectCargoMetadataError(failure, manifest).message).toContain('fake cargo: resolution failed');
362
+ }
363
+ expect(await spawned(cargo)).toBe(1);
364
+
365
+ // Nothing on disk changed, and a refusal is no answer: Cargo is asked again.
366
+ await cargo.recover();
367
+ await answer('recovered');
368
+ expect(await members()).toEqual(['recovered']);
369
+ expect(await spawned(cargo)).toBe(2);
370
+ expect(await members()).toEqual(['recovered']);
371
+ expect(await spawned(cargo)).toBe(2);
372
+ });
373
+ }, 20_000);
374
+
375
+ it('a Cargo that cannot run, or whose answer is not metadata, is a CargoMetadataError', async () => {
376
+ await withCannedWorkspace(async ({ cargo, workspace, manifest }) => {
377
+ for (const text of ['this is not JSON', '{"packages": 3}']) {
378
+ await cargo.answerWithText(text);
379
+ expectCargoMetadataError(await rejectionOf(readCargoResolve(manifest, workspace)), manifest);
380
+ }
381
+ expect(await spawned(cargo)).toBe(2);
382
+
383
+ await withEnvironment({ PATH: join(workspace, 'no-cargo-here') }, async () => {
384
+ expectCargoMetadataError(await rejectionOf(readCargoResolve(manifest, workspace)), manifest);
385
+ });
386
+ expect(await spawned(cargo)).toBe(2);
387
+ });
388
+ }, 20_000);
389
+
390
+ it('source edits, non-Rust edits and a rewrite of the same bytes never run Cargo', async () => {
391
+ await withCannedWorkspace(async ({ root, cargo, answer, members, workspace }) => {
392
+ await answer('cold');
393
+ expect(await members()).toEqual(['cold']);
394
+ const unkeyed: [string, () => Promise<void>][] = [
395
+ ['a source edit', () => put(workspace, 'crates/leaf/src/lib.rs', 'pub fn leaf() -> u8 { 2 }\n')],
396
+ ['a new source file', () => put(workspace, 'crates/leaf/src/extra.rs', 'pub const EXTRA: u8 = 1;\n')],
397
+ ['a non-Rust edit', () => put(workspace, 'README.md', '# edited\n')],
398
+ ['a new non-Rust file', () => put(workspace, 'crates/leaf/notes.json', '{}\n')],
399
+ ['the manifest rewritten with the same bytes', () => touch(workspace, 'crates/leaf/Cargo.toml')],
400
+ ['Cargo.lock rewritten with the same bytes', () => touch(workspace, 'Cargo.lock')],
401
+ [
402
+ 'a source edit outside the workspace',
403
+ () => put(root, 'external/src/lib.rs', 'pub fn external() -> u8 { 11 }\n'),
404
+ ],
405
+ ];
406
+ for (const [what, change] of unkeyed) {
407
+ await change();
408
+ // A Cargo asked after this change would say so.
409
+ await answer(`after ${what}`);
410
+ expect(await members(), what).toEqual(['cold']);
411
+ }
412
+ expect(await spawned(cargo)).toBe(1);
413
+ });
414
+ }, 20_000);
415
+
416
+ interface KeyedFile {
417
+ readonly name: string;
418
+ /** Relative to the fixture root; the workspace is `workspace/` in it. */
419
+ readonly path: string;
420
+ /** Whether the fixture has the file before the test touches it. */
421
+ readonly exists: boolean;
422
+ /** Whether the test may delete it: the fixture's Cargo answers with packages whose manifests must stay. */
423
+ readonly removable: boolean;
424
+ }
425
+
426
+ /** Every file whose bytes Cargo's answer depends on, or that the toolchain pin and configuration stand for. */
427
+ const KEYED_FILES: readonly KeyedFile[] = [
428
+ { name: 'the workspace manifest', path: 'workspace/Cargo.toml', exists: true, removable: false },
429
+ { name: "a member's manifest", path: 'workspace/crates/leaf/Cargo.toml', exists: true, removable: false },
430
+ {
431
+ name: "a path dependency's manifest outside the workspace",
432
+ path: 'external/Cargo.toml',
433
+ exists: true,
434
+ removable: false,
435
+ },
436
+ { name: 'a new manifest in the workspace', path: 'workspace/crates/new/Cargo.toml', exists: false, removable: true },
437
+ { name: 'Cargo.lock', path: 'workspace/Cargo.lock', exists: true, removable: true },
438
+ {
439
+ name: 'a .cargo/config.toml in the workspace',
440
+ path: 'workspace/.cargo/config.toml',
441
+ exists: false,
442
+ removable: true,
443
+ },
444
+ { name: 'a .cargo/config in the workspace', path: 'workspace/.cargo/config', exists: false, removable: true },
445
+ { name: 'a .cargo/config.toml above the workspace', path: '.cargo/config.toml', exists: false, removable: true },
446
+ { name: 'a Cargo.toml above the workspace', path: 'Cargo.toml', exists: false, removable: true },
447
+ { name: "CARGO_HOME's config.toml", path: 'cargo-home/config.toml', exists: false, removable: true },
448
+ { name: 'rust-toolchain.toml', path: 'workspace/rust-toolchain.toml', exists: false, removable: true },
449
+ { name: 'rust-toolchain', path: 'workspace/rust-toolchain', exists: false, removable: true },
450
+ { name: 'devenv.lock', path: 'workspace/devenv.lock', exists: false, removable: true },
451
+ { name: 'tooling/direnv/devenv.lock', path: 'workspace/tooling/direnv/devenv.lock', exists: false, removable: true },
452
+ ];
453
+
454
+ for (const file of KEYED_FILES) {
455
+ it(`resolves again exactly once when ${file.name} changes, and not again for the same bytes`, async () => {
456
+ await withCannedWorkspace(async ({ root, cargo, answer, members }) => {
457
+ const resolvesAs = async (name: string): Promise<string[]> => {
458
+ await answer(name);
459
+ return members();
460
+ };
461
+ expect(await resolvesAs('cold')).toEqual(['cold']);
462
+ expect(await spawned(cargo)).toBe(1);
463
+
464
+ const original = file.exists ? await readFile(join(root, file.path), 'utf8') : '';
465
+ await put(root, file.path, `${original}# one\n`);
466
+ expect(await resolvesAs('one')).toEqual(['one']);
467
+ expect(await spawned(cargo)).toBe(2);
468
+
469
+ // The bytes are the same, so Cargo, which would answer differently, is not asked.
470
+ await touch(root, file.path);
471
+ expect(await resolvesAs('same bytes')).toEqual(['one']);
472
+ expect(await spawned(cargo)).toBe(2);
473
+
474
+ await put(root, file.path, `${original}# two\n`);
475
+ expect(await resolvesAs('two')).toEqual(['two']);
476
+ expect(await spawned(cargo)).toBe(3);
477
+
478
+ if (file.removable) {
479
+ await rm(join(root, file.path));
480
+ expect(await resolvesAs('removed')).toEqual(['removed']);
481
+ expect(await spawned(cargo)).toBe(4);
482
+ }
483
+ expect(await resolvesAs('settled')).toEqual([file.removable ? 'removed' : 'two']);
484
+ expect(await spawned(cargo)).toBe(file.removable ? 4 : 3);
485
+ });
486
+ }, 30_000);
487
+ }
488
+
489
+ it('resolves again exactly once when the cargo on PATH or the rustup selection changes', async () => {
490
+ await withCannedWorkspace(async ({ root, cargo, answer, members, environment }) => {
491
+ const resolvesAs = async (name: string, selection: Record<string, string> = {}): Promise<string[]> => {
492
+ await answer(name);
493
+ return withEnvironment(selection, members);
494
+ };
495
+ expect(await resolvesAs('cold')).toEqual(['cold']);
496
+ expect(await spawned(cargo)).toBe(1);
497
+
498
+ expect(await resolvesAs('toolchain a', { RUSTUP_TOOLCHAIN: 'fixture-a' })).toEqual(['toolchain a']);
499
+ expect(await spawned(cargo)).toBe(2);
500
+ expect(await resolvesAs('same selection', { RUSTUP_TOOLCHAIN: 'fixture-a' })).toEqual(['toolchain a']);
501
+ expect(await spawned(cargo)).toBe(2);
502
+
503
+ expect(await resolvesAs('toolchain b', { RUSTUP_TOOLCHAIN: 'fixture-b' })).toEqual(['toolchain b']);
504
+ expect(await spawned(cargo)).toBe(3);
505
+
506
+ const selected = { RUSTUP_TOOLCHAIN: 'fixture-b', RUSTUP_HOME: join(root, 'rustup-home') };
507
+ expect(await resolvesAs('rustup home', selected)).toEqual(['rustup home']);
508
+ expect(await spawned(cargo)).toBe(4);
509
+
510
+ // The same bytes of Cargo, found elsewhere, are not the same Cargo: a toolchain proxy is a path.
511
+ const other = join(root, 'other-bin');
512
+ await mkdir(other, { recursive: true });
513
+ await writeFile(join(other, 'cargo'), await readFile(join(cargo.bin, 'cargo')), { mode: 0o755 });
514
+ const elsewhere = { ...selected, PATH: `${other}${delimiter}${environment.PATH}` };
515
+ expect(await resolvesAs('another cargo', elsewhere)).toEqual(['another cargo']);
516
+ expect(await spawned(cargo)).toBe(5);
517
+ expect(await resolvesAs('same cargo', elsewhere)).toEqual(['another cargo']);
518
+ expect(await spawned(cargo)).toBe(5);
519
+ });
520
+ }, 30_000);
521
+
522
+ it('a discovered manifest outside the workspace, edited while the first resolution holds, is never answered from before the edit', async () => {
523
+ await withCannedWorkspace(async ({ root, cargo, answer, members, workspace, manifest }) => {
524
+ // Nothing has resolved yet, so nothing knows the package outside the workspace is an input:
525
+ // Cargo's own answer is the first to name it, while the child that gave it still holds that answer.
526
+ await answer('before');
527
+ await cargo.beforeAnswer.close();
528
+ const first = readCargoResolve(manifest, workspace);
529
+ await cargo.waitForRuns((runs) => runs.read === 1, 'the first cargo child to read the workspace');
530
+ await appendFile(join(root, 'external/Cargo.toml'), '# edited\n');
531
+ await answer('after');
532
+ await cargo.beforeAnswer.open();
533
+ expect([...(await first).members]).toEqual(['after']);
534
+ const runs = await cargo.runs();
535
+ expect(runs.spawned).toBe(2);
536
+ expect(runs.peak).toBe(1);
537
+
538
+ // What was kept is what the edited workspace resolved to, under the edited bytes.
539
+ await answer('trap');
540
+ expect(await members()).toEqual(['after']);
541
+ expect(await spawned(cargo)).toBe(2);
542
+ });
543
+ }, 20_000);
544
+
545
+ it('an edit made while Cargo resolves is answered by a resolution that follows the first, never beside it', async () => {
546
+ await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
547
+ await answer('before');
548
+ await cargo.beforeAnswer.close();
549
+ const early = Array.from({ length: 4 }, () => readCargoResolve(manifest, workspace));
550
+ await cargo.waitForRuns((runs) => runs.read === 1, 'the first cargo child to read the workspace');
551
+
552
+ // That child holds the answer for the workspace as it was.
553
+ await appendFile(manifest, '# edited\n');
554
+ await answer('after');
555
+ const late = Array.from({ length: 4 }, () => readCargoResolve(manifest, workspace));
556
+ await cargo.beforeAnswer.open();
557
+
558
+ // A call that began after the edit is never answered from before it.
559
+ for (const result of await Promise.all(late)) expect([...result.members]).toEqual(['after']);
560
+ // A call that began before it may see either side of the edit, and nothing else.
561
+ for (const result of await Promise.all(early)) expect(['before', 'after']).toContain([...result.members][0]);
562
+ const runs = await cargo.runs();
563
+ expect(runs.spawned).toBe(2);
564
+ expect(runs.peak).toBe(1);
565
+
566
+ expect(await members()).toEqual(['after']);
567
+ expect(await spawned(cargo)).toBe(2);
568
+ });
569
+ }, 20_000);
570
+
571
+ it('an answer Cargo read after an edit is never kept for the workspace as it was before the edit', async () => {
572
+ await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
573
+ const original = await readFile(manifest, 'utf8');
574
+ await answer('before');
575
+ await cargo.beforeRead.close();
576
+ const first = readCargoResolve(manifest, workspace);
577
+ await cargo.waitForRuns((runs) => runs.spawned === 1, 'the cargo child to start');
578
+
579
+ // The call has taken the workspace as it is; Cargo reads it only after the edit.
580
+ await writeFile(manifest, `${original}# edited\n`);
581
+ await answer('after');
582
+ await cargo.beforeRead.open();
583
+ expect([...(await first).members]).toEqual(['after']);
584
+
585
+ // The original bytes bring back the content the first call began with.
586
+ // Whatever is kept for them must not be what Cargo said about the edit.
587
+ await writeFile(manifest, original);
588
+ await answer('before');
589
+ expect(await members()).toEqual(['before']);
590
+ });
591
+ }, 20_000);
592
+
593
+ it('a process that has never resolved an unchanged workspace reads the answer an earlier one left, without Cargo', async () => {
594
+ await withCannedWorkspace(async (fixture) => {
595
+ const { cargo, answer, workspace, manifest } = fixture;
596
+ await answer('cold');
597
+ const first = await freshResolver(fixture, 'first').result;
598
+ expect(first).toMatchObject({ members: ['cold'] });
599
+ expect(await spawned(cargo)).toBe(1);
600
+
601
+ // A Cargo asked now would say so.
602
+ await answer('trap');
603
+ expect(await freshResolver(fixture, 'second').result).toEqual(first);
604
+ expect(await spawned(cargo)).toBe(1);
605
+ expect(first).toEqual(summarize(await readCargoResolve(manifest, workspace)));
606
+ const together = await Promise.all(
607
+ Array.from({ length: 4 }, (_, index) => freshResolver(fixture, `together-${index}`).result),
608
+ );
609
+ for (const result of together) expect(result).toEqual(first);
610
+ expect(await spawned(cargo)).toBe(1);
611
+
612
+ await appendFile(manifest, '# edited\n');
613
+ await answer('edited');
614
+ const edited = await freshResolver(fixture, 'edited').result;
615
+ expect(edited).toMatchObject({ members: ['edited'] });
616
+ expect(await freshResolver(fixture, 'edited again').result).toEqual(edited);
617
+ expect(await spawned(cargo)).toBe(2);
618
+ });
619
+ }, 60_000);
620
+
621
+ it('fresh processes that ask at once for a workspace nobody has resolved share one cargo child', async () => {
622
+ await withCannedWorkspace(async (fixture) => {
623
+ const { cargo, answer } = fixture;
624
+ await answer('cold');
625
+ // The child that starts first is held before it reads the workspace until every process has
626
+ // said, on its stdout, that it is about to ask: they ask while that child resolves.
627
+ await cargo.beforeRead.close();
628
+ const resolvers = Array.from({ length: 4 }, (_, index) => freshResolver(fixture, `process-${index}`));
629
+ await Promise.all(resolvers.map((resolver) => resolver.ready()));
630
+ await cargo.waitForRuns((runs) => runs.spawned >= 1, 'a cargo child to start');
631
+ await cargo.beforeRead.open();
632
+
633
+ const results = await Promise.all(resolvers.map((resolver) => resolver.result));
634
+ for (const result of results) expect(result).toEqual(results[0]);
635
+ expect(results[0]).toMatchObject({ members: ['cold'] });
636
+ expect(await spawned(cargo)).toBe(1);
637
+ });
638
+ }, 60_000);
639
+
640
+ it('a worker that exits on SIGTERM while Cargo resolves leaves no cargo child behind', async () => {
641
+ await withCannedWorkspace(async ({ root, workspace, manifest, cargo, answer, environment }) => {
642
+ await answer('before');
643
+ await cargo.beforeAnswer.close();
644
+ const worker = join(root, 'worker.ts');
645
+ await writeFile(
646
+ worker,
647
+ [
648
+ `import { readCargoResolve } from ${JSON.stringify(sourceModule)};`,
649
+ // What an Nx plugin worker does on SIGTERM, SIGINT, SIGQUIT and its host hanging up.
650
+ "process.once('SIGTERM', () => process.exit(0));",
651
+ `readCargoResolve(${JSON.stringify(manifest)}, ${JSON.stringify(workspace)})`,
652
+ ' .then(() => process.exit(2), () => process.exit(3));',
653
+ '',
654
+ ].join('\n'),
655
+ );
656
+ const proc = spawnDrained([process.execPath, worker], workspace, environment);
657
+ const [pid] = (await cargo.waitForRuns((runs) => runs.spawned === 1, 'the cargo child')).pids;
658
+ if (pid === undefined) throw new Error('the cargo child has no pid');
659
+ expect(alive(pid)).toBe(true);
660
+ proc.kill('SIGTERM');
661
+ const ended = await guardEvent(proc.ended, 'the worker to exit on SIGTERM', () => proc.describe());
662
+ expect(ended.exitCode, proc.describe()).toBe(0);
663
+ // The child's end is the end of its connection to the fixture, killed before it answered.
664
+ await cargo.waitForDisconnects([pid]);
665
+ });
666
+ }, 20_000);
667
+
668
+ it("a worker that exits with callers waiting on two resolutions leaves none of Cargo's processes behind, and the next process resolves normally", async () => {
669
+ await withCannedWorkspace(async (fixture) => {
670
+ const { root, workspace, manifest, cargo, answer, environment } = fixture;
671
+ const otherWorkspace = join(root, 'other');
672
+ await put(otherWorkspace, 'Cargo.toml', WORKSPACE_MANIFEST);
673
+ const otherManifest = join(otherWorkspace, 'Cargo.toml');
674
+
675
+ await answer('before');
676
+ await cargo.leaveGrandchildren(true);
677
+ await cargo.beforeAnswer.close();
678
+ const worker = join(root, 'shared-worker.ts');
679
+ await writeFile(
680
+ worker,
681
+ [
682
+ `import { readCargoResolve } from ${JSON.stringify(sourceModule)};`,
683
+ "process.once('SIGTERM', () => process.exit(0));",
684
+ 'const [firstManifest, firstCwd, secondManifest, secondCwd] = process.argv.slice(2);',
685
+ 'const calls = [',
686
+ ' ...Array.from({ length: 8 }, () => readCargoResolve(firstManifest, firstCwd)),',
687
+ ' ...Array.from({ length: 8 }, () => readCargoResolve(secondManifest, secondCwd)),',
688
+ '];',
689
+ 'Promise.all(calls).then(() => process.exit(2), () => process.exit(3));',
690
+ '',
691
+ ].join('\n'),
692
+ );
693
+ const proc = spawnDrained(
694
+ [process.execPath, worker, manifest, workspace, otherManifest, otherWorkspace],
695
+ workspace,
696
+ environment,
697
+ );
698
+ // Sixteen callers, two workspaces: two children, each holding an answer and a process of its own.
699
+ const runs = await cargo.waitForRuns(
700
+ (held) => held.read === 2 && held.grandchildren.length === 2,
701
+ 'both cargo children to hold an answer',
702
+ );
703
+ expect(runs.spawned).toBe(2);
704
+ const running = [...runs.pids, ...runs.grandchildren];
705
+ for (const pid of running) expect(alive(pid)).toBe(true);
706
+
707
+ proc.kill('SIGTERM');
708
+ const ended = await guardEvent(proc.ended, 'the worker to exit on SIGTERM', () => proc.describe());
709
+ expect(ended.exitCode, proc.describe()).toBe(0);
710
+ // Every child and what it left behind is killed: each one's connection ends without a normal end.
711
+ await cargo.waitForDisconnects(running);
712
+
713
+ // Nothing the dead worker held, a lock or a half-written answer, is in the next process's way.
714
+ await cargo.leaveGrandchildren(false);
715
+ await cargo.beforeAnswer.open();
716
+ await answer('after');
717
+ const next = await freshResolver(fixture, 'next').result;
718
+ expect(next).toMatchObject({ members: ['after'] });
719
+ expect(await spawned(cargo)).toBe(3);
720
+ expect(await freshResolver(fixture, 'again').result).toEqual(next);
721
+ expect(await spawned(cargo)).toBe(3);
722
+ });
723
+ }, 60_000);
724
+
725
+ // A standalone `smoo-nx-cargo-hash` has no handler of its own, so a signal would end it on the spot,
726
+ // before any exit hook could take the Cargo it started along. The module forwards the signal to
727
+ // Cargo's process group and then raises it again, so the command still ends by that signal.
728
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
729
+ it(`a standalone smoo-nx-cargo-hash ended by ${signal} takes its cargo child and what the child left behind with it`, async () => {
730
+ await withCannedWorkspace(async ({ workspace, cargo, answer, environment }) => {
731
+ await answer('before');
732
+ await cargo.leaveGrandchildren(true);
733
+ await cargo.beforeAnswer.close();
734
+ const proc = spawnDrained([process.execPath, cliModule, 'Cargo.toml'], workspace, environment);
735
+ const runs = await cargo.waitForRuns(
736
+ (held) => held.read === 1 && held.grandchildren.length === 1,
737
+ 'the cargo child to hold an answer',
738
+ );
739
+ const running = [...runs.pids, ...runs.grandchildren];
740
+ for (const pid of running) expect(alive(pid)).toBe(true);
741
+
742
+ proc.kill(signal);
743
+ const ended = await guardEvent(proc.ended, `smoo-nx-cargo-hash to end by ${signal}`, () => proc.describe());
744
+ expect(ended.signalCode, proc.describe()).toBe(signal);
745
+ await cargo.waitForDisconnects(running);
746
+ });
747
+ }, 30_000);
748
+ }
749
+
750
+ /* ---- The same, with the real Cargo, through the project graph and the hash command ---- */
751
+
752
+ /** `leaf` as the fixture writes it, and the dependency that draws `unrelated` into every closure reaching `leaf`. */
753
+ const LEAF_MANIFEST = '[package]\nname="leaf"\nversion="0.1.0"\nedition="2021"\n';
754
+ const LEAF_LINK = '[dependencies]\nunrelated={path="../unrelated"}\n';
755
+
756
+ /** The fileset the plugin names for the closure members `crates` (a name or a `{a,b}` set) under `crates/`. */
757
+ const crateFiles = (crates: string) =>
758
+ `{workspaceRoot}/crates/${crates}/**/{*.rs,Cargo.toml,.cargo/config,.cargo/config.toml}`;
759
+
760
+ /** Bring Cargo.lock in line with the manifests. */
761
+ function relock(workspace: string): void {
762
+ execFileSync('cargo', ['generate-lockfile', '--offline', '--manifest-path', join(workspace, 'Cargo.toml')], {
763
+ stdio: 'pipe',
764
+ });
765
+ }
766
+
767
+ /**
768
+ * An Nx workspace that is also the Cargo workspace. `app` reaches `leaf` through `bridge`, and
769
+ * `external`, outside the Nx workspace, through `bridge` too. `unrelated` is a member nothing
770
+ * depends on. Returns the workspace.
771
+ */
772
+ async function graphFixture(root: string): Promise<string> {
773
+ const workspace = join(root, 'workspace');
774
+ const files: Record<string, string> = {
775
+ 'workspace/.gitignore': 'node_modules/\ntarget/\ndist/\n.nx/\n',
776
+ 'workspace/package.json':
777
+ '{"name":"cargo-resolve-cache-fixture","private":true,"workspaces":["packages/*","crates/*"]}\n',
778
+ 'workspace/nx.json': JSON.stringify({
779
+ plugins: ['@smoothbricks/nx-plugin'],
780
+ namedInputs: { externalRustCrates: [] },
781
+ }),
782
+ 'workspace/Cargo.toml':
783
+ '[workspace]\nmembers=["packages/app","crates/bridge","crates/leaf","crates/unrelated"]\nresolver="2"\n',
784
+ 'workspace/packages/app/package.json': '{"name":"app","private":true}\n',
785
+ 'workspace/packages/app/Cargo.toml':
786
+ '[package]\nname="app"\nversion="0.1.0"\nedition="2021"\n[dependencies]\nbridge={path="../../crates/bridge"}\n',
787
+ 'workspace/packages/app/src/main.rs': 'fn main() { println!("{}", bridge::answer()); }\n',
788
+ 'workspace/crates/bridge/Cargo.toml':
789
+ '[package]\nname="bridge"\nversion="0.1.0"\nedition="2021"\n[dependencies]\nleaf={path="../leaf"}\nexternal={path="../../../external"}\n',
790
+ 'workspace/crates/bridge/src/lib.rs': 'pub fn answer() -> u8 { leaf::answer() + external::answer() }\n',
791
+ 'workspace/crates/leaf/package.json': '{"name":"leaf","private":true}\n',
792
+ 'workspace/crates/leaf/Cargo.toml': LEAF_MANIFEST,
793
+ 'workspace/crates/leaf/src/lib.rs': 'pub fn answer() -> u8 { 1 }\n',
794
+ 'workspace/crates/unrelated/Cargo.toml': '[package]\nname="unrelated"\nversion="0.1.0"\nedition="2021"\n',
795
+ 'workspace/crates/unrelated/src/lib.rs': 'pub fn unrelated() -> u8 { 3 }\n',
796
+ 'external/Cargo.toml': '[package]\nname="external"\nversion="0.1.0"\nedition="2021"\n[workspace]\n',
797
+ 'external/src/lib.rs': 'pub fn answer() -> u8 { 10 }\n',
798
+ };
799
+ for (const [path, text] of Object.entries(files)) await put(root, path, text);
800
+ execFileSync('git', ['init', '--quiet', workspace], { stdio: 'pipe' });
801
+ await symlink(join(repositoryRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
802
+ relock(workspace);
803
+ return workspace;
804
+ }
805
+
806
+ interface GraphWorkspace {
807
+ readonly root: string;
808
+ readonly workspace: string;
809
+ readonly cargo: CountedCargo;
810
+ /** One project-graph computation over the fixture: the plugin's `createNodes`, as Nx runs it for each recomputation. */
811
+ graph(): Promise<CreateNodesResultV2>;
812
+ }
813
+
814
+ /** `body` over a temporary Nx and Cargo workspace, with the real Cargo counted. */
815
+ async function withGraphWorkspace(body: (fixture: GraphWorkspace) => Promise<void>): Promise<void> {
816
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-resolve-graph-')));
817
+ try {
818
+ const workspace = await graphFixture(root);
819
+ const cargo = await countedCargo(root);
820
+ const [, infer] = createNodesV2;
821
+ try {
822
+ await withEnvironment(cargo.environment, () => {
823
+ resetWorkspaceContext();
824
+ return body({
825
+ root,
826
+ workspace,
827
+ cargo,
828
+ graph: async () =>
829
+ infer(['package.json', 'packages/app/package.json', 'crates/leaf/package.json'], undefined, {
830
+ workspaceRoot: workspace,
831
+ nxJsonConfiguration: { namedInputs: { externalRustCrates: [] } },
832
+ }),
833
+ });
834
+ });
835
+ } finally {
836
+ await cargo.release();
837
+ }
838
+ } finally {
839
+ await rm(root, { recursive: true, force: true });
840
+ }
841
+ }
842
+
843
+ /** The computation's nodes in file order: the plugin pushes them as their projects finish. */
844
+ function byFile(graph: CreateNodesResultV2): CreateNodesResultV2 {
845
+ return [...graph].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
846
+ }
847
+
848
+ /** The `cargoClosure` definition the computation gave the project at `projectRoot`. */
849
+ function closureOf(graph: CreateNodesResultV2, projectRoot: string) {
850
+ return (
851
+ graph.find(([file]) => dirname(file) === projectRoot)?.[1].projects?.[projectRoot]?.namedInputs?.[
852
+ CARGO_CLOSURE_INPUT
853
+ ] ?? []
854
+ );
855
+ }
856
+
857
+ it('a project graph over an unchanged Cargo workspace runs Cargo once, however often it is recomputed', async () => {
858
+ await withGraphWorkspace(async ({ root, workspace, cargo, graph }) => {
859
+ const baseline = byFile(await graph());
860
+ expect(closureOf(baseline, 'packages/app')).toContain(crateFiles('{bridge,leaf}'));
861
+ expect(closureOf(baseline, 'packages/app')).not.toContain(crateFiles('{bridge,leaf,unrelated}'));
862
+ expect(await spawned(cargo)).toBe(1);
863
+
864
+ // The daemon recomputes the graph for every batch of file events.
865
+ for (let round = 0; round < 3; round += 1) expect(byFile(await graph())).toEqual(baseline);
866
+ expect(await spawned(cargo)).toBe(1);
867
+
868
+ // A source, a new source file, a file that is not Rust, a manifest or lockfile rewritten byte for byte.
869
+ await put(workspace, 'crates/leaf/src/lib.rs', 'pub fn answer() -> u8 { 2 }\n');
870
+ await put(workspace, 'crates/leaf/src/extra.rs', 'pub const EXTRA: u8 = 1;\n');
871
+ await put(workspace, 'crates/leaf/README.md', '# leaf\n');
872
+ await touch(workspace, 'crates/leaf/Cargo.toml');
873
+ await touch(workspace, 'Cargo.lock');
874
+ expect(byFile(await graph())).toEqual(baseline);
875
+ expect(await spawned(cargo)).toBe(1);
876
+
877
+ // What Cargo reads brings it back once for the bytes that changed, not for every recomputation after.
878
+ const inputs: [string, () => Promise<void>][] = [
879
+ ['a member manifest', () => appendFile(join(workspace, 'crates/leaf/Cargo.toml'), '# note\n')],
880
+ ['Cargo.lock', () => appendFile(join(workspace, 'Cargo.lock'), '# note\n')],
881
+ ['Cargo configuration', () => put(workspace, '.cargo/config.toml', '[env]\nFIXTURE = "1"\n')],
882
+ ['a manifest outside the Nx workspace', () => appendFile(join(root, 'external/Cargo.toml'), '# note\n')],
883
+ ['the toolchain pin', () => put(workspace, 'devenv.lock', '{"nodes":{}}\n')],
884
+ ];
885
+ let expected = 1;
886
+ for (const [what, change] of inputs) {
887
+ await change();
888
+ const changed = byFile(await graph());
889
+ // A manifest comment also changes the inferred versionless-manifest task
890
+ // input. Its dependency closure stays the same, and the new graph is stable.
891
+ expect(closureOf(changed, 'packages/app'), what).toEqual(closureOf(baseline, 'packages/app'));
892
+ expect(byFile(await graph()), what).toEqual(changed);
893
+ expected += 1;
894
+ expect(await spawned(cargo), what).toBe(expected);
895
+ }
896
+
897
+ // And what changes the resolution is seen: the new graph is not the cached one.
898
+ await put(workspace, 'crates/leaf/Cargo.toml', LEAF_MANIFEST + LEAF_LINK);
899
+ relock(workspace);
900
+ const edited = byFile(await graph());
901
+ expect(closureOf(edited, 'packages/app')).toContain(crateFiles('{bridge,leaf,unrelated}'));
902
+ expect(byFile(await graph())).toEqual(edited);
903
+ expect(await spawned(cargo)).toBe(expected + 1);
904
+ });
905
+ }, 120_000);
906
+
907
+ it('a Cargo workspace Cargo refuses fails the project graph with a CargoMetadataError, and no runtime hash stands in', async () => {
908
+ await withGraphWorkspace(async ({ workspace, cargo, graph }) => {
909
+ expect(closureOf(byFile(await graph()), 'packages/app')).toContain(crateFiles('{bridge,leaf}'));
910
+
911
+ // Cargo refuses a Cargo.lock the manifests have outgrown (`--locked`).
912
+ await put(workspace, 'crates/leaf/Cargo.toml', LEAF_MANIFEST + LEAF_LINK);
913
+ for (let attempt = 0; attempt < 2; attempt += 1) {
914
+ const refusal = expectGraphRefusal(await rejectionOf(graph()), join(workspace, 'Cargo.toml'));
915
+ for (const [, error] of refusal.errors) {
916
+ expect(error.message).toContain('lock file');
917
+ expect(error.message).toContain('--locked');
918
+ }
919
+ }
920
+ // A refusal is no answer: the second computation asked Cargo again.
921
+ expect(await spawned(cargo)).toBe(3);
922
+
923
+ relock(workspace);
924
+ const repaired = byFile(await graph());
925
+ expect(closureOf(repaired, 'packages/app')).toContain(crateFiles('{bridge,leaf,unrelated}'));
926
+ expect(JSON.stringify(repaired)).not.toContain('--include-workspace');
927
+ expect(byFile(await graph())).toEqual(repaired);
928
+ expect(await spawned(cargo)).toBe(4);
929
+ });
930
+ }, 120_000);
931
+
932
+ it('fresh smoo-nx-cargo-hash processes over an unchanged Cargo workspace run Cargo once between them', async () => {
933
+ await withGraphWorkspace(async ({ root, workspace, cargo }) => {
934
+ // As nx.json's runtime input runs it: a process per hash, many at once at the start of a run.
935
+ const hash = async (...flags: string[]): Promise<string> => {
936
+ const child = Bun.spawn([process.execPath, cliModule, ...flags, '--closure', 'packages/app', 'Cargo.toml'], {
937
+ cwd: workspace,
938
+ env: { ...process.env, ...cargo.environment },
939
+ stdout: 'pipe',
940
+ stderr: 'pipe',
941
+ });
942
+ const [stdout, stderr, exitCode] = await Promise.all([
943
+ new Response(child.stdout).text(),
944
+ new Response(child.stderr).text(),
945
+ child.exited,
946
+ ]);
947
+ expect(exitCode, stderr).toBe(0);
948
+ expect(stderr).toBe('');
949
+ return stdout;
950
+ };
951
+
952
+ const cold = await Promise.all(Array.from({ length: 4 }, () => hash()));
953
+ const [initial] = cold;
954
+ if (initial === undefined) throw new Error('no hash command ran');
955
+ for (const output of cold) expect(output).toBe(initial);
956
+ expect(await spawned(cargo)).toBe(1);
957
+ for (let round = 0; round < 3; round += 1) expect(await hash()).toBe(initial);
958
+ expect(await spawned(cargo)).toBe(1);
959
+
960
+ // The digest still follows what it hashes: a source outside the Nx workspace, not one inside it.
961
+ await put(root, 'external/src/lib.rs', 'pub fn answer() -> u8 { 20 }\n');
962
+ const sourceEdited = await hash();
963
+ expect(sourceEdited).not.toBe(initial);
964
+ await put(workspace, 'crates/leaf/src/lib.rs', 'pub fn answer() -> u8 { 2 }\n');
965
+ expect(await hash()).toBe(sourceEdited);
966
+ expect(await spawned(cargo)).toBe(1);
967
+
968
+ // A manifest outside the Nx workspace is one of Cargo's inputs: one more child, for it alone.
969
+ await appendFile(join(root, 'external/Cargo.toml'), '# note\n');
970
+ const manifestEdited = await hash();
971
+ expect(manifestEdited).not.toBe(sourceEdited);
972
+ expect(await hash()).toBe(manifestEdited);
973
+ expect(await spawned(cargo)).toBe(2);
974
+ });
975
+ }, 120_000);