Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ and this project adheres to [Semantic Versioning].

## Unreleased

### Added

- `rake vite:auto_build` builds stale assets the way auto build does, so a parallel test runner can build once before it starts its workers. `RailsVite::AutoBuild.build_if_stale` does the same from Ruby. Both do nothing when assets are fresh, and fail with `RailsVite::BuildError` when the build fails ([@brodienguyen])

### Changed

- `RailsVite.digest` is computed once outside development and test, instead of hashing the manifest file on every call (#57) ([@thomasklemm])
- A failed auto build raises `RailsVite::BuildError` instead of logging and serving the previous assets, and a process does not run it again until a source changes or `rake vite:build` writes a fresh manifest ([@brodienguyen])

### Fixed

- Auto build no longer walks the whole Rails root when Vite's `root` is the source directory (`prependSourceDirToEntries: false`). `log/` and `tmp/` made assets look stale on every request. The plugin now also writes the source directory to its metadata as `sourcePath`, and auto build watches it. Upgrade `rails-vite-plugin` together with the gem: metadata from older plugin versions has no `sourcePath`, so auto build falls back to `sourceDir` (#61) ([@mdesantis])
- Auto builds hold a file lock in `tmp/`, so parallel test workers and a server beside a test run no longer build into the same directory at once. The first process to find stale assets builds them, and the others wait and reuse that build ([@brodienguyen])

## rails_vite@0.3.0 / rails-vite-plugin@0.3.0 - 2026-10-11

Expand Down
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,15 @@ Rails.application.config.rails_vite.auto_build = false

By default, auto build is enabled in development and test (`Rails.env.local?`).

Note: for parallel test runners, disable auto build and use `rake vite:build` before the suite instead.
Auto builds hold a file lock in `tmp/`, so parallel test workers and a server beside a test run never build at once: the first process to find stale assets builds them, and the others wait and reuse that build. A failed build raises `RailsVite::BuildError`, and a process does not retry it until a source changes.

A parallel test runner can build once before it starts its workers, so no worker spends its first test waiting for the build. `rake vite:auto_build` runs the same check, lock and build as the middleware: it builds only when sources changed, does nothing while the dev server runs or with auto build off, and fails with `RailsVite::BuildError` when the build fails. Run it in the environment the workers use:

```bash
RAILS_ENV=test bin/rails vite:auto_build && bundle exec parallel_rspec
```

From Ruby, for example in a script that starts the workers itself, call `RailsVite::AutoBuild.build_if_stale`.

## CDN

Expand Down Expand Up @@ -431,6 +439,7 @@ Defaults match the plugin defaults — no config needed if you follow convention
| Task | Description |
|------|-------------|
| `rake vite:build` | Build assets for production |
| `rake vite:auto_build` | Build assets only if sources changed, as [auto build](#auto-build) does |
| `rake vite:install` | Install JavaScript dependencies |
| `rake vite:clobber` | Remove `public/vite/` |

Expand Down
63 changes: 56 additions & 7 deletions lib/rails_vite/auto_build.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
require "fileutils"
require "find"

module RailsVite
class AutoBuild
NEVER = Time.at(0).freeze
SOURCE_CHECK_INTERVAL = 2 # seconds

# Auto build runs when it is on and no dev server serves the assets.
def self.enabled?(config)
config.auto_build? && !config.dev_server_running?
end

# Builds stale assets outside a request, as the middleware does on the
# first one; for example, before a test runner starts its workers.
def self.build_if_stale(config = RailsVite.config)
new(nil, config).build_if_stale if enabled?(config)
end

def initialize(app, config)
@app = app
@config = config
Expand All @@ -14,30 +26,67 @@ def initialize(app, config)
end

def call(env)
build! if stale?
build_if_stale
@app.call(env)
end

# Builds the assets when a source is newer than the manifest, or waits for
# another process's build. Raises BuildError when the build fails.
def build_if_stale
build! if stale?
end

private

def build!
@mutex.synchronize do
return unless stale?

# Build quietly: vite's per-build summary is noise on every auto-build
# (e.g. each local system-test run). Warnings and errors still stream.
Rails.logger.error("rails-vite: build failed") unless system(RailsVite::Tasks.build_env, "#{RailsVite::Tasks.build_command} --logLevel warn", chdir: Rails.root)
with_build_lock do
# Another process may have finished a build while this one waited.
return unless stale?

sources = compute_latest_source_mtime
raise BuildError.new(skipped: true) if @failed_sources == sources

# Build quietly: vite's per-build summary is noise on every auto-build
# (e.g. each local system-test run). Warnings and errors still stream.
next if system(RailsVite::Tasks.build_env, "#{RailsVite::Tasks.build_command} --logLevel warn", chdir: Rails.root)

# Remember the failure for these sources, so this process does not
# rebuild them until a source changes.
@failed_sources = sources
raise BuildError
end
@failed_sources = nil
@cached_source_mtime = nil
@source_mtime_checked_at = nil
end
end

# Serializes builds across processes (parallel test workers, a server
# beside a test run): Vite empties the build directory first, so the lock
# lives outside it.
def with_build_lock
path = Rails.root.join("tmp", "rails-vite-build-#{@config.build_dir}.lock")
FileUtils.mkdir_p(path.dirname)
File.open(path, File::RDWR | File::CREAT, 0o644) do |lock|
lock.flock(File::LOCK_EX)
yield
end
end

def stale?
# The manifest file's mtime is our persisted "last build" timestamp: it
# lives on disk, so freshness survives process restarts (e.g. a new Rails
# process per local system-test run) without any extra state.
!File.exist?(@config.manifest_path) ||
latest_source_mtime > File.mtime(@config.manifest_path)
# process per local system-test run) without any extra state. A missing
# manifest is stale, including one another process's build has just
# removed: Vite empties the build directory first, so it can vanish
# between any check and the read. Stale takes the build lock, which
# waits for that build and then checks again.
latest_source_mtime > File.mtime(@config.manifest_path)
rescue Errno::ENOENT
true
end

def latest_source_mtime
Expand Down
2 changes: 1 addition & 1 deletion lib/rails_vite/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class Engine < ::Rails::Engine

initializer "rails_vite.auto_build", after: :load_config_initializers do |app|
vite_config = RailsVite.config
if vite_config.auto_build? && !vite_config.dev_server_running?
if RailsVite::AutoBuild.enabled?(vite_config)
app.middleware.use RailsVite::AutoBuild, vite_config
end
end
Expand Down
13 changes: 13 additions & 0 deletions lib/rails_vite/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ def initialize(path)
end
end

class BuildError < Error
# skipped: Vite did not run because these sources already failed to build
# in an earlier request, so its errors are not in this output.
def initialize(skipped: false)
message = if skipped
"Vite auto build failed earlier for these sources and is not retried until a source changes or the app restarts. Run `rake vite:build` to see its errors."
else
"Vite auto build failed; its errors are in the output above. It retries once a source changes, or run `rake vite:build`."
end
super(message)
end
end

class MissingEntryError < Error
def initialize(name, path)
super("Entry \"#{name}\" not found in Vite manifest at #{path}.")
Expand Down
5 changes: 5 additions & 0 deletions lib/tasks/rails_vite/build.rake
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ namespace :vite do

Rake::Task["vite:build"].prereqs << :install unless ENV["SKIP_VITE_INSTALL"]

desc "Build Vite assets the way auto build does, only if sources changed"
task auto_build: :environment do
RailsVite::AutoBuild.build_if_stale
end

desc "Remove Vite build artifacts"
task :clobber do
rm_rf Rails.root.join("public", RailsVite.config.asset_prefix.delete_prefix("/"))
Expand Down
180 changes: 178 additions & 2 deletions test/auto_build_test.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require "test_helper"
require "rails_vite/auto_build"
require "timeout"

class AutoBuildTest < Minitest::Test
def setup
Expand Down Expand Up @@ -211,6 +212,181 @@ def test_passes_request_through_to_app
end
end

def test_waits_for_a_build_in_another_process_and_skips_when_it_left_the_build_fresh
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: Time.now - 10)
lock_path = File.join(@dir, "tmp", "rails-vite-build-#{@config.build_dir}.lock")
FileUtils.mkdir_p(File.dirname(lock_path))

with_root do
built = false
stub_build(-> { built = true }) do
File.open(lock_path, File::RDWR | File::CREAT) do |other_process|
other_process.flock(File::LOCK_EX)
request = Thread.new { RailsVite::AutoBuild.new(@app, @config).call({}) }
# The request blocks on the lock rather than finishing.
Timeout.timeout(5) { Thread.pass until request.status == "sleep" }
assert request.alive?, "the request should wait while another process builds"
write_manifest
other_process.flock(File::LOCK_UN)
request.join
end
end

refute built
end
end

def test_waits_when_the_manifest_vanishes_under_another_process_build
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: Time.now - 10)
lock_path = File.join(@dir, "tmp", "rails-vite-build-#{@config.build_dir}.lock")
FileUtils.mkdir_p(File.dirname(lock_path))
manifest = @manifest_path.to_s
# The manifest was there a moment ago; the other process's build has since emptied the directory.
exist = File.method(:exist?)

