puma 8.1.3-java → 8.2.0.pre1-java

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.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +120 -0
  3. data/README.md +4 -3
  4. data/docs/GLOSSARY.md +160 -0
  5. data/docs/architecture.md +41 -42
  6. data/docs/binding.md +3 -0
  7. data/docs/cluster_mode.md +21 -21
  8. data/docs/control_server.md +4 -4
  9. data/docs/deployment/nginx.md +2 -0
  10. data/docs/deployment/systemd.md +15 -0
  11. data/docs/puma_support.md +12 -0
  12. data/docs/restart.md +2 -2
  13. data/docs/signals.md +3 -3
  14. data/docs/ssl.md +65 -0
  15. data/docs/upgrading/5.0-Upgrade.md +1 -1
  16. data/docs/upgrading/6.0-Upgrade.md +1 -1
  17. data/docs/upgrading/7.0-Upgrade.md +1 -1
  18. data/docs/upgrading/8.0-Upgrade.md +1 -1
  19. data/lib/puma/app/status.rb +22 -7
  20. data/lib/puma/binder.rb +0 -1
  21. data/lib/puma/cli.rb +1 -3
  22. data/lib/puma/client.rb +133 -57
  23. data/lib/puma/client_env.rb +9 -11
  24. data/lib/puma/cluster/worker.rb +0 -6
  25. data/lib/puma/cluster.rb +3 -14
  26. data/lib/puma/cluster_accept_loop_delay.rb +18 -7
  27. data/lib/puma/commonlogger.rb +3 -4
  28. data/lib/puma/configuration.rb +4 -1
  29. data/lib/puma/const.rb +5 -5
  30. data/lib/puma/control_cli.rb +5 -7
  31. data/lib/puma/detect.rb +1 -1
  32. data/lib/puma/dsl.rb +70 -14
  33. data/lib/puma/http_parser_error.rb +8 -0
  34. data/lib/puma/launcher/bundle_pruner.rb +3 -21
  35. data/lib/puma/launcher.rb +55 -25
  36. data/lib/puma/minissl/context_builder.rb +3 -2
  37. data/lib/puma/minissl.rb +12 -16
  38. data/lib/puma/plugin/systemd.rb +69 -3
  39. data/lib/puma/puma_http11.jar +0 -0
  40. data/lib/puma/rack/urlmap.rb +2 -2
  41. data/lib/puma/reactor.rb +138 -25
  42. data/lib/puma/response.rb +65 -38
  43. data/lib/puma/runner.rb +4 -1
  44. data/lib/puma/sd_notify.rb +21 -0
  45. data/lib/puma/server.rb +14 -14
  46. data/lib/puma/server_plugin_control.rb +2 -1
  47. data/lib/puma/single.rb +0 -1
  48. data/lib/puma/thread_pool.rb +87 -14
  49. data/lib/puma/util.rb +5 -16
  50. data/lib/puma.rb +22 -5
  51. data/lib/rack/handler/puma.rb +1 -5
  52. metadata +5 -2
data/lib/puma/response.rb CHANGED
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "time"
4
+
3
5
  module Puma
4
6
  #———————————————————————— DO NOT USE — this class is for internal use only ———
5
7
 
@@ -20,7 +22,7 @@ module Puma
20
22
  BODY_LEN_MAX = 1_024 * 256
21
23
 
22
24
  # File body: smaller bodies are combined with io_buffer, then written to
23
- # socket. Larger bodies are written separately using `copy_stream`
25
+ # socket. Larger bodies are written separately in chunks.
24
26
  IO_BODY_MAX = 1_024 * 64
25
27
 
26
28
  # Array body: elements are collected in io_buffer. When io_buffer's size
@@ -45,7 +47,6 @@ module Puma
45
47
  # It'll return +:async+ if the connection remains open but will be handled
46
48
  # elsewhere, i.e. the connection has been hijacked by the Rack application.
47
49
  #
48
- # Finally, it'll return +true+ on keep-alive connections.
49
50
  # @param processor [Puma::ThreadPool::ProcessorThread]
