denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
94.22k stars 5.24k forks source link

💡 Can executing 'Deno. cwd()' in the worker return an independent directory? #24347

Closed hanrea closed 2 months ago

hanrea commented 3 months ago

I want an independent environment for executing workers. I currently treat workers as a lightweight container and hope that each worker has their own directory to handle certain tasks in conjunction with Deno's permission management. In short, can the program customize the context of the worker.

dsherret commented 3 months ago

Deno.cwd() returns the current working directory of the process. Workers run in threads within that process, so no.

You'd have to create another api for the workers to use that could have its own local state for the cwd, or you'd need to or change the Deno global in the worker.

hanrea commented 2 months ago

I have solved this problem, and when initializing the runtime, the worker can write the proxy state parameter:

https://github.com/denoland/deno/blob/bc8a0e6e68547cf07a246b8b6c886de155dc8282/ext/fs/lib.rs#L258

When calling op_fs_cwd, it is possible to return diffent values based on the state parameter

vfssantos commented 3 weeks ago

@hanrea , I have a similar use case. Can you please elaborate on how you made it work? I mean, how did you customize the initialization of the runtime?

Thanks!

vfssantos commented 3 weeks ago

@dsherret , I'm trying to use tailwindcss without having allow-read=true in my web worker. However, a dependency from tailwindcss (more specifically, fast-glob) requires access to Deno.cwd. Now, even if I override Deno.cwd in the worker (which would be ok in my use-case) as

Deno.cwd = () =>'my/fixed/path'; 

It still asks for Deno.cwd() permission, which I find odd. Here's the exact error message:

Requires read access to , run again with the --allow-read flag","stack":"PermissionDenied: Requires read access to , run again with the --allow-read flag\n at Process.cwd (ext:deno_fs/30_fs.js:155:10)

Maybe it has something to do with this library dynamic require of node's process.cwd?

hanrea commented 3 weeks ago

@vfssantos I hack the deno's code , you can see the patch file deno_1.44.4_worker_cwd.patch

vfssantos commented 3 weeks ago

@hanrea, this is a very interesting solution. Thanks for sharing.

I know this issue is closed, but I'd like to suggest this discussion for future versions.

The exact use case would be:

@bartlomieju @dsherret