Class: StandardAudit::EventSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/standard_audit/event_subscriber.rb

Overview

Subscriber for Rails 8.1+ structured event reporting (‘Rails.event`).

Registered with ‘Rails.event.subscribe(…)` so that every `Rails.event.notify` call flows through StandardAudit for persistence. Events whose name does not match any configured `subscribe_to` pattern are ignored.

Payload is extracted with the same extractors used by the ActiveSupport::Notifications subscriber. Rails.event ‘context` supplies request_id/ip_address/user_agent/session_id and takes precedence over the Current.* resolvers. Tags and source_location are captured as metadata under the reserved keys `_tags` and `_source`.

Constant Summary collapse

RESERVED_PAYLOAD_KEYS =
%i[actor target scope request_id ip_address user_agent session_id].freeze

Instance Method Summary collapse

Constructor Details

#initializeEventSubscriber

Returns a new instance of EventSubscriber.



16
17
18
19
# File 'lib/standard_audit/event_subscriber.rb', line 16

def initialize
  @pattern_cache = {}
  @pattern_cache_mutex = Mutex.new
end

Instance Method Details

#emit(event) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/standard_audit/event_subscriber.rb', line 21

def emit(event)
  return unless StandardAudit.config.enabled

  name = event[:name]
  return if name.nil?
  return unless matches_subscription?(name)

  config  = StandardAudit.config
  payload = event[:payload] || {}
  context = event[:context] || {}

  actor  = config.actor_extractor.call(payload)
  target = config.target_extractor.call(payload)
  scope  = config.scope_extractor.call(payload)

   = (payload, event[:tags], event[:source_location], config)

  StandardAudit.record(
    name,
    actor: actor,
    target: target,
    scope: scope,
    metadata: ,
    request_id: context[:request_id] || payload[:request_id],
    ip_address: context[:ip_address] || payload[:ip_address],
    user_agent: context[:user_agent] || payload[:user_agent],
    session_id: context[:session_id] || payload[:session_id]
  )
rescue => e
  Rails.logger.error("[StandardAudit] Error handling Rails.event: #{e.class}: #{e.message}")
end