50
51
  # @param client [Puma::Client]
51
52
  # @param requests [Integer]
@@ -156,7 +157,7 @@ module Puma
156
157
  # Close the connection after a reasonable number of inline requests
157
158
  force_keep_alive = @enable_keep_alives && client.requests_served < @max_keep_alive
158
159
 
159
- resp_info = str_headers(env, status, headers, res_body, io_buffer, force_keep_alive)
160
+ resp_info = str_headers(env, status, headers, io_buffer, force_keep_alive)
160
161
 
161
162
  close_body = false
162
163
  response_hijack = nil
@@ -183,7 +184,7 @@ module Puma
183
184
  body = res_body
184
185
  end
185
186
  elsif !res_body.is_a?(::File) && res_body.respond_to?(:to_path) &&
186
- (fn = res_body.to_path) && File.readable?(fn = res_body.to_path)
187
+ (fn = res_body.to_path) && File.readable?(fn)
187
188
  body = File.open fn, 'rb'
188
189
  close_body = true
189
190
  content_length = body.size
@@ -211,6 +212,15 @@ module Puma
211
212
 
212
213
  cork_socket socket
213
214
 
215
+ http_10_keep_alive = resp_info[:http_10_keep_alive]
216
+ if http_10_keep_alive && !resp_info[:no_body] && !content_length &&
217
+ !resp_info[:transfer_encoding] && !response_hijack
218
+ # a body of unknown length can only be delimited by closing the
219
+ # connection (RFC 9112 §6.3), so it cannot be kept alive
220
+ keep_alive = http_10_keep_alive = false
221
+ end
222
+ io_buffer << CONNECTION_KEEP_ALIVE if http_10_keep_alive
223
+
214
224
  if resp_info[:no_body]
215
225
  # 101 (Switching Protocols) doesn't return here or have content_length,
216
226
  # it should be using `response_hijack`
@@ -246,7 +256,7 @@ module Puma
246
256
  return :async
247
257
  end
248
258
 
249
- fast_write_response socket, body, io_buffer, chunked, content_length.to_i
259
+ fast_write_response socket, body, io_buffer, chunked, content_length
250
260
 
251
261
  # if we're shutting down, close keep_alive connections
252
262
  !shutting_down? && keep_alive ? :keep_alive : :close
@@ -293,27 +303,20 @@ module Puma
293
303
  # @param body [Enumerable, File] the body object
294
304
  # @param io_buffer [Puma::IOBuffer] contains headers
295
305
  # @param chunked [Boolean]
296
- # @paramn content_length [Integer
306
+ # @param content_length [Integer, nil]
297
307
  # @raise [ConnectionError]
298
308
  #
299
309
  def fast_write_response(socket, body, io_buffer, chunked, content_length)
300
- if body.is_a?(::File) && body.respond_to?(:read)
301
- if chunked # would this ever happen?
302
- while chunk = body.read(BODY_LEN_MAX)
303
- io_buffer.append chunk.bytesize.to_s(16), LINE_END, chunk, LINE_END
304
- end
305
- fast_write_str socket, CLOSE_CHUNKED
310
+ if body.is_a?(::File) && content_length && body.respond_to?(:read)
311
+ if content_length <= IO_BODY_MAX
312
+ io_buffer.write body.read(content_length)
313
+ fast_write_str socket, io_buffer.read_and_reset
306
314
  else
307
- if content_length <= IO_BODY_MAX
308
- io_buffer.write body.read(content_length)
309
- fast_write_str socket, io_buffer.read_and_reset
310
- else
311
- fast_write_str socket, io_buffer.read_and_reset
312
- remaining = content_length
313
- while remaining > 0 && (chunk = body.read([remaining, BODY_LEN_MAX].min))
314
- fast_write_str socket, chunk
315
- remaining -= chunk.bytesize
316
- end
315
+ fast_write_str socket, io_buffer.read_and_reset
316
+ remaining = content_length
317
+ while remaining > 0 && (chunk = body.read([remaining, BODY_LEN_MAX].min))
318
+ fast_write_str socket, chunk
319
+ remaining -= chunk.bytesize
317
320
  end
