Class: Karafka::Core::Instrumentation::CallbacksManager
- Inherits:
-
Object
- Object
- Karafka::Core::Instrumentation::CallbacksManager
- Defined in:
- lib/karafka/core/instrumentation/callbacks_manager.rb
Overview
This manager allows us to register multiple callbacks into a hook that is suppose to support a single callback
Instance Method Summary collapse
-
#add(id, callable) ⇒ Object
Adds a callback to the manager.
-
#call(*args) ⇒ Object
Invokes all the callbacks registered one after another.
-
#delete(id) ⇒ Object
Removes the callback from the manager.
- #initialize ⇒ ::Karafka::Core::Instrumentation::CallbacksManager constructor
Constructor Details
#initialize ⇒ ::Karafka::Core::Instrumentation::CallbacksManager
11 12 13 14 |
# File 'lib/karafka/core/instrumentation/callbacks_manager.rb', line 11 def initialize @callbacks = {} @values_cache = nil end |
Instance Method Details
#add(id, callable) ⇒ Object
Adds a callback to the manager
33 34 35 36 |
# File 'lib/karafka/core/instrumentation/callbacks_manager.rb', line 33 def add(id, callable) @callbacks[id] = callable @values_cache = nil end |
#call(*args) ⇒ Object
We do not use ‘#each_value` here on purpose. With it being used, we cannot dispatch callbacks and add new at the same time. Since we don’t know when and in what thread things are going to be added to the manager, we need to extract values into an array and run it. That way we can add new things the same time. The values snapshot is cached and invalidated on add/delete to avoid allocating a new Array on every call while preserving the thread-safety snapshot semantics.
Invokes all the callbacks registered one after another
25 26 27 |
# File 'lib/karafka/core/instrumentation/callbacks_manager.rb', line 25 def call(*args) (@values_cache ||= @callbacks.values).each { |callback| callback.call(*args) } end |
#delete(id) ⇒ Object
Removes the callback from the manager
40 41 42 43 |
# File 'lib/karafka/core/instrumentation/callbacks_manager.rb', line 40 def delete(id) @callbacks.delete(id) @values_cache = nil end |