puma 3.12.6 → 6.2.2

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of puma might be problematic. Click here for more details.

Files changed (100) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +1775 -451
  3. data/LICENSE +23 -20
  4. data/README.md +193 -65
  5. data/bin/puma-wild +3 -9
  6. data/docs/architecture.md +59 -21
  7. data/docs/compile_options.md +55 -0
  8. data/docs/deployment.md +69 -58
  9. data/docs/fork_worker.md +31 -0
  10. data/docs/images/puma-connection-flow-no-reactor.png +0 -0
  11. data/docs/images/puma-connection-flow.png +0 -0
  12. data/docs/images/puma-general-arch.png +0 -0
  13. data/docs/jungle/README.md +9 -0
  14. data/{tools → docs}/jungle/rc.d/README.md +1 -1
  15. data/{tools → docs}/jungle/rc.d/puma +2 -2
  16. data/{tools → docs}/jungle/rc.d/puma.conf +0 -0
  17. data/docs/kubernetes.md +66 -0
  18. data/docs/nginx.md +2 -2
  19. data/docs/plugins.md +22 -12
  20. data/docs/rails_dev_mode.md +28 -0
  21. data/docs/restart.md +47 -22
  22. data/docs/signals.md +13 -11
  23. data/docs/stats.md +142 -0
  24. data/docs/systemd.md +94 -120
  25. data/docs/testing_benchmarks_local_files.md +150 -0
  26. data/docs/testing_test_rackup_ci_files.md +36 -0
  27. data/ext/puma_http11/PumaHttp11Service.java +2 -2
  28. data/ext/puma_http11/ext_help.h +1 -1
  29. data/ext/puma_http11/extconf.rb +61 -3
  30. data/ext/puma_http11/http11_parser.c +103 -117
  31. data/ext/puma_http11/http11_parser.h +2 -2
  32. data/ext/puma_http11/http11_parser.java.rl +22 -38
  33. data/ext/puma_http11/http11_parser.rl +3 -3
  34. data/ext/puma_http11/http11_parser_common.rl +6 -6
  35. data/ext/puma_http11/mini_ssl.c +361 -99
  36. data/ext/puma_http11/no_ssl/PumaHttp11Service.java +15 -0
  37. data/ext/puma_http11/org/jruby/puma/Http11.java +108 -116
  38. data/ext/puma_http11/org/jruby/puma/Http11Parser.java +84 -99
  39. data/ext/puma_http11/org/jruby/puma/MiniSSL.java +248 -92
  40. data/ext/puma_http11/puma_http11.c +49 -57
  41. data/lib/puma/app/status.rb +71 -49
  42. data/lib/puma/binder.rb +242 -150
  43. data/lib/puma/cli.rb +38 -34
  44. data/lib/puma/client.rb +387 -244
  45. data/lib/puma/cluster/worker.rb +180 -0
  46. data/lib/puma/cluster/worker_handle.rb +97 -0
  47. data/lib/puma/cluster.rb +261 -243
  48. data/lib/puma/commonlogger.rb +21 -14
  49. data/lib/puma/configuration.rb +116 -88
  50. data/lib/puma/const.rb +101 -100
  51. data/lib/puma/control_cli.rb +115 -70
  52. data/lib/puma/detect.rb +33 -2
  53. data/lib/puma/dsl.rb +731 -134
  54. data/lib/puma/error_logger.rb +113 -0
  55. data/lib/puma/events.rb +16 -112
  56. data/lib/puma/io_buffer.rb +42 -5
  57. data/lib/puma/jruby_restart.rb +2 -59
  58. data/lib/puma/json_serialization.rb +96 -0
  59. data/lib/puma/launcher/bundle_pruner.rb +104 -0
  60. data/lib/puma/launcher.rb +184 -133
  61. data/lib/puma/log_writer.rb +147 -0
  62. data/lib/puma/minissl/context_builder.rb +92 -0
  63. data/lib/puma/minissl.rb +246 -70
  64. data/lib/puma/null_io.rb +18 -1
  65. data/lib/puma/plugin/systemd.rb +90 -0
  66. data/lib/puma/plugin/tmp_restart.rb +3 -1
  67. data/lib/puma/plugin.rb +7 -13
  68. data/lib/puma/rack/builder.rb +7 -9
  69. data/lib/puma/rack/urlmap.rb +2 -0
  70. data/lib/puma/rack_default.rb +21 -4
  71. data/lib/puma/reactor.rb +85 -316
  72. data/lib/puma/request.rb +665 -0
  73. data/lib/puma/runner.rb +94 -69
  74. data/lib/puma/sd_notify.rb +149 -0
  75. data/lib/puma/server.rb +314 -771
  76. data/lib/puma/single.rb +20 -74
  77. data/lib/puma/state_file.rb +45 -8
  78. data/lib/puma/thread_pool.rb +142 -92
  79. data/lib/puma/util.rb +22 -10
  80. data/lib/puma.rb +60 -5
  81. data/lib/rack/handler/puma.rb +113 -91
  82. data/tools/Dockerfile +16 -0
  83. data/tools/trickletest.rb +0 -1
  84. metadata +54 -32
  85. data/ext/puma_http11/io_buffer.c +0 -155
  86. data/lib/puma/accept_nonblock.rb +0 -23
  87. data/lib/puma/compat.rb +0 -14
  88. data/lib/puma/convenient.rb +0 -25
  89. data/lib/puma/daemon_ext.rb +0 -33
  90. data/lib/puma/delegation.rb +0 -13
  91. data/lib/puma/java_io_buffer.rb +0 -47
  92. data/lib/puma/rack/backports/uri/common_193.rb +0 -33
  93. data/lib/puma/tcp_logger.rb +0 -41
  94. data/tools/jungle/README.md +0 -19
  95. data/tools/jungle/init.d/README.md +0 -61
  96. data/tools/jungle/init.d/puma +0 -421
  97. data/tools/jungle/init.d/run-puma +0 -18
  98. data/tools/jungle/upstart/README.md +0 -61
  99. data/tools/jungle/upstart/puma-manager.conf +0 -31
  100. data/tools/jungle/upstart/puma.conf +0 -69
