vfs: integrate with CJS and ESM module loaders#63653
Conversation
|
Review requested:
|
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #63653 +/- ##
==========================================
- Coverage 92.04% 90.23% -1.81%
==========================================
Files 381 741 +360
Lines 169208 242261 +73053
Branches 25926 45640 +19714
==========================================
+ Hits 155746 218611 +62865
- Misses 13174 15197 +2023
- Partials 288 8453 +8165
🚀 New features to boost your workflow:
|
|
@joyeecheung take a look, should be easier to review. |
Restore the "DO NOT depend on the patchability" warnings in esm/load.js and esm/resolve.js that were dropped along with the fs imports. The warning still applies; it now also points at node:vfs as one of the formal hook mechanisms callers should reach for instead. Addresses review feedback from @jsumners-nr in nodejs#63653
6321e08 to
51b033a
Compare
joyeecheung
left a comment
There was a problem hiding this comment.
A design question recently occurred to me: have we explored the versioning of the mounting?
what do you mean? You mean multiple vfs layers on top of each other? |
For the stacks to have some kind of version number/ID to identify the current status? BTW I just noticed that there's no mention of |
I did purge them when doing the splitting; I forgot to bring them back. I'll add them to this PR. |
No but we totally should. |
Each VirtualFileSystem now exposes a per-process monotonically increasing `layerId`, assigned at construction. The id is stable across mount/unmount cycles for the lifetime of the instance and surfaces in: - debug() output for register / deregister so the layer stack is visible when NODE_DEBUG=vfs is enabled; - the overlap ERR_INVALID_STATE message, which now names the layer ids of the conflicting mounts. The id is the building block for tagging cache entries with the owning VFS, which a follow-up will use to replace the global loader-cache flush in deregisterVFS with a scoped purge. Refs: nodejs#63653 Signed-off-by: Matteo Collina <hello@matteocollina.com>
51b033a to
294a19c
Compare
Replace the global loader-cache flush in deregisterVFS with a scope-purge that only drops entries owned by the unmounting VFS. Per-layer ownership is determined two ways: - For CJS-style filename-keyed caches (Module._cache, Module._pathCache, the CJS stat cache, the helpers.js realpath cache, and the package.json caches) entries are filtered with `vfs.shouldHandle(filename)`. __filename stays a clean absolute path so user code that does `path.dirname(__filename)` or similar is unaffected. - For the ESM cascaded loader's loadCache, entries are tagged at resolve time: when finalizeResolution() detects the resolved path is VFS-owned (via the new loaderGetLayerForPath hook), it appends `?vfs-layer=<id>` to the URL. The tag surfaces in `import.meta.url`, matching the cache-busting pattern used by HMR tooling. On deregister, entries whose URL carries the tag for the unmounting layer are deleted. Multi-mount setups no longer pay the cross-VFS cache-warmup penalty when a single VFS unmounts, and ESM modules loaded from a VFS become reachable for purge instead of leaking forever in the cascaded loader. New helpers exposed for VFS: - cjs/loader.js: clearStatCacheForVFS - helpers.js: purgeRealpathCacheForVFS, loaderGetLayerForPath - package_json_reader.js: purgePackageJSONCacheForVFS Adds test-vfs-scoped-cache-purge covering both the multi-mount isolation and the import.meta.url tag visibility. Refs: nodejs#63653 Signed-off-by: Matteo Collina <hello@matteocollina.com>
|
@joyeecheung PTAL |
75bb5c7 to
99a5a5c
Compare
`mount()` no longer accepts an argument. The user-supplied prefix
served no purpose beyond a cosmetic label - actual layer identity comes
from the per-instance `layerId`, so distinct instances never shared a
mount point even when they passed the same prefix. Removing the
argument eliminates the input validation, the escape check for `..`
segments, and the API-shape doubt about what a "logical prefix" means.
The `layer-` prefix on the layer segment of the mount path is likewise
gone: mount points are now `${os.devNull}/vfs/<id>` (for example
`/dev/null/vfs/0`) instead of `${os.devNull}/vfs/layer-0/<prefix>`.
The parser in `getLayerIdFromPath` simplifies to reading the digit
segment immediately after the VFS root.
Docs, tests and benchmark adapted. The dispatch benchmark still
reports flat per-call latency across 1..10 mounted layers.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
|
@joyeecheung ping. |
This comment was marked as outdated.
This comment was marked as outdated.
There was a problem hiding this comment.
High level direction looks much better and more aligned with https://github.com/nodejs/single-executable/blob/main/docs/virtual-file-system-requirements.md#no-interference-with-valid-paths-in-the-file-system now, thanks, though I think the implementation still leaves quite a bit hard-codes and repeitions that should be cleaned up before landing to avoid taxing future changes to module loading with extra maintenance complexity & divergence..
| * @returns {object|undefined} | ||
| */ | ||
| function loaderReadPackageJSON(jsonPath, isESM, base, specifier) { | ||
| if (readPackageJSONOverride !== null) { |
There was a problem hiding this comment.
Helpers like this look like a lot of maintainance burden - every time someone adds a new binding, they have to update all these, and if they end up updating some internal parameters as part of a semver major change, it can cause another wave of churns for backports. Can you just use a helper to forward them all? Something like
function wrapLoaderMethod(originalFn) {
return function(...args) {
const override = overrideMap.get(originalFn);
if (override) return ReflectApply(override, this, args);
return ReflectApply(originalFn, this, args);
}
}(if a benchmark shows it actually matters for perf we could even switch on originalFn.length and build arity-based dispatches like processTicksAndRejections but I suspect the overhead is negligible for this path in the bigger picture). This would also shrink the diff here quite a bit.
| @@ -174,11 +219,26 @@ class VirtualFileSystem { | |||
| * @returns {boolean} | |||
| */ | |||
| shouldHandle(inputPath) { | |||
There was a problem hiding this comment.
I think this is dead code now?
| const parsed = JSONParse(content); | ||
| return { vfs, pjsonPath, parsed, sentinel: pjsonPath }; | ||
| } catch { | ||
| // SyntaxError or other errors, continue walking |
There was a problem hiding this comment.
This diverges from GetPackageJSON which would throw ERR_INVALID_PACKAGE_CONFIG on the first syntactically malformed package.json instead of keep walking, I think we should at least align with the actual behavior here or otherwise this can introduce very subtle bugs for users that create a tree into VFS and one of the package.json end up corrupted somehow.
What would be even better is to simply split the C++ GetPackageJSON into read + parse, and let the VFS side reuse the parsing logic, that also eliminates the duplication of serializePackageJSON etc and would make use of partial parsing with simdjson (we could technically just read the pacakge.json as buffer and avoid the UTF8 encoding cost too) instead of a wasteful full parse with JSON.parse.
| // mount. Treat that as JS (the caller will surface the real | ||
| // error when it later tries to load source). Propagate every | ||
| // other code (EACCES, ELOOP, etc). | ||
| if (e?.code === 'ENOENT') return 0; // EXTENSIONLESS_FORMAT_JAVASCRIPT |
There was a problem hiding this comment.
The original version normalizes all errors for EXTENSIONLESS_FORMAT_JAVASCRIPT, not just ENOENT.
| if (content && content.length >= 4 && | ||
| content[0] === 0x00 && content[1] === 0x61 && | ||
| content[2] === 0x73 && content[3] === 0x6d) { | ||
| return 1; // EXTENSIONLESS_FORMAT_WASM |
There was a problem hiding this comment.
This shouldn't hard-code and should return internalBinding('constants').EXTENSIONLESS_FORMAT_WASM etc.
| // 7-9: try pkgPath + ./index.ext | ||
| const mainExts = ['', '.js', '.json', '.node', | ||
| '/index.js', '/index.json', '/index.node']; | ||
| const indexExts = ['./index.js', './index.json', './index.node']; |
There was a problem hiding this comment.
Do we need to duplicate all these? It can go out of sync easily. legacyMainResolveExtensions is already (inappropriately) located in esm/resolve.js, I think we can simply share the arrays and do something like
legacyMainResolve(pkgPath, main, base) {
if (findVFS(pkgPath) === null) return undefined;
for (let i = 0; i < legacyMainResolveExtensions.length; i++) {
const shouldResolveByMain = i <= kMaxResolvedByMainIndex; // kResolvedByMainIndexNode
if (shouldResolveByMain && !main) continue;
const prefix = shouldResolveByMain ? main : '';
const candidate = join(pkgPath, prefix + legacyMainResolveExtensions[i]);
if (findVFSForStat(candidate)?.result === 0) return i;
}
const initial = main ? join(pkgPath, main) : join(pkgPath, 'index.js');
throw new ERR_MODULE_NOT_FOUND(initial, base, undefined);
}| StringPrototypeEndsWith(currentDir, '\\node_modules')) { | ||
| break; | ||
| } | ||
| const pjsonPath = join(currentDir, 'package.json'); |
There was a problem hiding this comment.
Since dirname/join preserves the prefix if it's absolute, I think can just do something like if (!vfs.shouldHandleNormalized(currentDir)) break; to save on the repeated normalization in stat/read etc.
| } else { | ||
| filePath = resolved; | ||
| } | ||
| const vfs = findVFS(filePath); |
There was a problem hiding this comment.
Nit: findVFS discards the normalized filePath which is a bit wasteful, if it returns that back we can reuse that in e.g. findVFSPackageJSON.
Co-authored-by: Joyee Cheung <joyeec9h3@gmail.com>
Co-authored-by: Joyee Cheung <joyeec9h3@gmail.com>
`VirtualFileSystem#shouldHandle` had no remaining callers: dispatch
goes through `shouldHandleNormalized` and every code path outside
dispatch was rewritten to `findVFS` after the reserved-namespace
refactor.
Two router.js exports were also unreferenced: `getVfsRoot` (used only
internally by `getNormalizedVfsRoot` and `getLayerRoot`) and the
re-export of `path.isAbsolute` as `isAbsolutePath`. The corresponding
test-vfs-router assertions and the `isAbsolute` local binding on the
`require('path')` destructure go with them.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
This reverts commit a95717a.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
d1d72c3 to
0d5fb61
Compare
|
@joyeecheung done |
Makes
require()andimportresolve files served bynode:vfs. Before this PR, mounted VFS files were only visible throughfs.*; the loaders went straight to the real filesystem.Design
vfs.mount()takes no arguments and returns the reserved absolute mount point of the instance:${os.devNull}/vfs/<layerId>(for example/dev/null/vfs/0).os.devNullis a character device on POSIX and a device-namespace path on Windows; neither can have child filesystem entries, so no real path can ever exist under this root.Everything about ownership is decidable from the path alone:
benchmark/vfs/bench-fs-dispatch.js) reports flat per-call latency across 1..10 mounted layers.realpathSyncof a VFS entry always resolves to another path under the same mount point, so cache entries hidden behind symlinks are captured by the prefix scan.file:URLs under the mount point;import(import.meta.resolve(x))re-hits the same module job.Two instances mounting simultaneously never collide (each gets its own
layer-<id>segment), so there is no overlap validation and no ordering hazard between mounts.Loader integration
Toggleable wrappers in the loaders. Null fast-path when no VFS is mounted; otherwise the VFS answers
stat/readFile/realpath/legacyMainResolve/getFormatOfExtensionlessFileand the fourpackage.jsonC++-binding calls.Module identity follows the path:
__filename,module.filename, andimport.meta.urlare the plain absolute path (orfile:URL) of the module under the mount point — no synthetic decorations.Review guide
Suggested reading order:
lib/internal/vfs/router.jsgetVfsRoot,getLayerRoot,getLayerIdFromPath.lib/internal/vfs/file_system.jsmount()returns the layer's reserved mount point.lib/internal/vfs/setup.jsfindVFS(O(1) lookup), fs handler, loader overrides with parity tosrc/node_modules.cc/src/node_file.cc, prefix-scan cache purge.lib/internal/modules/helpers.jsloader*wrappers,setLoaderFsOverrides/setLoaderPackageOverrides,purgeRealpathCacheForPrefix.lib/internal/modules/cjs/loader.jsstat()+ TS read routed through wrappers;purgeModuleCachesForPrefixfor unmount.lib/internal/modules/esm/resolve.jslegacyMainResolve+internalModuleStat+toRealPathrouted. No URL decoration.lib/internal/modules/esm/load.jsgetSourceSyncreads via the wrapper.lib/internal/modules/esm/get_format.jslib/internal/modules/package_json_reader.jspurgePackageJSONCacheForPrefix.lib/fs.jsstatSync/lstatSynchonourthrowIfNoEntry:falseon ENOENT from the VFS handler.doc/api/vfs.mdTests (all gated by
--experimental-vfs):test-vfs-mount,test-vfs-mount-errors,test-vfs-multi-mount,test-vfs-require,test-vfs-import,test-vfs-module-hooks,test-vfs-module-hooks-cleanup,test-vfs-package-json,test-vfs-package-json-cache,test-vfs-invalid-package-json,test-vfs-scoped-cache-purge,test-vfs-layer-id,test-vfs-layer-tag-prefix.Refs
The reserved-namespace design follows the "no interference with valid paths in the file system" requirement from the SEA VFS requirements doc.
Out of scope
SEA + VFS, overlay/stacking of multiple VFS layers under one prefix, migrating the C++
package_configs_cache, broader permission-model integration.