318
321
  end
319
322
  elsif body.is_a?(::Array) && body.length == 1
@@ -391,14 +394,14 @@ module Puma
391
394
  # @return [Boolean]
392
395
  #
393
396
  def illegal_header_key?(header_key)
394
- !!(ILLEGAL_HEADER_KEY_REGEX =~ header_key.to_s)
397
+ ILLEGAL_HEADER_KEY_REGEX.match?(header_key.to_s)
395
398
  end
396
399
 
397
400
  # @param header_value [#to_s]
398
401
  # @return [Boolean]
399
402
  #
400
403
  def illegal_header_value?(header_value)
401
- !!(ILLEGAL_HEADER_VALUE_REGEX =~ header_value.to_s)
404
+ ILLEGAL_HEADER_VALUE_REGEX.match?(header_value.to_s)
402
405
  end
403
406
 
404
407
  # Used in the lambda for env[ `Puma::Const::EARLY_HINTS` ]
@@ -416,8 +419,6 @@ module Puma
416
419
  next if illegal_header_value?(v)
417
420
  eh_str << "#{k}: #{v}\r\n"
418
421
  end
419
- elsif !(vs.to_s.empty? || !illegal_header_value?(vs))
420
- eh_str << "#{k}: #{vs}\r\n"
421
422
  end
422
423
  end
423
424
  eh_str.freeze
@@ -433,7 +434,9 @@ module Puma
433
434
  private :fetch_status_code
434
435
 
435
436
  def request_has_close?(env)
436
- conn = env.fetch(HTTP_CONNECTION, "").downcase
437
+ return false unless (conn = env[HTTP_CONNECTION])
438
+
439
+ conn = conn.downcase
437
440
  conn.include?(CLOSE) && conn.split(",").any? { |option| option.strip == CLOSE }
438
441
  end
439
442
  private :request_has_close?
@@ -442,15 +445,13 @@ module Puma
442
445
  # @param env [Hash] see Puma::Client#env, from request
443
446
  # @param status [Integer] the status returned by the Rack application
444
447
  # @param headers [Hash] the headers returned by the Rack application
445
- # @param content_length [Integer,nil] content length if it can be determined from the
446
- # response body
447
- # @param io_buffer [Puma::IOBuffer] modified inn place
448
+ # @param io_buffer [Puma::IOBuffer] modified in place
448
449
  # @param force_keep_alive [Boolean] 'anded' with keep_alive, based on system
449
450
  # status and `@max_keep_alive`
450
451
  # @return [Hash] resp_info
451
452
  # @version 5.0.3
452
453
  #
453
- def str_headers(env, status, headers, res_body, io_buffer, force_keep_alive)
454
+ def str_headers(env, status, headers, io_buffer, force_keep_alive)
454
455
 
455
456
  line_ending = LINE_END
456
457
  colon = COLON
@@ -458,7 +459,8 @@ module Puma
458
459
  resp_info = {}
459
460
  resp_info[:no_body] = env[REQUEST_METHOD] == HEAD
460
461
 
461
- http_11 = env[SERVER_PROTOCOL] == HTTP_11
462
+ proto = env[SERVER_PROTOCOL]
463
+ http_11 = proto == HTTP_11 || status == 505 || (proto != HTTP_10 && proto&.start_with?('HTTP/1.'))
462
464
  if http_11
463
465
  resp_info[:allow_chunked] = true
464
466
  resp_info[:keep_alive] = !request_has_close?(env)
@@ -476,7 +478,8 @@ module Puma
476
478
  end
477
479
  else
478
480
  resp_info[:allow_chunked] = false
479
- resp_info[:keep_alive] = env.fetch(HTTP_CONNECTION, "").downcase == KEEP_ALIVE
481
+ conn = env[HTTP_CONNECTION]
482
+ resp_info[:keep_alive] = conn ? conn.downcase == KEEP_ALIVE : false
480
483
 
