Skip to content

Replace Timeout.timeout with Socket.tcp(..., open_timeout:) #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions lib/net/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1654,14 +1654,20 @@ def connect
end

debug "opening connection to #{conn_addr}:#{conn_port}..."
s = Timeout.timeout(@open_timeout, Net::OpenTimeout) {
begin
TCPSocket.open(conn_addr, conn_port, @local_host, @local_port)
rescue => e
raise e, "Failed to open TCP connection to " +
"#{conn_addr}:#{conn_port} (#{e.message})"
begin
# Use built-in timeout in Socket.tcp if available
s = if Socket.method(:tcp).parameters.any? {|param| param[0] == :key && param[1] == :open_timeout }
Socket.tcp(conn_addr, conn_port, @local_host, @local_port, open_timeout: @open_timeout)
else
Timeout.timeout(@open_timeout, Net::OpenTimeout) {
TCPSocket.open(conn_addr, conn_port, @local_host, @local_port)
}
end
}
rescue => e
e = Net::OpenTimeout.new(e) if e.is_a?(Errno::ETIMEDOUT) # for compatibility with previous versions
raise e, "Failed to open TCP connection to " +
"#{conn_addr}:#{conn_port} (#{e.message})"
end
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
debug "opened"
if use_ssl?
Expand Down
4 changes: 2 additions & 2 deletions test/net/http/test_http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,8 @@ def test_failure_message_includes_failed_domain_and_port
# hostname to be included in the error message
host = Struct.new(:to_s).new("<example>")
port = 2119
# hack to let TCPSocket.open fail
def host.to_str; raise SocketError, "open failure"; end
# hack to let Socket.tcp fail
def host.match?(_); raise SocketError, "open failure"; end
uri = Struct.new(:scheme, :hostname, :port).new("http", host, port)
assert_raise_with_message(SocketError, /#{host}:#{port}/) do
TestNetHTTPUtils.clean_http_proxy_env{ Net::HTTP.get(uri) }
Expand Down
Loading