puma 8.1.2 → 8.2.0.pre1

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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +129 -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/ext/puma_http11/extconf.rb +7 -5
  20. data/ext/puma_http11/http11_parser.c +66 -84
  21. data/ext/puma_http11/http11_parser.h +0 -5
  22. data/ext/puma_http11/mini_ssl.c +31 -68
  23. data/ext/puma_http11/puma_http11.c +125 -7
  24. data/lib/puma/app/status.rb +22 -7
  25. data/lib/puma/binder.rb +4 -4
  26. data/lib/puma/cli.rb +1 -3
  27. data/lib/puma/client.rb +133 -57
  28. data/lib/puma/client_env.rb +10 -12
  29. data/lib/puma/cluster/worker.rb +0 -6
  30. data/lib/puma/cluster.rb +3 -14
  31. data/lib/puma/cluster_accept_loop_delay.rb +18 -7
  32. data/lib/puma/commonlogger.rb +6 -4
  33. data/lib/puma/configuration.rb +4 -1
  34. data/lib/puma/const.rb +5 -5
  35. data/lib/puma/control_cli.rb +5 -7
  36. data/lib/puma/detect.rb +1 -1
  37. data/lib/puma/dsl.rb +70 -14
  38. data/lib/puma/error_logger.rb +2 -1
  39. data/lib/puma/http_parser_error.rb +8 -0
  40. data/lib/puma/launcher/bundle_pruner.rb +3 -21
  41. data/lib/puma/launcher.rb +55 -25
  42. data/lib/puma/minissl/context_builder.rb +3 -2
  43. data/lib/puma/minissl.rb +12 -16
  44. data/lib/puma/plugin/systemd.rb +69 -3
  45. data/lib/puma/rack/urlmap.rb +2 -2
  46. data/lib/puma/reactor.rb +138 -25
  47. data/lib/puma/response.rb +65 -38
  48. data/lib/puma/runner.rb +6 -2
  49. data/lib/puma/sd_notify.rb +21 -0
  50. data/lib/puma/server.rb +14 -14
  51. data/lib/puma/server_plugin_control.rb +2 -1
  52. data/lib/puma/single.rb +0 -1
  53. data/lib/puma/thread_pool.rb +87 -14
  54. data/lib/puma/util.rb +5 -16
  55. data/lib/puma.rb +22 -5
  56. data/lib/rack/handler/puma.rb +1 -5
  57. metadata +5 -2
data/lib/puma/client.rb CHANGED
@@ -3,16 +3,10 @@
3
3
  require_relative 'detect'
4
4
  require_relative 'io_buffer'
5
5
  require_relative 'client_env'
6
+ require_relative 'http_parser_error'
6
7
  require_relative 'null_io'
7
8
  require 'tempfile'
8
9
 
9
- if Puma::IS_JRUBY
10
- # We have to work around some OpenSSL buffer/io-readiness bugs
11
- # so we pull it in regardless of if the user is binding
12
- # to an SSL socket
13
- require 'openssl'
14
- end
15
-
16
10
  module Puma
17
11
 
18
12
  class ConnectionError < RuntimeError; end
@@ -57,10 +51,16 @@ module Puma
57
51
  # this tests all values but the last, which must be chunked
58
52
  ALLOWED_TRANSFER_ENCODING = %w[compress deflate gzip].freeze
59
53
 
60
- # chunked body validation
54
+ # chunked body validation (RFC 9112 §7.1, §7.1.1)
61
55
  CHUNK_SIZE_VALID = /\A\h+\z/.freeze
