hanami-reloader 3.0.0.rc1 → 3.1.0.rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 913be5a25eb98885b9f4dcac5eec20c0123a811d837dfc7f43e9243305c11257
4
- data.tar.gz: a9333303ff71bf34b956a48f7b0d1b0bb017398594929fafcb9fbe1b5d56bc69
3
+ metadata.gz: 3e0b22830bf2922bb7f76a67ef84c1cbdcdc68cd292c9106061f96e3accf72a3
4
+ data.tar.gz: a22c4005311375d93e50f06f39487c146d74c905b254607962f7589a78df2089
5
5
  SHA512:
6
- metadata.gz: dc5dd96a81bd8860b9644717c56ce883d6b1268432936bbc29d88239c748b89b4ae5e5a92414cb637f3d5395f783dc0bc1ca4c26e38ec2c428f53468b3366949
7
- data.tar.gz: c2330ec9f3a90a8ab3b0f9e3bc0d705072cf789230bb1f7548196e4b67dbe29b79da46ec5d6be735b8d7ca1fb1d53fe1bab53ed362b5d94f561104071126d3a5
6
+ metadata.gz: 29214f157e0ed1dda0243357aed05be19f1daacbdcc5e82fe675dcde65e72b4e14b921207c117d32374bf2ebf2df4fd7fad26813b4ccfa58af8cd9d2531d5fcf
7
+ data.tar.gz: 63e95e4241af0ba277204890a718e1c040f741bf774c5517b4a8f17dffb135793c537e5eb9ad6581a1657731c5a2f1fb011d1399b708fc4cc9978bde7fa6cba6
data/CHANGELOG.md CHANGED
@@ -19,7 +19,35 @@ and this project adheres to [Break Versioning](https://www.taoensso.com/break-ve
19
19
 
20
20
  ### Security
21
21
 
22
- [Unreleased]: https://github.com/hanami/reloader/compare/v3.0.0.rc1...HEAD
22
+ [Unreleased]: https://github.com/hanami/reloader/compare/v3.1.0.rc1...HEAD
23
+
24
+ ## [3.1.0.rc1] - 2026-11-27
25
+
26
+ ### Added
27
+
28
+ - Reload the app's code in place instead of restarting the server. `hanami server` now wraps the app in a Rack middleware that checks the app's source files once per request and reloads via `Hanami::Slice#reload` before dispatching, so the process stays up and requests are served from freshly loaded code. Changes to Ruby files, YAML files (such as translations) and templates (in any format) in `app/`, `config/`, `lib/` and `slices/` trigger a reload. (@afomera in #37, @timriley in #42)
29
+ - Render errors raised while reloading on the hanami-webconsole error page, where hanami-webconsole is bundled and `config.render_detailed_errors` is enabled, instead of returning a bare 500. (@afomera in #37, @timriley in #40 and #41)
30
+ - Warn, instead of silently doing nothing, when a changed file cannot be applied by a reload (`config/app.rb`, `Gemfile`, `Gemfile.lock`, `.env` files, `config/settings/*.yml`). (@afomera in #37, @timriley in #42)
31
+ - Put off a reload while a response is held open (such as a streamed response), and serve requests with the current code until it closes, instead of making every request wait for it. (@afomera in #37)
32
+
33
+ ### Changed
34
+
35
+ - `hanami install` no longer generates a `Guardfile`. Code reloading now needs no per-app configuration, so you can delete the `Guardfile` from your app. (@afomera in #37)
36
+ - Support Hanami CLI's move to Dry CLI 2. The `install` and `server` commands now use the `stdout` and `stderr` streams from Dry CLI, and no longer override `#initialize`. (@afomera in #38, @timriley in #39)
37
+
38
+ ### Removed
39
+
40
+ - Drop the `guard` and `guard-puma` dependencies, which are no longer used. (@afomera in #37)
41
+
42
+ [3.1.0.rc1]: https://github.com/hanami/reloader/compare/v3.0.0...v3.1.0.rc1
43
+
44
+ ## [3.0.0] - 2026-06-30
45
+
46
+ ### Changed
47
+
48
+ - Require Ruby 3.3 or newer.
49
+
50
+ [3.0.0]: https://github.com/hanami/reloader/compare/v2.3.0...v3.0.0
23
51
 
24
52
  ## [3.0.0.rc1] - 2026-06-16
25
53
 
data/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [actions]: https://github.com/hanami/hanami-reloader/actions
4
4
  [chat]: https://discord.gg/naQApPAsZB
5
- [forum]: https://discourse.hanamirb.org
5
+ [forum]: https://discourse.hanakai.org
6
6
  [rubygem]: https://rubygems.org/gems/hanami-reloader
7
7
 
8
8
  # Hanami Reloader [![Gem Version](https://badge.fury.io/rb/hanami-reloader.svg)][rubygem] [![CI Status](https://github.com/hanami/hanami-reloader/workflows/CI/badge.svg)][actions]
@@ -30,9 +30,8 @@ Gem::Specification.new do |spec|
30
30
 
31
31
  spec.required_ruby_version = ">= 3.3"
32
32
 
33
- spec.add_runtime_dependency "guard", "~> 2.19"
34
- spec.add_runtime_dependency "guard-puma", "~> 0.8"
35
- spec.add_runtime_dependency "hanami-cli", "~> 3.0.0.rc"
33
+ spec.add_runtime_dependency "hanami-cli", "~> 3.1.0.rc"
34
+ spec.add_runtime_dependency "rack", ">= 3.0"
36
35
  spec.add_runtime_dependency "zeitwerk", "~> 2.6"
37
36
  end
38
37
 
@@ -5,69 +5,41 @@ require "hanami/port"
5
5
  module Hanami
6
6
  module Reloader
7
7
  module Commands
8
- # Guardfile
9
- module Guardfile
10
- def self.group
11
- "server"
12
- end
13
-
14
- def self.default_path
15
- path("Guardfile")
16
- end
17
-
18
- def self.path(value)
19
- value
20
- end
21
- end
22
-
23
- # Generate hanami-reloader configuration
8
+ # Removes configuration left behind by previous versions of hanami-reloader.
9
+ #
10
+ # Reloading no longer runs through Guard, so the `Guardfile` it used to generate is now
11
+ # dead weight. Nothing is generated in its place: the reloader is wired up by the `server`
12
+ # command below, with no per-app configuration.
13
+ #
14
+ # @api private
15
+ # @since 2.1.0
24
16
  class Install < Hanami::CLI::Command
25
17
  # @api private
26
- # @since 2.1.0
27
- #
28
- # NOTE: Any change to this constant MUST be reflected in the `#generate_configuration` method,
29
- # by copying and pasting this regex.
30
- MATCHER = %r{^(app|config|lib|slices)([\\/][^\\/]+)*\.(rb|erb|haml|slim)$}i
18
+ # @since 3.1.0
19
+ GUARDFILE = "Guardfile"
31
20
 
32
- desc "Generate configuration for code reloading"
21
+ desc "Remove obsolete code reloading configuration"
33
22
 
34
- def initialize(fs: Dry::Files.new, **args)
35
- super
36
- end
23
+ def call
24
+ return unless fs.exist?(GUARDFILE)
25
+ return unless fs.read(GUARDFILE).include?("guard \"puma\"")
37
26
 
38
- def call(*, **)
39
- generate_configuration(Guardfile.default_path)
40
- end
41
-
42
- private
43
-
44
- def generate_configuration(path)
45
- fs.write path, <<~CODE
46
- # frozen_string_literal: true
47
-
48
- group :#{Guardfile.group} do
49
- guard "puma", port: ENV.fetch("#{Hanami::Port::ENV_VAR}", #{Hanami::Port::DEFAULT}), environment: ENV.fetch("HANAMI_ENV", "development") do
50
- # Edit the following regular expression for your needs.
51
- # See: https://guides.hanamirb.org/app/code-reloading/
52
- watch(%r{^(app|config|lib|slices)([\\/][^\\/]+)*.(rb|erb|haml|slim)$}i)
53
- end
54
- end
55
- CODE
27
+ fs.delete(GUARDFILE)
28
+ puts "Removed #{GUARDFILE} (code reloading no longer uses Guard)"
56
29
  end
57
30
  end
58
31
 
59
- # Override `hanami server` command
32
+ # Override `hanami server` to reload the app in place instead of restarting it.
33
+ #
34
+ # The app is built from `config.ru` here rather than by the Rack server, so that it can be
35
+ # wrapped in {Middleware} before being served. That keeps the reloader outside the app's own
36
+ # middleware stack, which a reload replaces, and means an app needs no `config.ru` changes to
37
+ # get reloading.
38
+ #
39
+ # @since 2.0.0
40
+ # @api private
60
41
  class Server < Hanami::CLI::Commands::App::Server
61
- # @since 2.0.0
62
- # @api private
63
- DEFAULT_GUARD_PUMA_OPTIONS = ["-n", "f", "-i", "-g", Guardfile.group, "-G"].freeze
64
-
65
- # @since 2.0.0
66
- # @api private
67
- OPTIONS_SEPARATOR = " "
68
-
69
- option :guardfile, type: :string, desc: "Path to Guardfile", default: Guardfile.default_path.to_s
70
- option :code_reloading, type: :boolean, desc: "Code reloading", default: true
42
+ option :code_reloading, type: :boolean, desc: "Code reloading", default: true
71
43
 
72
44
  desc "Start Hanami app server"
73
45
 
@@ -75,11 +47,25 @@ module Hanami
75
47
  "--no-code-reloading # Disable code reloading"
76
48
  ]
77
49
 
78
- def call(**args)
79
- code_reloading = args.fetch(:code_reloading)
50
+ def call(port: Hanami::Port::DEFAULT, **args)
51
+ return super(port: port, **args) unless code_reloading?(**args)
52
+
53
+ # Keeps HANAMI_PORT in step with an explicit `--port`, then resolves the port the same
54
+ # way the command we're replacing does, so a port set in `.env` is still honoured.
55
+ Hanami::Port.call!(port)
56
+
57
+ reloading_server.call(**args, port: Hanami::Port[port])
58
+ end
59
+
60
+ private
61
+
62
+ # @api private
63
+ # @since 3.1.0
64
+ def code_reloading?(**args)
65
+ return false unless args.fetch(:code_reloading)
80
66
 
81
67
  if ENV["HANAMI_ENV"] == "production"
82
- msg = <<~TEXT
68
+ stderr.puts <<~TEXT
83
69
  WARNING: You are running `hanami server` in the production environment via hanami-reloader.
84
70
 
85
71
  Code reloading is disabled, but `hanami server` and hanami-reloader are intended to be used in
@@ -88,29 +74,16 @@ module Hanami
88
74
  For production, start your web server directly, e.g. `bundle exec puma -C config/puma.rb`.
89
75
  TEXT
90
76
 
91
- err.puts msg
92
-
93
- return super
77
+ return false
94
78
  end
95
79
 
96
- if code_reloading
97
- guard_puma_env_vars!(**args)
98
- exec "bundle exec guard #{guard_puma_options(**args)}"
99
- else
100
- super
101
- end
80
+ true
102
81
  end
103
82
 
104
- private
105
-
106
- def guard_puma_env_vars!(**args)
107
- Hanami::Port.call!(args.fetch(:port))
108
- end
109
-
110
- def guard_puma_options(**args)
111
- options = DEFAULT_GUARD_PUMA_OPTIONS.dup
112
- options.push(Guardfile.path(args.fetch(:guardfile)))
113
- options.join(OPTIONS_SEPARATOR)
83
+ # @api private
84
+ # @since 3.1.0
85
+ def reloading_server
86
+ Reloader::Server.new(stdout:, stderr:)
114
87
  end
115
88
  end
116
89
  end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hanami
4
+ module Reloader
5
+ # Detects changes to an app's source files by comparing their modification times.
6
+ #
7
+ # Nothing runs in the background: files are stat'd when {#updated?} is called, which the
8
+ # reloader does once per request. This needs no native extensions, behaves the same on every
9
+ # platform, and means a reload only ever happens between requests. Only the directories Hanami
10
+ # loads code from are walked, so the cost is proportional to the app rather than to the project
11
+ # (`node_modules/` and friends are never visited).
12
+ #
13
+ # @api private
14
+ class FileChecker
15
+ # Directories whose contents {Hanami::Slice#reload} is able to pick up.
16
+ WATCHED_DIRS = %w[app config lib slices].freeze
17
+
18
+ # Ruby files and templates, plus YAML files such as translations.
19
+ WATCHED_EXTENSIONS = %w[rb erb haml slim yml yaml].freeze
20
+
21
+ # Directories whose files are all watched, whatever their extension.
22
+ #
23
+ # Templates can be in any format that Tilt supports, and their names can end in any extension
24
+ # (such as `.html.erb` or `.json.yajl`), so watching them by extension would miss some. This
25
+ # matches `app/templates/` as well as the `templates/` dir of every slice, nested slices too.
26
+ WATCHED_ANY_FILE_DIRS = %w[templates].freeze
27
+
28
+ # Files that a reload cannot apply, because they are loaded once before the app exists.
29
+ RESTART_REQUIRED_PATHS = [
30
+ File.join("config", "app.rb"),
31
+ "Gemfile",
32
+ "Gemfile.lock"
33
+ ].freeze
34
+
35
+ # `.env` files, which a reload also cannot apply.
36
+ #
37
+ # Hanami loads these once, when loading `config/app.rb`. Since a reload keeps that class,
38
+ # Hanami never loads these .env files again. Even if it did, dotenv does not overwrite values
39
+ # already in `ENV`.
40
+ #
41
+ # This matches `.env` and `.env.*`, but not names like `.envrc`. It matches some files Hanami
42
+ # does not load for the current env (such as `.env.test` in development), but those are
43
+ # rarely edited while the server runs.
44
+ DOTENV_GLOB = ".env{,.*}"
45
+
46
+ # Settings files, which a reload also cannot apply.
47
+ #
48
+ # Like the values loaded from `.env` files, Hanami reads these files once, and keeps their
49
+ # values for the life of the process.
50
+ SETTINGS_GLOB = File.join("config", "settings", "*.yml")
51
+
52
+ attr_reader :root
53
+
54
+ def initialize(root:)
55
+ @root = Pathname(root)
56
+ @globs = [
57
+ File.join("**", "*.{#{WATCHED_EXTENSIONS.join(",")}}"),
58
+ File.join("**", "{#{WATCHED_ANY_FILE_DIRS.join(",")}}", "**", "*")
59
+ ]
60
+ @signature = reloadable_signature
61
+ @seen = @signature
62
+ @failed = nil
63
+ @restart_mtimes = restart_required_mtimes
64
+ end
65
+
66
+ # Returns true if any reloadable file has changed since the last {#commit!}, and that change
67
+ # has not already been reported to {#failed!}.
68
+ #
69
+ # This deliberately does not record what it saw as the new baseline. Until {#commit!} is
70
+ # called the change is still considered outstanding, so a reload that raises is never taken
71
+ # as having been applied.
72
+ #
73
+ # @return [Boolean]
74
+ def updated?
75
+ @seen = reloadable_signature
76
+
77
+ # A failed reload leaves the app torn down, so once one has failed anything other than the
78
+ # state that failed needs a reload, even the state that was last committed.
79
+ return @seen != @failed if @failed
80
+
81
+ @seen != @signature
82
+ end
83
+
84
+ # Accepts the files seen by the last {#updated?} as the new baseline.
85
+ #
86
+ # The files are not checked again here. A file saved while the reload was running may not
87
+ # have been loaded, so it must stay outstanding for the next {#updated?} to report.
88
+ def commit!
89
+ @signature = @seen
90
+ @failed = nil
91
+ self
92
+ end
93
+
94
+ # Records that reloading the files seen by the last {#updated?} did not succeed.
95
+ #
96
+ # Nothing is committed: the change stays outstanding, so saving a fix is still picked up.
97
+ # What this does stop is {#updated?} reporting that same state again, which would otherwise
98
+ # have every request re-run a reload already known to raise.
99
+ def failed!
100
+ @failed = @seen
101
+ self
102
+ end
103
+
104
+ # Returns the paths of any changed files that a reload cannot apply.
105
+ #
106
+ # Unlike {#updated?} this records what it saw, so each change is reported once.
107
+ #
108
+ # @return [Array<String>] paths relative to the app root, empty if nothing changed
109
+ def restart_required
110
+ current = restart_required_mtimes
111
+
112
+ changed = current.reject { |path, mtime| @restart_mtimes[path] == mtime }.keys
113
+ # A deleted `.env` or settings file is no longer globbed, but its values are still loaded.
114
+ changed += @restart_mtimes.keys - current.keys
115
+ @restart_mtimes = current
116
+
117
+ changed
118
+ end
119
+
120
+ private
121
+
122
+ def reloadable_signature
123
+ # A template with a watched extension matches both globs, so remove the duplicates.
124
+ paths = WATCHED_DIRS.flat_map { |dir|
125
+ @globs.flat_map { |glob| Dir.glob(root.join(dir, glob)) }
126
+ }.uniq
127
+
128
+ # `config/app.rb` and settings files sit inside a watched directory but cannot be applied by
129
+ # a reload, so they are excluded here and reported by {#restart_required} instead.
130
+ # Otherwise every edit to them would both warn and trigger a reload that changes nothing.
131
+ signature(paths - restart_required_paths - Dir.glob(root.join(SETTINGS_GLOB)))
132
+ end
133
+
134
+ def restart_required_paths
135
+ @restart_required_paths ||= RESTART_REQUIRED_PATHS.map { |path| root.join(path).to_s }
136
+ end
137
+
138
+ # Keyed by the relative path so a change can be reported by name, and tracked individually so
139
+ # that touching one file does not mask a change to another.
140
+ def restart_required_mtimes
141
+ paths = RESTART_REQUIRED_PATHS + Dir.glob(DOTENV_GLOB, base: root) + Dir.glob(SETTINGS_GLOB, base: root)
142
+
143
+ paths.to_h do |path|
144
+ [path, File.mtime(root.join(path)).to_f]
145
+ rescue Errno::ENOENT
146
+ [path, nil]
147
+ end
148
+ end
149
+
150
+ # A hash of every file's path and mtime. A change to any file gives a different hash: a file
151
+ # being edited, added, deleted or renamed, and even an mtime moving backwards (such as a file
152
+ # restored from a backup).
153
+ #
154
+ # Only the hash is kept between requests, so memory does not grow with the app.
155
+ #
156
+ # `Dir.glob` returns paths sorted, so the same files always give the same hash.
157
+ #
158
+ # Directories are skipped. The templates glob matches them too, and a directory's mtime
159
+ # changes whenever a file is added to it, such as an editor's swap file when a template is
160
+ # opened. That would cause a reload when nothing has been edited.
161
+ def signature(paths)
162
+ entries = paths.filter_map do |path|
163
+ stat = File.stat(path)
164
+ next if stat.directory?
165
+
166
+ [path, stat.mtime.to_f]
167
+ rescue Errno::ENOENT
168
+ # Deleted between the glob and the stat; the next check will see a stable state.
169
+ nil
170
+ end
171
+
172
+ entries.hash
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,232 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/body_proxy"
4
+
5
+ module Hanami
6
+ module Reloader
7
+ # Rack middleware that reloads the app in place when its source files change.
8
+ #
9
+ # This sits *outside* the Hanami app rather than in the app's own middleware stack, because a
10
+ # reload replaces everything inside that stack. Wrapping from the outside means the request is
11
+ # dispatched into freshly loaded code, instead of into the code that was live when the request
12
+ # arrived.
13
+ #
14
+ # Files are checked once per request rather than watched in the background, so a reload only
15
+ # happens when there is something to serve, and never lands halfway through an edit.
16
+ #
17
+ # @api private
18
+ class Middleware
19
+ # Rack env key carrying a failed reload's exception to {RERAISE}.
20
+ RELOAD_ERROR = "hanami.reloader.reload_error"
21
+
22
+ # The app underneath the reloader's own webconsole middleware.
23
+ #
24
+ # Webconsole renders what is raised *below* it, but a reload error was raised before the
25
+ # request arrived. Raising it again here is what puts it back underneath webconsole. Ruby
26
+ # leaves the backtrace of an exception that already has one alone when it is re-raised, so
27
+ # the page still describes the reload rather than this line.
28
+ RERAISE = ->(env) { raise env.fetch(RELOAD_ERROR) }
29
+
30
+ # Seconds a reload waits for open responses to finish before it is put off.
31
+ #
32
+ # Ordinary responses close within milliseconds, so this only runs out when a response is
33
+ # held open, such as a streamed one.
34
+ RELOAD_WAIT = 1
35
+
36
+ def initialize(app, file_checker:, slice: nil, stdout: $stdout, reload_wait: RELOAD_WAIT)
37
+ @app = app
38
+ @file_checker = file_checker
39
+ @slice = slice
40
+ @stdout = stdout
41
+ @check_mutex = Mutex.new
42
+ @lock = ReadWriteLock.new
43
+ @reload_error = nil
44
+ @error_app = nil
45
+ @reload_wait = reload_wait
46
+ @reload_deferred = false
47
+ end
48
+
49
+ def call(env)
50
+ # While a reload is failing, console requests are the rendered error page asking for more
51
+ # detail about the very error being shown. Checking for changes first would retry a reload
52
+ # already known to raise, for a request that is not going to reach the app either way.
53
+ reload_if_needed unless @reload_error && console_request?(env)
54
+
55
+ dispatch(env)
56
+ end
57
+
58
+ private
59
+
60
+ def reload_if_needed
61
+ # `FileChecker` is not thread-safe, and `restart_required` reports each change once, so it
62
+ # must be consulted on every request and by one thread at a time.
63
+ @check_mutex.synchronize do
64
+ restart_required = @file_checker.restart_required
65
+ warn_restart_required(restart_required) if restart_required.any?
66
+
67
+ reload_slice if @file_checker.updated?
68
+ end
69
+ end
70
+
71
+ # Reloads the slice, and records whether the reload failed so requests can act on it.
72
+ #
73
+ # If open responses do not finish within the reload wait, the reload is put off and the
74
+ # request is served with the current code. The change stays outstanding, so a later request
75
+ # reloads it once those responses have closed.
76
+ #
77
+ # Must not be called while this thread holds a read lock. The write lock waits for every
78
+ # reader, including this thread, so the reload would always be put off.
79
+ def reload_slice
80
+ # If the last reload was put off (because a response stayed open past the reload wait),
81
+ # don't wait again. That response may stay open for a long time, and waiting for it on
82
+ # every request would slow each one by the full reload wait. Instead, reload only if no
83
+ # responses are open right now.
84
+ wait = @reload_deferred ? 0 : @reload_wait
85
+
86
+ # Reload under the write lock, so no request runs in the app while it is torn down.
87
+ #
88
+ # Record the result while under the lock too. A request that is waiting for this reload to
89
+ # finish must be able to see whether it failed as soon as it gets the read lock.
90
+ reloaded = @lock.with_write_lock(timeout: wait) do
91
+ reload
92
+ @reload_error = nil
93
+ @error_app = nil # Its pages are from code this reload has just replaced.
94
+ @file_checker.commit!
95
+ rescue StandardError, ScriptError => exception
96
+ # Include `ScriptError` (covering `SyntaxError` and `LoadError`) as a likely error to come
97
+ # from a reload. Ignore anything broader (such as `Interrupt` or `NoMemoryError`), as
98
+ # unlikely to be an app code concern.
99
+
100
+ @reload_error = exception
101
+ @file_checker.failed! # Before building the error app, in case that raises.
102
+ @error_app = build_error_app
103
+ end
104
+
105
+ if reloaded
106
+ @reload_deferred = false
107
+ elsif !@reload_deferred
108
+ @reload_deferred = true
109
+ warn_reload_deferred
110
+ end
111
+ end
112
+
113
+ # Dispatches the request to the app, or renders the error if the last reload failed.
114
+ #
115
+ # Holds a read lock until the response body is closed. Requests can run at the same time as
116
+ # each other, but never at the same time as a reload.
117
+ def dispatch(env)
118
+ @lock.acquire_read_lock
119
+ held = true
120
+
121
+ begin
122
+ # Never dispatch after a failed reload, which unloads before it prepares, leaving us a
123
+ # half-built app whose own errors would only obscure the real one.
124
+ #
125
+ # Check this after taking the lock, not before: if a reload was running when this request
126
+ # arrived, the request has now waited for it to finish, so it can see whether it failed.
127
+ return render_reload_error(env, @reload_error) if @reload_error
128
+
129
+ status, headers, body = @app.call(env)
130
+
131
+ # Rack bodies can be lazy, so returning from `call` does not mean the response has been
132
+ # written. Hold the lock until the body is closed, or a reload could pull the app out
133
+ # from under it mid-response.
134
+ proxied = Rack::BodyProxy.new(body) { @lock.release_read_lock }
135
+ held = false
136
+
137
+ [status, headers, proxied]
138
+ ensure
139
+ @lock.release_read_lock if held
140
+ end
141
+ end
142
+
143
+ # Renders the failed reload, so it is presented like any other error in development.
144
+ def render_reload_error(env, error)
145
+ # Nothing here can render it, so do what the reloader has always done and let it reach
146
+ # the server.
147
+ raise error unless @error_app
148
+
149
+ env[RELOAD_ERROR] = error
150
+ @error_app.call(env)
151
+ end
152
+
153
+ def console_request?(env)
154
+ return false unless @error_app
155
+
156
+ env["PATH_INFO"].to_s.start_with?(Hanami::Webconsole::MOUNT_PATH)
157
+ end
158
+
159
+ # Builds the middleware that renders a failed reload.
160
+ #
161
+ # This is the reloader's own webconsole instance rather than the app's, which is inside the
162
+ # stack the failed reload has just torn down.
163
+ #
164
+ # It is kept for as long as this failed reload stays the current one, because the console on
165
+ # the page it renders addresses error pages by id in that instance's registry, over later
166
+ # requests. It is built anew for each failed reload, and dropped after a successful one. This
167
+ # matches how Hanami builds the app's own webconsole anew after every reload: a webconsole's
168
+ # pages hold bindings into the code that was loaded when they were rendered, so they must go
169
+ # away when that code does. A console request from an older page then finds no page, and
170
+ # webconsole tells the developer to refresh.
171
+ #
172
+ # If building the error app raises, that error is logged and nil is returned. The actual
173
+ # reload error is what the developer needs to see, and it will still reach the server without
174
+ # an error app.
175
+ #
176
+ # @return [#call, nil] nil when webconsole cannot render the error
177
+ def build_error_app
178
+ return nil unless render_detailed_errors?
179
+
180
+ # Normally already loaded: the app's own stack requires it under this same condition.
181
+ require "hanami/webconsole" unless defined?(Hanami::Webconsole::Middleware)
182
+
183
+ Hanami::Webconsole::Middleware.new(RERAISE, slice)
184
+ rescue LoadError
185
+ nil
186
+ rescue StandardError => exception
187
+ @stdout.puts(
188
+ "[hanami] Could not render the reload error with hanami-webconsole " \
189
+ "(#{exception.class}: #{exception.message})"
190
+ )
191
+ nil
192
+ end
193
+
194
+ # Gated exactly as Hanami gates webconsole in the app's own middleware stack, so the
195
+ # reloader never shows a detailed error page where the app would not have.
196
+ def render_detailed_errors?
197
+ Hanami.bundled?("hanami-webconsole") && slice.config.render_detailed_errors
198
+ end
199
+
200
+ def reload
201
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
202
+
203
+ slice.reload
204
+
205
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
206
+ @stdout.puts("[hanami] Reloaded in #{(elapsed * 1000).round}ms")
207
+ end
208
+
209
+ def warn_reload_deferred
210
+ open = @lock.readers
211
+ responses = open == 1 ? "1 open response" : "#{open} open responses"
212
+
213
+ @stdout.puts(
214
+ "[hanami] Waiting for #{responses} to finish before reloading. " \
215
+ "Until then, requests are served with the current code."
216
+ )
217
+ end
218
+
219
+ def warn_restart_required(paths)
220
+ @stdout.puts(
221
+ "[hanami] #{paths.join(', ')} cannot be reloaded. " \
222
+ "Restart the server to apply your changes."
223
+ )
224
+ end
225
+
226
+ # Resolved lazily: the middleware is built while the app is being loaded.
227
+ def slice
228
+ @slice || Hanami.app
229
+ end
230
+ end
231
+ end
232
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hanami
4
+ module Reloader
5
+ # A read/write lock whose writer gives up after a timeout.
6
+ #
7
+ # Many readers can hold the lock at once, but a writer holds it alone. While a writer is
8
+ # waiting, new readers wait too, so a steady flow of readers cannot keep it out. If the writer
9
+ # gives up, those readers go ahead.
10
+ #
11
+ # This exists because the reloader needs a write lock that waits for readers, but only up to a
12
+ # timeout. `Concurrent::ReadWriteLock` has no timeout, and `Concurrent::ReentrantReadWriteLock`
13
+ # can only try for the write lock without waiting at all.
14
+ #
15
+ # `Concurrent::ReentrantReadWriteLock` also expects a read lock to be released by the fiber that
16
+ # acquired it. The reloader releases its read locks when the response body is closed, and Rack
17
+ # does not promise that happens on the same thread or fiber that called the app.
18
+ #
19
+ # @api private
20
+ class ReadWriteLock
21
+ def initialize
22
+ @mutex = Mutex.new
23
+ @changed = ConditionVariable.new
24
+ @readers = 0
25
+ @writer = false
26
+ @waiting_writers = 0
27
+ end
28
+
29
+ # Returns the number of read locks currently held.
30
+ #
31
+ # @return [Integer]
32
+ def readers
33
+ @mutex.synchronize { @readers }
34
+ end
35
+
36
+ # Blocks until no writer holds the lock or is waiting for it, then takes a read lock.
37
+ def acquire_read_lock
38
+ @mutex.synchronize do
39
+ @changed.wait(@mutex) while @writer || @waiting_writers.positive?
40
+ @readers += 1
41
+ end
42
+
43
+ self
44
+ end
45
+
46
+ # Releases a read lock. This may be called from any thread or fiber.
47
+ def release_read_lock
48
+ @mutex.synchronize do
49
+ raise ThreadError, "no read lock is held" if @readers.zero?
50
+
51
+ @readers -= 1
52
+ @changed.broadcast if @readers.zero?
53
+ end
54
+
55
+ self
56
+ end
57
+
58
+ # Takes the write lock and yields, waiting up to `timeout` seconds for readers to finish.
59
+ #
60
+ # With a timeout of zero, the lock is only taken if it is free right now.
61
+ #
62
+ # @param timeout [Numeric] seconds to wait for the lock
63
+ #
64
+ # @return [Boolean] true if the block ran, false if the lock could not be taken in time
65
+ def with_write_lock(timeout:)
66
+ return false unless try_acquire_write_lock(timeout)
67
+
68
+ begin
69
+ yield
70
+ ensure
71
+ release_write_lock
72
+ end
73
+
74
+ true
75
+ end
76
+
77
+ private
78
+
79
+ def try_acquire_write_lock(timeout)
80
+ deadline = now + timeout
81
+
82
+ @mutex.synchronize do
83
+ @waiting_writers += 1
84
+
85
+ begin
86
+ while @writer || @readers.positive?
87
+ remaining = deadline - now
88
+ return false if remaining <= 0
89
+
90
+ @changed.wait(@mutex, remaining)
91
+ end
92
+
93
+ @writer = true
94
+ ensure
95
+ @waiting_writers -= 1
96
+
97
+ # Readers queued behind this writer can go ahead if it gave up.
98
+ @changed.broadcast unless @writer
99
+ end
100
+ end
101
+ end
102
+
103
+ def release_write_lock
104
+ @mutex.synchronize do
105
+ @writer = false
106
+ @changed.broadcast
107
+ end
108
+ end
109
+
110
+ def now
111
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "hanami/cli/server"
4
+ require "rack/builder"
5
+
6
+ module Hanami
7
+ module Reloader
8
+ # Runs the rack server against an app wrapped in {Middleware}.
9
+ #
10
+ # Hanami's own middleware stack lives inside `Hanami.app`, which a reload replaces wholesale.
11
+ # The reloader therefore has to sit outside the app, and the only place outside it - short of
12
+ # every app editing its `config.ru` - is between the rack config file being read and the server
13
+ # being started.
14
+ #
15
+ # `Hanami::CLI::Server` hands the rack server a path to `config.ru` and lets it load the file,
16
+ # leaving no seam there. Subclassing it opens one while still inheriting its option mapping and
17
+ # its choice of rack server, so nothing about how a Hanami app is served is duplicated here.
18
+ #
19
+ # @api private
20
+ # @since 3.1.0
21
+ class Server < Hanami::CLI::Server
22
+ # @api private
23
+ # @since 3.1.0
24
+ def initialize(stdout: $stdout, stderr: $stderr, **opts)
25
+ super(**opts)
26
+ @stdout = stdout
27
+ @stderr = stderr
28
+ end
29
+
30
+ # @api private
31
+ # @since 3.1.0
32
+ def call(**options)
33
+ rack_options = Hash[
34
+ extract_rack_fallback_options(options) + extract_overriding_options(options)
35
+ ]
36
+
37
+ # Read here rather than by the caller, so a `--config` option is honoured.
38
+ rack_options[:app] = wrap(Rack::Builder.parse_file(rack_options.fetch(:config)))
39
+
40
+ rack_server.start(rack_options)
41
+ end
42
+
43
+ private
44
+
45
+ # The app is only available once the rack config file has been read, so this is the first
46
+ # point at which its config can be consulted.
47
+ #
48
+ # @api private
49
+ # @since 3.1.0
50
+ def wrap(app)
51
+ unless Hanami.app.config.code_reloading
52
+ @stderr.puts(
53
+ "WARNING: `config.code_reloading` is false, so the app cannot be reloaded. " \
54
+ "Starting without code reloading."
55
+ )
56
+ return app
57
+ end
58
+
59
+ Middleware.new(app, file_checker: FileChecker.new(root: Hanami.app.root), stdout: @stdout)
60
+ end
61
+ end
62
+ end
63
+ end
@@ -3,6 +3,6 @@
3
3
  module Hanami
4
4
  module Reloader
5
5
  # @api public
6
- VERSION = "3.0.0.rc1"
6
+ VERSION = "3.1.0.rc1"
7
7
  end
8
8
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: hanami-reloader
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.0.rc1
4
+ version: 3.1.0.rc1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Hanakai team
@@ -10,47 +10,33 @@ cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
- name: guard
14
- requirement: !ruby/object:Gem::Requirement
15
- requirements:
16
- - - "~>"
17
- - !ruby/object:Gem::Version
18
- version: '2.19'
19
- type: :runtime
20
- prerelease: false
21
- version_requirements: !ruby/object:Gem::Requirement
22
- requirements:
23
- - - "~>"
24
- - !ruby/object:Gem::Version
25
- version: '2.19'
26
- - !ruby/object:Gem::Dependency
27
- name: guard-puma
13
+ name: hanami-cli
28
14
  requirement: !ruby/object:Gem::Requirement
29
15
  requirements:
30
16
  - - "~>"
31
17
  - !ruby/object:Gem::Version
32
- version: '0.8'
18
+ version: 3.1.0.rc
33
19
  type: :runtime
34
20
  prerelease: false
35
21
  version_requirements: !ruby/object:Gem::Requirement
36
22
  requirements:
37
23
  - - "~>"
38
24
  - !ruby/object:Gem::Version
39
- version: '0.8'
25
+ version: 3.1.0.rc
40
26
  - !ruby/object:Gem::Dependency
41
- name: hanami-cli
27
+ name: rack
42
28
  requirement: !ruby/object:Gem::Requirement
43
29
  requirements:
44
- - - "~>"
30
+ - - ">="
45
31
  - !ruby/object:Gem::Version
46
- version: 3.0.0.rc
32
+ version: '3.0'
47
33
  type: :runtime
48
34
  prerelease: false
49
35
  version_requirements: !ruby/object:Gem::Requirement
50
36
  requirements:
51
- - - "~>"
37
+ - - ">="
52
38
  - !ruby/object:Gem::Version
53
- version: 3.0.0.rc
39
+ version: '3.0'
54
40
  - !ruby/object:Gem::Dependency
55
41
  name: zeitwerk
56
42
  requirement: !ruby/object:Gem::Requirement
@@ -82,6 +68,10 @@ files:
82
68
  - lib/hanami-reloader.rb
83
69
  - lib/hanami/reloader.rb
84
70
  - lib/hanami/reloader/commands.rb
71
+ - lib/hanami/reloader/file_checker.rb
72
+ - lib/hanami/reloader/middleware.rb
73
+ - lib/hanami/reloader/read_write_lock.rb
74
+ - lib/hanami/reloader/server.rb
85
75
  - lib/hanami/reloader/version.rb
86
76
  homepage: https://hanamirb.org
87
77
  licenses: