Class: Karafka::Core::Instrumentation::CallbacksManager

Inherits:
Object
  • Object
show all
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

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

Parameters:

  • id (String)

    id of the callback (used when deleting it)

  • callable (#call)

    object that responds to a ‘#call` method



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

Note:

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

Parameters:

  • args (Object)

    any args that should go to the callbacks



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

Parameters:

  • id (String)

    id of the callback we want to remove



40
41
42
43
# File 'lib/karafka/core/instrumentation/callbacks_manager.rb', line 40

def delete(id)
  @callbacks.delete(id)
  @values_cache = nil
end