56
+ CHUNK_EXT_TCHAR = /[!#$%&'*+\-.^_`|~0-9A-Za-z]/.freeze
57
+ CHUNK_EXT_TOKEN = /#{CHUNK_EXT_TCHAR}+/.freeze
58
+ CHUNK_EXT_QUOTED = /"(?:[\t \x21\x23-\x5B\x5D-\x7E\x80-\xFF]|\\[\t \x21-\x7E\x80-\xFF])*"/n.freeze
59
+ CHUNK_EXT_VALID = /\A(?:[ \t]*;[ \t]*#{CHUNK_EXT_TOKEN}(?:[ \t]*=[ \t]*(?:#{CHUNK_EXT_TOKEN}|#{CHUNK_EXT_QUOTED}))?)+\z/n.freeze
62
60
  CHUNK_VALID_ENDING = Const::LINE_END
63
61
  CHUNK_VALID_ENDING_SIZE = CHUNK_VALID_ENDING.bytesize
62
+ BARE_LF = /(?<!\r)\n/.freeze
63
+ private_constant :CHUNK_EXT_TCHAR, :CHUNK_EXT_TOKEN, :CHUNK_EXT_QUOTED, :CHUNK_EXT_VALID, :BARE_LF
64
64
 
65
65
  # The maximum number of bytes we'll buffer looking for a valid
66
66
  # chunk header, and the maximum size of a trailer section.
@@ -94,27 +94,30 @@ module Puma
94
94
  :allow_underscore_headers, :continue_callback
95
95
 
96
96
  attr_accessor :remote_addr_header, :listener, :env_set_http_version,
97
- :reactor_error
97
+ :reactor_error, :empty_rack_input
98
98
 
99
- def initialize(io, env=nil)
99
+ def initialize(io, env=nil, http_parser: nil)
100
100
  @io = io
101
101
  @to_io = io.to_io
102
102
  @io_buffer = IOBuffer.new
103
103
  @proto_env = env
104
104
  @env = env&.dup
105
105
 
106
- @parser = HttpParser.new
106
+ http_parser ||= Puma.default_http_parser
107
+ @parser = http_parser.respond_to?(:call) ? http_parser.call : http_parser.new
107
108
  @parsed_bytes = 0
108
109
  @read_header = true
109
110
  @read_proxy = false
110
111
  @ready = false
111
112
 
112
113
  @body = nil
114
+ @empty_rack_input = EmptyBody
113
115
  @body_read_start = nil
114
116
  @buffer = nil
115
117
  @tempfile = nil
116
118
 
117
119
  @timeout_at = nil
120
+ @header_deadline = nil
118
121
 
119
122
  @requests_served = 0
120
123
  @hijacked = false
@@ -142,7 +145,6 @@ module Puma
142
145
  @read_buffer = String.new # rubocop: disable Performance/UnfreezeString
143
146
  end
144
147
 
145
- # Remove in Puma 7?
146
148
  def closed?
147
149
  @to_io.closed?
148
150
  end
@@ -174,6 +176,14 @@ module Puma
174
176
  @timeout_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + val
175
177
  end
176
178
 
179
+ def set_read_timeout(val)
180
+ set_timeout(val)
181
+ return if in_data_phase
182
+
183
+ @header_deadline ||= @timeout_at
184
+ @timeout_at = @header_deadline
185
+ end
186
+
177
187
  # Number of seconds until the timeout elapses.
178
188
  # @!attribute [r] timeout
179
189
  def timeout
@@ -193,6 +203,7 @@ module Puma
193
203
  @in_last_chunk = false
194
204
  @http_content_length_limit_exceeded = nil
195
205
  @error_status_code = nil
206
+ @header_deadline = nil
196
207
  end
197
208
 
198
209
  # only used with back-to-back requests contained in the buffer
@@ -318,12 +329,13 @@ module Puma
318
329
 
319
330
  def finish(timeout, &deadline)
320
331
  return if @ready
321
- set_timeout timeout
332
+ set_read_timeout timeout
322
333
  read = @bytes_read
323
334
  until try_to_finish(&deadline)
324
335
  if @bytes_read > read
325
- set_timeout timeout
336
+ set_read_timeout timeout
326
337
  read = @bytes_read
338
+ timeout! if !in_data_phase && self.timeout == 0
327
339
  elsif self.timeout == 0
328
340
  timeout!
329
341
  end
@@ -360,6 +372,12 @@ module Puma
360
372
  def parser_execute
361
373
  ret = @parser.execute(@env, @buffer, @parsed_bytes)
362
374
 
375
+ if (proto = @env[SERVER_PROTOCOL]) && proto != HTTP_11 && !proto.start_with?('HTTP/1.')
376
+ @error_status_code = 505
377
+ @env[HTTP_CONNECTION] = CLOSE
378
+ raise HttpParserError, "HTTP Version Not Supported: #{proto}"
379
+ end
380
+
363
381
  if @env[REQUEST_METHOD] && @supported_http_methods != :any && !@supported_http_methods.key?(@env[REQUEST_METHOD])
364
382
  raise HttpParserError501, "#{@env[REQUEST_METHOD]} method is not supported"
365
383
  end
@@ -392,10 +410,12 @@ module Puma
392
410
  # protocol is bad
393
411
  text = request_line[/[^ ]*\z/]
394
412
  raise HttpParserError, "Invalid HTTP format, parsing fails. Bad protocol #{text}"
395
- elsif !headers.empty?
413
+ elsif headers && !headers.empty?
396
414
  # headers are bad
397
415
  hdrs = headers.split("\r\n").map { |h| h.gsub "\n", '\n'}.join "\n"
398
416
  raise HttpParserError, "Invalid HTTP format, parsing fails. Bad headers\n#{hdrs}"
417
+ else
418
+ raise e
399
419
  end
400
420
  end
401
421
 
@@ -525,19 +545,20 @@ module Puma
525
545
 
526
546
  @body_read_start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
527
547
 
528
- if @env[HTTP_EXPECT] == CONTINUE
529
- if @continue_callback && (response = @continue_callback.call(@env))
530
- reject_continue response
531
- end
532
- write_interim HTTP_11_100
533
- end
534
-
535
- @read_header = false
536
-
537
- parser_body = @parser.body
538
-
539
548
  te = @env[TRANSFER_ENCODING2]
549
+ cl = @env[CONTENT_LENGTH]
550
+
540
551
  if te
552
+ if @env.key?(CONTENT_LENGTH)
553
+ @error_status_code = 400
554
+ @env[HTTP_CONNECTION] = CLOSE
555
+ raise HttpParserError, "#{TE_ERR_MSG}, cannot be combined with Content-Length"
556
+ end
557
+ if te.empty?
558
+ @error_status_code = 400
559
+ @env[HTTP_CONNECTION] = CLOSE
560
+ raise HttpParserError, "#{TE_ERR_MSG}, empty value"
561
+ end
541
562
  te_lwr = te.downcase
542
563
  if te.include? ','
543
564
  te_ary = te_lwr.split(',').each { |te| te.gsub!(STRIP_OWS, "") }
@@ -550,30 +571,38 @@ module Puma
550
571
  elsif !te_valid
551
572
  raise HttpParserError501, "#{TE_ERR_MSG}, unknown value: '#{te}'"
552
573
  end
553
- @env.delete TRANSFER_ENCODING2
554
- return setup_chunked_body parser_body
555
- elsif te_lwr == CHUNKED
556
- @env.delete TRANSFER_ENCODING2
557
- return setup_chunked_body parser_body
558
- elsif ALLOWED_TRANSFER_ENCODING.include? te_lwr
559
- raise HttpParserError , "#{TE_ERR_MSG}, single value must be chunked: '#{te}'"
560
- else
561
- raise HttpParserError501 , "#{TE_ERR_MSG}, unknown value: '#{te}'"
574
+ elsif te_lwr != CHUNKED
575
+ if ALLOWED_TRANSFER_ENCODING.include? te_lwr
576
+ raise HttpParserError , "#{TE_ERR_MSG}, single value must be chunked: '#{te}'"
577
+ else
578
+ raise HttpParserError501, "#{TE_ERR_MSG}, unknown value: '#{te}'"
579
+ end
562
580
  end
581
+ elsif cl && (CONTENT_LENGTH_VALUE_INVALID.match?(cl) || cl.empty?)
582
+ @error_status_code = 400
583
+ @env[HTTP_CONNECTION] = 'close'
584
+ raise HttpParserError, "Invalid Content-Length: #{cl.inspect}"
563
585
  end
564
586
 
565
- @chunked_body = false
587
+ if @env[HTTP_EXPECT] == CONTINUE && @env[SERVER_PROTOCOL] != HTTP_10
588
+ if @continue_callback && (response = @continue_callback.call(@env))
589
+ reject_continue response
590
+ end
591
+ write_interim HTTP_11_100
592
+ end
566
593
 
567
- cl = @env[CONTENT_LENGTH]
594
+ @read_header = false
568
595
 
569
- if cl
570
- # cannot contain characters that are not \d, or be empty
571
- if CONTENT_LENGTH_VALUE_INVALID.match?(cl) || cl.empty?
572
- @error_status_code = 400
573
- @env[HTTP_CONNECTION] = 'close'
574
- raise HttpParserError, "Invalid Content-Length: #{cl.inspect}"
575
- end
576
- else
596
+ parser_body = @parser.body
597
+
598
+ if te
599
+ @env.delete TRANSFER_ENCODING2
600
+ return setup_chunked_body parser_body
601
+ end
602
+
603
+ @chunked_body = false
604
+
605
+ unless cl
577
606
  @buffer = parser_body.empty? ? nil : parser_body
578
607
  @body = EmptyBody
579
608
  set_ready
@@ -710,13 +739,13 @@ module Puma
710
739
  @partial_part_left = 0
711
740
  @prev_chunk = ""
712
741
  @excess_cr = 0
713
-
714
- @body = Tempfile.create(Const::PUMA_TMP_BASE)
715
- File.unlink @body.path unless IS_WINDOWS
716
- @body.binmode
717
- @tempfile = @body
742
+ @tempfile = nil
718
743
  @chunked_content_length = 0
719
744
 
745
+ # The body[0,0] trick is to get an empty string in the same
746
+ # encoding as body.
747
+ @body = StringIO.new body[0,0]
748
+
720
749
  if decode_chunk(body)
721
750
  @env[CONTENT_LENGTH] = @chunked_content_length.to_s
722
751
  return true
@@ -725,17 +754,41 @@ module Puma
725
754
 
726
755
  # @version 5.0.0
727
756
  def write_chunk(str)
728
- if @http_content_length_limit&.< @chunked_content_length + str.bytesize
757
+ remain = @chunked_content_length + str.bytesize
758
+
759
+ if @http_content_length_limit&.< remain
729
760
  raise_above_http_content_limit
730
761
  end
731
762
 
763
+ # The length of a chunked body is unknown up front, so it starts in memory
764
+ # and moves to a Tempfile once it grows past MAX_BODY, similar to Content-Length.
765
+ if @tempfile.nil? && remain > MAX_BODY
766
+ @tempfile = Tempfile.create(Const::PUMA_TMP_BASE)
767
+ File.unlink @tempfile.path unless IS_WINDOWS
768
+ @tempfile.binmode
769
+ @tempfile.write @body.string
770
+ @body = @tempfile
771
+ @env[RACK_INPUT] = @body
772
+ end
773
+
732
774
  @chunked_content_length += @body.write(str)
733
775
  end
734
776
 
777
+ def check_chunk_ending(str, left)
778
+ (left - CHUNK_VALID_ENDING_SIZE...left).each do |i|
779
+ next if i < 0 || i >= str.bytesize
780
+
781
+ unless str.getbyte(i) == CHUNK_VALID_ENDING.getbyte(i - left + CHUNK_VALID_ENDING_SIZE)
782
+ raise HttpParserError, "Chunk size mismatch"
783
+ end
784
+ end
785
+ end
786
+
735
787
  def decode_chunk(chunk)
736
788
  return finish_last_chunk(@prev_chunk + chunk) if @in_last_chunk
737
789
 
738
790
  if @partial_part_left > 0
791
+ check_chunk_ending(chunk, @partial_part_left)
739
792
  if @partial_part_left <= chunk.size
740
793
  if @partial_part_left > 2
741
794
  write_chunk(chunk[0..(@partial_part_left-3)]) # skip the \r\n
@@ -767,11 +820,19 @@ module Puma
767
820
  while !io.eof?
768
821
  line = io.gets
769
822
  if line.end_with?(CHUNK_VALID_ENDING)
770
- # Puma doesn't process chunk extensions, but should parse if they're
771
- # present, which is the reason for the semicolon regex
772
- chunk_hex = line.strip[/\A[^;]+/]
773
- unless CHUNK_SIZE_VALID.match? chunk_hex
774
- err_msg = chunk_hex && !chunk_hex.empty? ?
823
+ header = line.b.byteslice(0, line.bytesize - CHUNK_VALID_ENDING_SIZE)
824
+ if semi = header.index(';')
825
+ chunk_hex = header.byteslice(0, semi).sub(/[ \t]+\z/, '')
826
+ chunk_ext = header.byteslice(semi, header.bytesize - semi)
827
+ unless CHUNK_EXT_VALID.match?(chunk_ext)
828
+ raise HttpParserError, "Invalid chunk extension"
829
+ end
830
+ else
831
+ chunk_hex = header
832
+ end
833
+
834
+ unless CHUNK_SIZE_VALID.match?(chunk_hex)
835
+ err_msg = !chunk_hex.empty? ?
775
836
  "Invalid chunk size: '#{chunk_hex}'" :
776
837
  "Chunk size cannot be empty or nil"
777
838
  raise HttpParserError, err_msg
@@ -800,7 +861,8 @@ module Puma
800
861
 
801
862
  len += 2
802
863
 
803
- part = io.read(len)
864
+ # StringIO#read takes a C long, so don't ask for more than is buffered
865
+ part = io.read([len, io.size].min)
804
866
 
805
867
  unless part
806
868
  @partial_part_left = len
@@ -821,9 +883,12 @@ module Puma
821
883
  write_chunk(part)
822
884
  @partial_part_left = len - part.size
823
885
  when got == len - 1 # edge where we get just \r but not \n
886
+ check_chunk_ending(part, len)
824
887
  write_chunk(part[0..-2])
825
888
  @partial_part_left = len - part.size
826
889
  end
890
+ elsif line.end_with?("\n")
891
+ raise HttpParserError, "Invalid chunk header: bare LF"
827
892
  else
828
893
  if @prev_chunk.size + line.size >= MAX_CHUNK_HEADER_SIZE
829
894
  raise HttpParserError, "maximum size of chunk header exceeded"
@@ -842,10 +907,21 @@ module Puma
842
907
  # CRLF*2. Puma does not surface trailers, so we skip past them. Bytes
843
908
  # past the terminator belong to the next pipelined request.
844
909
  def finish_last_chunk(rest)
910
+ rest = rest.b
845
911
  if rest.start_with?(CHUNK_VALID_ENDING)
846
912
  trailer_end = CHUNK_VALID_ENDING_SIZE
913
+ elsif rest.start_with?("\n")
914
+ @env[HTTP_CONNECTION] = CLOSE
915
+ raise HttpParserError, "Invalid chunk trailer: bare LF"
847
916
  elsif idx = rest.index(CHUNK_VALID_ENDING * 2)
917
+ if BARE_LF.match?(rest.byteslice(0, idx))
918
+ @env[HTTP_CONNECTION] = CLOSE
919
+ raise HttpParserError, "Invalid chunk trailer: bare LF"
920
+ end
848
921
  trailer_end = idx + CHUNK_VALID_ENDING_SIZE * 2
922
+ elsif BARE_LF.match?(rest)
923
+ @env[HTTP_CONNECTION] = CLOSE
924
+ raise HttpParserError, "Invalid chunk trailer: bare LF"
849
925
  elsif rest.bytesize < MAX_CHUNK_HEADER_SIZE
850
926
  @prev_chunk = rest
851
927
  return false
@@ -13,25 +13,23 @@ module Puma
13
13
  include Puma::Const
14
14
 
15
15
  def validate_env
16
- return unless @env[SERVER_PROTOCOL] == HTTP_11
17
-
18
- unless @env.key? HTTP_HOST
16
+ if @env[REQUEST_URI] == '*' && @env[REQUEST_METHOD] != 'OPTIONS'
19
17
  @error_status_code = 400
20
18
  @env[HTTP_CONNECTION] = CLOSE
21
- raise HttpParserError, "Missing Host header"
19
+ raise HttpParserError, "Invalid request-target '*' for #{@env[REQUEST_METHOD]}"
22
20
  end
23
21
 
24
- if @env[HTTP_HOST].empty?
22
+ return if @env[SERVER_PROTOCOL] == HTTP_10
23
+
24
+ unless @env.key?(HTTP_HOST)
25
25
  @error_status_code = 400
26
26
  @env[HTTP_CONNECTION] = CLOSE
27
- raise HttpParserError, "Invalid Host header"
27
+ raise HttpParserError, "Missing Host header"
28
28
  end
29
29
  end
30
30
 
31
- # Given a Hash +env+ for the request read from +client+, add
31
+ # Given a Hash +@env+ for the request, add
32
32
  # and fixup keys to comply with Rack's env guidelines.
33
- # @param env [Hash] see Puma::Client#env, from request
34
- # @param client [Puma::Client] only needed for Client#peerip
35
33
  #
36
34
  def normalize_env
37
35
  if host = @env[HTTP_HOST]
@@ -54,7 +52,7 @@ module Puma
54
52
  unless @env[REQUEST_PATH]
55
53
  # it might be a dumbass full host request header
56
54
  uri = begin
57
- URI.parse(@env[REQUEST_URI])
55
+ URI::Generic.new(*URI.split(@env[REQUEST_URI]))
58
56
  rescue URI::InvalidURIError
59
57
  raise Puma::HttpParserError
60
58
  end
@@ -110,7 +108,8 @@ module Puma
110
108
  @env[HIJACK_P] = true
111
109
  @env[HIJACK] = method(:full_hijack).to_proc
112
110
 
113
- @env[RACK_INPUT] = @body || EmptyBody
111
+ input = @body.nil? || @body.equal?(Client::EmptyBody) ? @empty_rack_input : @body
112
+ @env[RACK_INPUT] = input if input
114
113
  @env[RACK_URL_SCHEME] ||= default_server_port == PORT_443 ? HTTPS : HTTP
115
114
  end
116
115
 
@@ -126,7 +125,6 @@ module Puma
126
125
  # ignore the `,` version. This prevents clobbering headers managed by
127
126
  # proxies but not by clients (Like X-Forwarded-For).
128
127
  #
129
- # @param env [Hash] see Puma::Client#env, from request, modifies in place
130
128
  # @version 5.0.3
131
129
  #
132
130
  def req_env_post_parse
@@ -244,12 +244,6 @@ module Puma
244
244
  new_worker.run
245
245
  end
246
246
 
247
- if !pid
248
- log "! Complete inability to spawn new workers detected"
249
- log "! Seppuku is the only choice."
250
- exit! 1
251
- end
252
-
253
247
  @worker_pids << pid
254
248
  @config.run_hooks(:after_worker_fork, idx, @log_writer, @hook_data)
255
249
  pid
data/lib/puma/cluster.rb CHANGED
@@ -25,7 +25,6 @@ module Puma
25
25
  @workers = []
26
26
  @next_check = Time.now
27
27
 
28
- @worker_max = [] # keeps track of 'max' stat values
29
28
  @pending_phased_restart = false
30
29
  @promoted_mold = nil
31
30
  @mold = nil
@@ -115,11 +114,6 @@ module Puma
115
114
  @config.run_hooks(:before_worker_fork, idx, @log_writer)
116
115
 
117
116
  pid = fork { worker(idx, master) }
118
- if !pid
119
- log "! Complete inability to spawn new workers detected"
120
- log "! Seppuku is the only choice."
121
- exit! 1
122
- end
123
117
 
124
118
  @config.run_hooks(:after_worker_fork, idx, @log_writer)
125
119
  pid
@@ -247,7 +241,6 @@ module Puma
247
241
  end
248
242
 
249
243
  def restart
250
- @restart = true
251
244
  stop
252
245
  end
253
246
 
@@ -425,13 +418,9 @@ module Puma
425
418
 
426
419
  if after.size > before.size
427
420
  threads = (after - before)
428
- if threads.first.respond_to? :backtrace
429
- log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot:"
430
- threads.each do |t|
431
- log "! #{t.inspect} - #{t.backtrace ? t.backtrace.first : ''}"
432
- end
433
- else
434
- log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot"
421
+ log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot:"
422
+ threads.each do |t|
423
+ log "! #{t.inspect} - #{t.backtrace ? t.backtrace.first : ''}"
435
424
  end
436
425
  end
437
426
  else
@@ -46,9 +46,11 @@ module Puma
46
46
  #
47
47
  # For now, both goals are framed as "load balancing" across workers (processes) and achieved through
48
48
  # the same mechanism of sleeping longer to delay busier workers. Rather than the prior Puma 6.x
49
- # and earlier behavior of using a binary on/off sleep value, we increase it an amount proportional
50
- # to the load the server is under, capping the maximum delay to the scenario where all threads are busy
51
- # and the todo list has reached a multiplier of the maximum number of threads.
49
+ # and earlier behavior of using a binary on/off sleep value, we scale the delay across two regimes:
50
+ # below thread saturation (`u <= 1.0`), a concave square-root ramp (`Math.sqrt(u)`) applies earlier
51
+ # tie-breaking backpressure as threads become busy (especially on CPU-bound workloads sharing a GVL);
52
+ # above saturation (`1.0 < u < overload_multiplier`), a linear overload ramp scales smoothly to
53
+ # `max_delay` at `max_threads * overload_multiplier` without over-sleeping during high-concurrency bursts.
52
54
  #
53
55
  # Private: API may change unexpectedly
54
56
  class ClusterAcceptLoopDelay
@@ -66,6 +68,8 @@ module Puma
66
68
 
67
69
  # Reach maximum delay when `max_threads * overload_multiplier` is reached in the system
68
70
  @overload_multiplier = 25.0
71
+ @knee_base = 1.25 / @overload_multiplier
72
+ @overload_slope = (1.0 - @knee_base) / (@overload_multiplier - 1.0)
69
73
  end
70
74
 
71
75
  def on?
@@ -75,7 +79,7 @@ module Puma
75
79
  # We want the extreme values of this delay to be known (minimum and maximum) as well as
76
80
  # a predictable curve between the two. i.e. no step functions or hard cliffs.
77
81
  #
78
- # Return value is always numeric. Returns 0 if there should be no delay.
82
+ # Return value is always a Float. Returns 0.0 if there should be no delay.
79
83
  def calculate(
80
84
  # Number of threads working right now, plus number of requests in the todo list
81
85
  busy_threads_plus_todo:,
@@ -83,9 +87,16 @@ module Puma
83
87
  # if the pool needs to be reaped. The busy thread plus todo count may go over this value by a large amount.
84
88
  max_threads:
85
89
  )
86
- max_value = @overload_multiplier * max_threads
87
- # Approaches max delay when `busy_threads_plus_todo` approaches `max_value`
88
- return max_delay * busy_threads_plus_todo.clamp(0, max_value) / max_value
90
+ return 0.0 if @max_delay == 0 || busy_threads_plus_todo <= 0
91
+
92
+ u = busy_threads_plus_todo.to_f / max_threads.to_f
93
+ if u <= 1.0
94
+ return @max_delay * @knee_base * Math.sqrt(u)
95
+ elsif u >= @overload_multiplier
96
+ return @max_delay
97
+ else
98
+ return @max_delay * (@knee_base + @overload_slope * (u - 1.0))
99
+ end
89
100
  end
90
101
  end
91
102
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Puma
4
- # Rack::CommonLogger forwards every request to the given +app+, and
4
+ # Puma::CommonLogger forwards every request to the given +app+, and
5
5
  # logs a line in the
6
6
  # {Apache common log format}[https://httpd.apache.org/docs/2.4/logs.html#common]
7
7
  # to the +logger+.
@@ -20,7 +20,6 @@ module Puma
20
20
  #
21
21
  # lilith.local - - [07/Aug/2006 23:58:02 -0400] "GET / HTTP/1.1" 500 -
22
22
  #
23
- # %{%s - %s [%s] "%s %s%s %s" %d %s\n} %
24
23
  FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n}
25
24
 
26
25
  HIJACK_FORMAT = %{%s - %s [%s] "%s %s%s %s" HIJACKED -1 %0.4f\n}
@@ -49,7 +48,7 @@ module Puma
49
48
 
50
49
  # If we've been hijacked, then output a special line
51
50
  if env['rack.hijack_io']
52
- log_hijacking(env, 'HIJACK', header, began_at)
51
+ log_hijacking(env, began_at)
53
52
  else
54
53
  ary = env['rack.after_reply']
55
54
  ary << lambda { log(env, status, header, began_at) }
@@ -60,7 +59,7 @@ module Puma
60
59
 
61
60
  private
62
61
 
63
- def log_hijacking(env, status, header, began_at)
62
+ def log_hijacking(env, began_at)
64
63
  now = Time.now
65
64
 
66
65
  msg = HIJACK_FORMAT % [
@@ -98,6 +97,9 @@ module Puma
98
97
  def write(env, msg)
99
98
  logger = @logger || env['rack.errors']
100
99
 
100
+ hex = ->(str) { str.bytes.map { |byte| "\\x%02X" % byte }.join }
101
+ msg = msg.dup.force_encoding(Encoding::UTF_8).scrub(&hex).gsub(/[\p{Cc}\u2028\u2029](?!\z)/, &hex)
102
+
101
103
  # Standard library logger doesn't support write but it supports << which actually
102
104
  # calls to write on the log device without formatting
103
105
  if logger.respond_to?(:write)
@@ -145,10 +145,12 @@ module Puma
145
145
  first_data_timeout: 30,
146
146
  force_shutdown_after: -1,
147
147
  http_content_length_limit: nil,
148
+ http_parser: nil,
148
149
  shutdown_body_timeout: 25,
149
150
  # Number of seconds to wait until the next request before shutting down.
150
151
  idle_timeout: nil,
151
152
  io_selector_backend: :auto,
153
+ date_header: true,
152
154
  log_requests: false,
153
155
  logger: STDOUT,
154
156
  # Limits how many requests a keep alive connection can make.
@@ -160,6 +162,7 @@ module Puma
160
162
  min_threads: 0,
161
163
  mode: :http,
162
164
  mutate_stdout_and_stderr_to_sync_on_write: true,
165
+ nil_rack_input_on_empty_body: false,
163
166
  out_of_band: [],
164
167
  # Number of seconds for another request within a persistent session.
165
168
  persistent_timeout: 65, # PUMA_PERSISTENT_TIMEOUT
@@ -223,7 +226,7 @@ module Puma
223
226
  def initialize_copy(other)
224
227
  @conf = nil
225
228
  @cli_options = nil
226
- @_options = @_options.dup
229
+ @_options = @_options.dup
227
230
  end
228
231
 
229
232
  def flatten
data/lib/puma/const.rb CHANGED
@@ -1,4 +1,3 @@
1
- #encoding: utf-8
2
1
  # frozen_string_literal: true
3
2
 
4
3
  module Puma
@@ -100,8 +99,8 @@ module Puma
100
99
  # too taxing on performance.
101
100
  module Const
102
101
 
103
- PUMA_VERSION = VERSION = "8.1.2"
104
- CODE_NAME = "Puma Psychosis"
102
+ PUMA_VERSION = VERSION = "8.2.0.pre1"
103
+ CODE_NAME = "Windows 96"
105
104
 
106
105
  PUMA_SERVER_STRING = ["puma", PUMA_VERSION, CODE_NAME].join(" ").freeze
107
106
 
@@ -125,7 +124,7 @@ module Puma
125
124
  ERROR_RESPONSE = {
126
125
  # Indicate that we couldn't parse the request
127
126
  400 => "HTTP/1.1 400 Bad Request\r\n\r\n",
128
- # The standard empty 404 response for bad requests. Use Error4040Handler for custom stuff.
127
+ # The standard empty 404 response for bad requests.
129
128
  404 => "HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n",
130
129
  # The standard empty 408 response for requests that timed out.
131
130
  408 => "HTTP/1.1 408 Request Timeout\r\nconnection: close\r\n\r\n",
@@ -199,7 +198,6 @@ module Puma
199
198
  VERSION-CONTROL
200
199
  ].freeze
201
200
 
202
- # ETag is based on the apache standard of hex mtime-size-inode (inode is 0 on win32)
203
201
  LINE_END = "\r\n"
204
202
  REMOTE_ADDR = "REMOTE_ADDR"
205
203
  HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR"
@@ -219,6 +217,7 @@ module Puma
219
217
  UNSPECIFIED_IPV6 = "::"
220
218
 
221
219
  SERVER_PROTOCOL = "SERVER_PROTOCOL"
220
+ HTTP_10 = "HTTP/1.0"
222
221
  HTTP_11 = "HTTP/1.1"
223
222
 
224
223
  SERVER_SOFTWARE = "SERVER_SOFTWARE"
@@ -274,6 +273,7 @@ module Puma
274
273
 
275
274
  HIJACK_P = "rack.hijack?"
276
275
  HIJACK = "rack.hijack"
276
+ DATE = "date"
277
277
  HIJACK_IO = "rack.hijack_io"
278
278
 
279
279
  EARLY_HINTS = "rack.early_hints"