Don't resolve symlinks when requiring
Currently, Node.js resolves symlinks when requiring and then uses the real location of the package/file as its __filename and __dirname instead of the symlinked one.
This is a problem because symlinked modules don't act the same as locally copied modules.
For example:
app
index.js //require("dep1")
node_modules
dep1
index.js //require("dep2")
dep2
index.js //console.log('fun!'):
works, but
app
index.js //require("dep1")
node_modules
dep1 -> ../../dep1
dep2
index.js
dep1
index.js //require("dep2")
does not, because dep1 does not act like it's located in the node_modules directory of module and thus cannot find dep2.
This is especially a problem when one wants to symlink modules that have peer-dependencies.
Therefore, I suggest changing the behavior to no longer resolve symlinks. What do you think?
Let's take a step back just a bit. Before considering reverting anything or debating whether or not this breaks a locked API, we should work on finding a solution that addresses both issues. As I understand it so far (please correct me if I'm wrong) the new behavior does not stop the alternative package managers from operating, just makes their operation less efficient? Is that correct?
If I'm reading the the above conversation correctly, this change renders a performance optimization used by some of the alternative package managers ineffective because it causes the module to be cached under according to the symlink rather than the realpath, leading to a situation where the same module code can be loaded multiple times if the symlinks are different? Is that also correct?
Assuming that is the situation, it would seem to me that the real problem is that we are inappropriately conflating module identity with lookup paths. A proper solution should seek to decouple the lookup path from the cache key.
@dlongley ... can I ask that you (and whomever else you've been working on this) look into finding a solution to the identity issue that also preserves the fix to problem this issue was originally looking to solve.
There is another issue here: it would appear that we had zero tests verifying the old behavior and no coverage of alternative package management strategies in our ecosystem smoke-testing. @TheAlphaNerd, can you please see about adding some of these alternative package managers to the citgm tests?
@jasnell,
If I'm reading the the above conversation correctly, this change renders a performance optimization used by some of the alternative package managers ineffective because it causes the module to be cached under according to the symlink rather than the realpath, leading to a situation where the same module code can be loaded multiple times if the symlinks are different? Is that also correct?
If a symlink is different, a different module instance is assumed, yes.
Assuming that is the situation, it would seem to me that the real problem is that we are inappropriately conflating module identity with lookup paths. A proper solution should seek to decouple the lookup path from the cache key.
Well, for peer dependencies, you want a different in-memory instance of a module if the symlink path is different. If you have the same instance in memory, you could potentially erroneously communicate with two different frameworks (with the same in memory module) if your application happens to load two different versions of the same framework. I do think this is perhaps an unlikely use case, but it would be unexpected, unfixable behavior if you did encounter it. Specifying a different path to a module is a way to establish a clear boundary. Perhaps a cache could still be used but avoid instantiating the code.
In any case, I am +1 for finding a solution for both issues.
I take a look at lib/module.js#L388, may be we can change the Module._cache key to realpath and solve lose cache problem.
var filename = Module._resolveFilename(request, parent, isMain);
var cacheKey = fs.realpathSync(filename);
var cachedModule = Module._cache[cacheKey];
if (cachedModule) {
return cachedModule.exports;
}
The node 6.0.0 behavior is completely consistent with the documented behavior of require:
https://nodejs.org/api/modules.html#modules_module_caching_caveats
Module Caching Caveats#
Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.
Additionally, on case-insensitive file systems or operating systems, different resolved filenames can point to the same file, but the cache will still treat them as different modules and will reload the file multiple times. For example, require('./foo') and require('./FOO') return two different objects, irrespective of whether or not ./foo and ./FOO are the same file.
@kzc ... at this point what would likely be more productive would be to say that there is some ambiguity in the docs as to what is or is not the expected behavior, and the module system is a currently a bit inconsistent with itself in several regards. Rather than dwell on that, we have one specific problem to address: how can we preserve the corrected behavior this change implements while also keeping the alternative package managers from having to suffer a performance hit. If at all possible, let's focus the conversation on that without dwelling any longer on what the docs happen to say (or not say)
I think if you're not using peer dependencies (or that is, modules that are identified by a path located up path in your parent), you should not assume that you'll be getting the same copy of a particular module in memory. The good news is -- if you do want modules to share the same instance of a module in memory, you can be guaranteed to if you place that shared module (or a symlink to it) in your parent's node_modules path. I'm not familiar with alternative node module installers -- can they be reworked to take advantage of this guarantee?
I am very for solving the cache issue and can devote some time into coming up with a solution.
@fengmk2 unfortunately, caching on the realpath will just introduce more issues here -- say you want to have two different versions of a framework in your app (that still share the same name). In v6, symlinking to each framework directory accomplishes that and will load each in as separate, but if we cache on realpath then one of the projects is going to load in and supersede the other in a kind of non deterministic way.
@jasnell In theory, there are ways how package managers could work around the problem:
On installation, modify the package.json's "main" property, to point to a newly created file that's in the same directory as package.json and contains:
module.exports = require("/absolute/path/to/module");
It's not pretty, but I think it could work.
but if we cache on realpath then one of the projects is going to load in an already cached and initialized object.
@lamara I think same realpath should be require once only.
Here's an attempt to pin down the semantics underlying the problem here:
Modules need to be uniquely identified.
Alternative package managers are essentially indicating that the same package.json version of a module should indicate the uniqueness of a module. I'm only guessing, but I would expect that they are written with this guarantee but implement it by exploiting the old realpath behavior. I assume they put a module on disk somewhere, and for that particular version of the module, they always symlink to that one instance on disk.
Now, that kind of uniqueness isn't explicitly true in node; it never has been. The reason is that node doesn't actually know about the version field in package.json. In node, modules are actually uniquely identified by path. This is also a simple way to reason about modules and how they'll be loaded -- the simplest identifiers we have to work with are file names. The documentation also indicates that loading a module using a different path should give you a different module.
In any case, in order to implement the kind of uniqueness alternative package managers desired, an undocumented (and unexpected) implementation detail, namely, the use of realpath to establish module identifiers, was exploited. To be clear, the child paths searched when loading modules is documented by example -- but this behavior isn't actually reliant upon the use of realpath which is misleading in the documentation. This same loading behavior persists when realpath is not used. To reiterate @jasnell's point -- clearly the documentation is inconsistent and needs work.
Now, symlinks are files in their own right. They are a filesystem abstraction that allow you to create new identifiers but, when read, actually pull data from elsewhere. In keeping with the mechanism used to identify modules, a symlink identifies a new module, even if the contents of that module on disk is the same. This ensures that you get a fresh copy of that module if it hasn't loaded yet. Furthermore, by preserving them as identifiers, the lookup path for modules that are in the parent path functions in an expected fashion now. Previously, modules that you had specifically indicated in your project would not be loaded, but rather, undesirable modules from elsewhere on disk would load.
Is it possible for alternative package managers to similarly exploit this now consistent, expected behavior to achieve the kind of uniquness that they want? Can you find ways to place modules in parent paths in an appropriate fashion? npm v3 takes a similar approach to ensure versions of the same module are only installed once and instantiated once.
I should also mention -- that the form of uniqueness put forth by alternative package managers (if I'm correct about it), won't actually work in some cases for users of peer dependencies, if they are employing more than one version of a framework in their application. So if that use case is to be supported, a change would be needed.
Author of ied here (from which pnpm was derived AFAIK)
Alternative package managers are essentially indicating that the same package.json version of a module should indicate the uniqueness of a module.
No, the shasum of the package is being used in order to uniquely identify it. That being said, the way the package manager itself identifies those modules is irrelevant. What is relevant is that fact that those are being used in order to construct the path names from which the actual (as in "no symlinks") are being linked.
I'm only guessing, but I would expect that they are written with this guarantee but implement it by exploiting the old realpath behavior.
Correct. The fact that Node follows the realpath was exploited. I would argue that's the way it is being documented:
Since Node.js looks up the realpath of any modules it loads (that is, resolves symlinks), and then looks for their dependencies in the node_modules folders as described here [...]
I assume they put a module on disk somewhere, and for that particular version of the module, they always symlink to that one instance on disk.
Correct as well. If a depends on b, a symlink will be created in a/node_modules/b -> /some/where/b.
Now, that kind of uniqueness isn't explicitly true in node; it never has been.
I would argue it was, since
- the API is locked
- the Module cache has always been implemented that way
- it's pretty common to require singletons assuming that the same package will be returned
The reason is that node doesn't actually know about the version field in package.json. In node, modules are actually uniquely identified by path.
Which is perfectly fine. Node doesn't (nor should it) care about a specific version of the package. Instead it should use the real path (like it did before). That way uniqueness can be guaranteed without sacrificing performance due to redundant modules.
In any case, in order to implement the kind of uniqueness alternative package managers desired, an undocumented (and unexpected) implementation detail, namely, the use of realpath to establish module identifiers, was exploited.
To be clear, the child paths searched when loading modules is documented by example -- but this behavior isn't actually reliant upon the use of realpath which is misleading in the documentation. This same loading behavior persists when realpath is not used. To reiterate @jasnell's point -- clearly the documentation is inconsistent and needs work.
Agreed. Again, even if it wasn't documented, the API is locked.
Is it possible for alternative package managers to similarly exploit this now consistent, expected behavior to achieve the kind of uniquness that they want? Can you find ways to place modules in parent paths in an appropriate fashion? npm v3 takes a similar approach to ensure versions of the same module are only installed once and instantiated once.
Unfortunately not. We need to be able to explicitly reference packages and get the exact same module instance back. Otherwise the only way to implement circular dependencies is by flattening trees and basically doing what npm3 does.
Let's make this a bit more concrete. Suppose we have the following...
myApp
/index.js
/node_modules
/foo --> ../../modules/foo
/bar (@version=1)
/baz
/node_modules
/foo --> ../../../../modules/foo
/bar (@version=2)
modules
/foo
require('bar')
/bar (@version=3)
Suppose the the foo module exports the following, making the assumption that bar is a peer-dependency:
const bar = require('bar');
module.exports = bar;
Now suppose that our three different versions of bar each do (in order of version)
myApp/node_modules/bar/index.js
module.exports = 1;
myApp/node_modules/baz/node_modules/bar/index.js
module.exports = 2;
modules/bar/index.js
module.exports = 3;
And baz does the following:
module.exports = require('foo');
What is the expected result when running node myApp/index.js?
const foo = require('foo');
const baz = require('baz');
console.log(foo);
console.log(baz);
Under v5.11.0, the behavior is for an error to be thrown because bar cannot be resolved relative to the realpath of foo:
bash-3.2$ node -v
v5.11.0
bash-3.2$ node index
module.js:341
throw err;
^
Error: Cannot find module 'bar'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/james/tmp/symlink/modules/foo/index.js:3:13)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
bash-3.2$
Note that v5.11.0 throws even with /modules/bar existing at the same level as /modules/foo.
The behavior in master (and v6) with this change applied is for foo to find the version of bar that is appropriate for it:
bash-3.2$ ~/node/main/node/node -v
v7.0.0-pre
bash-3.2$ ~/node/main/node/node index
1
2
bash-3.2$
This has the side effect that despite foo being pulled from the same location on disk, it maintains different internal state (one instance uses bar version 1, the other uses bar version 2, which, based on the way the symlinks are set up, is exactly what one would expect it to do. The two symlink'd instances of foo are treated as if they were not symlinks at all and the peer dependencies are resolved relative to their location in the relevant node_module paths.
@jasnell,
This has the side effect that despite foo being pulled from the same location on disk, it maintains different internal state (one instance uses bar version 1, the other uses bar version 2, which, based on the way the symlinks are set up, is exactly what one would expect it to do. The two symlink'd instances of foo are treated as if they were not symlinks at all and the peer dependencies are resolved relative to their location in the relevant node_module paths.
+1, yes, this is exactly the expected behavior and what node 6.x does. Thinking from the perspective of the person that set up myApp, that's just the output I'd want to see.
@VanCoding
module.exports = require("/absolute/path/to/module"); It's not pretty, but I think it could work.
Yes this could work and lerna use this method. Maybe alternative package managers could also use this method, I'm not sure...
Before we resort to "not pretty" hacks ;-) ... let's see if there's a better solution to be found.
@alexanderGugel ... I note that you gave my comment https://github.com/nodejs/node/issues/3402#issuecomment-215146463 a thumbs down, care to explain your thoughts further?
@jasnell I do not agree with the premise that that's the expected behaviour. I'm currently putting together an example as well.
I make a pr https://github.com/nodejs/node/pull/6425 to let require cache back.
@jasnell,
I haven't put much thought into this, so just throwing the idea out there ...
One potential way forward is to change the caching behavior based on whether a module is loaded from a child node_modules directory, or from somewhere up the parent path. The repercussions of this would have to be thought through. However, I'm not a fan, in general, of anything more complex than uniquely identifying modules by path, because it gets difficult to reason about.