data/lib/puma/plugin.rb CHANGED
@@ -10,7 +10,7 @@ module Puma
10
10
 
11
11
  def create(name)
12
12
  if cls = Plugins.find(name)
13
- plugin = cls.new(Plugin)
13
+ plugin = cls.new
14
14
  @instances << plugin
15
15
  return plugin
16
16
  end
@@ -62,8 +62,11 @@ module Puma
62
62
  end
63
63
 
64
64
  def fire_background
65
- @background.each do |b|
66
- Thread.new(&b)
65
+ @background.each_with_index do |b, i|
66
+ Thread.new do
67
+ Puma.set_thread_name "plgn bg #{i}"
68
+ b.call
69
+ end
67
70
  end
68
71
  end
69
72
  end
@@ -88,7 +91,7 @@ module Puma
88
91
  path = ary.first[CALLER_FILE]
89
92
 
90
93
  m = %r!puma/plugin/([^/]*)\.rb$!.match(path)
91
- return m[1]
94
+ m[1]
92
95
  end
93
96
 
94
97
  def self.create(&blk)
@@ -101,17 +104,8 @@ module Puma
101
104
  Plugins.register name, cls
102
105
  end
103
106
 
104
- def initialize(loader)
105
- @loader = loader
106
- end
107
-
108
107
  def in_background(&blk)
109
108
  Plugins.add_background blk
110
109
  end
111
-
112
- def workers_supported?
113
- return false if Puma.jruby? || Puma.windows?
114
- true
115
- end
116
110
  end
117
111
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Puma
2
4
  end
3
5
 
@@ -65,10 +67,6 @@ module Puma::Rack
65
67
  options[:environment] = e
66
68
  }
67
69
 
68
- opts.on("-D", "--daemonize", "run daemonized in the background") { |d|
69
- options[:daemonize] = d ? true : false
70
- }
71
-
72
70
  opts.on("-P", "--pid FILE", "file to store PID") { |f|
73
71
  options[:pid] = ::File.expand_path(f)
74
72
  }
