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

Make handlers Deferrable-aware #181

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
45 changes: 39 additions & 6 deletions lib/blather/client/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,23 @@ def receive_data(stanza)
end

def handle_data(stanza)
catch(:halt) do
run_filters :before, stanza
handle_stanza stanza
run_filters :after, stanza
end
df = EM::DefaultDeferrable.new

Fiber.new {
begin
catch(:halt) do
run_filters :before, stanza
handle_stanza stanza
run_filters :after, stanza
end
df.succeed
rescue => e
df.fail(e) # Fail in case anyone is listening
raise e # But still raise so it's not a silent failure
end
}.resume

df
end

# @private
Expand Down Expand Up @@ -303,7 +315,7 @@ def call_handler_for(type, stanza)
end

def call_handler(handler, guards, stanza)
if guards.first.respond_to?(:to_str)
result = if guards.first.respond_to?(:to_str)
found = stanza.find(*guards)
throw :pass if found.empty?

Expand All @@ -313,6 +325,27 @@ def call_handler(handler, guards, stanza)

handler.call(stanza)
end

return result unless result.is_a?(EM::Deferrable)

unless EM.reactor_thread == Thread.current
raise "Cannot sync EM::Deferrable across threads. " \
"Did you forget to setup with async: true?"
end

fiber = Fiber.current
EM.next_tick do
result.callback(&fiber.method(:resume))
result.errback do |e|
if e.is_a?(Exception)
fiber.raise(e)
else
fiber.raise(e.to_s)
end
end
end

Fiber.yield
end

# If any of the guards returns FALSE this returns true
Expand Down