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

Already on GitHub? Sign in to your account

Reconnect after "successful" callback. #4

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+40 −8
Split
View
@@ -94,14 +94,8 @@ def close
def listen
@conn, @req = prepare_request
- @req.errback do
- next if @ready_state == CLOSED
- @ready_state = CONNECTING
- @errors.each { |error| error.call("Connection lost. Reconnecting.") }
- EM.add_timer(@retry) do
- listen
- end
- end
+ @req.errback(&method(:handle_reconnect))
+ @req.callback(&method(:handle_reconnect))
@req.headers do |headers|
if headers.status != 200
close
@@ -127,6 +121,15 @@ def listen
end
end
+ def handle_reconnect(*args)
+ return if @ready_state == CLOSED
+ @ready_state = CONNECTING
+ @errors.each { |error| error.call("Connection lost. Reconnecting.") }
+ EM.add_timer(@retry) do
+ listen
+ end
+ end
+
def handle_stream(stream)
data = ""
name = nil
@@ -154,6 +154,26 @@ def create_response_headers(status, content_type="", other={})
end
end
+ it "reconnect after callback with last-event-id" do
+ start_source do |source, req|
+ req.stream_data("id: roger\n\n")
+ source.error do |error|
+ error.must_equal "Connection lost. Reconnecting."
+ source.ready_state.must_equal EM::EventSource::CONNECTING
+ EM.add_timer(4) do
+ req2 = source.instance_variable_get "@req"
+ refute_same(req2, req)
+ source.last_event_id.must_equal "roger"
+ req2.get_args[0].must_equal({ :head => { "Last-Event-Id" => "roger",
+ "Cache-Control" => "no-cache" },
+ :query => {} })
+ EM.stop
+ end
+ end
+ req.call_callback
+ end
+ end
+
it "handle retry event" do
start_source do |source ,req|
req.stream_data("retry: plop\n\n")
View
@@ -8,6 +8,7 @@ def initialize(url, opts={})
@url = url
@streams = []
@errors = []
+ @callbacks = []
@headers = []
@middlewares = []
@opts = opts
@@ -26,6 +27,10 @@ def errback(&block)
@errors << block
end
+ def callback(&block)
+ @callbacks << block
+ end
+
def use(*args, &block)
@middlewares << [*args, block]
end
@@ -42,6 +47,10 @@ def call_errback
@errors.each { |error| error.call() }
end
+ def call_callback
+ @callbacks.each { |callback| callback.call("chunk of data") }
+ end
+
def call_headers(headers)
@headers.each { |header| header.call(headers) }
end