rack 1.0.1 → 2.2.21

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 (147) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +829 -0
  3. data/CONTRIBUTING.md +136 -0
  4. data/{COPYING → MIT-LICENSE} +4 -2
  5. data/README.rdoc +355 -0
  6. data/Rakefile +64 -98
  7. data/SPEC.rdoc +292 -0
  8. data/bin/rackup +3 -174
  9. data/contrib/rack.png +0 -0
  10. data/contrib/rack.svg +150 -0
  11. data/contrib/rack_logo.svg +164 -111
  12. data/contrib/rdoc.css +412 -0
  13. data/example/lobster.ru +2 -0
  14. data/example/protectedlobster.rb +4 -2
  15. data/example/protectedlobster.ru +3 -1
  16. data/lib/rack/auth/abstract/handler.rb +7 -5
  17. data/lib/rack/auth/abstract/request.rb +12 -2
  18. data/lib/rack/auth/basic.rb +6 -4
  19. data/lib/rack/auth/digest/md5.rb +20 -13
  20. data/lib/rack/auth/digest/nonce.rb +6 -4
  21. data/lib/rack/auth/digest/params.rb +11 -12
  22. data/lib/rack/auth/digest/request.rb +15 -12
  23. data/lib/rack/body_proxy.rb +45 -0
  24. data/lib/rack/builder.rb +213 -19
  25. data/lib/rack/cascade.rb +50 -18
  26. data/lib/rack/chunked.rb +95 -27
  27. data/lib/rack/common_logger.rb +84 -0
  28. data/lib/rack/conditional_get.rb +83 -0
  29. data/lib/rack/config.rb +22 -0
  30. data/lib/rack/content_length.rb +19 -10
  31. data/lib/rack/content_type.rb +12 -5
  32. data/lib/rack/core_ext/regexp.rb +14 -0
  33. data/lib/rack/deflater.rb +90 -42
  34. data/lib/rack/directory.rb +118 -72
  35. data/lib/rack/etag.rb +77 -0
  36. data/lib/rack/events.rb +153 -0
  37. data/lib/rack/file.rb +4 -85
  38. data/lib/rack/files.rb +218 -0
  39. data/lib/rack/handler/cgi.rb +22 -24
  40. data/lib/rack/handler/fastcgi.rb +34 -24
  41. data/lib/rack/handler/lsws.rb +16 -15
  42. data/lib/rack/handler/scgi.rb +38 -29
  43. data/lib/rack/handler/thin.rb +23 -7
  44. data/lib/rack/handler/webrick.rb +95 -37
  45. data/lib/rack/handler.rb +49 -14
  46. data/lib/rack/head.rb +19 -13
  47. data/lib/rack/lint.rb +466 -217
  48. data/lib/rack/lobster.rb +19 -14
  49. data/lib/rack/lock.rb +24 -8
  50. data/lib/rack/logger.rb +20 -0
  51. data/lib/rack/media_type.rb +53 -0
  52. data/lib/rack/method_override.rb +52 -0
  53. data/lib/rack/mime.rb +652 -171
  54. data/lib/rack/mock.rb +203 -64
  55. data/lib/rack/multipart/generator.rb +97 -0
  56. data/lib/rack/multipart/parser.rb +440 -0
  57. data/lib/rack/multipart/uploaded_file.rb +41 -0
  58. data/lib/rack/multipart.rb +64 -0
  59. data/lib/rack/null_logger.rb +39 -0
  60. data/lib/rack/query_parser.rb +266 -0
  61. data/lib/rack/recursive.rb +18 -11
  62. data/lib/rack/reloader.rb +13 -5
  63. data/lib/rack/request.rb +607 -191
  64. data/lib/rack/response.rb +245 -110
  65. data/lib/rack/rewindable_input.rb +15 -21
  66. data/lib/rack/runtime.rb +34 -0
  67. data/lib/rack/sendfile.rb +192 -0
  68. data/lib/rack/server.rb +466 -0
  69. data/lib/rack/session/abstract/id.rb +449 -68
  70. data/lib/rack/session/cookie.rb +159 -47
  71. data/lib/rack/session/memcache.rb +4 -103
  72. data/lib/rack/session/pool.rb +39 -49
  73. data/lib/rack/show_exceptions.rb +390 -0
  74. data/lib/rack/{showstatus.rb → show_status.rb} +21 -14
  75. data/lib/rack/static.rb +164 -14
  76. data/lib/rack/tempfile_reaper.rb +22 -0
  77. data/lib/rack/urlmap.rb +60 -18
  78. data/lib/rack/utils.rb +508 -277
  79. data/lib/rack/version.rb +29 -0
  80. data/lib/rack.rb +85 -34
  81. data/rack.gemspec +43 -51
  82. metadata +119 -207
  83. data/KNOWN-ISSUES +0 -18
  84. data/RDOX +0 -428
  85. data/README +0 -364
  86. data/SPEC +0 -164
  87. data/lib/rack/adapter/camping.rb +0 -22
  88. data/lib/rack/auth/openid.rb +0 -480
  89. data/lib/rack/commonlogger.rb +0 -61
  90. data/lib/rack/conditionalget.rb +0 -47
  91. data/lib/rack/handler/evented_mongrel.rb +0 -8
  92. data/lib/rack/handler/mongrel.rb +0 -87
  93. data/lib/rack/handler/swiftiplied_mongrel.rb +0 -8
  94. data/lib/rack/methodoverride.rb +0 -27
  95. data/lib/rack/showexceptions.rb +0 -349
  96. data/test/cgi/lighttpd.conf +0 -20
  97. data/test/cgi/test +0 -9
  98. data/test/cgi/test.fcgi +0 -8
  99. data/test/cgi/test.ru +0 -7
  100. data/test/multipart/binary +0 -0
  101. data/test/multipart/empty +0 -10
  102. data/test/multipart/ie +0 -6
  103. data/test/multipart/nested +0 -10
  104. data/test/multipart/none +0 -9
  105. data/test/multipart/semicolon +0 -6
  106. data/test/multipart/text +0 -10
  107. data/test/spec_rack_auth_basic.rb +0 -73
  108. data/test/spec_rack_auth_digest.rb +0 -226
  109. data/test/spec_rack_auth_openid.rb +0 -84
  110. data/test/spec_rack_builder.rb +0 -84
  111. data/test/spec_rack_camping.rb +0 -51
  112. data/test/spec_rack_cascade.rb +0 -50
  113. data/test/spec_rack_cgi.rb +0 -89
  114. data/test/spec_rack_chunked.rb +0 -62
  115. data/test/spec_rack_commonlogger.rb +0 -32
  116. data/test/spec_rack_conditionalget.rb +0 -41
  117. data/test/spec_rack_content_length.rb +0 -43
  118. data/test/spec_rack_content_type.rb +0 -30
  119. data/test/spec_rack_deflater.rb +0 -127
  120. data/test/spec_rack_directory.rb +0 -61
  121. data/test/spec_rack_fastcgi.rb +0 -89
  122. data/test/spec_rack_file.rb +0 -75
  123. data/test/spec_rack_handler.rb +0 -43
  124. data/test/spec_rack_head.rb +0 -30
  125. data/test/spec_rack_lint.rb +0 -521
  126. data/test/spec_rack_lobster.rb +0 -45
  127. data/test/spec_rack_lock.rb +0 -38
  128. data/test/spec_rack_methodoverride.rb +0 -60
  129. data/test/spec_rack_mock.rb +0 -157
  130. data/test/spec_rack_mongrel.rb +0 -189
  131. data/test/spec_rack_recursive.rb +0 -77
  132. data/test/spec_rack_request.rb +0 -504
  133. data/test/spec_rack_response.rb +0 -218
  134. data/test/spec_rack_rewindable_input.rb +0 -118
  135. data/test/spec_rack_session_cookie.rb +0 -82
  136. data/test/spec_rack_session_memcache.rb +0 -240
  137. data/test/spec_rack_session_pool.rb +0 -172
  138. data/test/spec_rack_showexceptions.rb +0 -21
  139. data/test/spec_rack_showstatus.rb +0 -72
  140. data/test/spec_rack_static.rb +0 -37
  141. data/test/spec_rack_thin.rb +0 -91
  142. data/test/spec_rack_urlmap.rb +0 -185
  143. data/test/spec_rack_utils.rb +0 -387
  144. data/test/spec_rack_webrick.rb +0 -130
  145. data/test/testrequest.rb +0 -57
  146. data/test/unregistered_handler/rack/handler/unregistered.rb +0 -7
  147. data/test/unregistered_handler/rack/handler/unregistered_long_one.rb +0 -7