481
484
  # Same optimization as above for HTTP/1.1
482
485
  #
@@ -498,6 +501,7 @@ module Puma
498
501
  resp_info[:keep_alive] &&= force_keep_alive
499
502
 
500
503
  resp_info[:response_hijack] = nil
504
+ has_date = false
501
505
 
502
506
  headers.each do |k, vs|
503
507
  next if illegal_header_key?(k)
@@ -516,10 +520,17 @@ module Puma
516
520
  when HIJACK
517
521
  resp_info[:response_hijack] = vs
518
522
  next
523
+ when DATE
524
+ has_date = true
519
525
  when BANNED_HEADER_KEY
520
526
  next
521
527
  end
522
528
 
529
+ if vs.is_a?(::String) && (vs.empty? || !illegal_header_value?(vs))
530
+ io_buffer.append key, colon, vs, line_ending
531
+ next
532
+ end
533
+
523
534
  ary = if vs.is_a?(::Array) && !vs.empty?
524
535
  vs
525
536
  elsif vs.respond_to?(:to_s) && !vs.to_s.empty?
@@ -537,18 +548,34 @@ module Puma
537
548
  end
538
549
  end
539
550
 
551
+ # RFC 9110 §6.6.1: an origin server with a clock MUST send a Date header
552
+ # in 2xx/3xx/4xx responses and MUST NOT send one in 1xx responses
553
+ io_buffer << cached_date_header if @date_header && !has_date && status >= 200
554
+
540
555
  # HTTP/1.1 & 1.0 assume different defaults:
541
556
  # - HTTP 1.0 assumes the connection will be closed if not specified
542
557
  # - HTTP 1.1 assumes the connection will be kept alive if not specified.
543
558
  # Only set the header if we're doing something which is not the default
544
559
  # for this protocol version
545
- if http_11
546
- io_buffer << CONNECTION_CLOSE if !resp_info[:keep_alive]
547
- else
548
- io_buffer << CONNECTION_KEEP_ALIVE if resp_info[:keep_alive]
549
- end
560
+ # HTTP/1.0 keep-alive is written by prepare_response, which knows whether
561
+ # the body can be delimited without closing the connection
562
+ io_buffer << CONNECTION_CLOSE if http_11 && !resp_info[:keep_alive]
563
+ resp_info[:http_10_keep_alive] = !http_11 && resp_info[:keep_alive]
550
564
  resp_info
551
565
  end
552
566
  private :str_headers
567
+
568
+ def cached_date_header
569
+ sec = Process.clock_gettime(Process::CLOCK_REALTIME, :second)
570
+ thread = Thread.current
571
+ if thread.thread_variable_get(:puma_date_sec) == sec
572
+ thread.thread_variable_get(:puma_date_header)
573
+ else
574
+ header = -"date: #{Time.at(sec).utc.httpdate}\r\n"
575
+ thread.thread_variable_set(:puma_date_sec, sec)
576
+ thread.thread_variable_set(:puma_date_header, header)
577
+ end
578
+ end
579
+ private :cached_date_header
553
580
  end
554
581
  end
data/lib/puma/runner.rb CHANGED
@@ -70,7 +70,10 @@ module Puma
70
70
  token = nil if token.empty? || token == 'none'
71
71
  end
72
72
 
73
- app = Puma::App::Status.new @launcher, token: token, data_only: @options[:control_data_only]
73
+ app = Puma::App::Status.new @launcher,
74
+ token: token,
75
+ data_only: @options[:control_data_only],
76
+ data_token: @options[:control_data_token]
74
77
 
75
78
  # A Reactor is not created and nio4r is not loaded when 'queue_requests: false'
76
79
  # Use `nil` for events, no hooks in control server
@@ -48,6 +48,7 @@ module Puma
48
48
  MAINPID = "MAINPID="
49
49
  WATCHDOG = "WATCHDOG=1"
50
50
  FDSTORE = "FDSTORE=1"
51
+ EXTEND_TIMEOUT_USEC = "EXTEND_TIMEOUT_USEC="
51
52
 
