Skip to content

Commit

Permalink
Ensure that connecting to Rabbit is threadsafe
Browse files Browse the repository at this point in the history
When there are competing publisher threads, there is a chance that the
publisher has not been initialized when Hutch is registered as
connected. The following diagram should shed some light on the race
condition:

```
        Thread 1                  Hutch                   Thread 2
        --------                  -------                 ---------
t1      Hutch.publish()  --->  connected? (FALSE)
                           |-> open_connection!
t2                             connected? (TRUE)  <--- Hutch.publish()
                               @broker.publish()   |-> NoMethodError (@publisher)
t3                         |-> declare_publisher!
        PUBLISHED        <-|   @broker.publish()
```

Wrapping the `Hutch.connect` call should resolve this issue.
  • Loading branch information
cbarton committed Feb 9, 2018
1 parent 11996fb commit 3789000
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/hutch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
require 'hutch/tracers'

module Hutch
@@mutex = Mutex.new

def self.register_consumer(consumer)
self.consumers << consumer
end
Expand All @@ -40,10 +42,12 @@ def self.global_properties
# @param config [Hash] Configuration
# @option options [Boolean] :enable_http_api_use
def self.connect(options = {}, config = Hutch::Config)
return if connected?

@broker = Hutch::Broker.new(config)
@broker.connect(options)
@@mutex.synchronize do
unless connected?
@broker = Hutch::Broker.new(config)
@broker.connect(options)
end
end
end

def self.disconnect
Expand Down

0 comments on commit 3789000

Please sign in to comment.