Class: Lyra::Causation

Inherits:
Object
  • Object
show all
Defined in:
lib/lyra/correlation.rb

Overview

Causation system for tracking event chains causation_id: Points to the specific event that directly caused this event (parent-child relationship)

Example:

OrderPlaced (causation_id: nil)           <- root event
└── PaymentProcessed (causation_id: OrderPlaced.id)
      └── InventoryReserved (causation_id: PaymentProcessed.id)

Class Method Summary collapse

Class Method Details

.cause_of(event_id) ⇒ Object

Get direct cause of an event



79
80
81
# File 'lib/lyra/correlation.rb', line 79

def cause_of(event_id)
  causation_store[event_id]
end

.chain_for(event_id) ⇒ Object

Get the full causation chain for an event (root -> ... -> event)



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/lyra/correlation.rb', line 65

def chain_for(event_id)
  chain = [event_id]
  current = event_id

  while (parent = causation_store[current])
    chain.unshift(parent)
    current = parent
    break if chain.size > 100 # Prevent infinite loops
  end

  chain
end

.clear ⇒ Object

Clear causation (for root events)



55
56
57
# File 'lib/lyra/correlation.rb', line 55

def clear
  Thread.current[:lyra_causation_id] = nil
end

.current_id ⇒ Object

Current causation ID (the event that caused the current operation)



40
41
42
# File 'lib/lyra/correlation.rb', line 40

def current_id
  Thread.current[:lyra_causation_id]
end

.track(cause_event_id, effect_event_id) ⇒ Object

Track causation relationship (for building causation chains)



60
61
62
# File 'lib/lyra/correlation.rb', line 60

def track(cause_event_id, effect_event_id)
  causation_store[effect_event_id] = cause_event_id
end

.with_id(causation_id) ⇒ Object

Set causation ID for current context (when processing/handling an event)



45
46
47
48
49
50
51
52
# File 'lib/lyra/correlation.rb', line 45

def with_id(causation_id)
  previous_id = Thread.current[:lyra_causation_id]
  Thread.current[:lyra_causation_id] = causation_id

  yield causation_id if block_given?
ensure
  Thread.current[:lyra_causation_id] = previous_id
end