@@ -104,13 +102,13 @@ module Puma::Rack
104
102
  begin
105
103
  info = []
106
104
  server = Rack::Handler.get(options[:server]) || Rack::Handler.default(options)
107
- if server && server.respond_to?(:valid_options)
105
+ if server&.respond_to?(:valid_options)
108
106
  info << ""
109
107
  info << "Server-specific options for #{server.name}:"
110
108
 
111
109
  has_options = false
112
110
  server.valid_options.each do |name, description|
113
- next if name.to_s =~ /^(Host|Port)[^a-zA-Z]/ # ignore handler's host and port options, we do our own.
111
+ next if /^(Host|Port)[^a-zA-Z]/.match? name.to_s # ignore handler's host and port options, we do our own.
114
112
 
115
113
  info << " -O %-21s %s" % [name, description]
116
114
  has_options = true
@@ -167,7 +165,7 @@ module Puma::Rack
167
165
  require config
168
166
  app = Object.const_get(::File.basename(config, '.rb').capitalize)
169
167
  end
170
- return app, options
168
+ [app, options]
171
169
  end
172
170
 
173
171
  def self.new_from_string(builder_script, file="(rackup)")
@@ -278,7 +276,7 @@ module Puma::Rack
278
276
  app = @map ? generate_map(@run, @map) : @run
279
277
  fail "missing run or map statement" unless app
280
278
  app = @use.reverse.inject(app) { |a,e| e[a] }
281
- @warmup.call(app) if @warmup
279
+ @warmup&.call app
282
280
  app
283
281
  end
284
282
 
@@ -289,7 +287,7 @@ module Puma::Rack
289
287
  private
290
288
 
291
289
  def generate_map(default_app, mapping)
292
- require 'puma/rack/urlmap'
290
+ require_relative 'urlmap'
293
291
 
294
292
  mapped = default_app ? {'/' => default_app} : {}
295
293
  mapping.each { |r,b| mapped[r] = self.class.new(default_app, &b).to_app }
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Puma::Rack
2
4
  # Rack::URLMap takes a hash mapping urls or paths to apps, and
3
5
  # dispatches accordingly. Support for HTTP/1.1 host names exists if
@@ -1,7 +1,24 @@
1
- require 'rack/handler/puma'
1
+ # frozen_string_literal: true
2
2
 
3
- module Rack::Handler
4
- def self.default(options = {})
5
- Rack::Handler::Puma
3
+ require_relative '../rack/handler/puma'
4
+
5
+ # rackup was removed in Rack 3, it is now a separate gem
6
+ if Object.const_defined? :Rackup
7
+ module Rackup
8
+ module Handler
9
+ def self.default(options = {})
10
+ ::Rackup::Handler::Puma
11
+ end
12
+ end
13
+ end
14
+ elsif Object.const_defined?(:Rack) && Rack::RELEASE < '3'
15
+ module Rack
16
+ module Handler
17
+ def self.default(options = {})
18
+ ::Rack::Handler::Puma
19
+ end
20
+ end
6
21
  end
22
+ else
23
+ raise "Rack 3 must be used with the Rackup gem"
7
24
  end
data/lib/puma/reactor.rb CHANGED
@@ -1,347 +1,116 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'puma/util'
4
- require 'puma/minissl'
3
+ require_relative 'queue_close' unless ::Queue.instance_methods.include? :close
5
4
 
6
5
  module Puma
7
- # Internal Docs, Not a public interface.
8
- #
9
- # The Reactor object is responsible for ensuring that a request has been
10
- # completely received before it starts to be processed. This may be known as read buffering.
11
- # If read buffering is not done, and no other read buffering is performed (such as by an application server
12
- # such as nginx) then the application would be subject to a slow client attack.
13
- #
14
- # Each Puma "worker" process has its own Reactor. For example if you start puma with `$ puma -w 5` then
15
- # it will have 5 workers and each worker will have it's own reactor.
16
- #
17
- # For a graphical representation of how the reactor works see [architecture.md](https://github.com/puma/puma/blob/master/docs/architecture.md#connection-pipeline).
18
- #
19
- # ## Reactor Flow
20
- #
21
- # A request comes into a `Puma::Server` instance, it is then passed to a `Puma::Reactor` instance.
22
- # The reactor stores the request in an array and calls `IO.select` on the array in a loop.
6
+ class UnsupportedBackend < StandardError; end
7
+
8
+ # Monitors a collection of IO objects, calling a block whenever
9
+ # any monitored object either receives data or times out, or when the Reactor shuts down.
23
10
  #
