Class: Semian::PIDControllerThread

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/semian/pid_controller_thread.rb

Instance Method Summary collapse

Constructor Details

#initializePIDControllerThread

Returns a new instance of PIDControllerThread.



10
11
12
13
14
15
# File 'lib/semian/pid_controller_thread.rb', line 10

def initialize
  @stopped = true
  @update_thread = nil
  @circuit_breakers = Concurrent::Map.new
  @sliding_interval = ENV.fetch("SEMIAN_ADAPTIVE_CIRCUIT_BREAKER_SLIDING_INTERVAL", 1).to_i
end

Instance Method Details

#register_resource(circuit_breaker) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/semian/pid_controller_thread.rb', line 45

def register_resource(circuit_breaker)
  # Track every registered circuit breaker in a Concurrent::Map

  # Start the thread if it's not already running
  if @circuit_breakers.empty? && @stopped
    start
  end

  # Add the circuit breaker to the map
  @circuit_breakers[circuit_breaker.name] = circuit_breaker
  self
end

#startObject

As per the singleton pattern, this is called only once



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/semian/pid_controller_thread.rb', line 18

def start
  @stopped = false

  update_proc = proc do
    loop do
      break if @stopped

      wait_for_window

      # Update PID controller state for each registered circuit breaker
      @circuit_breakers.each do |_, circuit_breaker|
        circuit_breaker.pid_controller_update
      end
    rescue => e
      Semian.logger&.warn("[#{@name}] PID controller update thread error: #{e.message}")
    end
  end

  @update_thread = Thread.new(&update_proc)
end

#stopObject



39
40
41
42
43
# File 'lib/semian/pid_controller_thread.rb', line 39

def stop
  @stopped = true
  @update_thread&.kill
  @update_thread = nil
end

#unregister_resource(circuit_breaker) ⇒ Object



58
59
60
61
62
63
64
65
66
# File 'lib/semian/pid_controller_thread.rb', line 58

def unregister_resource(circuit_breaker)
  # Remove the circuit breaker from the map
  @circuit_breakers.delete(circuit_breaker.name)

  # Stop the thread if there are no more circuit breakers
  if @circuit_breakers.empty?
    stop
  end
end

#wait_for_windowObject



68
69
70
# File 'lib/semian/pid_controller_thread.rb', line 68

def wait_for_window
  Kernel.sleep(@sliding_interval)
end