Skip to content
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

Handle read_timeout for queries executed within EventMachine #971

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 8 additions & 0 deletions lib/mysql2/em.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

module Mysql2
module EM
class ReadTimeout < ::RuntimeError; end

class Client < ::Mysql2::Client
module Watcher
def initialize(client, deferable)
Expand Down Expand Up @@ -41,6 +43,12 @@ def query(sql, opts = {})
if ::EM.reactor_running?
super(sql, opts.merge(async: true))
deferable = ::EM::DefaultDeferrable.new
if @read_timeout
deferable.timeout(@read_timeout, Mysql2::EM::ReadTimeout.new)
deferable.errback do |error|
raise error if error.is_a?(Mysql2::EM::ReadTimeout)
end
end
@watch = ::EM.watch(socket, Watcher, self, deferable)
@watch.notify_readable = true
deferable
Expand Down
15 changes: 15 additions & 0 deletions spec/em/em_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,21 @@
end.to raise_error('some error')
end

it "should timeout if we wait longer than :read_timeout" do
expect do
EM.run do
client = Mysql2::EM::Client.new DatabaseCredentials['root'].merge(read_timeout: 1)
defer = client.query "SELECT sleep(2)"
defer.callback do
# This _shouldn't_ be run, but it needed to prevent the specs from
# freezing if this test fails.
client.close
EM.stop_event_loop
end
end
end.to raise_error(Mysql2::EM::ReadTimeout)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you switch to the defer.errback pattern see in the tests below? It is problematic to throw exceptions outside the scope of EM.run (throwing exceptions like this in fact would crash EM 1.2.x until I finally finally figured out the problem in EM 1.2.6)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I'll switch to defer.errback :)

end

context 'when an exception is raised by the client' do
let(:client) { Mysql2::EM::Client.new DatabaseCredentials['root'] }
let(:error) { StandardError.new('some error') }
Expand Down