with_root do
built = false
stub_build(-> { built = true }) do
File.stub(:exist?, ->(path) { path.to_s == manifest || exist.call(path) }) do
File.open(lock_path, File::RDWR | File::CREAT) do |other_process|
other_process.flock(File::LOCK_EX)
request = Thread.new { RailsVite::AutoBuild.new(@app, @config).call({}) }
# join returns nil while the request still waits, and re-raises if it failed instead.
assert_nil request.join(0.5), "the request should wait for the build, not fail on the missing manifest"
write_manifest
other_process.flock(File::LOCK_UN)
request.join
end
end
end

refute built
end
end

def test_does_not_rebuild_failed_sources_until_a_source_changes
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: @base_time)

with_root do
builds = 0
stub_build(-> {
builds += 1
false
}) do
middleware = RailsVite::AutoBuild.new(@app, @config)
2.times do
assert_raises(RailsVite::BuildError) { middleware.call({}) }
end
assert_equal 1, builds

# A source change earns one more build, whose failure is remembered too.
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: @base_time + 10)
2.times do
assert_raises(RailsVite::BuildError) { middleware.call({}) }
end
assert_equal 2, builds

# Another process, or this one after a restart, tries once more.
assert_raises(RailsVite::BuildError) { RailsVite::AutoBuild.new(@app, @config).call({}) }
end

