node icon indicating copy to clipboard operation
node copied to clipboard

Don't resolve symlinks when requiring

Open VanCoding opened this issue 11 years ago • 204 comments

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?

VanCoding avatar Oct 16 '15 12:10 VanCoding

After thinking a bit more about this, I really think that the _-prefix approach is the right one. I played around with the @-file idea as well. I think there might also be some confusion about how the currently proposed resolution mechanism works.

@VanCoding @kzc

While I think the solution with the @-files is way better that prefixing symlinks with "_", I still believe we're on the wrong road now.

I again want to point out the following scenario:

/a/b/c/d/e -> /e
/e/f/g/h/j.js
now let's do require('/a/b/c/d/e/f/g/h/j.js');

Currently, that's absolutely no problem, just read the file and that's it.
With your proposal, we'd have to do the following checks first:

isSymlink('/a')
isSymlink('/a/b')
isSymlink('/a/b/c')
isSymlink('/a/b/c/d')
isSymlink('/a/b/c/d/e')
isSymlink('/a/b/c/d/e/f')
isSymlink('/a/b/c/d/e/f/g')
isSymlink('/a/b/c/d/e/f/g/h')
isSymlink('/a/b/c/d/e/f/g/h/j.js')
And then when we've discovered that /a/b/c/d/e is a symlink, we'd also have to check if /a/b/c/d/e@ exists.

This is an interesting scenario. Let's have a look what actually happens.

The easiest way to find out is by adding a couple of debugs to 6460:

