1 # -*- encoding: binary -*-
2 # This middleware handles X-\Sendfile headers generated by applications
3 # or middlewares down the stack. It should be placed at the top
4 # (outermost layer) of the middleware stack to avoid having its
5 # +to_path+ method clobbered by another middleware.
7 # This converts X-\Sendfile responses to bodies which respond to the
8 # +to_path+ method which allows certain concurrency models to serve
9 # efficiently using sendfile() or similar. With multithreaded models
10 # under Ruby 1.9, IO.copy_stream will be used.
12 # This middleware is the opposite of Rack::Sendfile as it
13 # reverses the effect of Rack:::Sendfile. Unlike many Ruby
14 # web servers, some configurations of \Rainbows! are capable of
15 # serving static files efficiently.
17 # === Compatibility (via IO.copy_stream in Ruby 1.9):
23 # === Compatibility (Ruby 1.8 and 1.9)
25 # * NeverBlock (using EventMachine)
27 # DO NOT use this middleware if you're proxying to \Rainbows! with a
28 # server that understands X-\Sendfile (e.g. Apache, Lighttpd) natively.
30 # This does NOT understand X-Accel-Redirect headers intended for nginx.
31 # X-Accel-Redirect requires the application to be highly coupled with
32 # the corresponding nginx configuration, and is thus too complicated to
33 # be worth supporting.
37 # use Rainbows::Sendfile
39 # path = "#{Dir.pwd}/random_blob"
42 # 'X-Sendfile' => path,
43 # 'Content-Type' => 'application/octet-stream'
49 class Rainbows::Sendfile < Struct.new(:app)
51 # Body wrapper, this allows us to fall back gracefully to
52 # +each+ in case a given concurrency model does not optimize
54 class Body < Struct.new(:to_path) # :nodoc: all
55 CONTENT_LENGTH = 'Content-Length'.freeze
57 def self.new(path, headers)
58 unless headers[CONTENT_LENGTH]
59 stat = File.stat(path)
60 headers[CONTENT_LENGTH] = stat.size.to_s if stat.file?
65 # fallback in case our +to_path+ doesn't get handled for whatever reason
68 File.open(to_path) do |fp|
69 yield buf while fp.read(0x4000, buf)
75 X_SENDFILE = 'X-Sendfile'
78 def call(env) # :nodoc:
79 status, headers, body = app.call(env)
80 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
81 if path = headers.delete(X_SENDFILE)
82 body = Body.new(path, headers) unless body.respond_to?(:to_path)
84 [ status, headers, body ]