assert_equal 3, builds
end
end

def test_a_skipped_build_says_its_errors_are_not_in_the_output
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: @base_time)

with_root do
stub_build(-> { false }) do
middleware = RailsVite::AutoBuild.new(@app, @config)
first = assert_raises(RailsVite::BuildError) { middleware.call({}) }
again = assert_raises(RailsVite::BuildError) { middleware.call({}) }

assert_includes first.message, "errors are in the output above"
assert_includes again.message, "Run `rake vite:build` to see its errors"
end
end
end

def test_builds_again_after_a_failure_is_fixed
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: @base_time)

with_root do
stub_build(-> { false }) do
assert_raises(RailsVite::BuildError) { RailsVite::AutoBuild.new(@app, @config).call({}) }
end

FileUtils.touch(File.join(@source_dir, "app.js"), mtime: @base_time + 10)
stub_build(-> {
write_manifest
true
}) do
status, = RailsVite::AutoBuild.new(@app, @config).call({})
assert_equal 200, status
end
end
end

def test_build_if_stale_builds_without_a_request
with_root do
built = false
stub_build(-> { built = true }) do
RailsVite::AutoBuild.build_if_stale(@config)
end

assert built
end
end

def test_build_if_stale_skips_fresh_assets
FileUtils.touch(File.join(@source_dir, "app.js"), mtime: Time.now - 10)
write_manifest(mtime: Time.now)

with_root do
built = false
stub_build(-> { built = true }) do
RailsVite::AutoBuild.build_if_stale(@config)
end

refute built
end
end

def test_build_if_stale_skips_when_auto_build_is_off
@config.auto_build = false

with_root do
built = false
stub_build(-> { built = true }) do
RailsVite::AutoBuild.build_if_stale(@config)
end

refute built
end
end

def test_build_if_stale_skips_while_the_dev_server_runs
with_root do
built = false
@config.stub(:dev_server_running?, true) do
stub_build(-> { built = true }) do
RailsVite::AutoBuild.build_if_stale(@config)
end
end

refute built
end
end

def test_build_if_stale_raises_when_the_build_fails
with_root do
stub_build(-> { false }) do
assert_raises(RailsVite::BuildError) { RailsVite::AutoBuild.build_if_stale(@config) }
end
end
end

private

def with_root(&block)
Expand Down Expand Up @@ -250,8 +426,8 @@ def write_manifest(mtime: Time.now)
def stub_build(callback)
RailsVite::Tasks.stub(:build_command, "true") do
RailsVite::AutoBuild.define_method(:system) do |*, **|
callback.call
true
# The build succeeds unless the callback returns false.
callback.call != false
end
yield
ensure
Expand Down
9 changes: 9 additions & 0 deletions test/rake_tasks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,13 @@ def test_build_uses_config_from_the_app
ensure
main.singleton_class.remove_method(:system)
end

def test_auto_build_runs_auto_build_outside_a_request
called = false
RailsVite::AutoBuild.stub(:build_if_stale, -> { called = true }) do
Rake::Task["vite:auto_build"].invoke
end

assert called
end
end
Loading