diff --git a/lib/module.js b/lib/module.js
index 249b010..67b2aeb 100644
--- a/lib/module.js
+++ b/lib/module.js
@@ -113,6 +113,7 @@ function readPackagePath(filename, exts, isMain) {
 }

 function readFilePath(requestPath, isMain) {
+  debug(`readFilePath ${requestPath}`);
   if (isMain) {
     return fs.realpathSync(requestPath);
   }
@@ -123,6 +124,7 @@ function readFilePath(requestPath, isMain) {
 // resolve to the absolute realpath if running main module,
 // otherwise resolve to absolute while keeping symlinks intact.
 function tryFile(requestPath, isMain) {
+  debug(`tryFile ${requestPath}`);
   const rc = stat(requestPath);
   if (rc === 0) {
     return readFilePath(requestPath, isMain);

Because that's the "expensive" part where we're actually resolving the filename / stating it.

If we now create the directory structure you proposed in your original example, we end up with a tree that looks something like this:

/Users/alex/a
└── b
    └── c
        └── d
            └── e -> /Users/alex/e

4 directories, 0 files
/Users/alex/e
└── f
    └── g
        └── h
            └── j.js

3 directories, 1 file

Now, let's see what actually happens when we require the a file "under" the symlink:

NODE_DEBUG=module ./out/Release/node -e "require('/Users/alex/a/b/c/d/e/f/g/h/j.js')"

Output:

MODULE 93110: Module._load REQUEST vm parent: [eval]
MODULE 93110: load native module vm
MODULE 93110: Module._load REQUEST /Users/alex/a/b/c/d/e/f/g/h/j.js parent: [eval]
MODULE 93110: looking for "/Users/alex/a/b/c/d/e/f/g/h/j.js" in ["/Users/alex/repos/node/node_modules","/Users/alex/repos/node_modules","/Users/alex/node_modules","/Users/node_modules","/Users/alex/.node_modules","/Users/alex/.node_libraries","/Users/alex/repos/node/out/lib/node"]
MODULE 93110: readFilePath /Users/alex/a/b/c/d/e/f/g/h/j.js
MODULE 93110: load "/Users/alex/a/b/c/d/e/f/g/h/j.js" for module "/Users/alex/a/b/c/d/e/f/g/h/j.js"
required j.js

In fact the _ solution is fast, because of the very fact that we do not need to check whether or not an @ file exists.

TL;DR In short, that's simply not the way the module resolution works. Keep in mind that we also never check if a file is a symlink, but instead we resolve its real path.

alexanderGugel avatar Apr 29 '16 16:04 alexanderGugel

@alexanderGugel I'm okay with the _-prefixed symlink scheme. It's simple and easy to reason about what behavior you're getting. I just thought the @-suffix-file proposal or the other variations would make the install tree backwards compatible with older node version behavior as it does not alter the symlink name.

Regarding https://github.com/nodejs/node/issues/3402#issuecomment-215597796

If the symlink points to an absolute path, use the old mechanism, otherwise use the new one.

Could you please clarify the use of "absolute path" in that statement?

Under the '_'-prefix proposal would the following symlink use the new resolution scheme or the old realpath one:

foo ---> /usr/local/foo

kzc avatar Apr 29 '16 17:04 kzc

Here is another idea (conceptually similar to the @kzc's module_realpath proposal)....

Instead of relying on the dynamic behavior of require, we could provide some way to "bootstrap" the require cache, essentially overriding Node's default behavior.

Given an index.js file that looks something like this:

require('a')
require('b')

And a node_modules.json file in the same directory:

{
  "a": "/some/completely/different/path"
}

Now, when running node index.js, Node would read in the node_modules.json file and bootstrap Module._cache with it.

This would provide an easy migration path for use-cases that rely on the old mechanism (the node_modules.json file could easily be generated), while enabling possible performance improvements through some form of static declaration of resolved, required paths (as in "no node_modules path fallback or symlink real path resolving").

This kind of information could be encoded in the package.json as well. But the require strategy would be defined in the package that requires some dependency, rather than in the package.json file of the dependency itself (the package being required).

... just an idea that might be worth investigating (potentially independent of this discussion).

alexanderGugel avatar Apr 29 '16 19:04 alexanderGugel

@kzc

The _-prefix proposal and the absolute path idea are separate.

Under the '_'-prefix proposal would the following symlink use the new resolution scheme or the old realpath one:

foo ---> /usr/local/foo

When using the _-approach, this path would be resolved according to the v6.0.0 mechanism, since the linkname (foo) does not start with an underscore.

If the link would be called _foo, it would be resolved according to the original real-path mechanism.

When using the absolute path solution, this link would be resolved according to the pre-v6.0.0 mechanism (real path).


If the symlink points to an absolute path, use the old mechanism, otherwise use the new one. Could you please clarify the use of "absolute path" in that statement?

Absolute as in path.absolute (starting with / relative to the root of the filesystem).

Absolute: /hello/world Not absolute: hello/world

alexanderGugel avatar Apr 29 '16 19:04 alexanderGugel

foo ---> /usr/local/foo

When using the _-approach, this path would be resolved according to the v6.0.0 mechanism

Thanks for the clarification. Just wanted to verify that the underscore prefix is the sole "decider" of realpath or v6.0.0 module resolution behavior in your _-prefix proposal.

kzc avatar Apr 29 '16 20:04 kzc

@alexanderGugel I think the node_modules.json bootstrap proposal is good for a few reasons:

  1. It is explicit and clear.
  2. It does not alter the symlinks' names.
  3. It will be as performant as the _-prefix proposal.

kzc avatar Apr 29 '16 20:04 kzc

Just kill circular dependencies. All your problems are gone. (except from the whiny abusers of this misfeature).

domenkozar avatar Apr 30 '16 10:04 domenkozar

@domenkozar

Just kill circular dependencies. All your problems are gone. (except from the whiny abusers of this misfeature).

Circular dependencies have nothing to do with the ability to symlink a package.

Besides that, the majority of heavily modularised packages (e.g. browserify) have circular dependencies in some form or another. And that's totally cool. There is no reason this use-case shouldn't be supported.

(just in general, I don't think it's constructive to call people "whiny" - just my opinion)

alexanderGugel avatar Apr 30 '16 12:04 alexanderGugel

@kzc

@alexanderGugel I think the node_modules.json bootstrap proposal is good for a few reasons:

  1. It is explicit and clear.

I would argue that prefixing symlinks with _ is also a pretty good indicator that those are somehow "different". Keep in mind that the majority of users wouldn't create those links manually, but would use tools like npm link, pnpm, npminstall, or ied that create them.

  1. It does not alter the symlinks' names.

That's a fair point. I'm not sure that's a big disadvantage though, since we would still keep things backwards compatible to v6.0.0.

  1. It will be as performant as the _-prefix proposal.

It will be slightly less performant, because you now need to read and parse the node_modules.json file for every directory in the path that might potentially contain any symlinks.

alexanderGugel avatar Apr 30 '16 12:04 alexanderGugel

Circular dependencies have nothing to do with the ability to symlink a package.

All this nesting is a result of circular dependencies. Otherwise you could calculate a DAG graph of dependencies and be done. Just like we do it in Nix.

domenkozar avatar Apr 30 '16 12:04 domenkozar

@domenkozar

All this nesting is a result of circular dependencies. Otherwise you could calculate a DAG graph of dependencies and be done. Just like we do it in Nix.

While I like Nix, I don't think this is the right place to rant about the way modules are being resolved in general. I would suggest filing a new issue describing the proposed behaviour.

alexanderGugel avatar Apr 30 '16 13:04 alexanderGugel

Apparently node uses symlink resolution (https://github.com/nodejs/node/issues/6500#issuecomment-216378313) to protect itself from loading a binary module more than once.

Until another solution is found to assert particular module identity in some other, portable way (not easy!) this cannot be solved at the moment. (There would have been two different require code paths for binary and JavaScript modules). https://github.com/nodejs/node/issues/6500 is a nice example how the implementation https://github.com/nodejs/node/pull/5950 fails in that respect.

saper avatar May 02 '16 22:05 saper

Apologies for being late here, but can anyone tl;dr what was discussed? It's a long thread, and I'm not sure what the resolution is at the moment.

rstacruz avatar May 03 '16 12:05 rstacruz

Tl;Dr is this: we had a bug in the module loader that prevented symlinked peer dependencies from finding each other. We fixed it but the fix broke other things. So we are currently looking to revert that fix and look at solving it a different way. On May 3, 2016 5:21 AM, "Rico Sta. Cruz" [email protected] wrote:

Apologies for being late here, but can anyone tl;dr what was discussed? It's a long thread, and I'm not sure what the resolution is at the moment.

— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHub https://github.com/nodejs/node/issues/3402#issuecomment-216511065

jasnell avatar May 03 '16 13:05 jasnell

Thank you! On May 3, 2016 9:04 PM, "James M Snell" [email protected] wrote:

Tl;Dr is this: we had a bug in the module loader that prevented symlinked peer dependencies from finding each other. We fixed it but the fix broke other things. So we are currently looking to revert that fix and look at solving it a different way. On May 3, 2016 5:21 AM, "Rico Sta. Cruz" [email protected] wrote:

Apologies for being late here, but can anyone tl;dr what was discussed? It's a long thread, and I'm not sure what the resolution is at the moment.

— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHub https://github.com/nodejs/node/issues/3402#issuecomment-216511065

— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHub https://github.com/nodejs/node/issues/3402#issuecomment-216520014

rstacruz avatar May 03 '16 13:05 rstacruz

@jasnell Peer dependencies was just one advantage. The 6.0.0 module resolution behavior also facilitates testing of modules with symlinks without the need for copying files or installs. It also allows the layout of customized hand built installs to save disk space on constrained devices. It offered a lot of flexibility that the old scheme lacks.

It would be useful if the 6.0.0 module resolution behavior could exist behind a command line flag defaulted to false rather than removing it altogether.

kzc avatar May 03 '16 13:05 kzc

That very well could be an option but we need to unbreak things first, and then move forward from there.

I am definitely considering the flag approach to enable the new behavior. I've already started exploring that, in fact, and it shouldn't be too difficult to do at all. I'd just also like to continue looking into whether we can solve it without a flag tho.

jasnell avatar May 03 '16 13:05 jasnell

@jasnell Thanks. A non-flag solution is always preferable. But even with the flag it would be very helpful.

kzc avatar May 03 '16 14:05 kzc

Tl;Dr is this: we had a bug in the module loader that prevented symlinked peer dependencies from finding each other. We fixed it but the fix broke other things. So we are currently looking to revert that fix and look at solving it a different way.

I don't entirely agree that this is a bug.

However, if we are going to say that the require() look path should include the node_modules folders based on the symlinked location of a module, then it isn't acceptable to remove the node_modules folders based on the realpath location of a module.

Here is a git repo with 2 clear examples of what changed, and why this is either subtle and inefficient, or outright harmful and surprising, based on how module dependencies have been linked: https://github.com/isaacs/node6-module-system-change

(Note: I've written programs that require() a module from on a symlinked location and expect it to still be able to load its deps, so while the example is contrived in its minimal-ness, it's not contrived in principle and does reflect some real-world usage.)

An ideal solution, if it is a goal to have symlinked modules find one another if they are not otherwise dependent on one another (which, again, I am highly skeptical about as being a good idea) would have to prioritize the pre6.0 realpath-location-based lookup behavior as the first priority lookup path, and then add the node_modules lookup locations as a lower-priority set of paths.

The cache entry should still be based on the realpath for the sake of efficiency and minimizing the semantic change in what is a singleton.

If you are affected by this today, you can easily work around the bug by setting the NODE_PATH environment variable to the node_modules folder where you're sticking stuff.

I think that it'd be an interesting idea to add the main module's lookup paths to the require() calls done by other modules, but even that should be messaged front and center as a significant and potentially hazardous change.

isaacs avatar May 16 '16 00:05 isaacs

Updated the git repo with a few specific proposals.

isaacs avatar May 16 '16 00:05 isaacs