ed-precompiled_puma 7.0.4

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 (88) hide show
  1. checksums.yaml +7 -0
  2. data/History.md +3172 -0
  3. data/LICENSE +29 -0
  4. data/README.md +477 -0
  5. data/bin/puma +10 -0
  6. data/bin/puma-wild +25 -0
  7. data/bin/pumactl +12 -0
  8. data/docs/architecture.md +74 -0
  9. data/docs/compile_options.md +55 -0
  10. data/docs/deployment.md +102 -0
  11. data/docs/fork_worker.md +41 -0
  12. data/docs/images/puma-connection-flow-no-reactor.png +0 -0
  13. data/docs/images/puma-connection-flow.png +0 -0
  14. data/docs/images/puma-general-arch.png +0 -0
  15. data/docs/java_options.md +54 -0
  16. data/docs/jungle/README.md +9 -0
  17. data/docs/jungle/rc.d/README.md +74 -0
  18. data/docs/jungle/rc.d/puma +61 -0
  19. data/docs/jungle/rc.d/puma.conf +10 -0
  20. data/docs/kubernetes.md +80 -0
  21. data/docs/nginx.md +80 -0
  22. data/docs/plugins.md +42 -0
  23. data/docs/rails_dev_mode.md +28 -0
  24. data/docs/restart.md +65 -0
  25. data/docs/signals.md +98 -0
  26. data/docs/stats.md +148 -0
  27. data/docs/systemd.md +253 -0
  28. data/docs/testing_benchmarks_local_files.md +150 -0
  29. data/docs/testing_test_rackup_ci_files.md +36 -0
  30. data/ext/puma_http11/PumaHttp11Service.java +17 -0
  31. data/ext/puma_http11/ext_help.h +15 -0
  32. data/ext/puma_http11/extconf.rb +65 -0
  33. data/ext/puma_http11/http11_parser.c +1057 -0
  34. data/ext/puma_http11/http11_parser.h +65 -0
  35. data/ext/puma_http11/http11_parser.java.rl +145 -0
  36. data/ext/puma_http11/http11_parser.rl +149 -0
  37. data/ext/puma_http11/http11_parser_common.rl +54 -0
  38. data/ext/puma_http11/mini_ssl.c +852 -0
  39. data/ext/puma_http11/no_ssl/PumaHttp11Service.java +15 -0
  40. data/ext/puma_http11/org/jruby/puma/Http11.java +257 -0
  41. data/ext/puma_http11/org/jruby/puma/Http11Parser.java +455 -0
  42. data/ext/puma_http11/org/jruby/puma/MiniSSL.java +509 -0
  43. data/ext/puma_http11/puma_http11.c +507 -0
  44. data/lib/puma/app/status.rb +96 -0
  45. data/lib/puma/binder.rb +511 -0
  46. data/lib/puma/cli.rb +245 -0
  47. data/lib/puma/client.rb +720 -0
  48. data/lib/puma/cluster/worker.rb +182 -0
  49. data/lib/puma/cluster/worker_handle.rb +127 -0
  50. data/lib/puma/cluster.rb +635 -0
  51. data/lib/puma/cluster_accept_loop_delay.rb +91 -0
  52. data/lib/puma/commonlogger.rb +115 -0
  53. data/lib/puma/configuration.rb +452 -0
  54. data/lib/puma/const.rb +307 -0
  55. data/lib/puma/control_cli.rb +320 -0
  56. data/lib/puma/detect.rb +47 -0
  57. data/lib/puma/dsl.rb +1480 -0
  58. data/lib/puma/error_logger.rb +115 -0
  59. data/lib/puma/events.rb +72 -0
  60. data/lib/puma/io_buffer.rb +50 -0
  61. data/lib/puma/jruby_restart.rb +11 -0
  62. data/lib/puma/json_serialization.rb +96 -0
  63. data/lib/puma/launcher/bundle_pruner.rb +104 -0
  64. data/lib/puma/launcher.rb +496 -0
  65. data/lib/puma/log_writer.rb +147 -0
  66. data/lib/puma/minissl/context_builder.rb +96 -0
  67. data/lib/puma/minissl.rb +463 -0
  68. data/lib/puma/null_io.rb +101 -0
  69. data/lib/puma/plugin/systemd.rb +90 -0
  70. data/lib/puma/plugin/tmp_restart.rb +36 -0
  71. data/lib/puma/plugin.rb +111 -0
  72. data/lib/puma/rack/builder.rb +297 -0
  73. data/lib/puma/rack/urlmap.rb +93 -0
  74. data/lib/puma/rack_default.rb +24 -0
  75. data/lib/puma/reactor.rb +140 -0
  76. data/lib/puma/request.rb +701 -0
  77. data/lib/puma/runner.rb +211 -0
  78. data/lib/puma/sd_notify.rb +146 -0
  79. data/lib/puma/server.rb +734 -0
  80. data/lib/puma/single.rb +72 -0
  81. data/lib/puma/state_file.rb +69 -0
  82. data/lib/puma/thread_pool.rb +402 -0
  83. data/lib/puma/util.rb +134 -0
  84. data/lib/puma.rb +93 -0
  85. data/lib/rack/handler/puma.rb +144 -0
  86. data/tools/Dockerfile +18 -0
  87. data/tools/trickletest.rb +44 -0
  88. metadata +152 -0
