Module: Lyra::Consistency::ReadYourWrites

Defined in:
lib/lyra/consistency/read_your_writes.rb

Overview

Read-Your-Writes consistency helper for event_sourcing mode.

When using async projections, there's a window where a record might exist in the event store but not yet in the database. This helper ensures that within a block, any writes are immediately projected before reads happen.

Usage:

Lyra::Consistency::ReadYourWrites.with_guaranteed_read do
@registration = Registration.create!(params)
redirect_to @registration  # Guaranteed to find it
end

Class Method Summary collapse

Class Method Details

.in_guaranteed_block?Boolean

Check if we're in a guaranteed read block

Returns:

  • (Boolean)


48
49
50
# File 'lib/lyra/consistency/read_your_writes.rb', line 48

def in_guaranteed_block?
  !Thread.current[:lyra_pending_writes].nil?
end

.record_write(model_class, operation, result) ⇒ Object

Record a write that needs projection (called by interceptor)



40
41
42
43
44
45
# File 'lib/lyra/consistency/read_your_writes.rb', line 40

def record_write(model_class, operation, result)
  pending = Thread.current[:lyra_pending_writes]
  return unless pending

  pending << { model_class: model_class, operation: operation, result: result }
end

.with_guaranteed_readObject

Execute block with read-your-writes guarantee

Tracks any writes within the block and ensures they are projected before the block returns.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/lyra/consistency/read_your_writes.rb', line 24

def with_guaranteed_read
  return yield unless Lyra.event_sourcing_mode?

  # Store pending writes in thread-local storage
  Thread.current[:lyra_pending_writes] = []

  begin
    result = yield
    ensure_projected
    result
  ensure
    Thread.current[:lyra_pending_writes] = nil
  end
end