Skip to content

Commit

Permalink
tee_input: support for Rack::TempfileReaper middleware
Browse files Browse the repository at this point in the history
Rack::TempfileReaper was added in rack 1.6 to cleanup temporary
files.  Make Unicorn::TmpIO ducktype-compatible so
Rack::TempfileReaper may be used to free up space used by temporary
buffer files.

Ref: <CY1PR0301MB078011EB5A22B733EB222A45A4EE0@CY1PR0301MB0780.namprd03.prod.outlook.com>
Reported-by: Mike Mulvaney <MMulvaney@bna.com>
  • Loading branch information
Eric Wong committed Apr 24, 2015
1 parent 548e1e6 commit 3bdf548
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/unicorn/tee_input.rb
Expand Up @@ -28,13 +28,20 @@ def self.client_body_buffer_size
@@client_body_buffer_size
end

# for Rack::TempfileReaper in rack 1.6+
def new_tmpio # :nodoc:
tmpio = Unicorn::TmpIO.new
(@parser.env['rack.tempfiles'] ||= []) << tmpio
tmpio
end

# Initializes a new TeeInput object. You normally do not have to call
# this unless you are writing an HTTP server.
def initialize(socket, request)
@len = request.content_length
super
@tmp = @len && @len <= @@client_body_buffer_size ?
StringIO.new("") : Unicorn::TmpIO.new
StringIO.new("") : new_tmpio
end

# :call-seq:
Expand Down
3 changes: 3 additions & 0 deletions lib/unicorn/tmpio.rb
Expand Up @@ -26,4 +26,7 @@ def self.new
def size
stat.size
end unless File.method_defined?(:size)

# pretend we're Tempfile for Rack::TempfileReaper
alias close! close
end
10 changes: 10 additions & 0 deletions test/unit/test_tee_input.rb
Expand Up @@ -29,6 +29,13 @@ def teardown
end while true
end

def check_tempfiles
tmp = @parser.env["rack.tempfiles"]
assert_instance_of Array, tmp
assert_operator tmp.size, :>=, 1
assert_instance_of Unicorn::TmpIO, tmp[0]
end

def test_gets_long
r = init_request("hello", 5 + (4096 * 4 * 3) + "#$/foo#$/".size)
ti = TeeInput.new(@rd, r)
Expand Down Expand Up @@ -106,6 +113,7 @@ def test_big_body
assert_kind_of File, ti.tmp
assert_equal 0, ti.tmp.pos
assert_equal Unicorn::Const::MAX_BODY + 1, ti.size
check_tempfiles
end

def test_read_in_full_if_content_length
Expand Down Expand Up @@ -148,6 +156,7 @@ def test_big_body_multi
assert_nil ti.read(1)
pid, status = Process.waitpid2(pid)
assert status.success?
check_tempfiles
end

def test_chunked
Expand Down Expand Up @@ -183,6 +192,7 @@ def test_chunked
status = nil
pid, status = Process.waitpid2(pid)
assert status.success?
check_tempfiles
end

def test_chunked_ping_pong
Expand Down

0 comments on commit 3bdf548

Please sign in to comment.