Skip to content

Commit 71fd3ea

Browse files
committed
fix: avoid endless vite processes when Vite is missing
The runner starts Vite through the package manager, for example `bun x --bun vite`. When the vite package is not installed, Bun and pnpm look for `vite` on the PATH. There they find the `vite` executable of this gem, which starts the runner again. Each process waits for its child, so the processes accumulate without end. This commit adds a marker variable to the environment of the process that the runner starts. When `vite build` or `vite dev` sees the marker, it stops with an error. The error tells the user to install the JavaScript packages. vite-plugin-ruby removes the marker when Vite loads, so a process that Vite starts can still run `bin/vite`. The check runs before `Builder#build`. With the build lock of PR #630, a later check would deadlock instead of failing. The marker has no `VITE_` prefix, because Vite copies those variables into `import.meta.env`. A check for `node_modules/.bin/vite` is not possible, because Yarn Plug'n'Play has no `node_modules`. A check of the parent PID does not work either, because pnpm starts the child through two processes. With an older vite-plugin-ruby, `vite build` and `vite dev` fail when a process that Vite started runs them. `DEFAULT_PLUGIN_VERSION` should move to the next plugin release to prevent this.
1 parent 76fc36b commit 71fd3ea

8 files changed

Lines changed: 127 additions & 13 deletions

File tree

‎test/cli_test.rb‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
class CLITest < ViteRuby::Test
6+
def test_build_stops_when_started_by_runner
7+
built = clobbered = false
8+
with_env("RUBY_VITE_RUNNER_PID" => "123") {
9+
Dir.chdir(path_to_test_app) {
10+
ViteRuby::Commands.stub_any_instance(:clobber, -> { clobbered = true }) {
11+
ViteRuby::Commands.stub_any_instance(:build_from_task, ->(*) { built = true }) {
12+
assert_raises(ViteRuby::MissingExecutableError) { ViteRuby::CLI::Build.new.call(mode: "production", clobber: true) }
13+
}
14+
}
15+
}
16+
}
17+
18+
refute clobbered
19+
refute built
20+
end
21+
22+
def test_dev_stops_when_started_by_runner
23+
with_env("RUBY_VITE_RUNNER_PID" => "123") {
24+
Kernel.stub(:exec, ->(*) { flunk "started the dev server" }) {
25+
assert_raises(ViteRuby::MissingExecutableError) { ViteRuby::CLI::Dev.new.call(mode: "development") }
26+
}
27+
}
28+
end
29+
30+
def test_version_runs_when_started_by_runner
31+
printed = false
32+
with_env("RUBY_VITE_RUNNER_PID" => "123") {
33+
ViteRuby::Commands.stub_any_instance(:print_info, -> { printed = true }) { ViteRuby::CLI::Version.new.call }
34+
}
35+
36+
assert printed
37+
end
38+
end

‎test/runner_test.rb‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,38 @@ def test_command_capture
3030
assert status
3131
}
3232
end
33+
34+
def test_self_invocation_check_raises_when_started_by_runner
35+
refresh_config(package_manager: "bun")
36+
with_env("RUBY_VITE_RUNNER_PID" => "123") {
37+
ViteRuby::IO.stub(:capture, ->(*) { flunk "started a process" }) {
38+
error = assert_raises(ViteRuby::MissingExecutableError) {
39+
ViteRuby::Runner.check_for_self_invocation!
40+
}
41+
42+
assert_includes error.message, "`bun x --bun vite` started vite_ruby's own `vite` command"
43+
assert_includes error.message, "Run `bun install` and try again."
44+
}
45+
}
46+
end
47+
48+
def test_self_invocation_check_passes_when_not_started_by_runner
49+
with_env("RUBY_VITE_RUNNER_PID" => nil) {
50+
assert_nil ViteRuby::Runner.check_for_self_invocation!
51+
}
52+
end
53+
54+
def test_command_adds_runner_marker_to_env
55+
assert_equal Process.pid.to_s, run_command("build").first["RUBY_VITE_RUNNER_PID"]
56+
end
57+
58+
private
59+
60+
def run_command(*argv)
61+
Dir.chdir(path_to_test_app) {
62+
command = nil
63+
Kernel.stub(:exec, ->(*args) { command = args }) { ViteRuby.run(argv, exec: true) }
64+
command
65+
}
66+
end
3367
end

