Skip to content

Commit

Permalink
Call getaddrinfo from Ruby
Browse files Browse the repository at this point in the history
`getaddrinfo` is notorious for not having a timeout, which can make
it hang for a very long time. Since Trilogy releases the GVL before
calling it, that can cause the whole VM to be unresponsive and no
longer respond to ctrl+c etc.

In 3.3.0, Ruby is now doing name resolution from a background thread,
making `Socket.getaddrinfo` interruptible. So by doing the name resolution
on the Ruby side, we should avoid such scenarios.
  • Loading branch information
byroot committed Dec 11, 2023
1 parent e577853 commit 66f6560
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
13 changes: 13 additions & 0 deletions contrib/ruby/lib/trilogy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,23 @@

class Trilogy
def initialize(options = {})
options = options.dup
options[:port] = options[:port].to_i if options[:port]
mysql_encoding = options[:encoding] || "utf8mb4"
encoding = Trilogy::Encoding.find(mysql_encoding)
charset = Trilogy::Encoding.charset(mysql_encoding)

if options[:host]
addrs = begin
Socket.getaddrinfo(options[:host], options[:port], :PF_UNSPEC, :SOCK_STREAM)
rescue SocketError => error
raise Trilogy::BaseConnectionError, "Couldn't resolve host: #{options[:host].inspect}"
end

addrs.sort_by!(&:first) # Priority to IPv4
options[:host] = addrs.first[3]
end

@connection_options = options
@connected_host = nil

Expand Down
2 changes: 1 addition & 1 deletion contrib/ruby/test/client_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ def test_connection_invalid_dns
ex = assert_raises Trilogy::ConnectionError do
new_tcp_client(host: "mysql.invalid", port: 3306)
end
assert_equal "trilogy_connect - unable to connect to mysql.invalid:3306: TRILOGY_DNS_ERROR", ex.message
assert_includes ex.message, %{Couldn't resolve host: "mysql.invalid"}
end

def test_memsize
Expand Down

0 comments on commit 66f6560

Please sign in to comment.