oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
73.27k stars 2.69k forks source link

In Bundler and Watch mode, exit if stdin closes (implying parent process died) #11889

Open natrys opened 3 months ago

natrys commented 3 months ago

What is the problem this feature would solve?

It's not uncommon for a bundler to be launched in watch mode by some higher level web framework. Sometimes these frameworks are running on runtimes that do not expose OS process control APIs for portability reasons. Speaking for BEAM VM that powers Phoenix web framework e.g., if Bun is launched by Phoenix and then Phoenix dies, that just leaves a dangling Bun process.

It would be nice to have Bun itself monitor its own stdin in the Bundler and Watch mode and exit itself when stdin closes, because that's the only conventional and cross-platform way of knowing that parent process died.

What is the feature you are proposing to solve the problem?

To be minimally obtrusive, we can only enact this behaviour when stdin is not a TTY. This is what esbuild does.

This seems to be a good survey on what many tools does with regard to this behaviour: https://github.com/tailwindlabs/tailwindcss/issues/9264#issuecomment-1242481043

What alternatives have you considered?

Currently the workaround is to use a wrapper program/script with child process control capability to do this on behalf of Phoenix. It can even be another Bun program, which is how one integration with Phoenix does it. But if we can avoid an extra process, I think we should.

hauleth commented 1 month ago

Current workaround is to use script like that:

const command = process.argv.slice(2)

const sub = Bun.spawn(command, {
  stdout: 'inherit',
  stderr: 'inherit',
  onExit: (_, code) => process.exit(code)
})

process.stdin.resume()
process.stdin.on('close', () => sub.kill());

And then run it via:

bun wrapper.js bun <args>

So Bun is running in Bun, but it will listen for closing on stdin and will shutdown process. But yeah, that would be handy to have it built in.

That approach is what I have used in crbelaus/bun#16

hauleth commented 1 month ago

Related #7084