24
- # When the request is written to by the client then the `IO.select` will "wake up" and
25
- # return the references to any objects that caused it to "wake". The reactor
26
- # then loops through each of these request objects, and sees if they're complete. If they
27
- # have a full header and body then the reactor passes the request to a thread pool.
28
- # Once in a thread pool, a "worker thread" can run the the application's Ruby code against the request.
11
+ # The waiting/wake up is performed with nio4r, which will use the appropriate backend (libev,
12
+ # Java NIO or just plain IO#select). The call to `NIO::Selector#select` will
13
+ # 'wakeup' any IO object that receives data.
29
14
  #
30
- # If the request is not complete, then it stays in the array, and the next time any
31
- # data is written to that socket reference, then the loop is woken up and it is checked for completeness again.
15
+ # This class additionally tracks a timeout for every added object,
16
+ # and wakes up any object when its timeout elapses.
32
17
  #
33
- # A detailed example is given in the docs for `run_internal` which is where the bulk
34
- # of this logic lives.
18
+ # The implementation uses a Queue to synchronize adding new objects from the internal select loop.
35
19
  class Reactor
36
- DefaultSleepFor = 5
37
-
38
- # Creates an instance of Puma::Reactor
39
- #
40
- # The `server` argument is an instance of `Puma::Server`
41
- # this is used to write a response for "low level errors"
42
- # when there is an exception inside of the reactor.
43
- #
44
- # The `app_pool` is an instance of `Puma::ThreadPool`.
45
- # Once a request is fully formed (header and body are received)
46
- # it will be passed to the `app_pool`.
47
- def initialize(server, app_pool)
48
- @server = server
49
- @events = server.events
50
- @app_pool = app_pool
51
-
52
- @mutex = Mutex.new
53
-
54
- # Read / Write pipes to wake up internal while loop
55
- @ready, @trigger = Puma::Util.pipe
56
- @input = []
57
- @sleep_for = DefaultSleepFor
20
+ # Create a new Reactor to monitor IO objects added by #add.
21
+ # The provided block will be invoked when an IO has data available to read,
22
+ # its timeout elapses, or when the Reactor shuts down.
23
+ def initialize(backend, &block)
24
+ require 'nio'
25
+ unless backend == :auto || NIO::Selector.backends.include?(backend)
26
+ raise "unsupported IO selector backend: #{backend} (available backends: #{NIO::Selector.backends.join(', ')})"
27
+ end
28
+ @selector = backend == :auto ? NIO::Selector.new : NIO::Selector.new(backend)
29
+ @input = Queue.new
58
30
  @timeouts = []
59
-
60
- @sockets = [@ready]
31
+ @block = block
61
32
  end
62
33
 