‎test/test_helper.rb‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ def with_rails_env(env)
4444
refresh_config
4545
end
4646

47+
def with_env(vars)
48+
original = vars.keys.to_h { |key| [key, ENV[key]] }
49+
vars.each { |key, value| ENV[key] = value }
50+
yield
51+
ensure
52+
original.each { |key, value| ENV[key] = value }
53+
end
54+
4755
def path_to_test_app
4856
File.expand_path("test_app", __dir__)
4957
end
@@ -70,15 +78,16 @@ def stub_builder(build_errors: "", build_successful: build_errors.empty?, stale:
7078
end
7179

7280
def assert_run_command(*argv, flags: [])
81+
env = ViteRuby.config.to_env.merge(ViteRuby::Runner::RUNNER_PID_ENV_VAR => Process.pid.to_s)
7382
Dir.chdir(path_to_test_app) {
7483
begin
7584
mock = Minitest::Mock.new
76-
mock.expect(:call, nil, [ViteRuby.config.to_env, %r{node_modules/.bin/vite}, *argv, *flags])
85+
mock.expect(:call, nil, [env, %r{node_modules/.bin/vite}, *argv, *flags])
7786
Kernel.stub(:exec, mock) { ViteRuby.run(argv, exec: true) }
7887
mock.verify
7988
rescue ArgumentError => _error
8089
mock = Minitest::Mock.new
81-
mock.expect(:call, nil, [ViteRuby.config.to_env, "yarn", "vite", *argv, *flags])
90+
mock.expect(:call, nil, [env, "yarn", "vite", *argv, *flags])
8291
Kernel.stub(:exec, mock) { ViteRuby.run(argv, exec: true) }
8392
mock.verify
8493
end

‎vite-plugin-ruby/src/constants.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ export const APP_ENV = process.env.RAILS_ENV || process.env.RACK_ENV || process.
44
// Internal: Prefix used for environment variables that modify the configuration.
55
export const ENV_PREFIX = 'VITE_RUBY'
66

7+
// Internal: Marks the processes that vite_ruby starts. It has no VITE_ prefix, so Vite does not expose it.
8+
export const RUNNER_PID_ENV_VAR = 'RUBY_VITE_RUNNER_PID'
9+
710
// Internal: Key of the vite.json file that is applied to all environments.
811
export const ALL_ENVS_KEY = 'all'
912

‎vite-plugin-ruby/src/index.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { cleanConfig, configOptionFromEnv } from './utils'
77
import { filterEntrypointsForRollup, loadConfiguration, resolveGlobs } from './config'
88
import { assetsManifestPlugin } from './manifest'
99
import { bindDevServerCleanup, resolveDevServerMeta, writeDevServerMeta } from './dev-server'
10-
import { DEV_SERVER_META_FILE } from './constants'
10+
import { DEV_SERVER_META_FILE, RUNNER_PID_ENV_VAR } from './constants'
1111

1212
export * from './types'
1313

@@ -28,6 +28,9 @@ let watchAdditionalPaths: string[] = []
2828

2929
// Public: Vite Plugin to detect entrypoints in a Ruby app, and allows to load a shared JSON configuration file that can be read from Ruby.
3030
export default function ViteRubyPlugin (): PluginOption[] {
31+
// Vite is running, so processes that it starts can run vite_ruby again.
32+
delete process.env[RUNNER_PID_ENV_VAR]
33+
3134
return [
3235
{
3336
name: 'vite-plugin-ruby',

‎vite-plugin-ruby/tests/index.spec.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@ import { describe, test, expect } from 'vitest'
22
import { defaultConfig } from '@plugin/config'
33
import ViteRuby from '@plugin/index'
44

5+
describe('runner marker', () => {
6+
test('removes the marker so that processes started by Vite do not inherit it', () => {
7+
process.env.RUBY_VITE_RUNNER_PID = '123'
8+
ViteRuby()
9+
expect(process.env.RUBY_VITE_RUNNER_PID).toBeUndefined()
10+
})
11+
})
12+
513
describe('config', () => {
614
test('environment defaults', () => {
715
const plugin = ViteRuby()

‎vite_ruby/lib/vite_ruby/cli/vite.rb‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ def self.shared_options
1717
end
1818

1919
def call(mode:, args: [], clobber: false, node_options: nil, inspect: nil, trace_deprecation: nil, **boolean_opts)
20+
ViteRuby::Runner.check_for_self_invocation!
2021
ViteRuby.env["VITE_RUBY_MODE"] = mode
2122
ViteRuby.commands.clobber if clobber
2223

‎vite_ruby/lib/vite_ruby/runner.rb‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,32 @@
22

33
# Public: Executes Vite commands, providing conveniences for debugging.
44
class ViteRuby::Runner
5+
# Internal: Marks the processes that the runner starts. It has no VITE_ prefix, so Vite does not expose it.
6+
RUNNER_PID_ENV_VAR = "RUBY_VITE_RUNNER_PID"
7+
8+
# Internal: Stops a package manager from starting this gem's `vite` again. vite-plugin-ruby removes the marker.
9+
def self.check_for_self_invocation!
10+
return unless ENV[RUNNER_PID_ENV_VAR]
11+
12+
package_manager = ViteRuby.config.package_manager
13+
runner = [*package_runner(package_manager), "vite"].join(" ")
14+
raise ViteRuby::MissingExecutableError, <<~MSG
15+
vite_ruby could not find the Vite executable, and `#{runner}` started vite_ruby's own `vite` command.
16+
Run `#{package_manager} install` and try again.
17+
MSG
18+
end
19+
20+
# Internal: Returns the command that runs a package executable.
21+
def self.package_runner(package_manager)
22+
case package_manager
23+
when "npm" then %w[npx]
24+
when "pnpm" then %w[pnpm exec]
25+
when "bun" then %w[bun x --bun]
26+
when "yarn" then %w[yarn]
27+
else raise ArgumentError, "Unknown package manager #{package_manager.inspect}"
28+
end
29+
end
30+
531
def initialize(vite_ruby)
632
@vite_ruby = vite_ruby
733
end
@@ -27,7 +53,7 @@ def run(argv, exec: false)
2753

2854
# Internal: Returns an Array with the command to run.
2955
def command_for(args)
30-
[config.to_env(env)].tap do |cmd|
56+
[config.to_env(env).merge(RUNNER_PID_ENV_VAR => Process.pid.to_s)].tap do |cmd|
3157
exec_args, vite_args = args.partition { |arg| arg.start_with?("--node-options") }
3258
cmd.push(*vite_executable(*exec_args))
3359
cmd.push(*vite_args)
@@ -40,14 +66,6 @@ def vite_executable(*exec_args)
4066
bin_path = config.vite_bin_path
4167
return [bin_path] if bin_path && File.exist?(bin_path)
4268

43-
x = case config.package_manager
44-
when "npm" then %w[npx]
45-
when "pnpm" then %w[pnpm exec]
46-
when "bun" then %w[bun x --bun]
47-
when "yarn" then %w[yarn]
48-
else raise ArgumentError, "Unknown package manager #{config.package_manager.inspect}"
49-
end
50-
51-
[*x, *exec_args, "vite"]
69+
[*self.class.package_runner(config.package_manager), *exec_args, "vite"]
5270
end
5371
end

0 commit comments

Comments
 (0)