homura-runtime 0.3.3 → 0.3.5

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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +24 -0
  3. data/docs/ARCHITECTURE.md +2 -2
  4. data/lib/homura/runtime/ai.rb +31 -8
  5. data/lib/homura/runtime/async_registry.rb +18 -0
  6. data/lib/homura/runtime/durable_object.rb +43 -1
  7. data/lib/homura/runtime/queue.rb +12 -17
  8. data/lib/homura/runtime/version.rb +1 -1
  9. data/lib/homura/runtime.rb +103 -50
  10. data/vendor/rack/auth/abstract/handler.rb +41 -0
  11. data/vendor/rack/auth/abstract/request.rb +51 -0
  12. data/vendor/rack/auth/basic.rb +58 -0
  13. data/vendor/rack/bad_request.rb +8 -0
  14. data/vendor/rack/body_proxy.rb +63 -0
  15. data/vendor/rack/builder.rb +315 -0
  16. data/vendor/rack/cascade.rb +67 -0
  17. data/vendor/rack/common_logger.rb +94 -0
  18. data/vendor/rack/conditional_get.rb +87 -0
  19. data/vendor/rack/config.rb +22 -0
  20. data/vendor/rack/constants.rb +68 -0
  21. data/vendor/rack/content_length.rb +34 -0
  22. data/vendor/rack/content_type.rb +33 -0
  23. data/vendor/rack/deflater.rb +159 -0
  24. data/vendor/rack/directory.rb +210 -0
  25. data/vendor/rack/etag.rb +71 -0
  26. data/vendor/rack/events.rb +172 -0
  27. data/vendor/rack/files.rb +224 -0
  28. data/vendor/rack/head.rb +25 -0
  29. data/vendor/rack/headers.rb +238 -0
  30. data/vendor/rack/lint.rb +1000 -0
  31. data/vendor/rack/lock.rb +29 -0
  32. data/vendor/rack/media_type.rb +42 -0
  33. data/vendor/rack/method_override.rb +56 -0
  34. data/vendor/rack/mime.rb +694 -0
  35. data/vendor/rack/mock.rb +3 -0
  36. data/vendor/rack/mock_request.rb +161 -0
  37. data/vendor/rack/mock_response.rb +147 -0
  38. data/vendor/rack/multipart/generator.rb +99 -0
  39. data/vendor/rack/multipart/parser.rb +586 -0
  40. data/vendor/rack/multipart/uploaded_file.rb +82 -0
  41. data/vendor/rack/multipart.rb +77 -0
  42. data/vendor/rack/null_logger.rb +48 -0
  43. data/vendor/rack/protection/authenticity_token.rb +256 -0
  44. data/vendor/rack/protection/base.rb +140 -0
  45. data/vendor/rack/protection/content_security_policy.rb +80 -0
  46. data/vendor/rack/protection/cookie_tossing.rb +77 -0
  47. data/vendor/rack/protection/escaped_params.rb +93 -0
  48. data/vendor/rack/protection/form_token.rb +25 -0
  49. data/vendor/rack/protection/frame_options.rb +39 -0
  50. data/vendor/rack/protection/http_origin.rb +43 -0
  51. data/vendor/rack/protection/ip_spoofing.rb +27 -0
  52. data/vendor/rack/protection/json_csrf.rb +60 -0
  53. data/vendor/rack/protection/path_traversal.rb +45 -0
  54. data/vendor/rack/protection/referrer_policy.rb +27 -0
  55. data/vendor/rack/protection/remote_referrer.rb +22 -0
  56. data/vendor/rack/protection/remote_token.rb +24 -0
  57. data/vendor/rack/protection/session_hijacking.rb +37 -0
  58. data/vendor/rack/protection/strict_transport.rb +41 -0
  59. data/vendor/rack/protection/version.rb +7 -0
  60. data/vendor/rack/protection/xss_header.rb +27 -0
  61. data/vendor/rack/protection.rb +58 -0
  62. data/vendor/rack/query_parser.rb +261 -0
  63. data/vendor/rack/recursive.rb +66 -0
  64. data/vendor/rack/reloader.rb +112 -0
  65. data/vendor/rack/request.rb +818 -0
  66. data/vendor/rack/response.rb +403 -0
  67. data/vendor/rack/rewindable_input.rb +116 -0
  68. data/vendor/rack/runtime.rb +35 -0
  69. data/vendor/rack/sendfile.rb +197 -0
  70. data/vendor/rack/session/abstract/id.rb +533 -0
  71. data/vendor/rack/session/constants.rb +13 -0
  72. data/vendor/rack/session/cookie.rb +292 -0
  73. data/vendor/rack/session/encryptor.rb +415 -0
  74. data/vendor/rack/session/pool.rb +76 -0
  75. data/vendor/rack/session/version.rb +10 -0
  76. data/vendor/rack/session.rb +12 -0
  77. data/vendor/rack/show_exceptions.rb +433 -0
  78. data/vendor/rack/show_status.rb +121 -0
  79. data/vendor/rack/static.rb +188 -0
  80. data/vendor/rack/tempfile_reaper.rb +44 -0
  81. data/vendor/rack/urlmap.rb +99 -0
  82. data/vendor/rack/utils.rb +631 -0
  83. data/vendor/rack/version.rb +17 -0
  84. data/vendor/rack.rb +66 -0
  85. metadata +76 -1