63
- private
64
-
65
-
66
- # Until a request is added via the `add` method this method will internally
67
- # loop, waiting on the `sockets` array objects. The only object in this
68
- # array at first is the `@ready` IO object, which is the read end of a pipe
69
- # connected to `@trigger` object. When `@trigger` is written to, then the loop
70
- # will break on `IO.select` and return an array.
71
- #
72
- # ## When a request is added:
73
- #
74
- # When the `add` method is called, an instance of `Puma::Client` is added to the `@input` array.
75
- # Next the `@ready` pipe is "woken" by writing a string of `"*"` to `@trigger`.
76
- #
77
- # When that happens, the internal loop stops blocking at `IO.select` and returns a reference
78
- # to whatever "woke" it up. On the very first loop, the only thing in `sockets` is `@ready`.
79
- # When `@trigger` is written-to, the loop "wakes" and the `ready`
80
- # variable returns an array of arrays that looks like `[[#<IO:fd 10>], [], []]` where the
81
- # first IO object is the `@ready` object. This first array `[#<IO:fd 10>]`
82
- # is saved as a `reads` variable.
83
- #
84
- # The `reads` variable is iterated through. In the case that the object
85
- # is the same as the `@ready` input pipe, then we know that there was a `trigger` event.
86
- #
87
- # If there was a trigger event, then one byte of `@ready` is read into memory. In the case of the first request,
88
- # the reactor sees that it's a `"*"` value and the reactor adds the contents of `@input` into the `sockets` array.
89
- # The while then loop continues to iterate again, but now the `sockets` array contains a `Puma::Client` instance in addition
90
- # to the `@ready` IO object. For example: `[#<IO:fd 10>, #<Puma::Client:0x3fdc1103bee8 @ready=false>]`.
91
- #
92
- # Since the `Puma::Client` in this example has data that has not been read yet,
93
- # the `IO.select` is immediately able to "wake" and read from the `Puma::Client`. At this point the
94
- # `ready` output looks like this: `[[#<Puma::Client:0x3fdc1103bee8 @ready=false>], [], []]`.
95
- #
96
- # Each element in the first entry is iterated over. The `Puma::Client` object is not
97
- # the `@ready` pipe, so the reactor checks to see if it has the fully header and body with
98
- # the `Puma::Client#try_to_finish` method. If the full request has been sent,
99
- # then the request is passed off to the `@app_pool` thread pool so that a "worker thread"
100
- # can pick up the request and begin to execute application logic. This is done
101
- # via `@app_pool << c`. The `Puma::Client` is then removed from the `sockets` array.
102
- #
103
- # If the request body is not present then nothing will happen, and the loop will iterate
104
- # again. When the client sends more data to the socket the `Puma::Client` object will
105
- # wake up the `IO.select` and it can again be checked to see if it's ready to be
106
- # passed to the thread pool.
107
- #
108
- # ## Time Out Case
109
- #
110
- # In addition to being woken via a write to one of the sockets the `IO.select` will
111
- # periodically "time out" of the sleep. One of the functions of this is to check for
112
- # any requests that have "timed out". At the end of the loop it's checked to see if
113
- # the first element in the `@timeout` array has exceed it's allowed time. If so,
114
- # the client object is removed from the timeout aray, a 408 response is written.
115
- # Then it's connection is closed, and the object is removed from the `sockets` array
116
- # that watches for new data.
117
- #
118
- # This behavior loops until all the objects that have timed out have been removed.
119
- #
120
- # Once all the timeouts have been processed, the next duration of the `IO.select` sleep
121
- # will be set to be equal to the amount of time it will take for the next timeout to occur.
122
- # This calculation happens in `calculate_sleep`.
123
- def run_internal
124
- sockets = @sockets
125
-
126
- while true
127
- begin
128
- ready = IO.select sockets, nil, nil, @sleep_for
129
- rescue IOError => e
130
- Thread.current.purge_interrupt_queue if Thread.current.respond_to? :purge_interrupt_queue
131
- if sockets.any? { |socket| socket.closed? }
132
- STDERR.puts "Error in select: #{e.message} (#{e.class})"
133
- STDERR.puts e.backtrace
134
- sockets = sockets.reject { |socket| socket.closed? }
135
- retry
136
- else
137
- raise
138
- end
139
- end
140
-
141
- if ready and reads = ready[0]
142
- reads.each do |c|
143
- if c == @ready
144
- @mutex.synchronize do
145
- case @ready.read(1)
146
- when "*"
147
- sockets += @input
148
- @input.clear
149
- when "c"
150
- sockets.delete_if do |s|
151
- if s == @ready
152
- false
153
- else
154
- s.close
155
- true
156
- end
157
- end
158
- when "!"
159
- return
160
- end
161
- end
162
- else
163
- # We have to be sure to remove it from the timeout
164
- # list or we'll accidentally close the socket when
165
- # it's in use!
166
- if c.timeout_at
167
- @mutex.synchronize do
168
- @timeouts.delete c
169
- end
170
- end
171
-
172
- begin
173
- if c.try_to_finish
174
- @app_pool << c
175
- sockets.delete c
176
- end
177
-
178
- # Don't report these to the lowlevel_error handler, otherwise
179
- # will be flooding them with errors when persistent connections
180
- # are closed.
181
- rescue ConnectionError
182
- c.write_500
183
- c.close
184
-
185
- sockets.delete c
186
-
187
- # SSL handshake failure
188
- rescue MiniSSL::SSLError => e
189
- @server.lowlevel_error(e, c.env)
190
-
191
- ssl_socket = c.io
192
- addr = ssl_socket.peeraddr.last
193
- cert = ssl_socket.peercert
194
-
195
- c.close
196
- sockets.delete c
197
-
198
- @events.ssl_error @server, addr, cert, e
199
-
200
- # The client doesn't know HTTP well
201
- rescue HttpParserError => e
202
- @server.lowlevel_error(e, c.env)
203
-
204
- c.write_400
205
- c.close
206
-
207
- sockets.delete c
208
-
209
- @events.parse_error @server, c.env, e
210
- rescue StandardError => e
211
- @server.lowlevel_error(e, c.env)
212
-
213
- c.write_500
214
- c.close
215
-
216
- sockets.delete c
217
- end
218
- end
219
- end
220
- end
221
-
222
- unless @timeouts.empty?
223
- @mutex.synchronize do
224
- now = Time.now
225
-
226
- while @timeouts.first.timeout_at < now
227
- c = @timeouts.shift
228
- c.write_408 if c.in_data_phase
229
- c.close
230
- sockets.delete c
231
-
232
- break if @timeouts.empty?
233
- end
234
-
235
- calculate_sleep
236
- end
34
+ # Run the internal select loop, using a background thread by default.
35
+ def run(background=true)
36
+ if background
37
+ @thread = Thread.new do
38
+ Puma.set_thread_name "reactor"
39
+ select_loop
237
40
  end