@@ -1,14 +1,15 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Rack
2
4
  module Auth
3
5
  module Digest
4
6
  class Params < Hash
5
7
 
6
8
  def self.parse(str)
7
- split_header_value(str).inject(new) do |header, param|
9
+ Params[*split_header_value(str).map do |param|
8
10
  k, v = param.split('=', 2)
9
- header[k] = dequote(v)
10
- header
11
- end
11
+ [k, dequote(v)]
12
+ end.flatten]
12
13
  end
13
14
 
14
15
  def self.dequote(str) # From WEBrick::HTTPUtils
@@ -18,11 +19,11 @@ module Rack
18
19
  end
19
20
 
20
21
  def self.split_header_value(str)
21
- str.scan( /(\w+\=(?:"[^\"]+"|[^,]+))/n ).collect{ |v| v[0] }
22
+ str.scan(/\w+\=(?:"[^\"]+"|[^,]+)/n)
22
23
  end
23
24
 
24
25
  def initialize
25
- super
26
+ super()
26
27
 
27
28
  yield self if block_given?
28
29
  end
@@ -35,21 +36,19 @@ module Rack
35
36
  super k.to_s, v.to_s
36
37
  end
37
38
 
38
- UNQUOTED = ['qop', 'nc', 'stale']
39
+ UNQUOTED = ['nc', 'stale']
39
40
 