@@ -0,0 +1,63 @@
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
+ case method_name
19
+ when :to_str
20
+ false
21
+ else
22
+ super or @body.respond_to?(method_name, include_all)
23
+ end
24
+ end
25
+
26
+ # If not already closed, close the wrapped body and
27
+ # then call the block the proxy was initialized with.
28
+ def close
29
+ return if @closed
30
+ @closed = true
31
+ begin
32
+ @body.close if @body.respond_to?(:close)
33
+ ensure
34
+ @block.call
35
+ end
36
+ end
37
+
38
+ # Whether the proxy is closed. The proxy starts as not closed,
39
+ # and becomes closed on the first call to close.
40
+ def closed?
41
+ @closed
42
+ end
43
+
44
+ # Delegate missing methods to the wrapped body.
45
+ def method_missing(method_name, *args, &block)
46
+ case method_name
47
+ when :to_str
48
+ super
49
+ when :to_ary
50
+ begin
51
+ @body.__send__(method_name, *args, &block)
52
+ ensure
53
+ close
54
+ end
55
+ else
56
+ @body.__send__(method_name, *args, &block)
57
+ end
58
+ end
59
+ # :nocov:
60
+ ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
61
+ # :nocov:
62
+ end
63
+ end
@@ -0,0 +1,315 @@
1
+ # backtick_javascript: true
2
+ # frozen_string_literal: true
3
+
4
+ require_relative 'urlmap'
5
+
6
+ module Rack; end
7
+ Rack::BUILDER_TOPLEVEL_BINDING = ->(builder){builder.instance_eval{binding}}
8
+
9
+ module Rack
10
+ # Rack::Builder provides a domain-specific language (DSL) to construct Rack
11
+ # applications. It is primarily used to parse +config.ru+ files which
12
+ # instantiate several middleware and a final application which are hosted
13
+ # by a Rack-compatible web server.
14
+ #
15
+ # Example:
16
+ #
17
+ # app = Rack::Builder.new do
18
+ # use Rack::CommonLogger
19
+ # map "/ok" do
20
+ # run lambda { |env| [200, {'content-type' => 'text/plain'}, ['OK']] }
21
+ # end
22
+ # end
23
+ #
24
+ # run app
25
+ #
26
+ # Or
27
+ #
28
+ # app = Rack::Builder.app do
29
+ # use Rack::CommonLogger
30
+ # run lambda { |env| [200, {'content-type' => 'text/plain'}, ['OK']] }
31
+ # end
32
+ #
33
+ # run app
34
+ #
35
+ # +use+ adds middleware to the stack, +run+ dispatches to an application.
36
+ # You can use +map+ to construct a Rack::URLMap in a convenient way.
37
+ class Builder
38
+
39
+ # https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-without-bom
40
+ UTF_8_BOM = '\xef\xbb\xbf'
41
+
42
+ # Parse the given config file to get a Rack application.
43
+ #
44
+ # If the config file ends in +.ru+, it is treated as a
45
+ # rackup file and the contents will be treated as if
46
+ # specified inside a Rack::Builder block.
47
+ #
48
+ # If the config file does not end in +.ru+, it is
49
+ # required and Rack will use the basename of the file
50
+ # to guess which constant will be the Rack application to run.
51
+ #
52
+ # Examples:
53
+ #
54
+ # Rack::Builder.parse_file('config.ru')
55
+ # # Rack application built using Rack::Builder.new
56
+ #
57
+ # Rack::Builder.parse_file('app.rb')
58
+ # # requires app.rb, which can be anywhere in Ruby's
59
+ # # load path. After requiring, assumes App constant
60
+ # # is a Rack application
61
+ #
62
+ # Rack::Builder.parse_file('./my_app.rb')
63
+ # # requires ./my_app.rb, which should be in the
64
+ # # process's current directory. After requiring,
65
+ # # assumes MyApp constant is a Rack application
66
+ def self.parse_file(path, **options)
67
+ if path.end_with?('.ru')
68
+ return self.load_file(path, **options)
69
+ else
70
+ require path
71
+ return Object.const_get(::File.basename(path, '.rb').split('_').map(&:capitalize).join(''))
72
+ end
73
+ end
74
+
75
+ # Load the given file as a rackup file, treating the
76
+ # contents as if specified inside a Rack::Builder block.
77
+ #
78
+ # Ignores content in the file after +__END__+, so that
79
+ # use of +__END__+ will not result in a syntax error.
80
+ #
81
+ # Example config.ru file:
82
+ #
83
+ # $ cat config.ru
84
+ #
85
+ # use Rack::ContentLength
86
+ # require './app.rb'
87
+ # run App
88
+ def self.load_file(path, **options)
89
+ config = ::File.read(path)
90
+ config.slice!(/\A#{UTF_8_BOM}/) if config.encoding == Encoding::UTF_8
91
+
92
+ if config[/^#\\(.*)/]
93
+ fail "Parsing options from the first comment line is no longer supported: #{path}"
94
+ end
95
+
96
+ config.sub!(/^__END__\n.*\Z/m, '')
97
+
98
+ return new_from_string(config, path, **options)
99
+ end
100
+
101
+ # Evaluate the given +builder_script+ string in the context of
102
+ # a Rack::Builder block, returning a Rack application.
103
+ def self.new_from_string(builder_script, path = "(rackup)", **options)
104
+ builder = self.new(**options)
105
+
106
+ # We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance.
107
+ # We cannot use instance_eval(String) as that would resolve constants differently.
108
+ binding = BUILDER_TOPLEVEL_BINDING.call(builder)
109
+ eval(builder_script, binding, path)
110
+
111
+ return builder.to_app
112
+ end
113
+
114
+ # Initialize a new Rack::Builder instance. +default_app+ specifies the
115
+ # default application if +run+ is not called later. If a block
116
+ # is given, it is evaluated in the context of the instance.
117
+ def initialize(default_app = nil, **options, &block)
118
+ @use = []
119
+ @map = nil
120
+ @run = default_app
121
+ @warmup = nil
122
+ @freeze_app = false
123
+ @options = options
124
+
125
+ instance_eval(&block) if block_given?
126
+ end
127
+
128
+ # Any options provided to the Rack::Builder instance at initialization.
129
+ # These options can be server-specific. Some general options are:
130
+ #
131
+ # * +:isolation+: One of +process+, +thread+ or +fiber+. The execution
132
+ # isolation model to use.
133
+ attr :options
134
+
135
+ # Create a new Rack::Builder instance and return the Rack application
136
+ # generated from it.
137
+ def self.app(default_app = nil, &block)
138
+ self.new(default_app, &block).to_app
139
+ end
140
+
141
+ # Specifies middleware to use in a stack.
142
+ #
143
+ # class Middleware
144
+ # def initialize(app)
145
+ # @app = app
146
+ # end
147
+ #
148
+ # def call(env)
149
+ # env["rack.some_header"] = "setting an example"
150
+ # @app.call(env)
151
+ # end
152
+ # end
153
+ #
154
+ # use Middleware
155
+ # run lambda { |env| [200, { "content-type" => "text/plain" }, ["OK"]] }
156
+ #
157
+ # All requests through to this application will first be processed by the middleware class.
158
+ # The +call+ method in this example sets an additional environment key which then can be
159
+ # referenced in the application if required.
160
+ def use(middleware, *args, &block)
161
+ if @map
162
+ mapping, @map = @map, nil
163
+ @use << proc { |app| generate_map(app, mapping) }
164
+ end
165
+ @use << proc { |app| middleware.new(app, *args, &block) }
166
+
167
+ nil
168
+ end
169
+ # :nocov:
170
+ ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true)
171
+ # :nocov:
172
+
173
+ # Takes a block or argument that is an object that responds to #call and
174
+ # returns a Rack response.
175
+ #
176
+ # You can use a block:
177
+ #
178
+ # run do |env|
179
+ # [200, { "content-type" => "text/plain" }, ["Hello World!"]]
180
+ # end
181
+ #
182
+ # You can also provide a lambda:
183
+ #
184
+ # run lambda { |env| [200, { "content-type" => "text/plain" }, ["OK"]] }
185
+ #
186
+ # You can also provide a class instance:
187
+ #
188
+ # class Heartbeat
189
+ # def call(env)
190
+ # [200, { "content-type" => "text/plain" }, ["OK"]]
191
+ # end
192
+ # end
193
+ #
194
+ # run Heartbeat.new
195
+ #
196
+ def run(app = nil, &block)
197
+ raise ArgumentError, "Both app and block given!" if app && block_given?
198
+
199
+ @run = app || block
200
+
201
+ nil
202
+ end
203
+
204
+ # Takes a lambda or block that is used to warm-up the application. This block is called
205
+ # before the Rack application is returned by to_app.
206
+ #
207
+ # warmup do |app|
208
+ # client = Rack::MockRequest.new(app)
209
+ # client.get('/')
210
+ # end
211
+ #
212
+ # use SomeMiddleware
213
+ # run MyApp
214
+ def warmup(prc = nil, &block)
215
+ @warmup = prc || block
216
+ end
217
+
218
+ # Creates a route within the application. Routes under the mapped path will be sent to
219
+ # the Rack application specified by run inside the block. Other requests will be sent to the
220
+ # default application specified by run outside the block.
221
+ #
222
+ # class App
223
+ # def call(env)
224
+ # [200, {'content-type' => 'text/plain'}, ["Hello World"]]
225
+ # end
226
+ # end
227
+ #
228
+ # class Heartbeat
229
+ # def call(env)
230
+ # [200, { "content-type" => "text/plain" }, ["OK"]]
231
+ # end
232
+ # end
233
+ #
234
+ # app = Rack::Builder.app do
235
+ # map '/heartbeat' do
236
+ # run Heartbeat.new
237
+ # end
238
+ # run App.new
239
+ # end
240
+ #
241
+ # run app
242
+ #
243
+ # The +use+ method can also be used inside the block to specify middleware to run under a specific path:
244
+ #
245
+ # app = Rack::Builder.app do
246
+ # map '/heartbeat' do
247
+ # use Middleware
248
+ # run Heartbeat.new
249
+ # end
250
+ # run App.new
251
+ # end
252
+ #
253
+ # This example includes a piece of middleware which will run before +/heartbeat+ requests hit +Heartbeat+.
254
+ #
255
+ # Note that providing a +path+ of +/+ will ignore any default application given in a +run+ statement
256
+ # outside the block.
257
+ def map(path, &block)
258
+ @map ||= {}
259
+ @map[path] = block
260
+
261
+ nil
262
+ end
263
+
264
+ # Freeze the app (set using run) and all middleware instances when building the application
265
+ # in to_app.
266
+ def freeze_app
267
+ @freeze_app = true
268
+ end
269
+
270
+ # Return the Rack application generated by this instance.
271
+ def to_app
272
+ app = @map ? generate_map(@run, @map) : @run
273
+ fail "missing run or map statement" unless app
274
+ app.freeze if @freeze_app
275
+ # homura patch: neither Array#inject nor an `each` block with
276
+ # a closured local variable reliably threads the middleware
277
+ # accumulator through the chain on Opal (the closure copy of
278
+ # `acc` does not propagate). Use an index-based loop so the
279
+ # accumulator lives in a single function scope without closures.
280
+ list = @use.reverse
281
+ app = wrap_middleware_chain(list, app)
282
+ @warmup.call(app) if @warmup
283
+ app
284
+ end
285
+
286
+ def wrap_middleware_chain(list, initial)
287
+ acc = initial
288
+ i = 0
289
+ n = list.length
290
+ while i < n
291
+ acc = list[i].call(acc)
292
+ acc.freeze if @freeze_app
293
+ i += 1
294
+ end
295
+ acc
296
+ end
297
+
298
+ # Call the Rack application generated by this builder instance. Note that
299
+ # this rebuilds the Rack application and runs the warmup code (if any)
300
+ # every time it is called, so it should not be used if performance is important.
301
+ def call(env)
302
+ to_app.call(env)
303
+ end
304
+
305
+ private
306
+
307
+ # Generate a URLMap instance by generating new Rack applications for each
308
+ # map block in this instance.
309
+ def generate_map(default_app, mapping)
310
+ mapped = default_app ? { '/' => default_app } : {}
311
+ mapping.each { |r, b| mapped[r] = self.class.new(default_app, &b).to_app }
312
+ URLMap.new(mapped)
313
+ end
314
+ end
315
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'constants'
4
+
5
+ module Rack
6
+ # Rack::Cascade tries a request on several apps, and returns the
7
+ # first response that is not 404 or 405 (or in a list of configured
8
+ # status codes). If all applications tried return one of the configured
9
+ # status codes, return the last response.
10
+
11
+ class Cascade
12
+ # An array of applications to try in order.
13
+ attr_reader :apps
14
+
15
+ # Set the apps to send requests to, and what statuses result in
16
+ # cascading. Arguments:
17
+ #
18
+ # apps: An enumerable of rack applications.
19
+ # cascade_for: The statuses to use cascading for. If a response is received
20
+ # from an app, the next app is tried.
21
+ def initialize(apps, cascade_for = [404, 405])
22
+ @apps = []
23
+ apps.each { |app| add app }
24
+
25
+ @cascade_for = {}
26
+ [*cascade_for].each { |status| @cascade_for[status] = true }
27
+ end
28
+
29
+ # Call each app in order. If the responses uses a status that requires
30
+ # cascading, try the next app. If all responses require cascading,
31
+ # return the response from the last app.
32
+ def call(env)
33
+ return [404, { CONTENT_TYPE => "text/plain" }, []] if @apps.empty?
34
+ result = nil
35
+ last_body = nil
36
+
37
+ @apps.each do |app|
38
+ # The SPEC says that the body must be closed after it has been iterated
39
+ # by the server, or if it is replaced by a middleware action. Cascade
40
+ # replaces the body each time a cascade happens. It is assumed that nil
41
+ # does not respond to close, otherwise the previous application body
42
+ # will be closed. The final application body will not be closed, as it
43
+ # will be passed to the server as a result.
44
+ last_body.close if last_body.respond_to? :close
45
+
46
+ result = app.call(env)
47
+ return result unless @cascade_for.include?(result[0].to_i)
48
+ last_body = result[2]
49
+ end
50
+
51
+ result
52
+ end
53
+
54
+ # Append an app to the list of apps to cascade. This app will
55
+ # be tried last.
56
+ def add(app)
57
+ @apps << app
58
+ end
59
+
60
+ # Whether the given app is one of the apps to cascade to.
61
+ def include?(app)
62
+ @apps.include?(app)
63
+ end
64
+
65
+ alias_method :<<, :add
66
+ end
67
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'constants'
4
+ require_relative 'utils'
5
+ require_relative 'body_proxy'
6
+ require_relative 'request'
7
+
8
+ module Rack
9
+ # Rack::CommonLogger forwards every request to the given +app+, and
10
+ # logs a line in the
11
+ # {Apache common log format}[http://httpd.apache.org/docs/1.3/logs.html#common]
12
+ # to the configured logger.
13
+ class CommonLogger
14
+ # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common
15
+ #
16
+ # lilith.local - - [07/Aug/2006 23:58:02 -0400] "GET / HTTP/1.1" 500 -
17
+ #
18
+ # %{%s - %s [%s] "%s %s%s %s" %d %s\n} %
19
+ #
20
+ # The actual format is slightly different than the above due to the
21
+ # separation of SCRIPT_NAME and PATH_INFO, and because the elapsed
22
+ # time in seconds is included at the end.
23
+ FORMAT = %{%s - %s [%s] "%s %s%s%s %s" %d %s %0.4f }
24
+
25
+ # +logger+ can be any object that supports the +write+ or +<<+ methods,
26
+ # which includes the standard library Logger. These methods are called
27
+ # with a single string argument, the log message.
28
+ # If +logger+ is nil, CommonLogger will fall back <tt>env['rack.errors']</tt>.
29
+ def initialize(app, logger = nil)
30
+ @app = app
31
+ @logger = logger
32
+ end
33
+
34
+ # Log all requests in common_log format after a response has been
35
+ # returned. Note that if the app raises an exception, the request
36
+ # will not be logged, so if exception handling middleware are used,
37
+ # they should be loaded after this middleware. Additionally, because
38
+ # the logging happens after the request body has been fully sent, any
39
+ # exceptions raised during the sending of the response body will
40
+ # cause the request not to be logged.
41
+ def call(env)
42
+ began_at = Utils.clock_time
43
+ status, headers, body = response = @app.call(env)
44
+
45
+ response[2] = BodyProxy.new(body) { log(env, status, headers, began_at) }
46
+ response
47
+ end
48
+
49
+ private
50
+
51
+ # Log the request to the configured logger.
52
+ def log(env, status, response_headers, began_at)
53
+ request = Rack::Request.new(env)
54
+ length = extract_content_length(response_headers)
55
+
56
+ msg = sprintf(FORMAT,
57
+ request.ip || "-",
58
+ request.get_header("REMOTE_USER") || "-",
59
+ Time.now.strftime("%d/%b/%Y:%H:%M:%S %z"),
60
+ request.request_method,
61
+ request.script_name,
62
+ request.path_info,
63
+ request.query_string.empty? ? "" : "?#{request.query_string}",
64
+ request.get_header(SERVER_PROTOCOL),
65
+ status.to_s[0..3],
66
+ length,
67
+ Utils.clock_time - began_at)
68
+
69
+ # homura: Opal Strings are immutable, so use non-mutating gsub +
70
+ # chomp + concat instead of `gsub!` / `String#[]=`. Behaviour
71
+ # identical on MRI; required to keep CommonLogger usable when
72
+ # Sinatra default-middleware is active under the Workers + Opal
73
+ # stack.
74
+ msg = msg.gsub(/[^[:print:]]/) { |c| sprintf("\\x%x", c.ord) }
75
+ msg = msg.chomp + "\n"
76
+
77
+ logger = @logger || request.get_header(RACK_ERRORS)
78
+ # Standard library logger doesn't support write but it supports << which actually
79
+ # calls to write on the log device without formatting
80
+ if logger.respond_to?(:write)
81
+ logger.write(msg)
82
+ else
83
+ logger << msg
84
+ end
85
+ end
86
+
87
+ # Attempt to determine the content length for the response to
88
+ # include it in the logged data.
89
+ def extract_content_length(headers)
90
+ value = headers[CONTENT_LENGTH]
91
+ !value || value.to_s == '0' ? '-' : value
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'constants'
4
+ require_relative 'utils'
5
+ require_relative 'body_proxy'
6
+
7
+ module Rack
8
+
9
+ # Middleware that enables conditional GET using if-none-match and
10
+ # if-modified-since. The application should set either or both of the
11
+ # last-modified or etag response headers according to RFC 2616. When
12
+ # either of the conditions is met, the response body is set to be zero
13
+ # length and the response status is set to 304 Not Modified.
14
+ #
15
+ # Applications that defer response body generation until the body's each
16
+ # message is received will avoid response body generation completely when
17
+ # a conditional GET matches.
18
+ #
19
+ # Adapted from Michael Klishin's Merb implementation:
20
+ # https://github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb
21
+ class ConditionalGet
22
+ def initialize(app)
23
+ @app = app
24
+ end
25
+
26
+ # Return empty 304 response if the response has not been
27
+ # modified since the last request.
28
+ def call(env)
29
+ case env[REQUEST_METHOD]
30
+ when "GET", "HEAD"
31
+ status, headers, body = response = @app.call(env)
32
+
33
+ if status == 200 && fresh?(env, headers)
34
+ response[0] = 304
35
+ headers.delete(CONTENT_TYPE)
36
+ headers.delete(CONTENT_LENGTH)
37
+
38
+ # We are done with the body:
39
+ body.close if body.respond_to?(:close)
40
+ response[2] = []
41
+ end
42
+ response
43
+ else
44
+ @app.call(env)
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ # Return whether the response has not been modified since the
51
+ # last request.
52
+ def fresh?(env, headers)
53
+ # if-none-match has priority over if-modified-since per RFC 7232
54
+ if none_match = env['HTTP_IF_NONE_MATCH']
55
+ etag_matches?(none_match, headers)
56
+ elsif (modified_since = env['HTTP_IF_MODIFIED_SINCE']) && (modified_since = to_rfc2822(modified_since))
57
+ modified_since?(modified_since, headers)
58
+ end
59
+ end
60
+
61
+ # Whether the etag response header matches the if-none-match request header.
62
+ # If so, the request has not been modified.
63
+ def etag_matches?(none_match, headers)
64
+ headers[ETAG] == none_match
65
+ end
66
+
67
+ # Whether the last-modified response header matches the if-modified-since
68
+ # request header. If so, the request has not been modified.
69
+ def modified_since?(modified_since, headers)
70
+ last_modified = to_rfc2822(headers['last-modified']) and
71
+ modified_since >= last_modified
72
+ end
73
+
74
+ # Return a Time object for the given string (which should be in RFC2822
75
+ # format), or nil if the string cannot be parsed.
76
+ def to_rfc2822(since)
77
+ # shortest possible valid date is the obsolete: 1 Nov 97 09:55 A
78
+ # anything shorter is invalid, this avoids exceptions for common cases
79
+ # most common being the empty string
80
+ if since && since.length >= 16
81
+ # NOTE: there is no trivial way to write this in a non exception way
82
+ # _rfc2822 returns a hash but is not that usable
83
+ Time.rfc2822(since) rescue nil
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ # Rack::Config modifies the environment using the block given during
5
+ # initialization.
6
+ #
7
+ # Example:
8
+ # use Rack::Config do |env|
9
+ # env['my-key'] = 'some-value'
10
+ # end
11
+ class Config
12
+ def initialize(app, &block)
13
+ @app = app
14
+ @block = block
15
+ end
16
+
17
+ def call(env)
18
+ @block.call(env)
19
+ @app.call(env)
20
+ end
21
+ end
22
+ end