41
+ else
42
+ select_loop
238
43
  end
239
44
  end
240
45
 
241
- public
242
-
243
- def run
244
- run_internal
245
- ensure
246
- @trigger.close
247
- @ready.close
248
- end
249
-
250
- def run_in_thread
251
- @thread = Thread.new do
252
- begin
253
- run_internal
254
- rescue StandardError => e
255
- STDERR.puts "Error in reactor loop escaped: #{e.message} (#{e.class})"
256
- STDERR.puts e.backtrace
257
- retry
258
- ensure
259
- @trigger.close
260
- @ready.close
261
- end
262
- end
46
+ # Add a new client to monitor.
47
+ # The object must respond to #timeout and #timeout_at.
48
+ # Returns false if the reactor is already shut down.
49
+ def add(client)
50
+ @input << client
51
+ @selector.wakeup
52
+ true
53
+ rescue ClosedQueueError, IOError # Ignore if selector is already closed
54
+ false
263
55
  end
264
56
 
265
- # The `calculate_sleep` sets the value that the `IO.select` will
266
- # sleep for in the main reactor loop when no sockets are being written to.
267
- #
268
- # The values kept in `@timeouts` are sorted so that the first timeout
269
- # comes first in the array. When there are no timeouts the default timeout is used.
270
- #
271
- # Otherwise a sleep value is set that is the same as the amount of time it
272
- # would take for the first element to time out.
273
- #
274
- # If that value is in the past, then a sleep value of zero is used.
275
- def calculate_sleep
276
- if @timeouts.empty?
277
- @sleep_for = DefaultSleepFor
278
- else
279
- diff = @timeouts.first.timeout_at.to_f - Time.now.to_f
280
-
281
- if diff < 0.0
282
- @sleep_for = 0
283
- else
284
- @sleep_for = diff
285
- end
57
+ # Shutdown the reactor, blocking until the background thread is finished.
58
+ def shutdown
59
+ @input.close
60
+ begin
61
+ @selector.wakeup
62
+ rescue IOError # Ignore if selector is already closed
286
63
  end