40
41
  def to_s
41
- inject([]) do |parts, (k, v)|
42
- parts << "#{k}=" + (UNQUOTED.include?(k) ? v.to_s : quote(v))
43
- parts
42
+ map do |k, v|
43
+ "#{k}=#{(UNQUOTED.include?(k) ? v.to_s : quote(v))}"
44
44
  end.join(', ')
45
45
  end
46
46
 
47
47
  def quote(str) # From WEBrick::HTTPUtils
48
- '"' << str.gsub(/[\\\"]/o, "\\\1") << '"'
48
+ '"' + str.gsub(/[\\\"]/o, "\\\1") + '"'
49
49
  end
50
50
 
51
51
  end
52
52
  end
53
53
  end
54
54
  end
55
-
@@ -1,22 +1,23 @@
1
- require 'rack/auth/abstract/request'
2
- require 'rack/auth/digest/params'
3
- require 'rack/auth/digest/nonce'
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../abstract/request'
4
+ require_relative 'params'
5
+ require_relative 'nonce'
4
6
 
5
7
  module Rack
6
8
  module Auth
7
9
  module Digest
8
10
  class Request < Auth::AbstractRequest
9
-
10
11
  def method
11
- @env['rack.methodoverride.original_method'] || @env['REQUEST_METHOD']
12
+ @env[RACK_METHODOVERRIDE_ORIGINAL_METHOD] || @env[REQUEST_METHOD]
12
13
  end
13
14
 
14
15
  def digest?
15
- :digest == scheme
16
+ "digest" == scheme
16
17
  end
17
18
 
18
19
  def correct_uri?
19
- (@env['SCRIPT_NAME'].to_s + @env['PATH_INFO'].to_s) == uri
20
+ request.fullpath == uri
20
21
  end
21
22
 
22
23
  def nonce
@@ -27,13 +28,15 @@ module Rack
27
28
  @params ||= Params.parse(parts.last)
28
29
  end
29
30
 
30
- def method_missing(sym)
31
- if params.has_key? key = sym.to_s
32
- return params[key]
33
- end
34
- super
31
+ def respond_to?(sym, *)
32
+ super or params.has_key? sym.to_s
35
33
  end
36
34
 
35
+ def method_missing(sym, *args)
36
+ return super unless params.has_key?(key = sym.to_s)
37
+ return params[key] if args.size == 0
38
+ raise ArgumentError, "wrong number of arguments (#{args.size} for 0)"
39
+ end
37
40
  end
38
41
  end
39
42
  end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ # Proxy for response bodies allowing calling a block when
5
+ # the response body is closed (after the response has been fully
6
+ # sent to the client).
7
+ class BodyProxy
8
+ # Set the response body to wrap, and the block to call when the
9
+ # response has been fully sent.
10
+ def initialize(body, &block)
11
+ @body = body
12
+ @block = block
13
+ @closed = false
14
+ end
15
+
16
+ # Return whether the wrapped body responds to the method.
17
+ def respond_to_missing?(method_name, include_all = false)
18
+ super or @body.respond_to?(method_name, include_all)
19
+ end
20
+
21
+ # If not already closed, close the wrapped body and
22
+ # then call the block the proxy was initialized with.
23
+ def close
24
+ return if @closed
25
+ @closed = true
26
+ begin
27
+ @body.close if @body.respond_to? :close
28
+ ensure
29
+ @block.call
30
+ end
31
+ end
32
+
33
+ # Whether the proxy is closed. The proxy starts as not closed,
34
+ # and becomes closed on the first call to close.
35
+ def closed?
36
+ @closed
37
+ end
38
+
39
+ # Delegate missing methods to the wrapped body.
40
+ def method_missing(method_name, *args, &block)
41
+ @body.__send__(method_name, *args, &block)
42
+ end
43
+ ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
44
+ end
45
+ end
data/lib/rack/builder.rb CHANGED
@@ -1,63 +1,257 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Rack
2
4
  # Rack::Builder implements a small DSL to iteratively construct Rack
3
5
  # applications.
4
6
  #
5
7
  # Example:
6
8
  #
7
- # app = Rack::Builder.new {
9
+ # require 'rack/lobster'
10
+ # app = Rack::Builder.new do
8
11
  # use Rack::CommonLogger
9
12
  # use Rack::ShowExceptions
10
13
  # map "/lobster" do
11
14
  # use Rack::Lint
12
15
  # run Rack::Lobster.new
13
16
  # end
14
- # }
17
+ # end
18
+ #
19
+ # run app
15
20
  #
16
21
  # Or
17
22
  #
18
23
  # app = Rack::Builder.app do
19
24
  # use Rack::CommonLogger
20
- # lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'OK'] }
25
+ # run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }
21
26
  # end
22
27
  #
23
- # +use+ adds a middleware to the stack, +run+ dispatches to an application.
28
+ # run app
29
+ #
30
+ # +use+ adds middleware to the stack, +run+ dispatches to an application.
24
31
  # You can use +map+ to construct a Rack::URLMap in a convenient way.
25
32
 
26
33
  class Builder
27
- def initialize(&block)
28
- @ins = []
34
+
35
+ # https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-without-bom
36
+ UTF_8_BOM = '\xef\xbb\xbf'
37
+
38
+ # Parse the given config file to get a Rack application.
39
+ #
40
+ # If the config file ends in +.ru+, it is treated as a
41
+ # rackup file and the contents will be treated as if
42
+ # specified inside a Rack::Builder block, using the given
43
+ # options.
44
+ #
45
+ # If the config file does not end in +.ru+, it is
46
+ # required and Rack will use the basename of the file
47
+ # to guess which constant will be the Rack application to run.
48
+ # The options given will be ignored in this case.
49
+ #
50
+ # Examples:
51
+ #
52
+ # Rack::Builder.parse_file('config.ru')
53
+ # # Rack application built using Rack::Builder.new
54
+ #
55
+ # Rack::Builder.parse_file('app.rb')
56
+ # # requires app.rb, which can be anywhere in Ruby's
57
+ # # load path. After requiring, assumes App constant
58
+ # # contains Rack application
59
+ #
60
+ # Rack::Builder.parse_file('./my_app.rb')
61
+ # # requires ./my_app.rb, which should be in the
62
+ # # process's current directory. After requiring,
63
+ # # assumes MyApp constant contains Rack application
64
+ def self.parse_file(config, opts = Server::Options.new)
65
+ if config.end_with?('.ru')
66
+ return self.load_file(config, opts)
67
+ else
68
+ require config
69
+ app = Object.const_get(::File.basename(config, '.rb').split('_').map(&:capitalize).join(''))
70
+ return app, {}
71
+ end
72
+ end
73
+
74
+ # Load the given file as a rackup file, treating the
75
+ # contents as if specified inside a Rack::Builder block.
76
+ #
77
+ # Treats the first comment at the beginning of a line
78
+ # that starts with a backslash as options similar to
79
+ # options passed on a rackup command line.
80
+ #
81
+ # Ignores content in the file after +__END__+, so that
82
+ # use of +__END__+ will not result in a syntax error.
83
+ #
84
+ # Example config.ru file:
85
+ #
86
+ # $ cat config.ru
87
+ #
88
+ # #\ -p 9393
89
+ #
90
+ # use Rack::ContentLength
91
+ # require './app.rb'
92
+ # run App
93
+ def self.load_file(path, opts = Server::Options.new)
94
+ options = {}
95
+
96
+ cfgfile = ::File.read(path)
97
+ cfgfile.slice!(/\A#{UTF_8_BOM}/) if cfgfile.encoding == Encoding::UTF_8
98
+
99
+ if cfgfile[/^#\\(.*)/] && opts
100
+ warn "Parsing options from the first comment line is deprecated!"
101
+ options = opts.parse! $1.split(/\s+/)
102
+ end
103
+
104
+ cfgfile.sub!(/^__END__\n.*\Z/m, '')
105
+ app = new_from_string cfgfile, path
106
+
107
+ return app, options
108
+ end
109
+
110
+ # Evaluate the given +builder_script+ string in the context of
111
+ # a Rack::Builder block, returning a Rack application.
112
+ def self.new_from_string(builder_script, file = "(rackup)")
113
+ # We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance.
114
+ # We cannot use instance_eval(String) as that would resolve constants differently.
115
+ binding, builder = TOPLEVEL_BINDING.eval('Rack::Builder.new.instance_eval { [binding, self] }')
116
+ eval builder_script, binding, file
117
+ builder.to_app
118
+ end
119
+
120
+ # Initialize a new Rack::Builder instance. +default_app+ specifies the
121
+ # default application if +run+ is not called later. If a block
122
+ # is given, it is evaluted in the context of the instance.
123
+ def initialize(default_app = nil, &block)
124
+ @use, @map, @run, @warmup, @freeze_app = [], nil, default_app, nil, false
29
125
  instance_eval(&block) if block_given?
30
126
  end
31
127
 
32
- def self.app(&block)
33
- self.new(&block).to_app
128
+ # Create a new Rack::Builder instance and return the Rack application
129
+ # generated from it.
130
+ def self.app(default_app = nil, &block)
131
+ self.new(default_app, &block).to_app
34
132
  end
35
133
 
134
+ # Specifies middleware to use in a stack.
135
+ #
136
+ # class Middleware
137
+ # def initialize(app)
138
+ # @app = app
139
+ # end
140
+ #
141
+ # def call(env)
142
+ # env["rack.some_header"] = "setting an example"
143
+ # @app.call(env)
144
+ # end
145
+ # end
146
+ #
147
+ # use Middleware
148
+ # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
149
+ #
150
+ # All requests through to this application will first be processed by the middleware class.
151
+ # The +call+ method in this example sets an additional environment key which then can be
152
+ # referenced in the application if required.
36
153
  def use(middleware, *args, &block)
37
- @ins << lambda { |app| middleware.new(app, *args, &block) }
154
+ if @map
155
+ mapping, @map = @map, nil
156
+ @use << proc { |app| generate_map(app, mapping) }
157
+ end
158
+ @use << proc { |app| middleware.new(app, *args, &block) }
38
159
  end
160
+ ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true)
39
161
 
162
+ # Takes an argument that is an object that responds to #call and returns a Rack response.
163
+ # The simplest form of this is a lambda object:
164
+ #
165
+ # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
166
+ #
167
+ # However this could also be a class:
168
+ #
169
+ # class Heartbeat
170
+ # def self.call(env)
171
+ # [200, { "Content-Type" => "text/plain" }, ["OK"]]
172
+ # end
173
+ # end
174
+ #
175
+ # run Heartbeat
40
176
  def run(app)
41
- @ins << app #lambda { |nothing| app }
177
+ @run = app
178
+ end
179
+
180
+ # Takes a lambda or block that is used to warm-up the application. This block is called
181
+ # before the Rack application is returned by to_app.
182
+ #
183
+ # warmup do |app|
184
+ # client = Rack::MockRequest.new(app)
185
+ # client.get('/')
186
+ # end
187
+ #
188
+ # use SomeMiddleware
189
+ # run MyApp
190
+ def warmup(prc = nil, &block)
191
+ @warmup = prc || block
42
192
  end
43
193
 
194
+ # Creates a route within the application. Routes under the mapped path will be sent to
195
+ # the Rack application specified by run inside the block. Other requests will be sent to the
196
+ # default application specified by run outside the block.
197
+ #
198
+ # Rack::Builder.app do
199
+ # map '/heartbeat' do
200
+ # run Heartbeat
201
+ # end
202
+ # run App
203
+ # end
204
+ #
205
+ # The +use+ method can also be used inside the block to specify middleware to run under a specific path:
206
+ #
207
+ # Rack::Builder.app do
208
+ # map '/heartbeat' do
209
+ # use Middleware
210
+ # run Heartbeat
211
+ # end
212
+ # run App
213
+ # end
214
+ #
215
+ # This example includes a piece of middleware which will run before +/heartbeat+ requests hit +Heartbeat+.
216
+ #
217
+ # Note that providing a +path+ of +/+ will ignore any default application given in a +run+ statement
218
+ # outside the block.
44
219
  def map(path, &block)
45
- if @ins.last.kind_of? Hash
46
- @ins.last[path] = self.class.new(&block).to_app
47
- else
48
- @ins << {}
49
- map(path, &block)
50
- end
220
+ @map ||= {}
221
+ @map[path] = block
222
+ end
223
+
224
+ # Freeze the app (set using run) and all middleware instances when building the application
225
+ # in to_app.
226
+ def freeze_app
227
+ @freeze_app = true
51
228
  end
52
229
 
230
+ # Return the Rack application generated by this instance.
53
231
  def to_app
54
- @ins[-1] = Rack::URLMap.new(@ins.last) if Hash === @ins.last
55
- inner_app = @ins.last
56
- @ins[0...-1].reverse.inject(inner_app) { |a, e| e.call(a) }
232
+ app = @map ? generate_map(@run, @map) : @run
233
+ fail "missing run or map statement" unless app
234
+ app.freeze if @freeze_app
235
+ app = @use.reverse.inject(app) { |a, e| e[a].tap { |x| x.freeze if @freeze_app } }
236
+ @warmup.call(app) if @warmup
237
+ app
57
238
  end
58
239
 
240
+ # Call the Rack application generated by this builder instance. Note that
241
+ # this rebuilds the Rack application and runs the warmup code (if any)
242
+ # every time it is called, so it should not be used if performance is important.
59
243
  def call(env)
60
244
  to_app.call(env)
61
245
  end
246
+
247
+ private
248
+
249
+ # Generate a URLMap instance by generating new Rack applications for each
250
+ # map block in this instance.
251
+ def generate_map(default_app, mapping)
252
+ mapped = default_app ? { '/' => default_app } : {}
253
+ mapping.each { |r, b| mapped[r] = self.class.new(default_app, &b).to_app }
254
+ URLMap.new(mapped)
255
+ end
62
256
  end
63
257
  end
data/lib/rack/cascade.rb CHANGED
@@ -1,34 +1,66 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Rack
2
- # Rack::Cascade tries an request on several apps, and returns the
3
- # first response that is not 404 (or in a list of configurable
4
- # status codes).
4
+ # Rack::Cascade tries a request on several apps, and returns the
5
+ # first response that is not 404 or 405 (or in a list of configured
6
+ # status codes). If all applications tried return one of the configured
7
+ # status codes, return the last response.
5
8
 
6
9
  class Cascade
10
+ # deprecated, no longer used
11
+ NotFound = [404, { CONTENT_TYPE => "text/plain" }, []]
12
+
13
+ # An array of applications to try in order.
7
14
  attr_reader :apps
8
15
 
9
- def initialize(apps, catch=404)
10
- @apps = apps
11
- @catch = [*catch]
16
+ # Set the apps to send requests to, and what statuses result in
17
+ # cascading. Arguments:
18
+ #
19
+ # apps: An enumerable of rack applications.
20
+ # cascade_for: The statuses to use cascading for. If a response is received
21
+ # from an app, the next app is tried.
22
+ def initialize(apps, cascade_for = [404, 405])
23
+ @apps = []
24
+ apps.each { |app| add app }
25
+
26
+ @cascade_for = {}
27
+ [*cascade_for].each { |status| @cascade_for[status] = true }
12
28
  end
13
29
 
30
+ # Call each app in order. If the responses uses a status that requires
31
+ # cascading, try the next app. If all responses require cascading,
32
+ # return the response from the last app.
14
33
  def call(env)
15
- status = headers = body = nil
16
- raise ArgumentError, "empty cascade" if @apps.empty?
17
- @apps.each { |app|
18
- begin
19
- status, headers, body = app.call(env)
20
- break unless @catch.include?(status.to_i)
21
- end
22
- }
23
- [status, headers, body]
34
+ return [404, { CONTENT_TYPE => "text/plain" }, []] if @apps.empty?
35
+ result = nil
36
+ last_body = nil
37
+
38
+ @apps.each do |app|
39
+ # The SPEC says that the body must be closed after it has been iterated
40
+ # by the server, or if it is replaced by a middleware action. Cascade
41
+ # replaces the body each time a cascade happens. It is assumed that nil
42
+ # does not respond to close, otherwise the previous application body
43
+ # will be closed. The final application body will not be closed, as it
44
+ # will be passed to the server as a result.
45
+ last_body.close if last_body.respond_to? :close
46
+
47
+ result = app.call(env)
48
+ return result unless @cascade_for.include?(result[0].to_i)
49
+ last_body = result[2]
50
+ end
51
+
52
+ result
24
53
  end
25
54
 
26
- def add app
55
+ # Append an app to the list of apps to cascade. This app will
56
+ # be tried last.
57
+ def add(app)
27
58
  @apps << app
28
59
  end
29
60
 
30
- def include? app
31
- @apps.include? app
61
+ # Whether the given app is one of the apps to cascade to.
62
+ def include?(app)
63
+ @apps.include?(app)
32
64
  end
33
65
 
34
66
  alias_method :<<, :add
data/lib/rack/chunked.rb CHANGED
@@ -1,49 +1,117 @@
1
- require 'rack/utils'
1
+ # frozen_string_literal: true
2
2
 
3
3
  module Rack
4
4
 
5
5
  # Middleware that applies chunked transfer encoding to response bodies
6
6
  # when the response does not include a Content-Length header.
7
+ #
8
+ # This supports the Trailer response header to allow the use of trailing
9
+ # headers in the chunked encoding. However, using this requires you manually
10
+ # specify a response body that supports a +trailers+ method. Example:
11
+ #
12
+ # [200, { 'Trailer' => 'Expires'}, ["Hello", "World"]]
13
+ # # error raised
14
+ #
15
+ # body = ["Hello", "World"]
16
+ # def body.trailers
17
+ # { 'Expires' => Time.now.to_s }
18
+ # end
19
+ # [200, { 'Trailer' => 'Expires'}, body]
20
+ # # No exception raised
7
21
  class Chunked
8
22
  include Rack::Utils
9
23
 
10
- def initialize(app)
11
- @app = app
24
+ # A body wrapper that emits chunked responses.
25
+ class Body
26
+ TERM = "\r\n"
27
+ TAIL = "0#{TERM}"
28
+
29
+ # Store the response body to be chunked.
30
+ def initialize(body)
31
+ @body = body
32
+ end
33
+
34
+ # For each element yielded by the response body, yield
35
+ # the element in chunked encoding.
36
+ def each(&block)
37
+ term = TERM
38
+ @body.each do |chunk|
39
+ size = chunk.bytesize
40
+ next if size == 0
41
+
42
+ yield [size.to_s(16), term, chunk.b, term].join
43
+ end
44
+ yield TAIL
45
+ yield_trailers(&block)
46
+ yield term
47
+ end
48
+
49
+ # Close the response body if the response body supports it.
50
+ def close
51
+ @body.close if @body.respond_to?(:close)
52
+ end
53
+
54
+ private
55
+
56
+ # Do nothing as this class does not support trailer headers.
57
+ def yield_trailers
58
+ end
12
59
  end
13
60
 
14
- def call(env)
15
- status, headers, body = @app.call(env)
16
- headers = HeaderHash.new(headers)
61
+ # A body wrapper that emits chunked responses and also supports
62
+ # sending Trailer headers. Note that the response body provided to
63
+ # initialize must have a +trailers+ method that returns a hash
64
+ # of trailer headers, and the rack response itself should have a
65
+ # Trailer header listing the headers that the +trailers+ method
66
+ # will return.
67
+ class TrailerBody < Body
68
+ private
17
69
 
18
- if env['HTTP_VERSION'] == 'HTTP/1.0' ||
19
- STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
20
- headers['Content-Length'] ||
21
- headers['Transfer-Encoding']
22
- [status, headers.to_hash, body]
23
- else
24
- dup.chunk(status, headers, body)
70
+ # Yield strings for each trailer header.
71
+ def yield_trailers
72
+ @body.trailers.each_pair do |k, v|
73
+ yield "#{k}: #{v}\r\n"
74
+ end
25
75
  end
26
76
  end
27
77
 
28
- def chunk(status, headers, body)
29
- @body = body
30
- headers.delete('Content-Length')
31
- headers['Transfer-Encoding'] = 'chunked'
32
- [status, headers.to_hash, self]
78
+ def initialize(app)
79
+ @app = app
33
80
  end
34
81
 
35
- def each
36
- term = "\r\n"
37
- @body.each do |chunk|
38
- size = bytesize(chunk)
39
- next if size == 0
40
- yield [size.to_s(16), term, chunk, term].join
82
+ # Whether the HTTP version supports chunked encoding (HTTP 1.1 does).
83
+ def chunkable_version?(ver)
84
+ case ver
85
+ # pre-HTTP/1.0 (informally "HTTP/0.9") HTTP requests did not have
86
+ # a version (nor response headers)
87
+ when 'HTTP/1.0', nil, 'HTTP/0.9'
88
+ false
89
+ else
90
+ true
41
91
  end
42
- yield ["0", term, "", term].join
43
92
  end
44
93
 
45
- def close
46
- @body.close if @body.respond_to?(:close)
94
+ # If the rack app returns a response that should have a body,
95
+ # but does not have Content-Length or Transfer-Encoding headers,
96
+ # modify the response to use chunked Transfer-Encoding.
97
+ def call(env)
98
+ status, headers, body = @app.call(env)
99
+ headers = HeaderHash[headers]
100
+
101
+ if chunkable_version?(env[SERVER_PROTOCOL]) &&
102
+ !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) &&
103
+ !headers[CONTENT_LENGTH] &&
104
+ !headers[TRANSFER_ENCODING]
105
+
106
+ headers[TRANSFER_ENCODING] = 'chunked'
107
+ if headers['Trailer']
108
+ body = TrailerBody.new(body)
109
+ else
110
+ body = Body.new(body)
111
+ end
112
+ end
113
+
114
+ [status, headers, body]
47
115
  end
48
116
  end
49
117
  end