data/lib/puma/dsl.rb ADDED
@@ -0,0 +1,1480 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'const'
4
+ require_relative 'util'
5
+
6
+ module Puma
7
+ # The methods that are available for use inside the configuration file.
8
+ # These same methods are used in Puma cli and the rack handler
9
+ # internally.
10
+ #
11
+ # Used manually (via CLI class):
12
+ #
13
+ # config = Configuration.new({}) do |user_config|
14
+ # user_config.port 3001
15
+ # end
16
+ # config.clamp
17
+ #
18
+ # puts config.options[:binds] # => "tcp://127.0.0.1:3001"
19
+ #
20
+ # Used to load file:
21
+ #
22
+ # $ cat puma_config.rb
23
+ # port 3002
24
+ #
25
+ # Resulting configuration:
26
+ #
27
+ # config = Configuration.new(config_file: "puma_config.rb")
28
+ # config.clamp
29
+ #
30
+ # puts config.options[:binds] # => "tcp://127.0.0.1:3002"
31
+ #
32
+ # You can also find many examples being used by the test suite in
33
+ # +test/config+.
34
+ #
35
+ # Puma v6 adds the option to specify a key name (String or Symbol) to the
36
+ # hooks that run inside the forked workers. All the hooks run inside the
37
+ # {Puma::Cluster::Worker#run} method.
38
+ #
39
+ # Previously, the worker index and the LogWriter instance were passed to the
40
+ # hook blocks/procs. If a key name is specified, a hash is passed as the last
41
+ # parameter. This allows storage of data, typically objects that are created
42
+ # before the worker that need to be passed to the hook when the worker is shutdown.
43
+ #
44
+ # The following hooks have been updated:
45
+ #
46
+ # | DSL Method | Options Key | Fork Block Location |
47
+ # | before_worker_boot | :before_worker_boot | inside, before |
48
+ # | before_worker_shutdown | :before_worker_shutdown | inside, after |
49
+ # | before_refork | :before_refork | inside |
50
+ # | after_refork | :after_refork | inside |
51
+ #
52
+ class DSL
53
+ ON_WORKER_KEY = [String, Symbol].freeze
54
+
55
+ # Convenience method so logic can be used in CI.
56
+ #
57
+ # @see ssl_bind
58
+ #
59
+ def self.ssl_bind_str(host, port, opts)
60
+ verify = opts.fetch(:verify_mode, 'none').to_s
61
+
62
+ tls_str =
63
+ if opts[:no_tlsv1_1] then '&no_tlsv1_1=true'
64
+ elsif opts[:no_tlsv1] then '&no_tlsv1=true'
65
+ else ''
66
+ end
67
+
68
+ ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify)
69
+
70
+ low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : ''
71
+ backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : ''
72
+
73
+ if defined?(JRUBY_VERSION)
74
+ cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name
75
+ cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites]
76
+ protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil
77
+
78
+ keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}"
79
+ keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type]
80
+ if opts[:truststore]
81
+ truststore_additions = "&truststore=#{opts[:truststore]}"
82
+ truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass]
83
+ truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type]
84
+ end
85
+
86
+ "ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \
87
+ "&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}"
88
+ else
89
+ ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil
90
+ ssl_ciphersuites = opts[:ssl_ciphersuites] ? "&ssl_ciphersuites=#{opts[:ssl_ciphersuites]}" : nil
91
+ v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil
92
+
93
+ cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil
94
+ key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil
95
+ password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil
96
+
97
+ reuse_flag =
98
+ if (reuse = opts[:reuse])
99
+ if reuse == true
100
+ '&reuse=dflt'
101
+ elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout))
102
+ val = +''
103
+ if (size = reuse[:size]) && Integer === size
104
+ val << size.to_s
105
+ end
106
+ if (timeout = reuse[:timeout]) && Integer === timeout
107
+ val << ",#{timeout}"
108
+ end
109
+ if val.empty?
110
+ nil
111
+ else
112
+ "&reuse=#{val}"
113
+ end
114
+ else
115
+ nil
116
+ end
117
+ else
118
+ nil
119
+ end
120
+
121
+ "ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}#{ssl_ciphersuites}" \
122
+ "#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}"
123
+ end
124
+ end
125
+
126
+ def initialize(options, config)
127
+ @config = config
128
+ @options = options
129
+
130
+ @plugins = []
131
+ end
132
+
133
+ def _load_from(path)
134
+ if path
135
+ @path = path
136
+ instance_eval(File.read(path), path, 1)
137
+ end
138
+ ensure
139
+ _offer_plugins
140
+ end
141
+
142
+ def _offer_plugins
143
+ @plugins.each do |o|
144
+ if o.respond_to? :config
145
+ @options.shift
146
+ o.config self
147
+ end
148
+ end
149
+
150
+ @plugins.clear
151
+ end
152
+
153
+ def set_default_host(host)
154
+ @options[:default_host] = host
155
+ end
156
+
157
+ def default_host
158
+ @options[:default_host] || Configuration::DEFAULTS[:tcp_host]
159
+ end
160
+
161
+ def inject(&blk)
162
+ instance_eval(&blk)
163
+ end
164
+
165
+ def get(key,default=nil)
166
+ @options[key.to_sym] || default
167
+ end
168
+
169
+ # Load the named plugin for use by this configuration.
170
+ #
171
+ # @example
172
+ # plugin :tmp_restart
173
+ #
174
+ def plugin(name)
175
+ @plugins << @config.load_plugin(name)
176
+ end
177
+
178
+ # Use an object or block as the rack application. This allows the
179
+ # configuration file to be the application itself.
180
+ #
181
+ # @example
182
+ # app do |env|
183
+ # body = 'Hello, World!'
184
+ #
185
+ # [
186
+ # 200,
187
+ # {
188
+ # 'Content-Type' => 'text/plain',
189
+ # 'Content-Length' => body.length.to_s
190
+ # },
191
+ # [body]
192
+ # ]
193
+ # end
194
+ #
195
+ # @see Puma::Configuration#app
196
+ #
197
+ def app(obj=nil, &block)
198
+ obj ||= block
199
+
200
+ raise "Provide either a #call'able or a block" unless obj
201
+
202
+ @options[:app] = obj
203
+ end
204
+
205
+ # Start the Puma control rack application on +url+. This application can
206
+ # be communicated with to control the main server. Additionally, you can
207
+ # provide an authentication token, so all requests to the control server
208
+ # will need to include that token as a query parameter. This allows for
209
+ # simple authentication.
210
+ #
211
+ # Check out {Puma::App::Status} to see what the app has available.
212
+ #
213
+ # @example
214
+ # activate_control_app 'unix:///var/run/pumactl.sock'
215
+ # @example
216
+ # activate_control_app 'unix:///var/run/pumactl.sock', { auth_token: '12345' }
217
+ # @example
218
+ # activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true }
219
+ #
220
+ def activate_control_app(url="auto", opts={})
221
+ if url == "auto"
222
+ path = Configuration.temp_path
223
+ @options[:control_url] = "unix://#{path}"
224
+ @options[:control_url_temp] = path
225
+ else
226
+ @options[:control_url] = url
227
+ end
228
+
229
+ if opts[:no_token]
230
+ # We need to use 'none' rather than :none because this value will be
231
+ # passed on to an instance of OptionParser, which doesn't support
232
+ # symbols as option values.
233
+ #
234
+ # See: https://github.com/puma/puma/issues/1193#issuecomment-305995488
235
+ auth_token = 'none'
236
+ else
237
+ auth_token = opts[:auth_token]
238
+ auth_token ||= Configuration.random_token
239
+ end
240
+
241
+ @options[:control_auth_token] = auth_token
242
+ @options[:control_url_umask] = opts[:umask] if opts[:umask]
243
+ end
244
+
245
+ # Load additional configuration from a file.
246
+ # Files get loaded later via Configuration#load.
247
+ #
248
+ # @example
249
+ # load 'config/puma/production.rb'
250
+ #
251
+ def load(file)
252
+ @options[:config_files] ||= []
253
+ @options[:config_files] << file
254
+ end
255
+
256
+ # Bind the server to +url+. "tcp://", "unix://" and "ssl://" are the only
257
+ # accepted protocols. Multiple urls can be bound to, calling +bind+ does
258
+ # not overwrite previous bindings.
259
+ #
260
+ # The default is "tcp://0.0.0.0:9292".
261
+ #
262
+ # You can use query parameters within the url to specify options:
263
+ #
264
+ # * Set the socket backlog depth with +backlog+, default is 1024.
265
+ # * Set up an SSL certificate with +key+ & +cert+.
266
+ # * Set up an SSL certificate for mTLS with +key+, +cert+, +ca+ and +verify_mode+.
267
+ # * Set whether to optimize for low latency instead of throughput with
268
+ # +low_latency+, default is to not optimize for low latency. This is done
269
+ # via +Socket::TCP_NODELAY+.
270
+ # * Set socket permissions with +umask+.
271
+ #
272
+ # @example Backlog depth
273
+ # bind 'unix:///var/run/puma.sock?backlog=512'
274
+ # @example SSL cert
275
+ # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem'
276
+ # @example SSL cert for mutual TLS (mTLS)
277
+ # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem&ca=ca.pem&verify_mode=force_peer'
278
+ # @example Disable optimization for low latency
279
+ # bind 'tcp://0.0.0.0:9292?low_latency=false'
280
+ # @example Socket permissions
281
+ # bind 'unix:///var/run/puma.sock?umask=0111'
282
+ #
283
+ # @see Puma::Runner#load_and_bind
284
+ # @see Puma::Cluster#run
285
+ #
286
+ def bind(url)
287
+ @options[:binds] ||= []
288
+ @options[:binds] << url
289
+ end
290
+
291
+ def clear_binds!
292
+ @options[:binds] = []
293
+ end
294
+
295
+ # Bind to (systemd) activated sockets, regardless of configured binds.
296
+ #
297
+ # Systemd can present sockets as file descriptors that are already opened.
298
+ # By default Puma will use these but only if it was explicitly told to bind
299
+ # to the socket. If not, it will close the activated sockets. This means
300
+ # all configuration is duplicated.
301
+ #
302
+ # Binds can contain additional configuration, but only SSL config is really
303
+ # relevant since the unix and TCP socket options are ignored.
304
+ #
305
+ # This means there is a lot of duplicated configuration for no additional
306
+ # value in most setups. This method tells the launcher to bind to all
307
+ # activated sockets, regardless of existing bind.
308
+ #
309
+ # To clear configured binds, the value only can be passed. This will clear
310
+ # out any binds that may have been configured.
311
+ #
312
+ # @example Use any systemd activated sockets as well as configured binds
313
+ # bind_to_activated_sockets
314
+ #
315
+ # @example Only bind to systemd activated sockets, ignoring other binds
316
+ # bind_to_activated_sockets 'only'
317
+ #
318
+ def bind_to_activated_sockets(bind=true)
319
+ @options[:bind_to_activated_sockets] = bind
320
+ end
321
+
322
+ # Define the TCP port to bind to. Use `bind` for more advanced options.
323
+ #
324
+ # The default is +9292+.
325
+ #
326
+ # @example
327
+ # port 3000
328
+ #
329
+ def port(port, host=nil)
330
+ host ||= default_host
331
+ bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s
332
+ end
333
+
334
+ # Define how long the tcp socket stays open, if no data has been received.
335
+ #
336
+ # The default is 30 seconds.
337
+ #
338
+ # @example
339
+ # first_data_timeout 40
340
+ #
341
+ # @see Puma::Server.new
342
+ #
343
+ def first_data_timeout(seconds)
344
+ @options[:first_data_timeout] = Integer(seconds)
345
+ end
346
+
347
+ # Define how long persistent connections can be idle before Puma closes them.
348
+ #
349
+ # The default is 20 seconds.
350
+ #
351
+ # @example
352
+ # persistent_timeout 30
353
+ #
354
+ # @see Puma::Server.new
355
+ #
356
+ def persistent_timeout(seconds)
357
+ @options[:persistent_timeout] = Integer(seconds)
358
+ end
359
+
360
+ # If a new request is not received within this number of seconds, begin shutting down.
361
+ #
362
+ # The default is +nil+.
363
+ #
364
+ # @example
365
+ # idle_timeout 60
366
+ #
367
+ # @see Puma::Server.new
368
+ #
369
+ def idle_timeout(seconds)
370
+ @options[:idle_timeout] = Integer(seconds)
371
+ end
372
+
373
+ # Use a clean fiber per request which ensures a clean slate for fiber
374
+ # locals and fiber storage. Also provides a cleaner backtrace with less
375
+ # Puma internal stack frames.
376
+ #
377
+ # The default is +false+.
378
+ #
379
+ # @example
380
+ # fiber_per_request
381
+ #
382
+ def fiber_per_request(which=true)
383
+ @options[:fiber_per_request] = which
384
+ end
385
+
386
+ alias clean_thread_locals fiber_per_request
387
+
388
+ # When shutting down, drain the accept socket of pending connections and
389
+ # process them. This loops over the accept socket until there are no more
390
+ # read events and then stops looking and waits for the requests to finish.
391
+ #
392
+ # @see Puma::Server#graceful_shutdown
393
+ #
394
+ def drain_on_shutdown(which=true)
395
+ @options[:drain_on_shutdown] = which
396
+ end
397
+
398
+ # Set the environment in which the rack's app will run. The value must be
399
+ # a string.
400
+ #
401
+ # The default is "development".
402
+ #
403
+ # @example
404
+ # environment 'production'
405
+ #
406
+ def environment(environment)
407
+ @options[:environment] = environment
408
+ end
409
+
410
+ # How long to wait for threads to stop when shutting them down.
411
+ # Specifying :immediately will cause Puma to kill the threads immediately.
412
+ # Otherwise the value is the number of seconds to wait.
413
+ #
414
+ # Puma always waits a few seconds after killing a thread for it to try
415
+ # to finish up it's work, even in :immediately mode.
416
+ #
417
+ # The default is +:forever+.
418
+ #
419
+ # @see Puma::Server#graceful_shutdown
420
+ #
421
+ def force_shutdown_after(val=:forever)
422
+ i = case val
423
+ when :forever
424
+ -1
425
+ when :immediately
426
+ 0
427
+ else
428
+ Float(val)
429
+ end
430
+
431
+ @options[:force_shutdown_after] = i
432
+ end
433
+
434
+ # Code to run before doing a restart. This code should
435
+ # close log files, database connections, etc.
436
+ #
437
+ # This can be called multiple times to add code each time.
438
+ #
439
+ # @example
440
+ # before_restart do
441
+ # puts 'On restart...'
442
+ # end
443
+ #
444
+ def before_restart(&block)
445
+ Puma.deprecate_method_change :on_restart, __callee__, __method__
446
+
447
+ process_hook :before_restart, nil, block
448
+ end
449
+
450
+ alias_method :on_restart, :before_restart
451
+
452
+ # Command to use to restart Puma. This should be just how to
453
+ # load Puma itself (ie. 'ruby -Ilib bin/puma'), not the arguments
454
+ # to Puma, as those are the same as the original process.
455
+ #
456
+ # @example
457
+ # restart_command '/u/app/lolcat/bin/restart_puma'
458
+ #
459
+ def restart_command(cmd)
460
+ @options[:restart_cmd] = cmd.to_s
461
+ end
462
+
463
+ # Store the pid of the server in the file at "path".
464
+ #
465
+ # @example
466
+ # pidfile '/u/apps/lolcat/tmp/pids/puma.pid'
467
+ #
468
+ def pidfile(path)
469
+ @options[:pidfile] = path.to_s
470
+ end
471
+
472
+ # Disable request logging, the inverse of `log_requests`.
473
+ #
474
+ # The default is +true+.
475
+ #
476
+ # @example
477
+ # quiet
478
+ #
479
+ def quiet(which=true)
480
+ @options[:log_requests] = !which
481
+ end
482
+
483
+ # Enable request logging, the inverse of `quiet`.
484
+ #
485
+ # The default is +false+.
486
+ #
487
+ # @example
488
+ # log_requests
489
+ #
490
+ def log_requests(which=true)
491
+ @options[:log_requests] = which
492
+ end
493
+
494
+ # Pass in a custom logging class instance
495
+ #
496
+ # @example
497
+ # custom_logger Logger.new('t.log')
498
+ #
499
+ def custom_logger(custom_logger)
500
+ @options[:custom_logger] = custom_logger
501
+ end
502
+
503
+ # Show debugging info
504
+ #
505
+ # The default is +false+.
506
+ #
507
+ # @example
508
+ # debug
509
+ #
510
+ def debug
511
+ @options[:debug] = true
512
+ end
513
+
514
+ # Load +path+ as a rackup file.
515
+ #
516
+ # The default is "config.ru".
517
+ #
518
+ # @example
519
+ # rackup '/u/apps/lolcat/config.ru'
520
+ #
521
+ def rackup(path)
522
+ @options[:rackup] ||= path.to_s
523
+ end
524
+
525
+ # Allows setting `env['rack.url_scheme']`.
526
+ # Only necessary if X-Forwarded-Proto is not being set by your proxy
527
+ # Normal values are 'http' or 'https'.
528
+ #
529
+ def rack_url_scheme(scheme=nil)
530
+ @options[:rack_url_scheme] = scheme
531
+ end
532
+
533
+ # Enable HTTP 103 Early Hints responses.
534
+ #
535
+ # The default is +nil+.
536
+ #
537
+ # @example
538
+ # early_hints
539
+ #
540
+ def early_hints(answer=true)
541
+ @options[:early_hints] = answer
542
+ end
543
+
544
+ # Redirect +STDOUT+ and +STDERR+ to files specified. The +append+ parameter
545
+ # specifies whether the output is appended.
546
+ #
547
+ # The default is +false+.
548
+ #
549
+ # @example
550
+ # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr'
551
+ # @example
552
+ # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr', true
553
+ #
554
+ def stdout_redirect(stdout=nil, stderr=nil, append=false)
555
+ @options[:redirect_stdout] = stdout
556
+ @options[:redirect_stderr] = stderr
557
+ @options[:redirect_append] = append
558
+ end
559
+
560
+ def log_formatter(&block)
561
+ @options[:log_formatter] = block
562
+ end
563
+
564
+ # Configure the number of threads to use to answer requests.
565
+ #
566
+ # It can be a single fixed number, or a +min+ and a +max+.
567
+ #
568
+ # The default is the environment variables +PUMA_MIN_THREADS+ / +PUMA_MAX_THREADS+
569
+ # (or +MIN_THREADS+ / +MAX_THREADS+ if the +PUMA_+ variables aren't set).
570
+ #
571
+ # If these environment variables aren't set, the default is "0, 5" in MRI or "0, 16" for other interpreters.
572
+ #
573
+ # @example
574
+ # threads 5
575
+ # @example
576
+ # threads 0, 16
577
+ # @example
578
+ # threads 5, 5
579
+ #
580
+ def threads(min, max = min)
581
+ min = Integer(min)
582
+ max = Integer(max)
583
+ if min > max
584
+ raise "The minimum (#{min}) number of threads must be less than or equal to the max (#{max})"
585
+ end
586
+
587
+ if max < 1
588
+ raise "The maximum number of threads (#{max}) must be greater than 0"
589
+ end
590
+
591
+ @options[:min_threads] = min
592
+ @options[:max_threads] = max
593
+ end
594
+
595
+ # Instead of using +bind+ and manually constructing a URI like:
596
+ #
597
+ # bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path'
598
+ #
599
+ # you can use the this method.
600
+ #
601
+ # When binding on localhost you don't need to specify +cert+ and +key+,
602
+ # Puma will assume you are using the +localhost+ gem and try to load the
603
+ # appropriate files.
604
+ #
605
+ # When using the options hash parameter, the `reuse:` value is either
606
+ # `true`, which sets reuse 'on' with default values, or a hash, with `:size`
607
+ # and/or `:timeout` keys, each with integer values.
608
+ #
609
+ # The `cert:` options hash parameter can be the path to a certificate
610
+ # file including all intermediate certificates in PEM format.
611
+ #
612
+ # The `cert_pem:` options hash parameter can be String containing the
613
+ # cerificate and all intermediate certificates in PEM format.
614
+ #
615
+ # @example
616
+ # ssl_bind '127.0.0.1', '9292', {
617
+ # cert: path_to_cert,
618
+ # key: path_to_key,
619
+ # ssl_cipher_filter: cipher_filter, # optional
620
+ # ssl_ciphersuites: ciphersuites, # optional
621
+ # verify_mode: verify_mode, # default 'none'
622
+ # verification_flags: flags, # optional, not supported by JRuby
623
+ # reuse: true # optional
624
+ # }
625
+ #
626
+ # @example Using self-signed certificate with the +localhost+ gem:
627
+ # ssl_bind '127.0.0.1', '9292'
628
+ #
629
+ # @example Alternatively, you can provide +cert_pem+ and +key_pem+:
630
+ # ssl_bind '127.0.0.1', '9292', {
631
+ # cert_pem: File.read(path_to_cert),
632
+ # key_pem: File.read(path_to_key),
633
+ # reuse: {size: 2_000, timeout: 20} # optional
634
+ # }
635
+ #
636
+ # @example For JRuby, two keys are required: +keystore+ & +keystore_pass+
637
+ # ssl_bind '127.0.0.1', '9292', {
638
+ # keystore: path_to_keystore,
639
+ # keystore_pass: password,
640
+ # ssl_cipher_list: cipher_list, # optional
641
+ # verify_mode: verify_mode # default 'none'
642
+ # }
643
+ #
644
+ def ssl_bind(host, port, opts = {})
645
+ add_pem_values_to_options_store(opts)
646
+ bind self.class.ssl_bind_str(host, port, opts)
647
+ end
648
+
649
+ # Use +path+ as the file to store the server info state. This is
650
+ # used by +pumactl+ to query and control the server.
651
+ #
652
+ # @example
653
+ # state_path '/u/apps/lolcat/tmp/pids/puma.state'
654
+ #
655
+ def state_path(path)
656
+ @options[:state] = path.to_s
657
+ end
658
+
659
+ # Use +permission+ to restrict permissions for the state file. By convention,
660
+ # +permission+ is an octal number (e.g. `0640` or `0o640`).
661
+ #
662
+ # @example
663
+ # state_permission 0600
664
+ #
665
+ def state_permission(permission)
666
+ @options[:state_permission] = permission
667
+ end
668
+
669
+ # How many worker processes to run. Typically this is set to
670
+ # the number of available cores.
671
+ #
672
+ # The default is the value of the environment variable +WEB_CONCURRENCY+ if
673
+ # set, otherwise 0.
674
+ #
675
+ # @note Cluster mode only.
676
+ #
677
+ # @example
678
+ # workers 2
679
+ #
680
+ # @see Puma::Cluster
681
+ #
682
+ def workers(count)
683
+ @options[:workers] = count.to_i
684
+ end
685
+
686
+ # Disable warning message when running in cluster mode with a single worker.
687
+ #
688
+ # Cluster mode has some overhead of running an additional 'control' process
689
+ # in order to manage the cluster. If only running a single worker it is
690
+ # likely not worth paying that overhead vs running in single mode with
691
+ # additional threads instead.
692
+ #
693
+ # There are some scenarios where running cluster mode with a single worker
694
+ # may still be warranted and valid under certain deployment scenarios, see
695
+ # https://github.com/puma/puma/issues/2534
696
+ #
697
+ # Moving from workers = 1 to workers = 0 will save 10-30% of memory use.
698
+ #
699
+ # The default is +false+.
700
+ #
701
+ # @note Cluster mode only.
702
+ #
703
+ # @example
704
+ # silence_single_worker_warning
705
+ #
706
+ def silence_single_worker_warning
707
+ @options[:silence_single_worker_warning] = true
708
+ end
709
+
710
+ # Disable warning message when running single mode with callback hook defined.
711
+ #
712
+ # The default is +false+.
713
+ #
714
+ # @example
715
+ # silence_fork_callback_warning
716
+ #
717
+ def silence_fork_callback_warning
718
+ @options[:silence_fork_callback_warning] = true
719
+ end
720
+
721
+ # Code to run immediately before master process
722
+ # forks workers (once on boot). These hooks can block if necessary
723
+ # to wait for background operations unknown to Puma to finish before
724
+ # the process terminates.
725
+ # This can be used to close any connections to remote servers (database,
726
+ # Redis, ...) that were opened when preloading the code.
727
+ #
728
+ # This can be called multiple times to add several hooks.
729
+ #
730
+ # @note Cluster mode only.
731
+ #
732
+ # @example
733
+ # before_fork do
734
+ # puts "Starting workers..."
735
+ # end
736
+ #
737
+ def before_fork(&block)
738
+ process_hook :before_fork, nil, block, cluster_only: true
739
+ end
740
+
741
+ # Code to run in a worker when it boots to setup
742
+ # the process before booting the app.
743
+ #
744
+ # This can be called multiple times to add several hooks.
745
+ #
746
+ # @note Cluster mode only.
747
+ #
748
+ # @example
749
+ # before_worker_boot do
750
+ # puts 'Before worker boot...'
751
+ # end
752
+ #
753
+ def before_worker_boot(key = nil, &block)
754
+ Puma.deprecate_method_change :on_worker_boot, __callee__, __method__
755
+
756
+ process_hook :before_worker_boot, key, block, cluster_only: true
757
+ end
758
+
759
+ alias_method :on_worker_boot, :before_worker_boot
760
+
761
+ # Code to run immediately before a worker shuts
762
+ # down (after it has finished processing HTTP requests). The worker's
763
+ # index is passed as an argument. These hooks
764
+ # can block if necessary to wait for background operations unknown
765
+ # to Puma to finish before the process terminates.
766
+ #
767
+ # This can be called multiple times to add several hooks.
768
+ #
769
+ # @note Cluster mode only.
770
+ #
771
+ # @example
772
+ # before_worker_shutdown do
773
+ # puts 'On worker shutdown...'
774
+ # end
775
+ #
776
+ def before_worker_shutdown(key = nil, &block)
777
+ Puma.deprecate_method_change :on_worker_shutdown, __callee__, __method__
778
+
779
+ process_hook :before_worker_shutdown, key, block, cluster_only: true
780
+ end
781
+
782
+ alias_method :on_worker_shutdown, :before_worker_shutdown
783
+
784
+ # Code to run in the master right before a worker is started. The worker's
785
+ # index is passed as an argument.
786
+ #
787
+ # This can be called multiple times to add several hooks.
788
+ #
789
+ # @note Cluster mode only.
790
+ #
791
+ # @example
792
+ # before_worker_fork do
793
+ # puts 'Before worker fork...'
794
+ # end
795
+ #
796
+ def before_worker_fork(&block)
797
+ Puma.deprecate_method_change :on_worker_fork, __callee__, __method__
798
+
799
+ process_hook :before_worker_fork, nil, block, cluster_only: true
800
+ end
801
+
802
+ alias_method :on_worker_fork, :before_worker_fork
803
+
804
+ # Code to run in the master after a worker has been started. The worker's
805
+ # index is passed as an argument.
806
+ #
807
+ # This is called everytime a worker is to be started.
808
+ #
809
+ # @note Cluster mode only.
810
+ #
811
+ # @example
812
+ # after_worker_fork do
813
+ # puts 'After worker fork...'
814
+ # end
815
+ #
816
+ def after_worker_fork(&block)
817
+ process_hook :after_worker_fork, nil, block, cluster_only: true
818
+ end
819
+
820
+ alias_method :after_worker_boot, :after_worker_fork
821
+
822
+ # Code to run in the master right after a worker has stopped. The worker's
823
+ # index and Process::Status are passed as arguments.
824
+ #
825
+ # @note Cluster mode only.
826
+ #
827
+ # @example
828
+ # after_worker_shutdown do |worker_handle|
829
+ # puts 'Worker crashed' unless worker_handle.process_status.success?
830
+ # end
831
+ #
832
+ def after_worker_shutdown(&block)
833
+ process_hook :after_worker_shutdown, nil, block, cluster_only: true
834
+ end
835
+
836
+ # Code to run after puma is booted (works for both single and cluster modes).
837
+ #
838
+ # @example
839
+ # after_booted do
840
+ # puts 'After booting...'
841
+ # end
842
+ #
843
+ def after_booted(&block)
844
+ Puma.deprecate_method_change :on_booted, __callee__, __method__
845
+
846
+ @config.events.after_booted(&block)
847
+ end
848
+
849
+ alias_method :on_booted, :after_booted
850
+
851
+ # Code to run after puma is stopped (works for both: single and clustered)
852
+ #
853
+ # @example
854
+ # after_stopped do
855
+ # puts 'After stopping...'
856
+ # end
857
+ #
858
+ def after_stopped(&block)
859
+ Puma.deprecate_method_change :on_stopped, __callee__, __method__
860
+
861
+ @config.events.after_stopped(&block)
862
+ end
863
+ alias_method :on_stopped, :after_stopped
864
+
865
+ # When `fork_worker` is enabled, code to run in Worker 0
866
+ # before all other workers are re-forked from this process,
867
+ # after the server has temporarily stopped serving requests
868
+ # (once per complete refork cycle).
869
+ #
870
+ # This can be used to trigger extra garbage-collection to maximize
871
+ # copy-on-write efficiency, or close any connections to remote servers
872
+ # (database, Redis, ...) that were opened while the server was running.
873
+ #
874
+ # This can be called multiple times to add several hooks.
875
+ #
876
+ # @note Cluster mode with `fork_worker` enabled only.
877
+ #
878
+ # @example
879
+ # before_refork do
880
+ # 3.times {GC.start}
881
+ # end
882
+ #
883
+ # @version 5.0.0
884
+ #
885
+ def before_refork(key = nil, &block)
886
+ Puma.deprecate_method_change :on_refork, __callee__, __method__
887
+
888
+ process_hook :before_refork, key, block, cluster_only: true
889
+ end
890
+
891
+ alias_method :on_refork, :before_refork
892
+
893
+ # When `fork_worker` is enabled, code to run in Worker 0
894
+ # after all other workers are re-forked from this process,
895
+ # after the server has temporarily stopped serving requests
896
+ # (once per complete refork cycle).
897
+ #
898
+ # This can be used to re-open any connections to remote servers
899
+ # (database, Redis, ...) that were closed via before_refork.
900
+ #
901
+ # This can be called multiple times to add several hooks.
902
+ #
903
+ # @note Cluster mode with `fork_worker` enabled only.
904
+ #
905
+ # @example
906
+ # after_refork do
907
+ # puts 'After refork...'
908
+ # end
909
+ #
910
+ def after_refork(key = nil, &block)
911
+ process_hook :after_refork, key, block
912
+ end
913
+
914
+ # Provide a block to be executed just before a thread is added to the thread
915
+ # pool. Be careful: while the block executes, thread creation is delayed, and
916
+ # probably a request will have to wait too! The new thread will not be added to
917
+ # the threadpool until the provided block returns.
918
+ #
919
+ # Return values are ignored.
920
+ # Raising an exception will log a warning.
921
+ #
922
+ # This hook is useful for doing something when the thread pool grows.
923
+ #
924
+ # This can be called multiple times to add several hooks.
925
+ #
926
+ # @example
927
+ # before_thread_start do
928
+ # puts 'On thread start...'
929
+ # end
930
+ #
931
+ def before_thread_start(&block)
932
+ Puma.deprecate_method_change :on_thread_start, __callee__, __method__
933
+
934
+ process_hook :before_thread_start, nil, block
935
+ end
936
+
937
+ alias_method :on_thread_start, :before_thread_start
938
+
939
+ # Provide a block to be executed after a thread is trimmed from the thread
940
+ # pool. Be careful: while this block executes, Puma's main loop is
941
+ # blocked, so no new requests will be picked up.
942
+ #
943
+ # This hook only runs when a thread in the threadpool is trimmed by Puma.
944
+ # It does not run when a thread dies due to exceptions or any other cause.
945
+ #
946
+ # Return values are ignored.
947
+ # Raising an exception will log a warning.
948
+ #
949
+ # This hook is useful for cleaning up thread local resources when a thread
950
+ # is trimmed.
951
+ #
952
+ # This can be called multiple times to add several hooks.
953
+ #
954
+ # @example
955
+ # before_thread_exit do
956
+ # puts 'On thread exit...'
957
+ # end
958
+ #
959
+ def before_thread_exit(&block)
960
+ Puma.deprecate_method_change :on_thread_exit, __callee__, __method__
961
+
962
+ process_hook :before_thread_exit, nil, block
963
+ end
964
+
965
+ alias_method :on_thread_exit, :before_thread_exit
966
+
967
+ # Code to run out-of-band when the worker is idle.
968
+ # These hooks run immediately after a request has finished
969
+ # processing and there are no busy threads on the worker.
970
+ # The worker doesn't accept new requests until this code finishes.
971
+ #
972
+ # This hook is useful for running out-of-band garbage collection
973
+ # or scheduling asynchronous tasks to execute after a response.
974
+ #
975
+ # This can be called multiple times to add several hooks.
976
+ #
977
+ def out_of_band(&block)
978
+ process_hook :out_of_band, nil, block
979
+ end
980
+
981
+ # The directory to operate out of.
982
+ #
983
+ # The default is the current directory.
984
+ #
985
+ # @example
986
+ # directory '/u/apps/lolcat'
987
+ #
988
+ def directory(dir)
989
+ @options[:directory] = dir.to_s
990
+ end
991
+
992
+ # Preload the application before forking the workers; this conflicts with
993
+ # the phased restart feature.
994
+ #
995
+ # The default is +true+ if your app uses more than 1 worker.
996
+ #
997
+ # @note Cluster mode only.
998
+ #
999
+ # @example
1000
+ # preload_app!
1001
+ #
1002
+ def preload_app!(answer=true)
1003
+ @options[:preload_app] = answer
1004
+ end
1005
+
1006
+ # Use +obj+ or +block+ as the low level error handler. This allows the
1007
+ # configuration file to change the default error on the server.
1008
+ #
1009
+ # @example
1010
+ # lowlevel_error_handler do |err|
1011
+ # [200, {}, ["error page"]]
1012
+ # end
1013
+ #
1014
+ def lowlevel_error_handler(obj=nil, &block)
1015
+ obj ||= block
1016
+ raise "Provide either a #call'able or a block" unless obj
1017
+ @options[:lowlevel_error_handler] = obj
1018
+ end
1019
+
1020
+ # This option is used to allow your app and its gems to be
1021
+ # properly reloaded when not using preload.
1022
+ #
1023
+ # When set, if Puma detects that it's been invoked in the
1024
+ # context of Bundler, it will cleanup the environment and
1025
+ # re-run itself outside the Bundler environment, but directly
1026
+ # using the files that Bundler has setup.
1027
+ #
1028
+ # This means that Puma is now decoupled from your Bundler
1029
+ # context and when each worker loads, it will be loading a
1030
+ # new Bundler context and thus can float around as the release
1031
+ # dictates.
1032
+ #
1033
+ # @note This is incompatible with +preload_app!+.
1034
+ # @note This is only supported for RubyGems 2.2+
1035
+ #
1036
+ # @see extra_runtime_dependencies
1037
+ #
1038
+ def prune_bundler(answer=true)
1039
+ @options[:prune_bundler] = answer
1040
+ end
1041
+
1042
+ # Raises a SignalException when SIGTERM is received. In environments where
1043
+ # SIGTERM is something expected, you can suppress these with this option.
1044
+ #
1045
+ # This can be useful for example in Kubernetes, where rolling restart is
1046
+ # guaranteed usually on the infrastructure level.
1047
+ #
1048
+ # The default is +true+.
1049
+ #
1050
+ # @example
1051
+ # raise_exception_on_sigterm false
1052
+ #
1053
+ # @see Puma::Launcher#setup_signals
1054
+ # @see Puma::Cluster#setup_signals
1055
+ #
1056
+ def raise_exception_on_sigterm(answer=true)
1057
+ @options[:raise_exception_on_sigterm] = answer
1058
+ end
1059
+
1060
+ # When using prune_bundler, if extra runtime dependencies need to be loaded to
1061
+ # initialize your app, then this setting can be used. This includes any Puma plugins.
1062
+ #
1063
+ # Before bundler is pruned, the gem names supplied will be looked up in the bundler
1064
+ # context and then loaded again after bundler is pruned.
1065
+ # Only applies if prune_bundler is used.
1066
+ #
1067
+ # @example
1068
+ # extra_runtime_dependencies ['gem_name_1', 'gem_name_2']
1069
+ # @example
1070
+ # extra_runtime_dependencies ['puma_worker_killer', 'puma-heroku']
1071
+ #
1072
+ # @see Puma::Launcher#extra_runtime_deps_directories
1073
+ #
1074
+ def extra_runtime_dependencies(answer = [])
1075
+ @options[:extra_runtime_dependencies] = Array(answer)
1076
+ end
1077
+
1078
+ # Additional text to display in process listing.
1079
+ #
1080
+ # If you do not specify a tag, Puma will infer it. If you do not want Puma
1081
+ # to add a tag, use an empty string.
1082
+ #
1083
+ # The default is the current file or directory base name.
1084
+ #
1085
+ # @example
1086
+ # tag 'app name'
1087
+ # @example
1088
+ # tag ''
1089
+ #
1090
+ def tag(string)
1091
+ @options[:tag] = string.to_s
1092
+ end
1093
+
1094
+ # Change the default interval for checking workers.
1095
+ #
1096
+ # The default is 5 seconds.
1097
+ #
1098
+ # @note Cluster mode only.
1099
+ #
1100
+ # @example
1101
+ # worker_check_interval 10
1102
+ #
1103
+ # @see Puma::Cluster#check_workers
1104
+ #
1105
+ def worker_check_interval(interval)
1106
+ @options[:worker_check_interval] = Integer(interval)
1107
+ end
1108
+
1109
+ # Verifies that all workers have checked in to the master process within
1110
+ # the given timeout. If not the worker process will be restarted. This is
1111
+ # not a request timeout, it is to protect against a hung or dead process.
1112
+ # Setting this value will not protect against slow requests.
1113
+ #
1114
+ # This value must be greater than worker_check_interval.
1115
+ #
1116
+ # The default is 60 seconds.
1117
+ #
1118
+ # @note Cluster mode only.
1119
+ #
1120
+ # @example
1121
+ # worker_timeout 60
1122
+ #
1123
+ # @see Puma::Cluster::Worker#ping_timeout
1124
+ #
1125
+ def worker_timeout(timeout)
1126
+ timeout = Integer(timeout)
1127
+ min = @options.fetch(:worker_check_interval, Configuration::DEFAULTS[:worker_check_interval])
1128
+
1129
+ if timeout <= min
1130
+ raise "The minimum worker_timeout must be greater than the worker reporting interval (#{min})"
1131
+ end
1132
+
1133
+ @options[:worker_timeout] = timeout
1134
+ end
1135
+
1136
+ # Change the default worker timeout for booting.
1137
+ #
1138
+ # The default is the value of `worker_timeout`.
1139
+ #
1140
+ # @note Cluster mode only.
1141
+ #
1142
+ # @example
1143
+ # worker_boot_timeout 60
1144
+ #
1145
+ # @see Puma::Cluster::Worker#ping_timeout
1146
+ #
1147
+ def worker_boot_timeout(timeout)
1148
+ @options[:worker_boot_timeout] = Integer(timeout)
1149
+ end
1150
+
1151
+ # Set the timeout for worker shutdown.
1152
+ #
1153
+ # The default is 30 seconds.
1154
+ #
1155
+ # @note Cluster mode only.
1156
+ #
1157
+ # @example
1158
+ # worker_shutdown_timeout 90
1159
+ #
1160
+ # @see Puma::Cluster::Worker#term
1161
+ #
1162
+ def worker_shutdown_timeout(timeout)
1163
+ @options[:worker_shutdown_timeout] = Integer(timeout)
1164
+ end
1165
+
1166
+ # Set the strategy for worker culling.
1167
+ #
1168
+ # There are two possible values:
1169
+ #
1170
+ # 1. **:youngest** - the youngest workers (i.e. the workers that were
1171
+ # the most recently started) will be culled.
1172
+ # 2. **:oldest** - the oldest workers (i.e. the workers that were started
1173
+ # the longest time ago) will be culled.
1174
+ #
1175
+ # The default is +:youngest+.
1176
+ #
1177
+ # @note Cluster mode only.
1178
+ #
1179
+ # @example
1180
+ # worker_culling_strategy :oldest
1181
+ #
1182
+ # @see Puma::Cluster#cull_workers
1183
+ #
1184
+ def worker_culling_strategy(strategy)
1185
+ strategy = strategy.to_sym
1186
+
1187
+ if ![:youngest, :oldest].include?(strategy)
1188
+ raise "Invalid value for worker_culling_strategy - #{strategy}"
1189
+ end
1190
+
1191
+ @options[:worker_culling_strategy] = strategy
1192
+ end
1193
+
1194
+ # When set to true, workers accept all requests
1195
+ # and queue them before passing them to the handlers.
1196
+ # When set to false, each worker process accepts exactly as
1197
+ # many requests as it is configured to simultaneously handle.
1198
+ #
1199
+ # Queueing requests generally improves performance. In some
1200
+ # cases, such as a single threaded application, it may be
1201
+ # better to ensure requests get balanced across workers.
1202
+ #
1203
+ # Note that setting this to false disables HTTP keepalive and
1204
+ # slow clients will occupy a handler thread while the request
1205
+ # is being sent. A reverse proxy, such as nginx, can handle
1206
+ # slow clients and queue requests before they reach Puma.
1207
+ #
1208
+ # The default is +true+.
1209
+ #
1210
+ # @see Puma::Server
1211
+ #
1212
+ def queue_requests(answer=true)
1213
+ @options[:queue_requests] = answer
1214
+ end
1215
+
1216
+ # When a shutdown is requested, the backtraces of all the
1217
+ # threads will be written to $stdout. This can help figure
1218
+ # out why shutdown is hanging.
1219
+ #
1220
+ def shutdown_debug(val=true)
1221
+ @options[:shutdown_debug] = val
1222
+ end
1223
+
1224
+
1225
+ # Attempts to route traffic to less-busy workers by causing them to delay
1226
+ # listening on the socket, allowing workers which are not processing any
1227
+ # requests to pick up new requests first.
1228
+ #
1229
+ # The default is 0.005 seconds.
1230
+ #
1231
+ # Only works on MRI. For all other interpreters, this setting does nothing.
1232
+ #
1233
+ # @see Puma::Server#handle_servers
1234
+ # @see Puma::ThreadPool#wait_for_less_busy_worker
1235
+ #
1236
+ def wait_for_less_busy_worker(val=0.005)
1237
+ @options[:wait_for_less_busy_worker] = val.to_f
1238
+ end
1239
+
1240
+ # Control how the remote address of the connection is set. This
1241
+ # is configurable because to calculate the true socket peer address
1242
+ # a kernel syscall is required which for very fast rack handlers
1243
+ # slows down the handling significantly.
1244
+ #
1245
+ # There are 5 possible values:
1246
+ #
1247
+ # 1. **:socket** - read the peername from the socket using the
1248
+ # syscall. This is the normal behavior. If this fails for any reason (e.g.,
1249
+ # if the peer disconnects between the connection being accepted and the getpeername
1250
+ # system call), Puma will return "0.0.0.0"
1251
+ # 2. **:localhost** - set the remote address to "127.0.0.1"
1252
+ # 3. **header: <http_header>**- set the remote address to the value of the
1253
+ # provided http header. For instance:
1254
+ # `set_remote_address header: "X-Real-IP"`.
1255
+ # Only the first word (as separated by spaces or comma) is used, allowing
1256
+ # headers such as X-Forwarded-For to be used as well. If this header is absent,
1257
+ # Puma will fall back to the behavior of :socket
1258
+ # 4. **proxy_protocol: :v1**- set the remote address to the value read from the
1259
+ # HAproxy PROXY protocol, version 1. If the request does not have the PROXY
1260
+ # protocol attached to it, will fall back to :socket
1261
+ # 5. **\<Any string\>** - this allows you to hardcode remote address to any value
1262
+ # you wish. Because Puma never uses this field anyway, it's format is
1263
+ # entirely in your hands.
1264
+ #
1265
+ # The default is +:socket+.
1266
+ #
1267
+ # @example
1268
+ # set_remote_address :localhost
1269
+ #
1270
+ def set_remote_address(val=:socket)
1271
+ case val
1272
+ when :socket
1273
+ @options[:remote_address] = val
1274
+ when :localhost
1275
+ @options[:remote_address] = :value
1276
+ @options[:remote_address_value] = "127.0.0.1".freeze
1277
+ when String
1278
+ @options[:remote_address] = :value
1279
+ @options[:remote_address_value] = val
1280
+ when Hash
1281
+ if hdr = val[:header]
1282
+ @options[:remote_address] = :header
1283
+ @options[:remote_address_header] = "HTTP_" + hdr.upcase.tr("-", "_")
1284
+ elsif protocol_version = val[:proxy_protocol]
1285
+ @options[:remote_address] = :proxy_protocol
1286
+ protocol_version = protocol_version.downcase.to_sym
1287
+ unless [:v1].include?(protocol_version)
1288
+ raise "Invalid value for proxy_protocol - #{protocol_version.inspect}"
1289
+ end
1290
+ @options[:remote_address_proxy_protocol] = protocol_version
1291
+ else
1292
+ raise "Invalid value for set_remote_address - #{val.inspect}"
1293
+ end
1294
+ else
1295
+ raise "Invalid value for set_remote_address - #{val}"
1296
+ end
1297
+ end
1298
+
1299
+ # When enabled, workers will be forked from worker 0 instead of from the master process.
1300
+ # This option is similar to `preload_app` because the app is preloaded before forking,
1301
+ # but it is compatible with phased restart.
1302
+ #
1303
+ # This option also enables the `refork` command (SIGURG), which optimizes copy-on-write performance
1304
+ # in a running app.
1305
+ #
1306
+ # A refork will automatically trigger once after the specified number of requests
1307
+ # (default 1000), or pass 0 to disable auto refork.
1308
+ #
1309
+ # @note This is experimental.
1310
+ # @note Cluster mode only.
1311
+ #
1312
+ def fork_worker(after_requests=1000)
1313
+ @options[:fork_worker] = Integer(after_requests)
1314
+ end
1315
+
1316
+ # @deprecated Use {#max_keep_alive} instead.
1317
+ #
1318
+ def max_fast_inline(num_of_requests)
1319
+ Puma.deprecate_method_change :max_fast_inline, __method__, :max_keep_alive
1320
+ @options[:max_keep_alive] ||= Float(num_of_requests) unless num_of_requests.nil?
1321
+ end
1322
+
1323
+ # The number of requests a keep-alive client can submit before being closed.
1324
+ # Note that some applications (server to server) may benefit from a very high
1325
+ # number or Float::INFINITY.
1326
+ #
1327
+ # The default is 999.
1328
+ #
1329
+ # @example
1330
+ # max_keep_alive 20
1331
+ #
1332
+ def max_keep_alive(num_of_requests)
1333
+ @options[:max_keep_alive] = Float(num_of_requests) unless num_of_requests.nil?
1334
+ end
1335
+
1336
+ # When `true`, keep-alive connections are maintained on inbound requests.
1337
+ # Enabling this setting reduces the number of TCP operations, reducing response
1338
+ # times for connections that can send multiple requests in a single connection.
1339
+ #
1340
+ # When Puma receives more incoming connections than available Puma threads,
1341
+ # enabling the keep-alive behavior may result in processing requests out-of-order,
1342
+ # increasing overall response time variance. Increased response time variance
1343
+ # means that the overall average of response times might not change, but more
1344
+ # outliers will exist. Those long-tail outliers may significantly affect response
1345
+ # times for some processed requests.
1346
+ #
1347
+ # When `false`, Puma closes the connection after each request, requiring the
1348
+ # client to open a new request. Disabling this setting guarantees that requests
1349
+ # will be processed in the order they are fully received, decreasing response
1350
+ # variance and eliminating long-tail outliers caused by keep-alive behavior.
1351
+ # The trade-off is that the number of TCP operations required will increase.
1352
+ #
1353
+ # The default is +true+.
1354
+ #
1355
+ # @example
1356
+ # enable_keep_alives false
1357
+ #
1358
+ def enable_keep_alives(enabled=true)
1359
+ @options[:enable_keep_alives] = enabled
1360
+ end
1361
+
1362
+ # Specify the backend for the IO selector.
1363
+ #
1364
+ # Provided values will be passed directly to +NIO::Selector.new+, with the
1365
+ # exception of +:auto+ which will let nio4r choose the backend.
1366
+ #
1367
+ # Check the documentation of +NIO::Selector.backends+ for the list of valid
1368
+ # options. Note that the available options on your system will depend on the
1369
+ # operating system. If you want to use the pure Ruby backend (not
1370
+ # recommended due to its comparatively low performance), set environment
1371
+ # variable +NIO4R_PURE+ to +true+.
1372
+ #
1373
+ # The default is +:auto+.
1374
+ #
1375
+ # @see https://github.com/socketry/nio4r/blob/master/lib/nio/selector.rb
1376
+ #
1377
+ def io_selector_backend(backend)
1378
+ @options[:io_selector_backend] = backend.to_sym
1379
+ end
1380
+
1381
+ # Ensures +STDOUT+ and +STDERR+ is immediately flushed to the underlying
1382
+ # operating system and is not buffered internally
1383
+ #
1384
+ # The default is +true+.
1385
+ #
1386
+ # @example
1387
+ # mutate_stdout_and_stderr_to_sync_on_write false
1388
+ #
1389
+ def mutate_stdout_and_stderr_to_sync_on_write(enabled=true)
1390
+ @options[:mutate_stdout_and_stderr_to_sync_on_write] = enabled
1391
+ end
1392
+
1393
+ # Specify how big the request payload should be, in bytes.
1394
+ # This limit is compared against Content-Length HTTP header.
1395
+ # If the payload size (CONTENT_LENGTH) is larger than http_content_length_limit,
1396
+ # HTTP 413 status code is returned.
1397
+ #
1398
+ # When no Content-Length http header is present, it is compared against the
1399
+ # size of the body of the request.
1400
+ #
1401
+ # The default is +nil+.
1402
+ #
1403
+ # @example
1404
+ # http_content_length_limit 2_000_000_000
1405
+ #
1406
+ def http_content_length_limit(limit)
1407
+ @options[:http_content_length_limit] = limit
1408
+ end
1409
+
1410
+ # Supported http methods, which will replace `Puma::Const::SUPPORTED_HTTP_METHODS`.
1411
+ # The value of `:any` will allows all methods, otherwise, the value must be
1412
+ # an array of strings. Note that methods are all uppercase.
1413
+ #
1414
+ # `Puma::Const::SUPPORTED_HTTP_METHODS` is conservative, if you want a
1415
+ # complete set of methods, the methods defined by the
1416
+ # [IANA Method Registry](https://www.iana.org/assignments/http-methods/http-methods.xhtml)
1417
+ # are pre-defined as the constant `Puma::Const::IANA_HTTP_METHODS`.
1418
+ #
1419
+ # @note If the `methods` value is `:any`, no method check with be performed,
1420
+ # similar to Puma v5 and earlier.
1421
+ #
1422
+ # @example Adds 'PROPFIND' to existing supported methods
1423
+ # supported_http_methods(Puma::Const::SUPPORTED_HTTP_METHODS + ['PROPFIND'])
1424
+ # @example Restricts methods to the array elements
1425
+ # supported_http_methods %w[HEAD GET POST PUT DELETE OPTIONS PROPFIND]
1426
+ # @example Restricts methods to the methods in the IANA Registry
1427
+ # supported_http_methods Puma::Const::IANA_HTTP_METHODS
1428
+ # @example Allows any method
1429
+ # supported_http_methods :any
1430
+ #
1431
+ def supported_http_methods(methods)
1432
+ if methods == :any
1433
+ @options[:supported_http_methods] = :any
1434
+ elsif Array === methods && methods == (ary = methods.grep(String).uniq) &&
1435
+ !ary.empty?
1436
+ @options[:supported_http_methods] = ary
1437
+ else
1438
+ raise "supported_http_methods must be ':any' or a unique array of strings"
1439
+ end
1440
+ end
1441
+
1442
+ private
1443
+
1444
+ # To avoid adding cert_pem and key_pem as URI params, we store them on the
1445
+ # options[:store] from where Puma binder knows how to find and extract them.
1446
+ #
1447
+ def add_pem_values_to_options_store(opts)
1448
+ return if defined?(JRUBY_VERSION)
1449
+
1450
+ @options[:store] ||= []
1451
+
1452
+ # Store cert_pem and key_pem to options[:store] if present
1453
+ [:cert, :key].each do |v|
1454
+ opt_key = :"#{v}_pem"
1455
+ if opts[opt_key]
1456
+ index = @options[:store].length
1457
+ @options[:store] << opts[opt_key]
1458
+ opts[v] = "store:#{index}"
1459
+ end
1460
+ end
1461
+ end
1462
+
1463
+ def process_hook(options_key, key, block, cluster_only: false)
1464
+ raise ArgumentError, "expected #{options_key} to be given a block" unless block
1465
+
1466
+ @config.hooks[options_key] = true
1467
+
1468
+ @options[options_key] ||= []
1469
+ hook_options = { block: block, cluster_only: cluster_only }
1470
+ hook_options[:id] = if ON_WORKER_KEY.include?(key.class)
1471
+ key.to_sym
1472
+ elsif key.nil?
1473
+ nil
1474
+ else
1475
+ raise "'#{options_key}' key must be String or Symbol"
1476
+ end
1477
+ @options[options_key] << hook_options
1478
+ end
1479
+ end
1480
+ end