64
+ @thread&.join
287
65
  end
288
66
 
289
- # This method adds a connection to the reactor
290
- #
291
- # Typically called by `Puma::Server` the value passed in
292
- # is usually a `Puma::Client` object that responds like an IO
293
- # object.
294
- #
295
- # The main body of the reactor loop is in `run_internal` and it
296
- # will sleep on `IO.select`. When a new connection is added to the
297
- # reactor it cannot be added directly to the `sockets` aray, because
298
- # the `IO.select` will not be watching for it yet.
299
- #
300
- # Instead what needs to happen is that `IO.select` needs to be woken up,
301
- # the contents of `@input` added to the `sockets` array, and then
302
- # another call to `IO.select` needs to happen. Since the `Puma::Client`
303
- # object can be read immediately, it does not block, but instead returns
304
- # right away.
305
- #
306
- # This behavior is accomplished by writing to `@trigger` which wakes up
307
- # the `IO.select` and then there is logic to detect the value of `*`,
308
- # pull the contents from `@input` and add them to the sockets array.
309
- #
310
- # If the object passed in has a timeout value in `timeout_at` then
311
- # it is added to a `@timeouts` array. This array is then re-arranged
312
- # so that the first element to timeout will be at the front of the
313
- # array. Then a value to sleep for is derived in the call to `calculate_sleep`
314
- def add(c)
315
- @mutex.synchronize do
316
- @input << c
317
- @trigger << "*"
318
-
319
- if c.timeout_at
320
- @timeouts << c
321
- @timeouts.sort! { |a,b| a.timeout_at <=> b.timeout_at }
67
+ private
322
68
 
323
- calculate_sleep
69
+ def select_loop
70
+ begin
71
+ until @input.closed? && @input.empty?
72
+ # Wakeup any registered object that receives incoming data.
73
+ # Block until the earliest timeout or Selector#wakeup is called.
74
+ timeout = (earliest = @timeouts.first) && earliest.timeout
75
+ @selector.select(timeout) {|mon| wakeup!(mon.value)}
76
+
77
+ # Wakeup all objects that timed out.
78
+ timed_out = @timeouts.take_while {|t| t.timeout == 0}
79
+ timed_out.each { |c| wakeup! c }
80
+
81
+ unless @input.empty?
82
+ until @input.empty?
83
+ client = @input.pop
84
+ register(client) if client.io_ok?
85
+ end
86
+ @timeouts.sort_by!(&:timeout_at)
87
+ end
324
88
  end
89
+ rescue StandardError => e
90
+ STDERR.puts "Error in reactor loop escaped: #{e.message} (#{e.class})"
91
+ STDERR.puts e.backtrace
92
+ retry
325
93
  end
94
+ # Wakeup all remaining objects on shutdown.
95
+ @timeouts.each(&@block)
96
+ @selector.close
326
97
  end
327
98
 
328
- # Close all watched sockets and clear them from being watched
329
- def clear!
330
- begin
331
- @trigger << "c"
332
- rescue IOError
333
- Thread.current.purge_interrupt_queue if Thread.current.respond_to? :purge_interrupt_queue
334
- end
99
+ # Start monitoring the object.
100
+ def register(client)
101
+ @selector.register(client.to_io, :r).value = client
102
+ @timeouts << client
103
+ rescue ArgumentError
104
+ # unreadable clients raise error when processed by NIO
335
105
  end
336
106
 
337
- def shutdown
338
- begin
339
- @trigger << "!"
340
- rescue IOError
341
- Thread.current.purge_interrupt_queue if Thread.current.respond_to? :purge_interrupt_queue
107
+ # 'Wake up' a monitored object by calling the provided block.
108
+ # Stop monitoring the object if the block returns `true`.
109
+ def wakeup!(client)
110
+ if @block.call client
111
+ @selector.deregister client.to_io
112
+ @timeouts.delete client
342
113
  end
343
-
344
- @thread.join
345
114
  end
346
115
  end
347
116
  end