diff --git a/lib/net/http.rb b/lib/net/http.rb index 708a7f2e..09b898db 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -2520,6 +2520,7 @@ def send_entity(path, data, initheader, dest, type, &block) def transport_request(req) count = 0 + finished = false begin body_sent = false begin_transport req @@ -2569,17 +2570,18 @@ def transport_request(req) retry end debug "Conn close because of error #{exception}" - @socket.close if @socket raise end @socket.close unless body_sent end_transport req, res + finished = true res rescue => exception debug "Conn close because of error #{exception}" - @socket.close if @socket raise exception + ensure + @socket.close if !finished && @socket && !@socket.closed? end def begin_transport(req) diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 2c9894fd..5cccb06e 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -1621,6 +1621,21 @@ def test_http_no_retry_with_multipart_io } end + def test_leaving_request_block_closes_connection + start {|http| + [ + -> { http.request_get('/') { break } }, + -> { catch(:done) { http.request_get('/') { throw :done } } }, + -> { assert_raise(Interrupt) { http.request_get('/') { raise Interrupt } } }, + ].each do |leave| + leave.call + assert_predicate http.instance_variable_get(:@socket), :closed? + res = http.get('/') + assert_kind_of Net::HTTPResponse, res + end + } + end + def test_keep_alive_server_close def @server.run(sock) sock.close