52
53
  # @note When the service manager expects watchdog pings, this sends an
53
54
  # immediate `WATCHDOG=1` in the same datagram, which closes the watchdog
@@ -88,6 +89,26 @@ module Puma
88
89
  notify(FDSTORE, unset_env)
89
90
  end
90
91
 
92
+ def self.extend_timeout(usec, unset_env=false)
93
+ notify("#{EXTEND_TIMEOUT_USEC}#{usec}", unset_env)
94
+ end
95
+
96
+ def self.extend_timeout_usec
97
+ env_seconds_to_usec("PUMA_EXTEND_TIMEOUT_SEC")
98
+ end
99
+
100
+ def self.extend_timeout_max_usec
101
+ env_seconds_to_usec("PUMA_EXTEND_TIMEOUT_MAX_SEC")
102
+ end
103
+
104
+ def self.env_seconds_to_usec(name)
105
+ seconds = Float(ENV[name])
106
+ seconds.positive? ? (seconds * 1_000_000).ceil : 0
107
+ rescue ArgumentError, TypeError, FloatDomainError
108
+ 0
109
+ end
110
+ private_class_method :env_seconds_to_usec
111
+
91
112
  # @param [Boolean] true if the service manager expects watchdog keep-alive
92
113
  # notification messages to be sent from this process.
93
114
  #
data/lib/puma/server.rb CHANGED
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'stringio'
4
-
5
3
  require_relative 'thread_pool'
6
4
  require_relative 'const'
7
5
  require_relative 'log_writer'
@@ -85,6 +83,7 @@ module Puma
85
83
  @reactor = nil
86
84
 
87
85
  @env_set_http_version = nil
86
+ @empty_rack_input = nil
88
87
 
89
88
  @options = if options.is_a?(UserFileDefaultOptions)
90
89
  options
@@ -107,8 +106,10 @@ module Puma
107
106
  @max_keep_alive = @options[:max_keep_alive]
108
107
  @enable_keep_alives = @options[:enable_keep_alives]
109
108
  @enable_keep_alives &&= @queue_requests
109
+ @date_header = @options[:date_header]
110
110
  @io_selector_backend = @options[:io_selector_backend]
111
111
  @http_content_length_limit = @options[:http_content_length_limit]
112
+ @http_parser = @options[:http_parser] || Puma.default_http_parser
112
113
  @continue_callback = @options[:continue_callback]
113
114
  @allow_underscore_headers = @options.fetch(:allow_underscore_headers, true)
