Skip to content

Commit

Permalink
Refactor and unit test reconnect time
Browse files Browse the repository at this point in the history
  • Loading branch information
anson627 committed Jun 14, 2019
1 parent 495ca2c commit d2da647
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
18 changes: 12 additions & 6 deletions lib/synapse/service_watcher/zookeeper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -369,15 +369,10 @@ def zk_connect
log.info "synapse: ZK client has reconnected #{@name}"
# random backoff to avoid checking and refreshing all watchers at the same time
sleep rand(10)
now = Time.now
# ensure there is only one refresh can happen within a time window
if !@last_reconnect_time.nil? && (now - @last_reconnect_time) < 60
unless test_and_set_reconnect_time(Time.now)
log.info "synapse: ZK client skip since last reconnect is too close #{@name}"
return
end
# test-and-set should be thread safe based on per-callback model
# https://github.com/zk-ruby/zk/wiki/EventDeliveryModel
@last_reconnect_time = now
# zookeeper watcher is one-time trigger, and can be lost when disconnected
# https://zookeeper.apache.org/doc/r3.3.5/zookeeperProgrammers.html#ch_zkWatches
# only need re-enable watcher on parent path and children list
Expand All @@ -397,6 +392,17 @@ def zk_connect
end
end

def test_and_set_reconnect_time(now)
# ensure there is only one refresh can happen within a time window
if !@last_reconnect_time.nil? && (now - @last_reconnect_time) < 60
return false
end
# test-and-set should be thread safe based on per-callback model
# https://github.com/zk-ruby/zk/wiki/EventDeliveryModel
@last_reconnect_time = now
true

end
# decode the data at a zookeeper endpoint
def deserialize_service_instance(data)
log.debug "synapse: deserializing process data"
Expand Down
11 changes: 11 additions & 0 deletions spec/lib/synapse/service_watcher_zookeeper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,17 @@
subject.send(:watcher_callback).call
end

it 'test and set reconnect time' do
now = Time.now
expect(subject.send(:test_and_set_reconnect_time, now)).to be true
now += 10
expect(subject.send(:test_and_set_reconnect_time, now)).to be false
now += 50
expect(subject.send(:test_and_set_reconnect_time, now)).to be true
now += 60
expect(subject.send(:test_and_set_reconnect_time, now)).to be true
end

it 'handles zk consistency issues' do
expect(subject).to receive(:watch)
expect(subject).to receive(:discover).and_call_original
Expand Down

0 comments on commit d2da647

Please sign in to comment.