Class: Faulty::CircuitRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/faulty/circuit_registry.rb

Overview

Used by Faulty instances to track and memoize Circuits

Whenever a circuit is requested by Faulty#circuit, it calls #retrieve. That will return a resolved circuit if there is one, or otherwise, it will create a new circuit instance.

Once any circuit is run, the circuit calls #resolve. That saves the instance into the registry. Any calls to #retrieve after the circuit is resolved will result in the same instance being returned.

However, before a circuit is resolved, calling Faulty#circuit will result in a new Circuit instance being created for every call. If multiples of these call resolve, only the first one will "win" and be memoized.

Instance Method Summary collapse

Constructor Details

#initialize(circuit_options) ⇒ CircuitRegistry

Returns a new instance of CircuitRegistry.


18
19
20
21
22
# File 'lib/faulty/circuit_registry.rb', line 18

def initialize(circuit_options)
  @circuit_options = circuit_options
  @circuit_options[:registry] = self
  @circuits = Concurrent::Map.new
end

Instance Method Details

#resolve(circuit) ⇒ Circuit?

Save and memoize the given circuit as the "canonical" instance for the circuit name

If the name is already resolved, this will be ignored

Returns:

  • (Circuit, nil)

    If this circuit name is already resolved, the already-resolved circuit


45
46
47
# File 'lib/faulty/circuit_registry.rb', line 45

def resolve(circuit)
  @circuits.put_if_absent(circuit.name, circuit)
end

#retrieve(name, options) {|Circuit::Options| ... } ⇒ Circuit

Retrieve a memoized circuit with the same name, or if none is yet resolved, create a new one.

Parameters:

Yields:

Returns:

  • (Circuit)

    The new or memoized circuit


31
32
33
34
35
36
# File 'lib/faulty/circuit_registry.rb', line 31

def retrieve(name, options, &block)
  @circuits.fetch(name) do
    options = @circuit_options.merge(options)
    Circuit.new(name, **options, &block)
  end
end