diff --git a/bun.lock b/bun.lock index b3c1b70a53c..8a036680920 100644 --- a/bun.lock +++ b/bun.lock @@ -1426,7 +1426,6 @@ "version": "0.1.0", "dependencies": { "@parcel/watcher": "2.5.6", - "chokidar": "4.0.3", "fast-glob": "3.3.3", "picomatch": "4.0.4", }, @@ -4241,7 +4240,7 @@ "check-error": ["check-error@2.1.3", "", {}, "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA=="], - "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + "chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], "chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="], @@ -6047,7 +6046,7 @@ "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], - "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + "readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], "recast": ["recast@0.23.21", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw=="], @@ -6967,8 +6966,6 @@ "@lingui/cli/@lingui/conf": ["@lingui/conf@6.12.0", "", { "dependencies": { "jest-validate": "^29.4.3", "jiti": "^2.5.1", "lilconfig": "^3.1.3", "normalize-path": "^3.0.0" } }, "sha512-A4Xcip2Mcgd0iN/rs3RpxDc8MPlYiET9elP44knC7IVpJwH5zb7feK8NFsdtFQ3YlJebdLz6Qk6zjrCbq5TZKg=="], - "@lingui/cli/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], - "@lingui/cli/commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="], "@lingui/cli/jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], @@ -7187,14 +7184,10 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], - "@tanstack/router-cli/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], - "@tanstack/router-generator/jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], "@tanstack/router-generator/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - "@tanstack/router-plugin/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], - "@temporalio/client/uuid": ["uuid@11.1.1", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ=="], "@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="], @@ -7375,8 +7368,6 @@ "fumadocs-core/shiki": ["shiki@4.4.3", "", { "dependencies": { "@shikijs/core": "4.4.3", "@shikijs/engine-javascript": "4.4.3", "@shikijs/engine-oniguruma": "4.4.3", "@shikijs/langs": "4.4.3", "@shikijs/themes": "4.4.3", "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g=="], - "fumadocs-mdx/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], - "fumadocs-mdx/esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], "fumadocs-mdx/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], @@ -7595,6 +7586,8 @@ "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], + "react-email/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + "react-email/esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="], "react-email/glob": ["glob@11.1.0", "", { "dependencies": { "foreground-child": "^3.3.1", "jackspeak": "^4.1.1", "minimatch": "^10.1.1", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw=="], @@ -7995,8 +7988,6 @@ "@lingui/babel-plugin-lingui-macro/@lingui/conf/jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], - "@lingui/cli/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], - "@lingui/cli/ora/cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="], "@lingui/cli/ora/cli-spinners": ["cli-spinners@3.4.0", "", {}, "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw=="], @@ -8263,10 +8254,6 @@ "@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], - "@tanstack/router-cli/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], - - "@tanstack/router-plugin/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], - "@vercel/cli-exec/execa/get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], "@vercel/cli-exec/execa/human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], @@ -8505,8 +8492,6 @@ "fumadocs-core/shiki/@shikijs/types": ["@shikijs/types@4.4.3", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g=="], - "fumadocs-mdx/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], - "fumadocs-mdx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], "fumadocs-mdx/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], @@ -8797,6 +8782,8 @@ "pkg-up/find-up/locate-path": ["locate-path@3.0.0", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="], + "react-email/chokidar/readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + "react-email/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], "react-email/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], diff --git a/packages/workspace-fs/package.json b/packages/workspace-fs/package.json index e31cae4230a..e128d649a1d 100644 --- a/packages/workspace-fs/package.json +++ b/packages/workspace-fs/package.json @@ -37,7 +37,6 @@ }, "dependencies": { "@parcel/watcher": "2.5.6", - "chokidar": "4.0.3", "fast-glob": "3.3.3", "picomatch": "4.0.4" }, diff --git a/packages/workspace-fs/src/watch-backend/chokidar-backend.ts b/packages/workspace-fs/src/watch-backend/chokidar-backend.ts deleted file mode 100644 index a7a213966a4..00000000000 --- a/packages/workspace-fs/src/watch-backend/chokidar-backend.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { watch } from "chokidar"; -import { createIgnoreMatcher } from "./ignore-matcher"; -import type { NativeWatchBackend, NativeWatchEvent } from "./types"; - -const EVENT_TYPES = { - add: "create", - addDir: "create", - change: "update", - unlink: "delete", - unlinkDir: "delete", -} as const satisfies Record; - -/** - * Watches through Node's own `fs.watch`, so every event is delivered by libuv - * on the event loop: no watcher thread for a signal to interrupt, and no - * native state shared between subscriptions. - */ -export const chokidarWatchBackend: NativeWatchBackend = { - name: "chokidar", - subscribe({ rootPath, ignore, onEvents, onError }) { - const isIgnored = createIgnoreMatcher(rootPath, ignore); - const watcher = watch(rootPath, { - ignoreInitial: true, - followSymlinks: false, - ignorePermissionErrors: true, - // Atomic-write folding would hide the delete half of a rename from - // the rename reconciliation in watch-event-coalescing.ts. - atomic: false, - ignored: (candidate, stats) => isIgnored(candidate, stats?.isDirectory()), - }); - - for (const [chokidarEvent, type] of Object.entries(EVENT_TYPES)) { - watcher.on(chokidarEvent as keyof typeof EVENT_TYPES, (eventPath) => { - onEvents([{ type, path: eventPath }]); - }); - } - watcher.on("error", onError); - - return new Promise((resolve) => { - watcher.once("ready", () => { - resolve({ unsubscribe: () => watcher.close() }); - }); - }); - }, -}; diff --git a/packages/workspace-fs/src/watch-backend/chokidar-ignore.test.ts b/packages/workspace-fs/src/watch-backend/directory-backend-ignore.test.ts similarity index 97% rename from packages/workspace-fs/src/watch-backend/chokidar-ignore.test.ts rename to packages/workspace-fs/src/watch-backend/directory-backend-ignore.test.ts index 0e7dcf0341c..67f38b41bbb 100644 --- a/packages/workspace-fs/src/watch-backend/chokidar-ignore.test.ts +++ b/packages/workspace-fs/src/watch-backend/directory-backend-ignore.test.ts @@ -5,7 +5,7 @@ import path from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { FsWatcherManager } from "../watch"; import { watchSingleFile } from "../watch-file"; -import { chokidarWatchBackend } from "./chokidar-backend"; +import { directoryWatchBackend } from "./directory-backend"; const cleanups: Array<() => void | Promise> = []; afterEach(async () => { @@ -39,7 +39,7 @@ test("concurrent roots preserve tracked and explicit file events through detach (_, i) => `packages/p${i}/vendor`, ); const manager = new FsWatcherManager({ - backend: chokidarWatchBackend, + backend: directoryWatchBackend, useDefaultIgnores: false, listGitIgnoredDirs: async () => ignored, debounceMs: 10, diff --git a/packages/workspace-fs/src/watch-backend/directory-backend.test.ts b/packages/workspace-fs/src/watch-backend/directory-backend.test.ts new file mode 100644 index 00000000000..158d2618dc6 --- /dev/null +++ b/packages/workspace-fs/src/watch-backend/directory-backend.test.ts @@ -0,0 +1,214 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { + mkdir, + mkdtemp, + realpath, + rename, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { directoryWatchBackend } from "./directory-backend"; +import type { NativeWatchEvent } from "./types"; + +const cleanups: Array<() => Promise> = []; +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); +}); + +async function makeRoot(): Promise { + const root = await realpath(await mkdtemp(path.join(tmpdir(), "dwb-"))); + cleanups.push(() => rm(root, { recursive: true, force: true })); + return root; +} + +async function waitFor(check: () => boolean, label: string): Promise { + const deadline = Date.now() + 3_000; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out: ${label}`); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + +// Bun's fs.watch (unlike Node's) drops an event for a name that follows +// another for the same name within a few milliseconds. +function outsideBunMergeWindow(): Promise { + return new Promise((resolve) => setTimeout(resolve, 20)); +} + +function inotifyWatchCount(): number { + let count = 0; + for (const fd of readdirSync("/proc/self/fdinfo")) { + try { + const info = readFileSync(`/proc/self/fdinfo/${fd}`, "utf8"); + count += info.split("\n").filter((l) => l.startsWith("inotify")).length; + } catch {} + } + return count; +} + +async function attach(root: string, ignore: string[] = []) { + const events: NativeWatchEvent[] = []; + const subscription = await directoryWatchBackend.subscribe({ + rootPath: root, + ignore, + generation: 1, + onEvents: (batch) => events.push(...batch), + onError: (error) => { + throw error; + }, + }); + cleanups.push(() => subscription.unsubscribe()); + const saw = (type: NativeWatchEvent["type"], target: string) => + events.some((event) => event.type === type && event.path === target); + // Events are reconciled in order, so once a later write is seen every + // event for earlier operations has been delivered. + let sentinels = 0; + const settle = async () => { + const sentinel = path.join(root, `sentinel-${sentinels++}`); + await writeFile(sentinel, "x"); + await waitFor(() => saw("create", sentinel), sentinel); + }; + return { events, saw, settle }; +} + +describe.skipIf(process.platform !== "linux")("directory watch backend", () => { + test("watches directories only", async () => { + const root = await makeRoot(); + await mkdir(path.join(root, "a", "b"), { recursive: true }); + for (let i = 0; i < 20; i++) { + await writeFile(path.join(root, "a", `f${i}`), "x"); + } + const before = inotifyWatchCount(); + await attach(root); + expect(inotifyWatchCount() - before).toBe(3); + }); + + test("reports the contents of a directory moved away as deleted", async () => { + const root = await makeRoot(); + const outside = await makeRoot(); + await mkdir(path.join(root, "d", "e"), { recursive: true }); + await writeFile(path.join(root, "d", "e", "f"), "x"); + const { events, saw, settle } = await attach(root); + + await rename(path.join(root, "d"), path.join(outside, "d")); + await waitFor(() => saw("delete", path.join(root, "d", "e", "f")), "f"); + expect(saw("delete", path.join(root, "d", "e"))).toBe(true); + expect(saw("delete", path.join(root, "d"))).toBe(true); + + events.length = 0; + await writeFile(path.join(outside, "d", "e", "f"), "y"); + await settle(); + expect(events.filter((e) => !e.path.includes("sentinel"))).toEqual([]); + }); + + test("keeps watching a directory moved within the tree", async () => { + const root = await makeRoot(); + await mkdir(path.join(root, "d", "e"), { recursive: true }); + const { saw } = await attach(root); + + await rename(path.join(root, "d"), path.join(root, "m")); + await waitFor(() => saw("create", path.join(root, "m", "e")), "moved"); + const file = path.join(root, "m", "e", "f"); + await writeFile(file, "x"); + await waitFor(() => saw("create", file), "write after move"); + }); + + test("watches a directory replaced at the same path", async () => { + const root = await makeRoot(); + await mkdir(path.join(root, "d")); + await mkdir(path.join(root, "replacement")); + const { saw } = await attach(root); + + await rename(path.join(root, "replacement"), path.join(root, "d")); + const file = path.join(root, "d", "f"); + await writeFile(file, "x"); + await waitFor(() => saw("create", file), "create in replacement"); + await writeFile(file, "longer"); + await waitFor(() => saw("update", file), "update in replacement"); + }); + + test("follows a file replaced by a directory and back", async () => { + const root = await makeRoot(); + const entry = path.join(root, "x"); + await writeFile(entry, "x"); + const { saw, events } = await attach(root); + + await rm(entry); + await waitFor(() => saw("delete", entry), "file gone"); + await outsideBunMergeWindow(); + await mkdir(entry); + await writeFile(path.join(entry, "inner"), "x"); + await waitFor(() => saw("create", path.join(entry, "inner")), "inner"); + + events.length = 0; + await rm(entry, { recursive: true }); + await waitFor(() => saw("delete", path.join(entry, "inner")), "inner gone"); + await outsideBunMergeWindow(); + await writeFile(entry, "file again"); + await waitFor(() => saw("create", entry), "file again"); + await writeFile(entry, "updated"); + await waitFor(() => saw("update", entry), "file updated"); + }); + + test("does not follow symlinks to directories", async () => { + const root = await makeRoot(); + const outside = await makeRoot(); + const link = path.join(root, "link"); + const { saw, events, settle } = await attach(root); + + await symlink(outside, link); + await waitFor(() => saw("create", link), "link"); + await writeFile(path.join(outside, "f"), "x"); + await settle(); + expect(events.some((e) => e.path.startsWith(`${link}/`))).toBe(false); + }); + + test("reports a child named like its directory", async () => { + const root = await makeRoot(); + const file = path.join(root, "cache", "cache"); + await mkdir(path.dirname(file)); + await writeFile(file, "x"); + const { saw } = await attach(root); + + await writeFile(file, "longer"); + await waitFor(() => saw("update", file), "update"); + await rm(file); + await waitFor(() => saw("delete", file), "delete"); + }); + + test("an attach aborted mid-crawl rejects and leaves nothing watched", async () => { + const root = await makeRoot(); + for (let i = 0; i < 200; i++) { + await mkdir(path.join(root, `d${i}`, "e"), { recursive: true }); + } + const before = inotifyWatchCount(); + const controller = new AbortController(); + const attaching = directoryWatchBackend.subscribe({ + rootPath: root, + ignore: [], + generation: 1, + signal: controller.signal, + onEvents: () => {}, + onError: () => {}, + }); + let settled = false; + attaching.then( + (subscription) => { + settled = true; + cleanups.push(() => subscription.unsubscribe()); + }, + () => (settled = true), + ); + while (!settled && inotifyWatchCount() - before < 5) { + await new Promise((resolve) => setImmediate(resolve)); + } + expect(settled).toBe(false); + controller.abort(); + await expect(attaching).rejects.toThrow(); + expect(inotifyWatchCount()).toBe(before); + }); +}); diff --git a/packages/workspace-fs/src/watch-backend/directory-backend.ts b/packages/workspace-fs/src/watch-backend/directory-backend.ts new file mode 100644 index 00000000000..6e52a0d3b74 --- /dev/null +++ b/packages/workspace-fs/src/watch-backend/directory-backend.ts @@ -0,0 +1,355 @@ +import { type FSWatcher, type Stats, watch } from "node:fs"; +import { lstat, opendir } from "node:fs/promises"; +import path from "node:path"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { createIgnoreMatcher } from "./ignore-matcher"; +import type { + NativeWatchBackend, + NativeWatchEvent, + NativeWatchRequest, + NativeWatchSubscription, +} from "./types"; + +type EntryKind = "file" | "dir"; + +interface DirectoryRecord { + dev: number; + ino: number; + watcher: FSWatcher; + children: Map; +} + +const ABSENT = new Set(["ENOENT", "ENOTDIR"]); +const SKIPPED = new Set([...ABSENT, "EACCES", "EPERM"]); + +function isSkipped(error: unknown): boolean { + return SKIPPED.has((error as NodeJS.ErrnoException | null)?.code ?? ""); +} + +function isAbsent(error: unknown): boolean { + return ABSENT.has((error as NodeJS.ErrnoException | null)?.code ?? ""); +} + +/** + * One inotify watch per directory: a directory's watch already reports + * writes, attribute changes, creates, deletes and renames of its children, + * so files never get a watch of their own. Callbacks only queue the path they + * name; one queue reconciles each path against `lstat` and the recorded + * children, which is also how create is told apart from update. + * + * Writes made through a hard link outside the watched tree are not seen. + */ +class DirectoryWatch implements NativeWatchSubscription { + private readonly directories = new Map(); + private readonly queue = new Set(); + /** Directories whose own watch reported an event about the directory itself. */ + private readonly reopen = new Set(); + private readonly isIgnored: ReturnType; + private pendingEvents: NativeWatchEvent[] = []; + private draining = false; + private attachError: unknown; + private attached = false; + private closed = false; + + constructor(private readonly request: NativeWatchRequest) { + this.isIgnored = createIgnoreMatcher(request.rootPath, request.ignore); + } + + async attach(): Promise { + const { rootPath, signal } = this.request; + signal?.throwIfAborted(); + const onAbort = () => void this.unsubscribe(); + signal?.addEventListener("abort", onAbort, { once: true }); + try { + await this.addDirectory(rootPath, false); + // Settle what changed during the crawl; a steady stream of later + // changes must not hold up the attach, so those drain afterwards. + await this.drain(this.queue.size); + signal?.throwIfAborted(); + if (this.attachError !== undefined) throw this.attachError; + if (this.closed) throw new Error("Watch closed during attach"); + if (!this.directories.has(rootPath)) { + throw new Error(`Cannot watch path: ${rootPath}`); + } + this.attached = true; + if (this.queue.size > 0) void this.drainInBackground(); + } catch (error) { + await this.unsubscribe(); + throw error; + } finally { + signal?.removeEventListener("abort", onAbort); + } + } + + async unsubscribe(): Promise { + this.closed = true; + this.queue.clear(); + this.reopen.clear(); + this.pendingEvents = []; + for (const record of this.directories.values()) record.watcher.close(); + this.directories.clear(); + } + + /** Losing coverage fails an attach; once attached it is only reported. */ + private fail(error: unknown): void { + if (!this.attached) throw error; + this.request.onError(error); + } + + private emit(type: NativeWatchEvent["type"], target: string): void { + this.pendingEvents.push({ type, path: target }); + } + + private flush(): void { + if (this.closed || this.pendingEvents.length === 0) return; + const events = this.pendingEvents; + this.pendingEvents = []; + this.request.onEvents(events); + } + + private enqueue(target: string): void { + if (this.closed) return; + this.queue.add(target); + if (this.attached && !this.draining) void this.drainInBackground(); + } + + private async drainInBackground(): Promise { + this.draining = true; + try { + await this.drain(); + } catch (error) { + this.request.onError(error); + } finally { + this.draining = false; + } + if (!this.closed && this.queue.size > 0) void this.drainInBackground(); + } + + private async drain(limit = Number.POSITIVE_INFINITY): Promise { + // Let the rest of the inotify read batch join the queue first. + await nextTurn(); + for (let n = 0; n < limit && !this.closed && this.queue.size > 0; n++) { + const target = this.queue.values().next().value as string; + this.queue.delete(target); + await this.reconcile(target); + this.flush(); + } + } + + private watchDirectory(directory: string): FSWatcher { + const watcher: FSWatcher = watch(directory, (type, filename) => { + if (this.directories.get(directory)?.watcher !== watcher) return; + // libuv names an event on the watched directory itself after its + // basename, which a child can share; treat it as both. Only a + // `rename` (deleted, moved, or watch removed) can end the watch. + const name = filename?.toString(); + if (name !== undefined) this.enqueue(path.join(directory, name)); + if ( + name === undefined || + (type === "rename" && name === path.basename(directory)) + ) { + this.reopen.add(directory); + this.enqueue(directory); + } + }); + watcher.on("error", (error) => { + if (this.directories.get(directory)?.watcher !== watcher) return; + if (this.attached) this.request.onError(error); + else this.attachError ??= error; + this.removeDirectory(directory, true); + this.enqueue(directory); + }); + return watcher; + } + + /** The directory's included entries, or undefined if it cannot be listed. */ + private async list( + directory: string, + ): Promise | undefined> { + const entries = new Map(); + try { + for await (const entry of await opendir(directory)) { + if (this.closed) return; + const child = path.join(directory, entry.name); + let kind: EntryKind = entry.isDirectory() ? "dir" : "file"; + if ( + !entry.isDirectory() && + !entry.isFile() && + !entry.isSymbolicLink() + ) { + try { + kind = (await lstat(child)).isDirectory() ? "dir" : "file"; + } catch (error) { + if (isSkipped(error)) continue; + throw error; + } + } + if (!this.isIgnored(child, kind === "dir")) + entries.set(entry.name, kind); + } + } catch (error) { + if (!isSkipped(error)) this.fail(error); + return; + } + return entries; + } + + /** + * Watches `directory` before listing it, so a change made while it is + * listed reaches the queue and is reconciled afterwards. + */ + private async addDirectory(directory: string, emit: boolean): Promise { + if (this.closed || this.directories.has(directory)) return; + let stats: Stats; + try { + stats = await lstat(directory); + } catch (error) { + if (!isSkipped(error)) this.fail(error); + return; + } + if ( + this.closed || + this.directories.has(directory) || + !stats.isDirectory() + ) { + return; + } + let watcher: FSWatcher; + try { + watcher = this.watchDirectory(directory); + } catch (error) { + if (!isSkipped(error)) this.fail(error); + return; + } + const record: DirectoryRecord = { + dev: stats.dev, + ino: stats.ino, + watcher, + children: new Map(), + }; + this.directories.set(directory, record); + + const entries = await this.list(directory); + if (!entries || this.directories.get(directory) !== record) return; + for (const [name, kind] of entries) { + record.children.set(name, kind); + if (emit) this.emit("create", path.join(directory, name)); + } + for (const [name, kind] of entries) { + if (kind !== "dir") continue; + if (this.directories.get(directory) !== record) return; + await this.addDirectory(path.join(directory, name), emit); + } + } + + /** Forgets `directory` and everything recorded below it. */ + private removeDirectory(directory: string, emit: boolean): void { + const record = this.directories.get(directory); + if (!record) return; + this.directories.delete(directory); + this.reopen.delete(directory); + record.watcher.close(); + for (const [name, kind] of record.children) { + const child = path.join(directory, name); + if (kind === "dir") this.removeDirectory(child, emit); + if (emit) this.emit("delete", child); + } + } + + /** + * Replaces a directory's watch, which an event about the directory itself + * may have ended, and queues every entry that changed meanwhile. + */ + private async rewatch( + directory: string, + record: DirectoryRecord, + ): Promise { + let watcher: FSWatcher; + try { + watcher = this.watchDirectory(directory); + } catch (error) { + if (!isAbsent(error)) this.request.onError(error); + return; + } + record.watcher.close(); + record.watcher = watcher; + const entries = await this.list(directory); + if (!entries || this.directories.get(directory) !== record) return; + for (const [name, kind] of record.children) { + if (entries.get(name) !== kind) this.enqueue(path.join(directory, name)); + } + for (const name of entries.keys()) { + if (!record.children.has(name)) this.enqueue(path.join(directory, name)); + } + } + + private async reconcile(target: string): Promise { + const rewatch = this.reopen.delete(target); + const isRoot = target === this.request.rootPath; + const parentPath = path.dirname(target); + const parent = isRoot ? undefined : this.directories.get(parentPath); + if (!isRoot && !parent) return; + + let stats: Stats | undefined; + try { + stats = await lstat(target); + } catch (error) { + if (!isAbsent(error)) { + this.request.onError(error); + return; + } + } + if (this.closed) return; + if (!isRoot && this.directories.get(parentPath) !== parent) return; + + let kind: EntryKind | undefined = + stats === undefined ? undefined : stats.isDirectory() ? "dir" : "file"; + if (kind && !isRoot && this.isIgnored(target, kind === "dir")) { + kind = undefined; + } + const record = this.directories.get(target); + if ( + record && + stats && + kind === "dir" && + record.dev === stats.dev && + record.ino === stats.ino + ) { + if (rewatch) await this.rewatch(target, record); + return; + } + + if (isRoot) { + this.removeDirectory(target, kind !== undefined); + if (kind === "dir") await this.addDirectory(target, true); + else this.emit("delete", target); + return; + } + if (!parent) return; + + const name = path.basename(target); + const known = parent.children.get(name); + if (known === "file" && kind === "file") { + this.emit("update", target); + return; + } + if (known !== undefined) { + if (known === "dir") this.removeDirectory(target, true); + parent.children.delete(name); + this.emit("delete", target); + } + if (kind === undefined) return; + parent.children.set(name, kind); + this.emit("create", target); + if (kind === "dir") await this.addDirectory(target, true); + } +} + +export const directoryWatchBackend: NativeWatchBackend = { + name: "directory", + async subscribe(request) { + const subscription = new DirectoryWatch(request); + await subscription.attach(); + return subscription; + }, +}; diff --git a/packages/workspace-fs/src/watch-backend/chokidar-crawl.bench.ts b/packages/workspace-fs/src/watch-backend/directory-crawl.bench.ts similarity index 95% rename from packages/workspace-fs/src/watch-backend/chokidar-crawl.bench.ts rename to packages/workspace-fs/src/watch-backend/directory-crawl.bench.ts index ebadef0392b..c6f5c6ce6f3 100644 --- a/packages/workspace-fs/src/watch-backend/chokidar-crawl.bench.ts +++ b/packages/workspace-fs/src/watch-backend/directory-crawl.bench.ts @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { monitorEventLoopDelay, performance } from "node:perf_hooks"; import { setTimeout as delay } from "node:timers/promises"; -import { chokidarWatchBackend } from "./chokidar-backend"; +import { directoryWatchBackend } from "./directory-backend"; import type { NativeWatchSubscription } from "./types"; const roots = Number(process.argv[2] ?? 4); @@ -14,7 +14,7 @@ if (![1, 4].includes(roots) || ![1, 4].includes(concurrency)) { const packageCount = 100; const visibleFilesPerPackage = 40; const ignoredFilesPerDirectory = 8; -const fixture = await mkdtemp(path.join(tmpdir(), "chokidar-crawl-")); +const fixture = await mkdtemp(path.join(tmpdir(), "directory-crawl-")); const subscriptions: NativeWatchSubscription[] = []; const deadline = setTimeout(() => { console.error("Benchmark exceeded 45 seconds"); @@ -73,7 +73,7 @@ try { for (let offset = 0; offset < roots; offset += concurrency) { await Promise.all( rootPaths.slice(offset, offset + concurrency).map(async (rootPath) => { - const subscription = await chokidarWatchBackend.subscribe({ + const subscription = await directoryWatchBackend.subscribe({ rootPath, ignore, generation: 1, diff --git a/packages/workspace-fs/src/watch-backend/index.ts b/packages/workspace-fs/src/watch-backend/index.ts index 030ac251587..d3d4b6fdf94 100644 --- a/packages/workspace-fs/src/watch-backend/index.ts +++ b/packages/workspace-fs/src/watch-backend/index.ts @@ -1,8 +1,8 @@ -import { chokidarWatchBackend } from "./chokidar-backend"; +import { directoryWatchBackend } from "./directory-backend"; import { parcelWatchBackend } from "./parcel-backend"; import type { NativeWatchBackend } from "./types"; -export { chokidarWatchBackend } from "./chokidar-backend"; +export { directoryWatchBackend } from "./directory-backend"; export { createIgnoreMatcher } from "./ignore-matcher"; export { parcelWatchBackend } from "./parcel-backend"; export type { @@ -20,6 +20,6 @@ export type { */ export function defaultWatchBackend(): NativeWatchBackend { return process.platform === "linux" - ? chokidarWatchBackend + ? directoryWatchBackend : parcelWatchBackend; } diff --git a/packages/workspace-fs/src/watch-backend/types.ts b/packages/workspace-fs/src/watch-backend/types.ts index 22ce4dfa7f3..6d7458c3f52 100644 --- a/packages/workspace-fs/src/watch-backend/types.ts +++ b/packages/workspace-fs/src/watch-backend/types.ts @@ -14,6 +14,8 @@ export interface NativeWatchRequest { ignore: string[]; /** Unique per attach of one watcher; grows on every re-attach. */ generation: number; + /** Aborts an attach still in progress. */ + signal?: AbortSignal; onEvents(events: NativeWatchEvent[]): void; onError(error: unknown): void; } diff --git a/packages/workspace-fs/src/watch-backend/watch-backend.test.ts b/packages/workspace-fs/src/watch-backend/watch-backend.test.ts index f4a17a04b56..4ac992e36a2 100644 --- a/packages/workspace-fs/src/watch-backend/watch-backend.test.ts +++ b/packages/workspace-fs/src/watch-backend/watch-backend.test.ts @@ -3,8 +3,8 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { - chokidarWatchBackend, createIgnoreMatcher, + directoryWatchBackend, type NativeWatchBackend, type NativeWatchEvent, parcelWatchBackend, @@ -52,7 +52,7 @@ async function attach( return { events, errors, saw }; } -for (const backend of [parcelWatchBackend, chokidarWatchBackend]) { +for (const backend of [parcelWatchBackend, directoryWatchBackend]) { describe(`${backend.name} watch backend`, () => { test("reports create, update and delete with absolute paths", async () => { const root = await makeRoot(); diff --git a/packages/workspace-fs/src/watch-pathtypes-growth.test.ts b/packages/workspace-fs/src/watch-pathtypes-growth.test.ts index 47980e44654..570f0779e0d 100644 --- a/packages/workspace-fs/src/watch-pathtypes-growth.test.ts +++ b/packages/workspace-fs/src/watch-pathtypes-growth.test.ts @@ -217,9 +217,9 @@ describe("FsWatcherManager.pathTypes — monotonic growth", () => { const rootPath = await createTempRoot(); tempRoots.push(rootPath); - // A real backend does not deliver events in write order (chokidar on - // Linux emits per file after async stats, and adds late `change`s), so - // the LRU order is driven here instead. + // A real backend does not deliver events in write order (the Linux + // backend emits after an async lstat per path), so the LRU order is + // driven here instead. let emitNative: ((events: NativeWatchEvent[]) => void) | undefined; const backend: NativeWatchBackend = { name: "scripted", diff --git a/packages/workspace-fs/src/watch.ts b/packages/workspace-fs/src/watch.ts index bb52ec4b2b5..296559d8d87 100644 --- a/packages/workspace-fs/src/watch.ts +++ b/packages/workspace-fs/src/watch.ts @@ -669,6 +669,7 @@ export class FsWatcherManager { rootPath: realPath, ignore, generation, + signal: state.controller.signal, // A late callback from a superseded stream (suspended or replaced by // recovery) describes a dead tree. onError: (error) => {