Class: Exa::Instrumentation::EventRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/exa/instrumentation.rb

Overview

Thread-safe event registry for subscribing to and emitting API events. Supports wildcard pattern matching (e.g., 'exa.request.*').

Instance Method Summary collapse

Constructor Details

#initializeEventRegistry

Returns a new instance of EventRegistry.



10
11
12
13
# File 'lib/exa/instrumentation.rb', line 10

def initialize
  @listeners = {}
  @mutex = Mutex.new
end

Instance Method Details

#clear_listenersObject

Clear all listeners.



42
43
44
45
46
# File 'lib/exa/instrumentation.rb', line 42

def clear_listeners
  @mutex.synchronize do
    @listeners.clear
  end
end

#listener_countObject

Returns the count of registered listeners.



67
68
69
# File 'lib/exa/instrumentation.rb', line 67

def listener_count
  @mutex.synchronize { @listeners.size }
end

#notify(event_name, payload) ⇒ Object

Emit an event to all matching subscribers.

Parameters:

  • event_name (String)

    The event name (e.g., 'exa.request.complete')

  • payload (Object)

    The event payload (usually a typed struct)



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/exa/instrumentation.rb', line 51

def notify(event_name, payload)
  # Take a snapshot of current listeners to avoid holding the mutex during execution
  matching_listeners = @mutex.synchronize do
    @listeners.select do |_id, listener|
      pattern_matches?(listener[:pattern], event_name)
    end.dup
  end

  matching_listeners.each do |_id, listener|
    listener[:block].call(event_name, payload)
  rescue StandardError
    # Silently ignore listener errors to avoid breaking the main flow
  end
end

#subscribe(pattern) {|event_name, payload| ... } ⇒ String

Subscribe to events matching a pattern.

Parameters:

  • pattern (String)

    Event pattern (supports '*' wildcard)

Yields:

  • (event_name, payload)

    Block called when matching events are emitted

Returns:

  • (String)

    Subscription ID for later unsubscription



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/exa/instrumentation.rb', line 19

def subscribe(pattern, &block)
  return unless block_given?

  subscription_id = SecureRandom.uuid
  @mutex.synchronize do
    @listeners[subscription_id] = {
      pattern: pattern,
      block: block
    }
  end

  subscription_id
end

#unsubscribe(subscription_id) ⇒ Object

Unsubscribe from events.

Parameters:

  • subscription_id (String)

    The ID returned from subscribe



35
36
37
38
39
# File 'lib/exa/instrumentation.rb', line 35

def unsubscribe(subscription_id)
  @mutex.synchronize do
    @listeners.delete(subscription_id)
  end
end