@smoothbricks/nx-plugin 0.4.26 → 0.4.27

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 (343) hide show
  1. package/README.md +994 -117
  2. package/dist/bin/smoo-nx-bound-failures.d.ts +3 -0
  3. package/dist/bin/smoo-nx-bound-failures.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-bound-failures.js +31 -0
  5. package/dist/bin/smoo-nx-cargo-hash.js +28 -3
  6. package/dist/bin/smoo-nx-exec.js +15 -73
  7. package/dist/bin/smoo-nx-failures.d.ts +3 -0
  8. package/dist/bin/smoo-nx-failures.d.ts.map +1 -0
  9. package/dist/bin/smoo-nx-failures.js +3 -0
  10. package/dist/bin/smoo-nx-nextest-extract.js +3 -2
  11. package/dist/bin/smoo-nx-test-walks.d.ts +3 -0
  12. package/dist/bin/smoo-nx-test-walks.d.ts.map +1 -0
  13. package/dist/bin/smoo-nx-test-walks.js +34 -0
  14. package/dist/bounded-test-policy.d.ts +7 -1
  15. package/dist/bounded-test-policy.d.ts.map +1 -1
  16. package/dist/bounded-test-policy.js +101 -40
  17. package/dist/build-state-output-policy.d.ts +25 -0
  18. package/dist/build-state-output-policy.d.ts.map +1 -0
  19. package/dist/build-state-output-policy.js +64 -0
  20. package/dist/cargo-closure-input.d.ts +3 -2
  21. package/dist/cargo-closure-input.d.ts.map +1 -1
  22. package/dist/cargo-closure-input.js +16 -15
  23. package/dist/cargo-dev-profile.d.ts +37 -0
  24. package/dist/cargo-dev-profile.d.ts.map +1 -0
  25. package/dist/cargo-dev-profile.js +108 -0
  26. package/dist/cargo-source-hash.d.ts +43 -6
  27. package/dist/cargo-source-hash.d.ts.map +1 -1
  28. package/dist/cargo-source-hash.js +309 -73
  29. package/dist/cargo-toolchain-policy.d.ts +4 -0
  30. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  31. package/dist/cargo-toolchain-policy.js +5 -0
  32. package/dist/cargo-workspace.d.ts +101 -5
  33. package/dist/cargo-workspace.d.ts.map +1 -1
  34. package/dist/cargo-workspace.js +291 -10
  35. package/dist/cross-check-policy.d.ts +21 -3
  36. package/dist/cross-check-policy.d.ts.map +1 -1
  37. package/dist/cross-check-policy.js +24 -6
  38. package/dist/disk-command-policy.d.ts +7 -0
  39. package/dist/disk-command-policy.d.ts.map +1 -0
  40. package/dist/disk-command-policy.js +98 -0
  41. package/dist/ensure-built-receipt.d.ts +25 -0
  42. package/dist/ensure-built-receipt.d.ts.map +1 -0
  43. package/dist/ensure-built-receipt.js +261 -0
  44. package/dist/ensure-built-witness.d.ts +57 -0
  45. package/dist/ensure-built-witness.d.ts.map +1 -0
  46. package/dist/ensure-built-witness.js +412 -0
  47. package/dist/ensure-built.d.ts +207 -12
  48. package/dist/ensure-built.d.ts.map +1 -1
  49. package/dist/ensure-built.js +576 -202
  50. package/dist/eslint-file-set.d.ts +7 -0
  51. package/dist/eslint-file-set.d.ts.map +1 -0
  52. package/dist/eslint-file-set.js +12 -0
  53. package/dist/executors/bounded-exec/cpu-pool.d.ts +63 -0
  54. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -0
  55. package/dist/executors/bounded-exec/cpu-pool.js +379 -0
  56. package/dist/executors/bounded-exec/cpu-tokens.d.ts +82 -0
  57. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +1 -0
  58. package/dist/executors/bounded-exec/cpu-tokens.js +114 -0
  59. package/dist/executors/bounded-exec/disk-lease.d.ts +61 -0
  60. package/dist/executors/bounded-exec/disk-lease.d.ts.map +1 -0
  61. package/dist/executors/bounded-exec/disk-lease.js +91 -0
  62. package/dist/executors/bounded-exec/executor.d.ts +45 -2
  63. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  64. package/dist/executors/bounded-exec/executor.js +447 -52
  65. package/dist/executors/bounded-exec/gateway-lease.d.ts +52 -0
  66. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -0
  67. package/dist/executors/bounded-exec/gateway-lease.js +143 -0
  68. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +35 -0
  69. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -0
  70. package/dist/executors/bounded-exec/hang-diagnostics.js +231 -0
  71. package/dist/executors/bounded-exec/progress.d.ts +35 -0
  72. package/dist/executors/bounded-exec/progress.d.ts.map +1 -0
  73. package/dist/executors/bounded-exec/progress.js +79 -0
  74. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +3 -0
  75. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -0
  76. package/dist/executors/bounded-exec/ram-temp-fixtures.js +12 -0
  77. package/dist/executors/bounded-exec/ram-temp-held.d.ts +91 -0
  78. package/dist/executors/bounded-exec/ram-temp-held.d.ts.map +1 -0
  79. package/dist/executors/bounded-exec/ram-temp-held.js +152 -0
  80. package/dist/executors/bounded-exec/ram-temp.d.ts +223 -0
  81. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -0
  82. package/dist/executors/bounded-exec/ram-temp.js +1528 -0
  83. package/dist/executors/bounded-exec/schema.d.ts +29 -11
  84. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  85. package/dist/executors/bounded-exec/verdict.d.ts +162 -0
  86. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/verdict.js +318 -0
  88. package/dist/executors/shard-timings/executor.d.ts +14 -0
  89. package/dist/executors/shard-timings/executor.d.ts.map +1 -0
  90. package/dist/executors/shard-timings/executor.js +25 -0
  91. package/dist/executors/shard-timings/schema.d.ts +4 -0
  92. package/dist/executors/shard-timings/schema.d.ts.map +1 -0
  93. package/dist/executors/shard-timings/schema.js +1 -0
  94. package/dist/failure-summary.d.ts +5 -0
  95. package/dist/failure-summary.d.ts.map +1 -0
  96. package/dist/failure-summary.js +118 -0
  97. package/dist/generators/create-package/generator.d.ts.map +1 -1
  98. package/dist/generators/create-package/generator.js +6 -2
  99. package/dist/index.d.ts +14 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +370 -138
  102. package/dist/managed-files/ci-workflow.d.ts +13 -0
  103. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  104. package/dist/managed-files/ci-workflow.js +44 -13
  105. package/dist/managed-files/files.d.ts +7 -1
  106. package/dist/managed-files/files.d.ts.map +1 -1
  107. package/dist/managed-files/files.js +62 -8
  108. package/dist/managed-files/json-edit.d.ts +21 -0
  109. package/dist/managed-files/json-edit.d.ts.map +1 -0
  110. package/dist/managed-files/json-edit.js +295 -0
  111. package/dist/managed-files/managed-format.d.ts +33 -1
  112. package/dist/managed-files/managed-format.d.ts.map +1 -1
  113. package/dist/managed-files/managed-format.js +82 -2
  114. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +7 -0
  115. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -1
  116. package/dist/managed-files/pr-preview-cleanup-workflow.js +68 -4
  117. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  118. package/dist/managed-files/publish-workflow.js +231 -48
  119. package/dist/managed-files/tree.d.ts +5 -0
  120. package/dist/managed-files/tree.d.ts.map +1 -1
  121. package/dist/managed-files/tree.js +5 -3
  122. package/dist/manifest-hash.d.ts.map +1 -1
  123. package/dist/manifest-hash.js +2 -5
  124. package/dist/nextest-code-bound.d.ts +62 -0
  125. package/dist/nextest-code-bound.d.ts.map +1 -0
  126. package/dist/nextest-code-bound.js +154 -0
  127. package/dist/nextest-extraction.d.ts +24 -8
  128. package/dist/nextest-extraction.d.ts.map +1 -1
  129. package/dist/nextest-extraction.js +42 -7
  130. package/dist/package-target-policy.d.ts.map +1 -1
  131. package/dist/package-target-policy.js +3 -5
  132. package/dist/release-config-policy.d.ts.map +1 -1
  133. package/dist/release-config-policy.js +3 -5
  134. package/dist/runtime-input.d.ts +14 -0
  135. package/dist/runtime-input.d.ts.map +1 -0
  136. package/dist/runtime-input.js +15 -0
  137. package/dist/rust-tokens.d.ts +11 -0
  138. package/dist/rust-tokens.d.ts.map +1 -0
  139. package/dist/rust-tokens.js +81 -0
  140. package/dist/task-results.d.ts +6 -0
  141. package/dist/task-results.d.ts.map +1 -0
  142. package/dist/task-results.js +61 -0
  143. package/dist/test-program.d.ts +54 -0
  144. package/dist/test-program.d.ts.map +1 -0
  145. package/dist/test-program.js +292 -0
  146. package/dist/test-timings.d.ts +71 -0
  147. package/dist/test-timings.d.ts.map +1 -0
  148. package/dist/test-timings.js +393 -0
  149. package/dist/test-walk-policy.d.ts +103 -0
  150. package/dist/test-walk-policy.d.ts.map +1 -0
  151. package/dist/test-walk-policy.js +657 -0
  152. package/dist/testing.d.ts +177 -0
  153. package/dist/testing.d.ts.map +1 -0
  154. package/dist/testing.js +824 -0
  155. package/dist/type-guards.d.ts +3 -0
  156. package/dist/type-guards.d.ts.map +1 -0
  157. package/dist/type-guards.js +4 -0
  158. package/dist/typecheck-test-policy.d.ts +8 -5
  159. package/dist/typecheck-test-policy.d.ts.map +1 -1
  160. package/dist/typecheck-test-policy.js +113 -100
  161. package/dist/workspace-config-policy.d.ts +8 -0
  162. package/dist/workspace-config-policy.d.ts.map +1 -1
  163. package/dist/workspace-config-policy.js +175 -63
  164. package/dist/workspace-index.d.ts +12 -0
  165. package/dist/workspace-index.d.ts.map +1 -0
  166. package/dist/workspace-index.js +17 -0
  167. package/dist/workspace-manifest.d.ts +37 -0
  168. package/dist/workspace-manifest.d.ts.map +1 -1
  169. package/executors.json +5 -0
  170. package/loader.js +13 -11
  171. package/managed/raw/envrc +33 -67
  172. package/managed/raw/git-format-staged.yml +30 -35
  173. package/managed/raw/patches/nx@23.2.1.patch +3484 -0
  174. package/managed/raw/tooling/direnv/apple-developer.sh +83 -0
  175. package/managed/raw/tooling/direnv/developer-links.ts +569 -11
  176. package/managed/raw/tooling/direnv/devenv.smoo.nix +314 -93
  177. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +20 -11
  178. package/managed/raw/tooling/direnv/linked-snapshots.ts +845 -0
  179. package/managed/raw/tooling/direnv/nx-socket-dir.sh +82 -0
  180. package/managed/raw/tooling/direnv/repo-path +14 -2
  181. package/managed/raw/tooling/direnv/setup-environment.ts +962 -148
  182. package/managed/raw/tooling/direnv/toolchain-stamp.ts +45 -3
  183. package/managed/raw/tooling/direnv/ttsc-env.sh +39 -0
  184. package/managed/raw/tooling/git-hooks/commit-msg.sh +5 -6
  185. package/managed/raw/tooling/git-hooks/pre-commit.sh +7 -6
  186. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -15
  187. package/managed/templates/github/actions/cache-nix-devenv/action.yml +6 -6
  188. package/managed/templates/github/actions/cache-node-modules/action.yml +6 -4
  189. package/managed/templates/github/actions/cache-nx/action.yml +1 -1
  190. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +1 -1
  191. package/managed/templates/github/actions/forgejo-artifact.cjs +99 -0
  192. package/managed/templates/github/actions/forgejo-download-artifact/action.yml +49 -0
  193. package/managed/templates/github/actions/forgejo-download-artifact/index.cjs +7 -0
  194. package/managed/templates/github/actions/forgejo-upload-artifact/action.yml +65 -0
  195. package/managed/templates/github/actions/forgejo-upload-artifact/index.cjs +7 -0
  196. package/managed/templates/github/actions/setup-devenv/action.yml +21 -3
  197. package/managed/templates/github/workflows/managed-files.yml +1 -2
  198. package/nextest.toml +8 -41
  199. package/package.json +74 -12
  200. package/runtime-input.sh +81 -0
  201. package/src/__tests__/counted-cargo.ts +33 -14
  202. package/src/__tests__/fixture-nx-env.ts +111 -46
  203. package/src/__tests__/progress-clock.ts +43 -0
  204. package/src/__tests__/runtime-input.ts +23 -0
  205. package/src/bin/smoo-nx-bound-failures.test.ts +127 -0
  206. package/src/bin/smoo-nx-bound-failures.ts +33 -0
  207. package/src/bin/smoo-nx-cargo-hash.ts +28 -3
  208. package/src/bin/smoo-nx-exec.ts +16 -74
  209. package/src/bin/smoo-nx-failures.ts +4 -0
  210. package/src/bin/smoo-nx-nextest-extract.ts +3 -2
  211. package/src/bin/smoo-nx-test-walks.ts +42 -0
  212. package/src/bounded-test-policy.test.ts +268 -21
  213. package/src/bounded-test-policy.ts +114 -42
  214. package/src/build-state-output-policy.test.ts +115 -0
  215. package/src/build-state-output-policy.ts +90 -0
  216. package/src/bun-bootstrap.test.ts +57 -3
  217. package/src/bun-file-packages.test.ts +47 -0
  218. package/src/cargo-closure-input.test.ts +138 -66
  219. package/src/cargo-closure-input.ts +17 -15
  220. package/src/cargo-dev-profile.ts +137 -0
  221. package/src/cargo-resolve-cache.test.ts +70 -1
  222. package/src/cargo-source-hash.test.ts +193 -97
  223. package/src/cargo-source-hash.ts +345 -68
  224. package/src/cargo-toolchain-policy.ts +6 -0
  225. package/src/cargo-workspace.test.ts +320 -0
  226. package/src/cargo-workspace.ts +336 -10
  227. package/src/cross-check-policy.test.ts +59 -1
  228. package/src/cross-check-policy.ts +25 -6
  229. package/src/disk-command-policy.test.ts +61 -0
  230. package/src/disk-command-policy.ts +107 -0
  231. package/src/ensure-built-receipt.test.ts +184 -0
  232. package/src/ensure-built-receipt.ts +263 -0
  233. package/src/ensure-built-witness.test.ts +344 -0
  234. package/src/ensure-built-witness.ts +252 -0
  235. package/src/ensure-built.test.ts +1036 -578
  236. package/src/ensure-built.ts +820 -224
  237. package/src/eslint-file-set.ts +9 -0
  238. package/src/executors/bounded-exec/cpu-pool.test.ts +454 -0
  239. package/src/executors/bounded-exec/cpu-pool.ts +417 -0
  240. package/src/executors/bounded-exec/cpu-tokens.test.ts +269 -0
  241. package/src/executors/bounded-exec/cpu-tokens.ts +177 -0
  242. package/src/executors/bounded-exec/disk-lease.test.ts +185 -0
  243. package/src/executors/bounded-exec/disk-lease.ts +139 -0
  244. package/src/executors/bounded-exec/executor-host.test.ts +778 -0
  245. package/src/executors/bounded-exec/executor.test.ts +1116 -63
  246. package/src/executors/bounded-exec/executor.ts +565 -67
  247. package/src/executors/bounded-exec/gateway-lease.ts +176 -0
  248. package/src/executors/bounded-exec/hang-diagnostics.test.ts +285 -0
  249. package/src/executors/bounded-exec/hang-diagnostics.ts +283 -0
  250. package/src/executors/bounded-exec/progress.test.ts +79 -0
  251. package/src/executors/bounded-exec/progress.ts +118 -0
  252. package/src/executors/bounded-exec/ram-temp-fixtures.ts +12 -0
  253. package/src/executors/bounded-exec/ram-temp-held.test.ts +264 -0
  254. package/src/executors/bounded-exec/ram-temp-held.ts +242 -0
  255. package/src/executors/bounded-exec/ram-temp-host.test.ts +605 -0
  256. package/src/executors/bounded-exec/ram-temp.test.ts +674 -0
  257. package/src/executors/bounded-exec/ram-temp.ts +1918 -0
  258. package/src/executors/bounded-exec/schema.json +11 -5
  259. package/src/executors/bounded-exec/schema.ts +27 -11
  260. package/src/executors/bounded-exec/verdict.test.ts +440 -0
  261. package/src/executors/bounded-exec/verdict.ts +433 -0
  262. package/src/executors/shard-timings/executor.ts +36 -0
  263. package/src/executors/shard-timings/schema.json +21 -0
  264. package/src/executors/shard-timings/schema.ts +4 -0
  265. package/src/failure-summary.ts +119 -0
  266. package/src/generators/bounded-test-targets/generator.test.ts +4 -4
  267. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  268. package/src/generators/create-package/generator.test.ts +6 -0
  269. package/src/generators/create-package/generator.ts +6 -2
  270. package/src/host-controller-wiring.test.ts +31 -0
  271. package/src/index.test.ts +909 -295
  272. package/src/index.ts +441 -143
  273. package/src/linked-snapshots.nx.test.ts +172 -0
  274. package/src/managed-files/ci-workflow.ts +54 -13
  275. package/src/managed-files/files.ts +65 -9
  276. package/src/managed-files/forgejo-artifact.test.ts +395 -0
  277. package/src/managed-files/generator.test.ts +60 -1
  278. package/src/managed-files/json-edit.test.ts +216 -0
  279. package/src/managed-files/json-edit.ts +290 -0
  280. package/src/managed-files/managed-format-json.test.ts +308 -0
  281. package/src/managed-files/managed-format.ts +90 -2
  282. package/src/managed-files/pr-preview-cleanup-workflow.ts +69 -3
  283. package/src/managed-files/publish-workflow.ts +285 -67
  284. package/src/managed-files/repo-path.test.ts +129 -0
  285. package/src/managed-files/trace-db-artifact.test.ts +7 -0
  286. package/src/managed-files/tree.ts +11 -3
  287. package/src/manifest-hash.ts +2 -6
  288. package/src/nextest-code-bound.test.ts +155 -0
  289. package/src/nextest-code-bound.ts +195 -0
  290. package/src/nextest-extraction.test.ts +37 -5
  291. package/src/nextest-extraction.ts +51 -9
  292. package/src/nextest-partitions.test.ts +427 -82
  293. package/src/nx-cache-bound.test.ts +5 -10
  294. package/src/nx-cache-restore-mtime.test.ts +170 -0
  295. package/src/nx-daemon-claim.test.ts +277 -0
  296. package/src/nx-daemon-idle-cpu.test.ts +81 -0
  297. package/src/nx-daemon-idle-policy.test.ts +51 -0
  298. package/src/nx-daemon-ignore-files.test.ts +210 -0
  299. package/src/nx-daemon-root-normalization.test.ts +105 -0
  300. package/src/nx-daemon-validity.test.ts +925 -0
  301. package/src/nx-dot-input-policy.test.ts +353 -0
  302. package/src/nx-failure-life-cycles.test.ts +207 -0
  303. package/src/nx-files-archive-racy.test.ts +97 -0
  304. package/src/nx-foreign-workspace-env.test.ts +329 -0
  305. package/src/nx-incomplete-run-summary.test.ts +70 -0
  306. package/src/nx-plugin-load-errors.test.ts +120 -0
  307. package/src/nx-project-resolution-cache.test.ts +176 -0
  308. package/src/nx-raw-inputs.test.ts +166 -0
  309. package/src/nx-resident-graph-workers.test.ts +7 -16
  310. package/src/nx-run-information.test.ts +118 -0
  311. package/src/nx-skipped-task-exit.test.ts +180 -0
  312. package/src/nx-state-location.test.ts +63 -0
  313. package/src/nx-store-resolution.test.ts +26 -25
  314. package/src/nx-task-graph-cycles.test.ts +148 -0
  315. package/src/nx-task-output-lease.test.ts +414 -0
  316. package/src/nx-use-local.test.ts +103 -0
  317. package/src/package-target-policy.ts +3 -6
  318. package/src/release-config-policy.ts +3 -6
  319. package/src/runtime-input.test.ts +215 -0
  320. package/src/runtime-input.ts +17 -0
  321. package/src/rust-tokens.ts +78 -0
  322. package/src/serial-group-wiring.test.ts +326 -0
  323. package/src/task-history-namespace.test.ts +87 -89
  324. package/src/task-results.test.ts +226 -0
  325. package/src/task-results.ts +75 -0
  326. package/src/test-program.test.ts +303 -0
  327. package/src/test-program.ts +341 -0
  328. package/src/test-timings.test.ts +240 -0
  329. package/src/test-timings.ts +311 -0
  330. package/src/test-walk-policy.test.ts +585 -0
  331. package/src/test-walk-policy.ts +731 -0
  332. package/src/testing.test.ts +509 -0
  333. package/src/testing.ts +922 -0
  334. package/src/type-guards.ts +4 -0
  335. package/src/typecheck-test-policy.test.ts +496 -11
  336. package/src/typecheck-test-policy.ts +137 -103
  337. package/src/workspace-config-policy.test.ts +212 -13
  338. package/src/workspace-config-policy.ts +101 -73
  339. package/src/workspace-index.ts +18 -0
  340. package/src/workspace-manifest.ts +41 -0
  341. package/test-timings.json +85 -30
  342. package/managed/raw/tooling/direnv/inherited-devenv.ts +0 -665
  343. package/managed/raw/tooling/direnv/shared-caches.sh +0 -53
