Class: Freeswitch::ESL::Connection::EventDispatcher
- Inherits:
-
Object
- Object
- Freeswitch::ESL::Connection::EventDispatcher
- Defined in:
- lib/freeswitch/esl/connection/event_dispatcher.rb
Overview
Manages event dispatching from a queue to registered handlers. Runs in a dedicated thread and handles both event handlers and bgapi callbacks.
Instance Method Summary collapse
-
#enqueue_event(event) ⇒ Object
Enqueue an event for async dispatch.
-
#initialize ⇒ EventDispatcher
constructor
A new instance of EventDispatcher.
-
#on(event_name, &block) ⇒ Object
Register a handler block for an event name.
-
#register_bgapi_handler(job_uuid, block) ⇒ Object
Register a handler for a background job result (by job UUID).
-
#start ⇒ Object
Start the dispatcher thread.
-
#stop ⇒ Object
Stop the dispatcher thread (close queue and join).
Constructor Details
#initialize ⇒ EventDispatcher
Returns a new instance of EventDispatcher.
9 10 11 12 13 14 15 16 |
# File 'lib/freeswitch/esl/connection/event_dispatcher.rb', line 9 def initialize @event_queue = Queue.new @event_handlers = Hash.new { |h, k| h[k] = [] } @bgapi_handlers = {} @bgapi_mutex = Mutex.new @handlers_mutex = Mutex.new @dispatcher_thread = nil end |
Instance Method Details
#enqueue_event(event) ⇒ Object
Enqueue an event for async dispatch.
19 20 21 |
# File 'lib/freeswitch/esl/connection/event_dispatcher.rb', line 19 def enqueue_event(event) @event_queue << event end |
#on(event_name, &block) ⇒ Object
Register a handler block for an event name. Use “ALL” to handle every event. Multiple handlers per event are supported. Returns self for chaining.
26 27 28 29 30 31 |
# File 'lib/freeswitch/esl/connection/event_dispatcher.rb', line 26 def on(event_name, &block) @handlers_mutex.synchronize do @event_handlers[event_name.to_s.upcase] << block end self end |
#register_bgapi_handler(job_uuid, block) ⇒ Object
Register a handler for a background job result (by job UUID).
34 35 36 |
# File 'lib/freeswitch/esl/connection/event_dispatcher.rb', line 34 def register_bgapi_handler(job_uuid, block) @bgapi_mutex.synchronize { @bgapi_handlers[job_uuid] = block } end |
#start ⇒ Object
Start the dispatcher thread.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/freeswitch/esl/connection/event_dispatcher.rb', line 39 def start return if @dispatcher_thread @dispatcher_thread = Thread.new do loop do event = @event_queue.pop break if event.nil? # Queue closed (Ruby 3.x returns nil on closed empty queue) dispatch(event) end end @dispatcher_thread.name = "esl-dispatcher" @dispatcher_thread.abort_on_exception = false end |
#stop ⇒ Object
Stop the dispatcher thread (close queue and join).
55 56 57 58 |
# File 'lib/freeswitch/esl/connection/event_dispatcher.rb', line 55 def stop @event_queue&.close @dispatcher_thread&.join end |