114
115
  @cluster_accept_loop_delay = ClusterAcceptLoopDelay.new(
@@ -139,8 +140,6 @@ module Puma
139
140
 
140
141
  ENV['RACK_ENV'] ||= "development"
141
142
 
142
- @mode = :http
143
-
144
143
  @precheck_closing = true
145
144
 
146
145
  @requests_count = 0
@@ -334,7 +333,7 @@ module Puma
334
333
  elsif shutdown || client.timeout == 0
335
334
  client.timeout!
336
335
  else
337
- client.set_timeout(@first_data_timeout) if client.bytes_read > read
336
+ client.set_read_timeout(@first_data_timeout) if client.bytes_read > read
338
337
  false
339
338
  end
340
339
  rescue ConnectionError, EOFError
@@ -360,6 +359,7 @@ module Puma
360
359
  def handle_servers
361
360
  @env_set_http_version = Object.const_defined?(:Rack) && ::Rack.respond_to?(:release) &&
362
361
  Gem::Version.new(::Rack.release) < Gem::Version.new('3.1.0')
362
+ @empty_rack_input = @options[:nil_rack_input_on_empty_body] && !@env_set_http_version ? nil : Client::EmptyBody
363
363
 
364
364
  begin
365
365
  check = @check
@@ -491,9 +491,10 @@ module Puma
491
491
 
492
492
  # :nodoc:
493
493
  def new_client(io, sock)
494
- client = Client.new(io, @binder.env(sock))
494
+ client = Client.new(io, @binder.env(sock), http_parser: @http_parser)
495
495
  client.listener = sock
496
496
  client.env_set_http_version = @env_set_http_version
497
+ client.empty_rack_input = @empty_rack_input
497
498
  client.http_content_length_limit = @http_content_length_limit
498
499
  client.supported_http_methods = @supported_http_methods
499
500
  client.allow_underscore_headers = @allow_underscore_headers
@@ -542,7 +543,7 @@ module Puma
542
543
 
543
544
  if @queue_requests && !client.eagerly_finish { shutdown_body_limit }
544
545
 
545
- client.set_timeout(@first_data_timeout)
546
+ client.set_read_timeout(@first_data_timeout)
546
547
  if @reactor.add client
547
548
  close_socket = false
548
549
  return false
@@ -588,7 +589,11 @@ module Puma
588
589
  end
589
590
  end
590
591
  elsif @queue_requests
591
- client.set_timeout @persistent_timeout
592
+ if client.can_close?
593
+ client.set_timeout @persistent_timeout
594
+ else
595
+ client.set_read_timeout @first_data_timeout
596
+ end
592
597
  if @reactor.add client
593
598
  close_socket = false
594
599
  end
@@ -645,8 +650,6 @@ module Puma
645
650
  client.timeout!
646
651
  end
647
652
 
648
- # :nocov:
649
-
650
653
  # Handle various error types thrown by Client I/O operations.
651
654
  def client_error(e, client, requests = 1)
652
655
  # Swallow, do not log
@@ -802,9 +805,6 @@ module Puma
802
805
  end
803
806
 
804
807
  # below are 'delegations' to binder
805
- # remove in Puma 7?
806
-
807
-
808
808
  def add_tcp_listener(host, port, optimize_for_latency = true, backlog = 1024)
809
809
  @binder.add_tcp_listener host, port, optimize_for_latency, backlog
810
810
  end
@@ -856,7 +856,7 @@ module Puma
856
856
  end
857
857
 
858
858
  @thread_pool&.with_mutex do
859
- @thread_pool.min, @thread_pool.max = min, max
859
+ @thread_pool.update_min_max(min, max)
860
860
  @min_threads, @max_threads = min, max
861
861
  end
862
862
  end
@@ -22,10 +22,11 @@ module Puma
22
22
  end
23
23
 
24
24
  # Updates the minimum and maximum number of threads in the thread pool.
25
+ # Omitted arguments default to the corresponding current thread limits.
25
26
  #
26
27
  # @see Puma::Server#update_thread_pool_min_max
27
28
  #
28
- def update_thread_pool_min_max(min: max_threads, max: min_threads)
29
+ def update_thread_pool_min_max(min: min_threads, max: max_threads)
29
30
  @server.update_thread_pool_min_max(min: min, max: max)
30
31
  end
31
32
  end
data/lib/puma/single.rb CHANGED
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'runner'
4
- require_relative 'detect'
5
4
  require_relative 'plugin'
6
5
 
7
6
  module Puma
@@ -1,8 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'thread'
4
-
5
- require_relative 'io_buffer'
6
3
  require_relative 'server_plugin_control'
7
4
 
8
5
  module Puma
@@ -210,21 +207,25 @@ module Puma
210
207
  processor.marked_as_io_thread = false
211
208
  else
212
209
  # We're already at max threads, so we exit the extra io thread.
213
- @spawned -= 1
214
- @processors.delete(processor)
215
- trigger_before_thread_exit_hooks
216
- Thread.exit
210
+ trim_thread(processor)
217
211
  end
218
212
  end
219
213
 
214
+ trim_thread_if_requested(processor)
215
+
220
216
  while todo.empty?
217
+ # Thread trimming could be requested when process is idle, when
218
+ # max was lowered, or during shutdown, hence we need to trim when
219
+ # todo is empty.
221
220
  if @trim_requested > 0
222
221
  @trim_requested -= 1
223
- @spawned -= 1
224
- @processors.delete(processor)
225
- not_full.signal
226
- trigger_before_thread_exit_hooks
227
- Thread.exit
222
+ if @shutdown || @spawned > @min
223
+ trim_thread(processor)
224
+ else
225
+ @trim_requested = 0
226
+ end
227
+ elsif !@shutdown && @spawned > @min && over_max_processors?
228
+ trim_thread(processor)
228
229
  end
229
230
 
230
231
  @waiting += 1
@@ -257,6 +258,40 @@ module Puma
257
258
 
258
259
  private :spawn_thread
259
260
 
261
+ # :nodoc:
262
+ #
263
+ # Must be called with @mutex held, on a pool thread, between work items.
264
+ #
265
+ def trim_thread_if_requested(processor)
266
+ return if @shutdown || @spawned <= @min || @spawned <= 1
267
+
268
+ if @trim_requested > 0
269
+ @trim_requested -= 1
270
+ trim_thread(processor)
271
+ elsif over_max_processors?
272
+ trim_thread(processor)
273
+ end
274
+ end
275
+
276
+ private :trim_thread_if_requested
277
+
278
+ # :nodoc:
279
+ #
280
+ # Must be called with @mutex held, on the pool thread being trimmed.
281
+ # Performs the trim bookkeeping and exits the current thread. Signals
282
+ # not_full because the exit lowers busy_threads, which may unblock
283
+ # threads waiting in wait_until_not_full.
284
+ #
285
+ def trim_thread(processor)
286
+ @spawned -= 1
287
+ @processors.delete(processor)
288
+ @not_full.signal
289
+ trigger_before_thread_exit_hooks
290
+ Thread.exit
291
+ end
292
+
293
+ private :trim_thread
294
+
260
295
  def trigger_before_thread_start_hooks
261
296
  return unless @before_thread_start&.any?
262
297
 
@@ -318,7 +353,8 @@ module Puma
318
353
  with_mutex do
319
354
  while true
320
355
  return if @shutdown
321
- return if (@spawned - @waiting + @todo.size) < @max
356
+ io_threads = [@processors.count(&:marked_as_io_thread?), @max_io_threads].min
357
+ return if (@spawned - @waiting + @todo.size) < @max + io_threads
322
358
 
323
359
  @not_full.wait @mutex
324
360
  end
@@ -337,9 +373,45 @@ module Puma
337
373
  # Must be called with @mutex held!
338
374
  #
339
375
  def can_spawn_processor?
376
+ normal_processors_delta < 0
377
+ end
378
+
379
+ # :nodoc:
380
+ #
381
+ # Must be called with @mutex held!
382
+ #
383
+ def over_max_processors?
384
+ normal_processors_delta > 0
385
+ end
386
+
387
+ private :over_max_processors?
388
+
389
+ def normal_processors_delta
340
390
  io_processors_count = @processors.count(&:marked_as_io_thread?)
341
391
  extra_io_processors_count = io_processors_count > @max_io_threads ? io_processors_count - @max_io_threads : 0
342
- (@spawned - io_processors_count) < (@max - extra_io_processors_count)
392
+ (@spawned - io_processors_count) - (@max - extra_io_processors_count)
393
+ end
394
+
395
+ private :normal_processors_delta
396
+
397
+ # Update the minimum and maximum number of threads in the pool.
398
+ #
399
+ # When +max+ is lowered below the current thread count, idle threads are
400
+ # woken to exit immediately and busy threads exit between work items.
401
+ # When +max+ is raised, threads waiting in +wait_until_not_full+ are woken.
402
+ #
403
+ def update_min_max(min, max)
404
+ with_mutex do
405
+ @min = min
406
+ @max = max
407
+ return if @shutdown
408
+
409
+ max_trims = [@spawned - @min, 0].max
410
+ @trim_requested = max_trims if @trim_requested > max_trims
411
+
412
+ @not_empty.broadcast if over_max_processors?
413
+ @not_full.broadcast if (@spawned - @waiting + @todo.size) < @max
414
+ end
343
415
  end
344
416
 
345
417
  # Add +work+ to the todo list for a Thread to pickup and process.
@@ -367,6 +439,7 @@ module Puma
367
439
  if @waiting < @todo.size and can_spawn_processor?
368
440
  spawn_thread
369
441
  end
442
+ @not_full.signal
370
443
  end
371
444
  end
372
445
 
data/lib/puma/util.rb CHANGED
@@ -17,24 +17,13 @@ module Puma
17
17
  # Unlike form encoding, escape writes a space as '%20' and unescape
18
18
  # keeps a literal '+', so values such as OpenSSL cipher strings
19
19
  # ("AES+SHA") survive.
20
- if defined?(::Encoding)
21
- def escape(s, encoding = Encoding::UTF_8)
22
- URI.encode_www_form_component(s, encoding).gsub('+', '%20')
23
- end
24
-
25
- def unescape(s, encoding = Encoding::UTF_8)
26
- URI.decode_www_form_component(s.gsub('+', '%2B'), encoding)
27
- end
28
- else
29
- def escape(s, encoding = nil)
30
- URI.encode_www_form_component(s, encoding).gsub('+', '%20')
31
- end
20
+ def escape(s, encoding = Encoding::UTF_8)
21
+ URI.encode_www_form_component(s, encoding).gsub('+', '%20')
22
+ end
32
23
 
33
- def unescape(s, encoding = nil)
34
- URI.decode_www_form_component(s.gsub('+', '%2B'), encoding)
35
- end
24
+ def unescape(s, encoding = Encoding::UTF_8)
25
+ URI.decode_www_form_component(s.gsub('+', '%2B'), encoding)
36
26
  end
37
- module_function :unescape, :escape
38
27
 
39
28
  DEFAULT_SEP = /[&;] */n
40
29
 
data/lib/puma.rb CHANGED
@@ -6,15 +6,32 @@ require 'tempfile'
6
6
  require 'uri'
7
7
  require 'stringio'
8
8
 
9
- require 'thread'
10
-
11
- # use require, see https://github.com/puma/puma/pull/2381
12
- require 'puma/puma_http11'
13
-
9
+ require_relative 'puma/http_parser_error'
14
10
  require_relative 'puma/detect'
15
11
  require_relative 'puma/json_serialization'
16
12
 
17
13
  module Puma
14
+ # The puma_http11 extension provides `Puma::HttpParser` and `MiniSSL::Engine`.
15
+ # Puma loads without it, and a server then needs a parser class or factory
16
+ # from the `http_parser` option.
17
+ @http11_load_error = begin
18
+ # use require, see https://github.com/puma/puma/pull/2381
19
+ require 'puma/puma_http11'
20
+ nil
21
+ rescue LoadError => e
22
+ e
23
+ end
24
+
25
+ # Returns the default HTTP parser class from the `puma_http11` extension,
26
+ # or raises `LoadError` (preserving the original cause) if it could not be loaded.
27
+ def self.default_http_parser
28
+ return HttpParser if const_defined?(:HttpParser, false)
29
+
30
+ message = "Puma's puma_http11 extension could not be loaded, so there is no default HTTP parser. " \
31
+ "Reinstall Puma with a compiler, or set the http_parser option."
32
+ message = "#{message} (#{@http11_load_error.message})" if @http11_load_error
33
+ raise LoadError, message, cause: @http11_load_error
34
+ end
18
35
  # when Puma is loaded via `Puma::CLI`, all files are loaded via
19
36
  # `require_relative`. The below are for non-standard loading
20
37
  autoload :Const, "#{__dir__}/puma/const"
@@ -34,11 +34,7 @@ module Puma
34
34
 
35
35
  conf = ::Puma::Configuration.new(options, default_options.merge({ events: @events })) do |user_config, file_config, default_config|
36
36
  if options.delete(:Verbose)
37
- begin
38
- require 'rack/commonlogger' # Rack 1.x
39
- rescue LoadError
40
- require 'rack/common_logger' # Rack 2 and later
41
- end
37
+ require 'rack/common_logger'
42
38
  app = ::Rack::CommonLogger.new(app, STDOUT)
43
39
  end
44
40