@@ -0,0 +1,824 @@
1
+ /**
2
+ * Ownership and retirement of the temp workspaces a test suite runs real Nx
3
+ * in, shared by every package whose tests do.
4
+ *
5
+ * A fixture that runs Nx with its daemon on leaves a daemon whose working
6
+ * directory is the fixture: it idles, watches files and burns CPU until
7
+ * someone stops it. A test that throws stops it in its `finally`; a test
8
+ * process that is killed runs no `finally`. So every fixture root lives in a
9
+ * run directory named for the test process that owns it,
10
+ * `<parent>/smoothbricks-fixtures/<suite>/run-<pid>`, where the caller names
11
+ * the parent: the temp directory, or the directory of a volume the fixture has
12
+ * to lie on. A process that gets SIGTERM, SIGINT or SIGHUP (a bounded test
13
+ * leg's timeout sends SIGTERM, and SIGKILL 10 s later) first stops whatever
14
+ * still works in every run it holds, then dies of that signal. One killed
15
+ * outright cannot, so the first fixture a process creates for a suite under a
16
+ * parent reclaims every run of that suite there whose owner is gone: each
17
+ * process working in it is stopped, then the run is deleted. A run whose owner
18
+ * still exists is never touched by another process, so nothing outside a dead
19
+ * or dying run of the same suite is ever signalled.
20
+ *
21
+ * The module also says where a fixture's sockets and loopback listeners may
22
+ * live, because a Cowshed sandbox admits only its own: a Unix socket under its
23
+ * own tree or short runtime link, a TCP connect to a port of its own block. A
24
+ * literal `/tmp/x.sock` or a port-0 listener still binds there, and then no
25
+ * process of the workspace can reach it (specs/cowshed/04_sandbox.md).
26
+ *
27
+ * Node APIs and the library's public workspace-root finder only: this module
28
+ * is built with the library and imported by Bun tests in other packages.
29
+ */
30
+ import { execFile } from 'node:child_process';
31
+ import { createHash } from 'node:crypto';
32
+ import { lstatSync, readlinkSync, realpathSync, statSync } from 'node:fs';
33
+ import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, realpath, rm, symlink, writeFile } from 'node:fs/promises';
34
+ import { tmpdir, userInfo } from 'node:os';
35
+ import { dirname, isAbsolute, join, sep } from 'node:path';
36
+ import { setTimeout as sleep } from 'node:timers/promises';
37
+ import { promisify } from 'node:util';
38
+ import { findNxWorkspaceRoot } from './ensure-built.js';
39
+ const run = promisify(execFile);
40
+ const EXIT_TIMEOUT_MS = 10_000;
41
+ /** Under half of the SIGTERM-to-SIGKILL grace a bounded test leg gives, per round of signals. */
42
+ const SIGNALLED_GRACE_MS = 3_000;
43
+ const FIXTURE_HOME = 'smoothbricks-fixtures';
44
+ const RUN_NAME = /^run-(\d+)$/;
45
+ const SWEEP_LOCK = 'sweep.lock';
46
+ /** Every process on the host, as `ps` lists it on macOS and Linux alike. */
47
+ export async function processTable() {
48
+ const { stdout } = await run('ps', ['-A', '-o', 'pid=', '-o', 'ppid=', '-o', 'stat=', '-o', 'command='], {
49
+ maxBuffer: 64 * 1024 * 1024,
50
+ });
51
+ return stdout
52
+ .split('\n')
53
+ .filter((line) => line.trim() !== '')
54
+ .map((line) => {
55
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s?(.*)$/.exec(line);
56
+ if (match === null) {
57
+ throw new Error(`Unable to parse ps line: ${line}`);
58
+ }
59
+ const [, pid, ppid, stat, command] = match;
60
+ return { pid: Number(pid), ppid: Number(ppid), stat: stat ?? '', command: command ?? '' };
61
+ });
62
+ }
63
+ /**
64
+ * The listed processes among `pids`, and every process descending from one, each once: a pid that
65
+ * descends from another in `pids` is not listed twice.
66
+ */
67
+ export function withDescendants(table, pids) {
68
+ const found = new Map();
69
+ const pending = table.filter((entry) => pids.includes(entry.pid));
70
+ for (let entry = pending.pop(); entry !== undefined; entry = pending.pop()) {
71
+ if (found.has(entry.pid)) {
72
+ continue;
73
+ }
74
+ found.set(entry.pid, entry);
75
+ const parent = entry.pid;
76
+ pending.push(...table.filter((child) => child.ppid === parent));
77
+ }
78
+ return [...found.values()];
79
+ }
80
+ function errorCode(error) {
81
+ return error instanceof Error && 'code' in error ? error.code : undefined;
82
+ }
83
+ /** Whether `pid` names a process, this user's or not. A zombie still answers. */
84
+ export function isRunning(pid) {
85
+ try {
86
+ process.kill(pid, 0);
87
+ return true;
88
+ }
89
+ catch (error) {
90
+ switch (errorCode(error)) {
91
+ case 'ESRCH':
92
+ return false;
93
+ case 'EPERM':
94
+ return true;
95
+ default:
96
+ throw error;
97
+ }
98
+ }
99
+ }
100
+ /** Signal `pid`; one that has already exited is not an error. */
101
+ export function terminate(pid, signal = 'SIGTERM') {
102
+ try {
103
+ process.kill(pid, signal);
104
+ }
105
+ catch (error) {
106
+ if (errorCode(error) !== 'ESRCH') {
107
+ throw error;
108
+ }
109
+ }
110
+ }
111
+ /**
112
+ * Wait until every one of `processes` has exited. One still running
113
+ * `timeoutMs` later is an error naming it and `owner`.
114
+ */
115
+ export async function awaitExit(processes, owner, timeoutMs = EXIT_TIMEOUT_MS) {
116
+ const deadline = Date.now() + timeoutMs;
117
+ for (let waiting = processes.filter((entry) => isRunning(entry.pid)); waiting.length > 0;) {
118
+ if (Date.now() > deadline) {
119
+ // A signal probe also answers for a zombie, which has already exited.
120
+ const live = new Set((await processTable()).filter((entry) => !entry.stat.startsWith('Z')).map((entry) => entry.pid));
121
+ const survivors = waiting.filter((entry) => live.has(entry.pid));
122
+ if (survivors.length === 0) {
123
+ return;
124
+ }
125
+ throw new Error(`${owner}: ${survivors.map((entry) => `${entry.pid} (${entry.command})`).join(', ')} still running ${timeoutMs}ms after it was stopped`);
126
+ }
127
+ await sleep(50);
128
+ waiting = waiting.filter((entry) => isRunning(entry.pid));
129
+ }
130
+ }
131
+ /** Every process of this user whose working directory is `root` or lies beneath it, deleted or not. */
132
+ export async function pidsWorkingIn(root) {
133
+ const under = (cwd) => cwd === root || cwd.startsWith(`${root}/`);
134
+ switch (process.platform) {
135
+ case 'linux': {
136
+ const found = [];
137
+ for (const pid of (await readdir('/proc')).filter((name) => /^\d+$/.test(name))) {
138
+ const cwd = await readlink(`/proc/${pid}/cwd`).catch((error) => {
139
+ // Another user's process, or one that exited since the listing.
140
+ if (errorCode(error) === 'EACCES' || errorCode(error) === 'ENOENT') {
141
+ return null;
142
+ }
143
+ throw error;
144
+ });
145
+ if (cwd !== null && under(cwd.replace(/ \(deleted\)$/, ''))) {
146
+ found.push(Number(pid));
147
+ }
148
+ }
149
+ return found;
150
+ }
151
+ case 'darwin': {
152
+ // lsof keeps naming a working directory after it has been deleted. It
153
+ // exits 1 when a listed process vanished before it was read; what it
154
+ // printed for the rest is still the answer.
155
+ const fields = await run('/usr/sbin/lsof', ['-nP', '-a', '-d', 'cwd', '-u', String(userInfo().uid), '-Fpn'], {
156
+ maxBuffer: 64 * 1024 * 1024,
157
+ }).then(({ stdout }) => stdout, (error) => {
158
+ if (error instanceof Error && 'code' in error && error.code === 1 && 'stdout' in error) {
159
+ return String(error.stdout);
160
+ }
161
+ throw error;
162
+ });
163
+ const found = [];
164
+ let pid = 0;
165
+ for (const line of fields.split('\n')) {
166
+ if (line.startsWith('p')) {
167
+ pid = Number(line.slice(1));
168
+ }
169
+ else if (line.startsWith('n') && under(line.slice(1))) {
170
+ found.push(pid);
171
+ }
172
+ }
173
+ return found;
174
+ }
175
+ default:
176
+ throw new Error(`No working-directory scan for ${process.platform}`);
177
+ }
178
+ }
179
+ /**
180
+ * The Nx daemon `workspace` runs, the daemon first, then every process it
181
+ * started. Empty when the workspace records no daemon or the recorded one is
182
+ * gone. The record is `d/server-process.json` under the workspace's own
183
+ * `.nx/workspace-data`, where every fixture keeps its Nx state.
184
+ */
185
+ export async function nxDaemonProcesses(workspace) {
186
+ const record = join(workspace, '.nx', 'workspace-data', 'd', 'server-process.json');
187
+ const text = await readFile(record, 'utf8').catch((error) => {
188
+ if (errorCode(error) === 'ENOENT') {
189
+ return null;
190
+ }
191
+ throw error;
192
+ });
193
+ if (text === null) {
194
+ return [];
195
+ }
196
+ const parsed = JSON.parse(text);
197
+ if (typeof parsed !== 'object' ||
198
+ parsed === null ||
199
+ !('processId' in parsed) ||
200
+ typeof parsed.processId !== 'number' ||
201
+ !Number.isSafeInteger(parsed.processId)) {
202
+ throw new Error(`Nx daemon record ${record} names no process id`);
203
+ }
204
+ return withDescendants(await processTable(), [parsed.processId]);
205
+ }
206
+ /**
207
+ * Release the Nx daemon `workspace` started and wait until the daemon and
208
+ * every process it ran have exited. `stop` runs `nx daemon --stop` against
209
+ * the workspace, in the environment that started it. Nx deletes the daemon's
210
+ * record before the daemon exits, so the record cannot say when the workspace
211
+ * is free to delete; the processes can. The daemon also leaves what it
212
+ * spawned to end on its own: plugin workers once they see it gone, the editor
213
+ * extension probe it starts at launch never. Those get SIGTERM with it, the
214
+ * ones it started while it was stopping included. A child that outlives the
215
+ * daemon is reparented to init and leaves the daemon's process tree, but it
216
+ * still works in the workspace, so the workspace census ends what is left.
217
+ * A missing record can mean startup has not published it yet: skip the
218
+ * daemon-stop command, but never skip the working-directory census.
219
+ */
220
+ export async function stopNxDaemon(workspace, stop) {
221
+ const [daemon, ...before] = await nxDaemonProcesses(workspace);
222
+ if (daemon !== undefined) {
223
+ await stop();
224
+ const known = new Set([daemon.pid, ...before.map((entry) => entry.pid)]);
225
+ const after = withDescendants(await processTable(), [daemon.pid]).filter((entry) => !known.has(entry.pid));
226
+ const spawned = [...before, ...after];
227
+ for (const entry of spawned) {
228
+ terminate(entry.pid);
229
+ }
230
+ await awaitExit([daemon, ...spawned], `Nx daemon of ${workspace}`);
231
+ }
232
+ await endWorkspaceProcesses(workspace, `Nx processes of ${workspace}`);
233
+ }
234
+ /**
235
+ * End every process still working in `workspace`, round after round, until a
236
+ * census finds none. The daemon has exited by now, so a process can start
237
+ * another under the workspace only while it is alive, and a child started
238
+ * just before its parent was ended is in the next census. A zombie has
239
+ * exited already, and this process never ends itself.
240
+ */
241
+ async function endWorkspaceProcesses(workspace, owner) {
242
+ for (;;) {
243
+ const working = new Set(await pidsWorkingIn(workspace));
244
+ const leftovers = (await processTable()).filter((entry) => working.has(entry.pid) && entry.pid !== process.pid && !entry.stat.startsWith('Z'));
245
+ if (leftovers.length === 0) {
246
+ return;
247
+ }
248
+ for (const entry of leftovers) {
249
+ terminate(entry.pid);
250
+ }
251
+ await awaitExit(leftovers, owner);
252
+ }
253
+ }
254
+ /**
255
+ * The run this process holds in each suite directory, opened or still opening,
256
+ * by that directory's canonical path: one for each parent and suite, however
257
+ * the parent is spelled. Entries are kept for the life of the process, an open
258
+ * that failed included.
259
+ */
260
+ const runDirectories = new Map();
261
+ const RUN_SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'];
262
+ /** The handlers this process made for {@link RUN_SIGNALS}, by signal: none until it opens its first run. */
263
+ const runSignalHandlers = new Map();
264
+ /** Reclaiming every run this process holds, begun by the first of {@link RUN_SIGNALS} it received. */
265
+ let retirement;
266
+ /**
267
+ * A fresh fixture root for `suite`, owned by this process: a `prefix`-named
268
+ * directory (mode 0700) in this process's run directory under
269
+ * `parentDirectory`, `<parent>/smoothbricks-fixtures/<suite>/run-<pid>`. The
270
+ * caller always names the parent: the temp directory, or the directory of the
271
+ * volume the fixture has to lie on. The parent is resolved through every link,
272
+ * so the root is canonical (macOS puts the temp directory behind a /private
273
+ * symlink, and a daemon never sees an edit made under a root named through
274
+ * one) and a parent spelled two ways is one run. A process holds one run for
275
+ * each parent and suite, and the first root of a suite under a parent reclaims
276
+ * that suite's dead runs there first. Once a signal has this process
277
+ * reclaiming its runs, no root is made.
278
+ */
279
+ export async function ownedFixtureRoot(parentDirectory, suite, prefix) {
280
+ const suiteDirectory = join(await realpath(parentDirectory), FIXTURE_HOME, suite);
281
+ refuseWhileRetiring();
282
+ let opened = runDirectories.get(suiteDirectory);
283
+ if (opened === undefined) {
284
+ opened = openRun(suiteDirectory);
285
+ runDirectories.set(suiteDirectory, opened);
286
+ }
287
+ const directory = await opened;
288
+ refuseWhileRetiring();
289
+ return mkdtemp(join(directory, prefix));
290
+ }
291
+ async function openRun(suiteDirectory) {
292
+ await sweepSuite(suiteDirectory);
293
+ const directory = join(suiteDirectory, `run-${process.pid}`);
294
+ await mkdir(directory, { recursive: true });
295
+ ownRunSignals();
296
+ return directory;
297
+ }
298
+ /**
299
+ * Own the signals that end this process, once however many runs it holds. The
300
+ * first of them reclaims every run (`retireRuns`) before it takes its course. A
301
+ * handler for each run would let the first to finish re-raise the signal over
302
+ * the reclaim of the rest, and a signal repeated meanwhile would meet no handler
303
+ * and kill the process before any reclaim ended.
304
+ */
305
+ function ownRunSignals() {
306
+ if (runSignalHandlers.size > 0) {
307
+ return;
308
+ }
309
+ for (const signal of RUN_SIGNALS) {
310
+ const handler = () => {
311
+ retirement ??= retireRuns(signal);
312
+ };
313
+ runSignalHandlers.set(signal, handler);
314
+ process.on(signal, handler);
315
+ }
316
+ }
317
+ /**
318
+ * Reclaim every run this process holds at once, then let `signal`, the first it
319
+ * received, take its course: the handlers go and the process dies of it, as it
320
+ * would have without them. Every run is awaited, one still opening or one whose
321
+ * open failed included, and one failing cuts no other short; each failure is
322
+ * written to stderr with the suite directory of its run. A repeated signal
323
+ * meets a handler, not the default, so it waits for this and neither starts a
324
+ * second reclaim nor kills the first. That wait is the reclaim's own: for each
325
+ * run, after any sweep it was still opening with, the scans, two rounds of
326
+ * `SIGNALLED_GRACE_MS` (SIGTERM, then SIGKILL) for its processes, and the
327
+ * delete. A bounded test leg's SIGKILL ends it whatever it is.
328
+ */
329
+ async function retireRuns(signal) {
330
+ const runs = [...runDirectories];
331
+ // Inside the 10 s a bounded leg grants between SIGTERM and SIGKILL.
332
+ const outcomes = await Promise.allSettled(runs.map(async ([, opened]) => reclaimRun(await opened, 'signalled fixture run', SIGNALLED_GRACE_MS)));
333
+ for (const [index, outcome] of outcomes.entries()) {
334
+ if (outcome.status === 'rejected') {
335
+ const reason = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
336
+ process.stderr.write(`could not reclaim this process's run in ${runs[index][0]}: ${reason}\n`);
337
+ }
338
+ }
339
+ for (const [name, handler] of runSignalHandlers) {
340
+ process.removeListener(name, handler);
341
+ }
342
+ process.kill(process.pid, signal);
343
+ }
344
+ function refuseWhileRetiring() {
345
+ if (retirement !== undefined) {
346
+ throw new Error('no fixture root is made: a signal has this process reclaiming the fixture runs it owns');
347
+ }
348
+ }
349
+ /**
350
+ * Stop every process working in a run of `suite` under `parentDirectory` whose
351
+ * owner is gone, then delete the run, and return the suite's directory there.
352
+ * The first fixture root of a suite under a parent in a process does this; a
353
+ * test that just watched a fixture-owning process die may too. An owner's pid
354
+ * reused by an unrelated process makes its run look alive; it is reclaimed once
355
+ * that process is gone too, never early.
356
+ */
357
+ export async function reclaimDeadFixtureRuns(parentDirectory, suite) {
358
+ const suiteDirectory = join(await realpath(parentDirectory), FIXTURE_HOME, suite);
359
+ await sweepSuite(suiteDirectory);
360
+ return suiteDirectory;
361
+ }
362
+ async function sweepSuite(suiteDirectory) {
363
+ await mkdir(suiteDirectory, { recursive: true });
364
+ await reclaimDeadRuns(suiteDirectory);
365
+ }
366
+ async function reclaimDeadRuns(suiteDirectory) {
367
+ const dead = (await readdir(suiteDirectory)).flatMap((name) => {
368
+ const owner = RUN_NAME.exec(name)?.[1];
369
+ if (owner === undefined) {
370
+ return [];
371
+ }
372
+ const pid = Number(owner);
373
+ return pid !== process.pid && !isRunning(pid) ? [join(suiteDirectory, name)] : [];
374
+ });
375
+ if (dead.length === 0) {
376
+ return;
377
+ }
378
+ const lock = await takeSweepLock(suiteDirectory);
379
+ if (lock === null) {
380
+ // Another process of the suite is reclaiming them right now.
381
+ return;
382
+ }
383
+ try {
384
+ for (const directory of dead) {
385
+ await reclaimRun(directory, 'dead fixture run');
386
+ }
387
+ }
388
+ finally {
389
+ await rm(lock, { force: true });
390
+ }
391
+ }
392
+ async function reclaimRun(directory, owner, graceMs = EXIT_TIMEOUT_MS) {
393
+ const roots = await readdir(directory).catch((error) => {
394
+ if (errorCode(error) === 'ENOENT') {
395
+ return null;
396
+ }
397
+ throw error;
398
+ });
399
+ if (roots === null) {
400
+ return;
401
+ }
402
+ // A fixture deletes its root only once nothing runs in it, so an emptied
403
+ // run holds no process and needs no scan.
404
+ if (roots.length > 0) {
405
+ const working = await pidsWorkingIn(directory);
406
+ const processes = (await processTable()).filter((entry) => working.includes(entry.pid));
407
+ if (processes.length > 0) {
408
+ process.stderr.write(`reclaiming ${owner} ${directory}: ${processes.map((entry) => `${entry.pid} (${entry.command})`).join(', ')}\n`);
409
+ for (const entry of processes) {
410
+ terminate(entry.pid);
411
+ }
412
+ try {
413
+ await awaitExit(processes, `processes of ${owner} ${directory}`, graceMs);
414
+ }
415
+ catch (error) {
416
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}; sending SIGKILL\n`);
417
+ for (const entry of processes) {
418
+ terminate(entry.pid, 'SIGKILL');
419
+ }
420
+ await awaitExit(processes, `processes of ${owner} ${directory} after SIGKILL`, graceMs);
421
+ }
422
+ }
423
+ }
424
+ // A killed fixture may never have reached its own alias retirement, and its
425
+ // workspace may be gone. The alias is its own record: one whose target is the
426
+ // socket state of a workspace in this reclaimed run, and whose name is that
427
+ // workspace's, is this sweep's to retire. Every other entry is left alone.
428
+ const { directory: namespace } = socketNamespace();
429
+ for (const entry of await readdir(namespace, { withFileTypes: true })) {
430
+ if (!entry.isSymbolicLink())
431
+ continue;
432
+ const target = await readlink(join(namespace, entry.name)).catch((error) => {
433
+ if (errorCode(error) === 'ENOENT')
434
+ return undefined;
435
+ throw error;
436
+ });
437
+ if (target === undefined)
438
+ continue;
439
+ const workspace = dirname(dirname(target));
440
+ if (workspace.startsWith(`${directory}${sep}`) &&
441
+ target === fixtureSocketTarget(workspace) &&
442
+ entry.name === fixtureSocketAliasName(workspace)) {
443
+ await retireFixtureSocketDirectory(workspace);
444
+ }
445
+ }
446
+ await rm(directory, { recursive: true, force: true });
447
+ }
448
+ /**
449
+ * The suite's sweep lock, or null while a live process holds it. A lock left
450
+ * by a process that died mid-sweep is taken over. Reclaiming is idempotent, so
451
+ * the lock only keeps concurrent test processes from scanning the same runs.
452
+ */
453
+ async function takeSweepLock(suiteDirectory) {
454
+ const lock = join(suiteDirectory, SWEEP_LOCK);
455
+ for (let attempt = 0; attempt < 2; attempt += 1) {
456
+ try {
457
+ await writeFile(lock, `${process.pid}\n`, { flag: 'wx' });
458
+ return lock;
459
+ }
460
+ catch (error) {
461
+ if (errorCode(error) !== 'EEXIST') {
462
+ throw error;
463
+ }
464
+ }
465
+ const holder = Number((await readFile(lock, 'utf8').catch((error) => {
466
+ if (errorCode(error) === 'ENOENT') {
467
+ return '';
468
+ }
469
+ throw error;
470
+ })).trim());
471
+ if (Number.isSafeInteger(holder) && holder > 0 && isRunning(holder)) {
472
+ return null;
473
+ }
474
+ await rm(lock, { force: true });
475
+ }
476
+ return null;
477
+ }
478
+ /**
479
+ * The longest path a fixture binds a Unix socket at: the stricter of Nx's own
480
+ * limit (`assertValidSocketPath` refuses over 95 characters) and the kernel's
481
+ * (macOS's `sun_path` holds 104 bytes, the terminating NUL included), counted
482
+ * in UTF-8 bytes, which is what the kernel limits.
483
+ */
484
+ const SOCKET_PATH_BYTES = 95;
485
+ /**
486
+ * The longest socket Nx binds in a configured socket directory: an isolated
487
+ * plugin worker's `p<pid>-<counter>-<8 hex>.sock` (`getPluginSocketFileName`;
488
+ * with a configured directory `getPluginSocketDir` is the daemon's own), which
489
+ * outgrows the daemon's `d.sock` and a forked task's `fp<pid>-<n>.sock`. macOS
490
+ * pids stop at 99999, Linux's have seven digits; two base-36 digits count 1295
491
+ * workers.
492
+ */
493
+ export const NX_LONGEST_SOCKET_NAME = `p${'9'.repeat(process.platform === 'darwin' ? 5 : 7)}-zz-ffffffff.sock`;
494
+ const RUNTIME_LINK_ENV = 'COWSHED_RUNTIME_LINK';
495
+ const PORT_BASE_ENV = 'COWSHED_PORT_BASE';
496
+ const PORT_BLOCK_SIZE_ENV = 'COWSHED_PORT_BLOCK_SIZE';
497
+ const MAX_PORT = 65_535;
498
+ const DECIMAL = /^[0-9]+$/;
499
+ /**
500
+ * The directory a fixture's sockets are made in: a short root this process's
501
+ * own environment supplies for the checkout it runs in. In order: the parent
502
+ * of `NX_SOCKET_DIR`, which for a Cowshed job is the workspace's short runtime
503
+ * link (its Nx socket directory is `nx` below it); `COWSHED_RUNTIME_LINK`,
504
+ * that link; else the temp directory. Never `NX_SOCKET_DIR` itself: Nx deletes
505
+ * that directory, recursively and whatever else is in it, whenever its daemon
506
+ * stops, so a fixture's sockets live beside it. The sandbox admits Unix sockets
507
+ * under the link by its literal path, and under the temp directory only for a
508
+ * job's own `TMPDIR`. Spelled as the environment gives it and never resolved,
509
+ * since the physical path is too long for a socket.
510
+ *
511
+ * As `nx-socket-dir.sh` does, a shell's variable is trusted only when it is
512
+ * this checkout's. The public finder names the checkout from the working
513
+ * directory; an `NX_SOCKET_DIR` also needs a matching `NX_WORKSPACE_ROOT_PATH`.
514
+ * The link must resolve to that checkout's `.cowshed/run`, even when a test
515
+ * preload has removed the inherited Nx variables. Unproven candidates are
516
+ * passed over with their resolution or permission failure, so the fallback
517
+ * directory, or the length refusal it leads to, names what it fell from. One
518
+ * that is this checkout's but is not an existing directory of this user is an
519
+ * error naming it.
520
+ */
521
+ export function socketNamespace() {
522
+ const passedOver = [];
523
+ const socketDirectory = environmentValue('NX_SOCKET_DIR');
524
+ const link = environmentValue(RUNTIME_LINK_ENV);
525
+ if (socketDirectory !== undefined || link !== undefined) {
526
+ const checkout = checkoutRoot();
527
+ if (checkout.kind === 'unresolved') {
528
+ passedOver.push(`NX_SOCKET_DIR and ${RUNTIME_LINK_ENV} cannot be tied to a checkout: ${checkout.why}`);
529
+ }
530
+ else {
531
+ if (socketDirectory !== undefined) {
532
+ const named = environmentValue('NX_WORKSPACE_ROOT_PATH');
533
+ const binding = named === undefined ? { kind: 'unresolved', why: 'NX_WORKSPACE_ROOT_PATH is not set' } : resolution(named);
534
+ if (binding.kind === 'resolved' && binding.path === checkout.path) {
535
+ const leaf = resolution(socketDirectory);
536
+ if (leaf.kind === 'resolved' && isWithin(leaf.path, checkout.path)) {
537
+ const source = `the parent of NX_SOCKET_DIR=${socketDirectory}`;
538
+ return { directory: ownedDirectory(source, dirname(socketDirectory), passedOver, 'private'), passedOver };
539
+ }
540
+ passedOver.push(`NX_SOCKET_DIR=${socketDirectory} ${describeResolution(leaf)}, not inside the checkout ${checkout.path}`);
541
+ }
542
+ else {
543
+ passedOver.push(`NX_SOCKET_DIR=${socketDirectory} has no current checkout binding: ${describeResolution(binding)}`);
544
+ }
545
+ }
546
+ if (link !== undefined) {
547
+ const run = join(checkout.path, '.cowshed', 'run');
548
+ const runResolved = resolution(run);
549
+ const linked = resolution(link);
550
+ if (runResolved.kind === 'resolved' && linked.kind === 'resolved' && linked.path === runResolved.path) {
551
+ return { directory: ownedDirectory(RUNTIME_LINK_ENV, link, passedOver, 'private'), passedOver };
552
+ }
553
+ passedOver.push(`${RUNTIME_LINK_ENV}=${link} ${describeResolution(linked)}, and the checkout's ${run} ${describeResolution(runResolved)}`);
554
+ }
555
+ }
556
+ }
557
+ return { directory: ownedDirectory('the temp directory', tmpdir(), passedOver, 'process-temp'), passedOver };
558
+ }
559
+ /** The variable's value, or undefined when it is unset or empty. */
560
+ function environmentValue(name) {
561
+ const value = process.env[name];
562
+ return value === undefined || value === '' ? undefined : value;
563
+ }
564
+ function describeResolution(resolved) {
565
+ return resolved.kind === 'resolved' ? `resolves to ${resolved.path}` : `cannot be resolved (${resolved.why})`;
566
+ }
567
+ /** The current checkout, read from its marker rather than an inherited Nx override. */
568
+ function checkoutRoot() {
569
+ const here = resolution(process.cwd());
570
+ if (here.kind === 'unresolved') {
571
+ return { kind: 'unresolved', why: `the working directory cannot be resolved (${here.why})` };
572
+ }
573
+ const root = findNxWorkspaceRoot(here.path);
574
+ return root === null
575
+ ? { kind: 'unresolved', why: `no nx.json at or above the working directory ${here.path}` }
576
+ : resolution(root);
577
+ }
578
+ /** `path` resolved through every link, or the errno of a path that does not exist or may not be looked at. */
579
+ function resolution(path) {
580
+ try {
581
+ return { kind: 'resolved', path: realpathSync(path) };
582
+ }
583
+ catch (error) {
584
+ const code = errorCode(error);
585
+ if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EACCES' || code === 'EPERM') {
586
+ return { kind: 'unresolved', why: `${code} on ${path}` };
587
+ }
588
+ throw error;
589
+ }
590
+ }
591
+ /** Whether the resolved `path` is `root` or lies beneath it. */
592
+ function isWithin(path, root) {
593
+ return path === root || path.startsWith(`${root}${sep}`);
594
+ }
595
+ function ownedDirectory(source, directory, passedOver, ownership) {
596
+ const stat = statSync(directory, { throwIfNoEntry: false });
597
+ const user = process.getuid?.();
598
+ const owned = user === undefined || stat?.uid === user;
599
+ const publicTemp = ownership === 'process-temp' && stat?.uid === 0 && (stat.mode & 0o7777) === 0o1777;
600
+ if (!isAbsolute(directory) || stat === undefined || !stat.isDirectory() || (!owned && !publicTemp)) {
601
+ throw new Error(`${source} (${directory}, uid=${stat?.uid}, mode=${stat?.mode.toString(8)}) is not an existing absolute ` +
602
+ 'user-owned directory or an admitted sticky public temp directory, so no fixture socket can be ' +
603
+ `made under it${passedOver.length === 0 ? '' : `; passed over: ${passedOver.join('; ')}`}`);
604
+ }
605
+ return directory;
606
+ }
607
+ /**
608
+ * `path`, or an error naming it, its length and the namespace it was made in
609
+ * (with what that namespace passed over) when Nx and the kernel would refuse
610
+ * to bind a socket there.
611
+ */
612
+ export function assertSocketPath(path, namespace) {
613
+ const bytes = Buffer.byteLength(path, 'utf8');
614
+ if (bytes > SOCKET_PATH_BYTES) {
615
+ const { directory, passedOver } = namespace;
616
+ throw new Error(`the socket path ${path} is ${bytes} UTF-8 bytes, over the ${SOCKET_PATH_BYTES} a Unix socket may have; ` +
617
+ `the socket namespace ${directory} leaves too little room` +
618
+ `${passedOver.length === 0 ? '' : `; passed over: ${passedOver.join('; ')}`}`);
619
+ }
620
+ return path;
621
+ }
622
+ /**
623
+ * A fresh directory, mode 0700 and named `prefix` plus six random characters,
624
+ * in {@link socketNamespace}: the one owner of the sockets a fixture makes
625
+ * there, so the fixture removes the directory and nothing else. `longestSocketName`
626
+ * is the longest socket it will hold, and the call fails before creating
627
+ * anything when that socket's path would be too long to bind.
628
+ */
629
+ export async function ownedSocketDirectory(prefix, longestSocketName) {
630
+ const namespace = socketNamespace();
631
+ assertSocketPath(join(namespace.directory, `${prefix}XXXXXX`, longestSocketName), namespace);
632
+ return mkdtemp(join(namespace.directory, prefix));
633
+ }
634
+ /** The alias's name: a digest of the workspace's physical path, which is the whole of its identity. */
635
+ function fixtureSocketAliasName(workspace) {
636
+ return `nx-${createHash('sha256').update(workspace).digest('hex').slice(0, 16)}`;
637
+ }
638
+ /** The real directory below the workspace that its alias names. */
639
+ function fixtureSocketTarget(workspace) {
640
+ return join(workspace, '.nx', 'sockets');
641
+ }
642
+ /** A colliding or retargeted alias is not this fixture's and must not be used or removed. */
643
+ function assertFixtureSocketAlias(alias, target) {
644
+ const entry = lstatSync(alias);
645
+ if (!entry.isSymbolicLink() || readlinkSync(alias) !== target) {
646
+ throw new Error(`fixture socket alias ${alias} does not name its owned target ${target}`);
647
+ }
648
+ }
649
+ /**
650
+ * The fixture's `NX_SOCKET_DIR`, named and nothing more: the real `nx` leaf
651
+ * below the short parent alias {@link publishFixtureSocketDirectory} makes in
652
+ * the job's admitted namespace. `workspace` is the physical path that
653
+ * publication was given; the alias is named for a hash of it, so every client,
654
+ * daemon stop and retirement of the workspace names the same leaf, and no two
655
+ * fixtures share one. A long private `TMPDIR` affects neither the bind path nor
656
+ * workspace ownership. A namespace too small for Nx's longest socket name is
657
+ * refused here, so before any publication.
658
+ */
659
+ export function fixtureSocketDirectory(workspace) {
660
+ const namespace = socketNamespace();
661
+ const directory = join(namespace.directory, fixtureSocketAliasName(workspace), 'nx');
662
+ assertSocketPath(join(directory, NX_LONGEST_SOCKET_NAME), namespace);
663
+ return directory;
664
+ }
665
+ /**
666
+ * Publish the fixture's short socket alias and return its
667
+ * {@link fixtureSocketDirectory}. The workspace must be a physical directory in
668
+ * a fixture run this process holds ({@link ownedFixtureRoot}): then the run's
669
+ * sweep reclaims the alias even if this process dies before its
670
+ * {@link retireFixtureSocketDirectory}. The alias points at the workspace's own
671
+ * `.nx/sockets`, made mode 0700; a symlinked `.nx` or `.nx/sockets` is refused
672
+ * before anything is written through it. Nx makes the `nx` leaf itself.
673
+ */
674
+ export async function publishFixtureSocketDirectory(workspace) {
675
+ refuseWhileRetiring();
676
+ const runs = await Promise.allSettled(runDirectories.values());
677
+ const owned = runs.some((run) => run.status === 'fulfilled' && workspace.startsWith(`${run.value}${sep}`));
678
+ if (!owned || (await realpath(workspace)) !== workspace) {
679
+ throw new Error(`no socket alias is published for ${workspace}: it is not a physical workspace in a fixture run this ` +
680
+ 'process owns, so no sweep could reclaim its alias');
681
+ }
682
+ const directory = fixtureSocketDirectory(workspace);
683
+ const alias = dirname(directory);
684
+ const target = fixtureSocketTarget(workspace);
685
+ for (const state of [dirname(target), target]) {
686
+ try {
687
+ await mkdir(state, { mode: 0o700 });
688
+ }
689
+ catch (error) {
690
+ if (errorCode(error) !== 'EEXIST')
691
+ throw error;
692
+ }
693
+ if (!(await lstat(state)).isDirectory()) {
694
+ throw new Error(`fixture socket target ${state} is not a real directory in its physical workspace`);
695
+ }
696
+ }
697
+ try {
698
+ await symlink(target, alias, 'dir');
699
+ }
700
+ catch (error) {
701
+ if (errorCode(error) !== 'EEXIST')
702
+ throw error;
703
+ }
704
+ assertFixtureSocketAlias(alias, target);
705
+ return directory;
706
+ }
707
+ /**
708
+ * A second real leaf, `slot`, beside the `nx` one below the workspace's
709
+ * published alias, for tests whose subject is two daemon socket directories.
710
+ * A slot name is shorter than `nx`, so it fits wherever the published leaf
711
+ * does. An existing slot is an error. Its caller stops the daemon bound in it
712
+ * before removing it.
713
+ */
714
+ export async function ownedWorkspaceSocketDirectory(workspace, slot) {
715
+ const alias = dirname(fixtureSocketDirectory(workspace));
716
+ assertFixtureSocketAlias(alias, fixtureSocketTarget(workspace));
717
+ const directory = join(alias, slot);
718
+ await mkdir(directory, { mode: 0o700 });
719
+ return directory;
720
+ }
721
+ /**
722
+ * After the daemon exits, unlink only this workspace's verified parent alias,
723
+ * not its target. Named from the workspace's path alone, so a workspace already
724
+ * deleted retires too. No alias is not an error; any other entry under its name
725
+ * is refused and left in place.
726
+ */
727
+ export async function retireFixtureSocketDirectory(workspace) {
728
+ const alias = join(socketNamespace().directory, fixtureSocketAliasName(workspace));
729
+ try {
730
+ assertFixtureSocketAlias(alias, fixtureSocketTarget(workspace));
731
+ }
732
+ catch (error) {
733
+ if (errorCode(error) === 'ENOENT')
734
+ return;
735
+ throw error;
736
+ }
737
+ await rm(alias);
738
+ }
739
+ /**
740
+ * The block `env` (`COWSHED_PORT_BASE`, `COWSHED_PORT_BLOCK_SIZE`) names. A
741
+ * size without a base, a base without a size (never assumed), a value that is
742
+ * not a decimal number, a size that is not a power of two of at least two, a
743
+ * base not aligned to it, or a block outside the TCP ports 1–65535 is a broken
744
+ * environment, refused rather than guessed around (04_sandbox.md).
745
+ */
746
+ function portBlockEnvironment(env) {
747
+ const baseText = env[PORT_BASE_ENV];
748
+ const sizeText = env[PORT_BLOCK_SIZE_ENV];
749
+ if (baseText === undefined && sizeText === undefined) {
750
+ return { kind: 'none' };
751
+ }
752
+ if (baseText === undefined) {
753
+ return { kind: 'broken', reason: `${PORT_BLOCK_SIZE_ENV}=${sizeText} is set without ${PORT_BASE_ENV}` };
754
+ }
755
+ if (sizeText === undefined) {
756
+ return { kind: 'broken', reason: `${PORT_BASE_ENV}=${baseText} is set without ${PORT_BLOCK_SIZE_ENV}` };
757
+ }
758
+ if (!DECIMAL.test(baseText) || !DECIMAL.test(sizeText)) {
759
+ return {
760
+ kind: 'broken',
761
+ reason: `${PORT_BASE_ENV}=${JSON.stringify(baseText)} and ${PORT_BLOCK_SIZE_ENV}=${JSON.stringify(sizeText)} are not both decimal numbers`,
762
+ };
763
+ }
764
+ const base = Number(baseText);
765
+ const size = Number(sizeText);
766
+ if (!Number.isSafeInteger(size) || size < 2 || (size & (size - 1)) !== 0) {
767
+ return {
768
+ kind: 'broken',
769
+ reason: `${PORT_BLOCK_SIZE_ENV}=${sizeText} is not a power of two of at least 2`,
770
+ };
771
+ }
772
+ if (!Number.isSafeInteger(base) || base < 1 || base % size !== 0) {
773
+ return {
774
+ kind: 'broken',
775
+ reason: `${PORT_BASE_ENV}=${baseText} is not a positive multiple of ${PORT_BLOCK_SIZE_ENV}=${sizeText}`,
776
+ };
777
+ }
778
+ if (base + size - 1 > MAX_PORT) {
779
+ return {
780
+ kind: 'broken',
781
+ reason: `the block ${base}+${size} (${PORT_BASE_ENV}, ${PORT_BLOCK_SIZE_ENV}) runs past TCP port ${MAX_PORT}`,
782
+ };
783
+ }
784
+ return { kind: 'block', base, size };
785
+ }
786
+ /**
787
+ * Bind a real listener where a Cowshed job's other processes can connect to
788
+ * it. In a block, `bind` is called with each candidate `base+1 … base+size-1`,
789
+ * lowest first (a long-lived test listener scans from the bottom), and the
790
+ * first that binds is kept: only a real bind claims a port, so nothing probes
791
+ * and closes. Only `EADDRINUSE` (by `code`) moves on to the next candidate;
792
+ * any other failure is that bind's own and surfaces as is, and so does the
793
+ * last candidate's, so an exhausted block reports `EADDRINUSE`, never a silent
794
+ * port 0. Outside a block `bind` is called with 0, and the kernel picks.
795
+ *
796
+ * `bind` creates and binds one listener per call and returns it, and a failed
797
+ * bind leaves nothing behind. It may throw (`Bun.serve` does) or reject (a
798
+ * Node `net` server reports a failed `listen` as an `error` event, which the
799
+ * caller turns into a rejection). The listener the winning call returns is the
800
+ * caller's to keep and close.
801
+ */
802
+ export async function bindListener(bind) {
803
+ const block = portBlockEnvironment(process.env);
804
+ switch (block.kind) {
805
+ case 'none':
806
+ return bind(0);
807
+ case 'broken':
808
+ throw new Error(`a listener cannot bind in a broken Cowshed port-block environment: ${block.reason}`);
809
+ case 'block': {
810
+ const last = block.base + block.size - 1;
811
+ for (let port = block.base + 1; port < last; port += 1) {
812
+ try {
813
+ return await bind(port);
814
+ }
815
+ catch (error) {
816
+ if (errorCode(error) !== 'EADDRINUSE') {
817
+ throw error;
818
+ }
819
+ }
820
+ }
821
+ return bind(last);
822
+ }
823
+ }
824
+ }