Class: Smplkit::Audit::EventBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/smplkit/audit/buffer.rb

Overview

Bounded in-memory queue + worker thread for fire-and-forget audit emits (ADR-047 ยง2.6).

#enqueue returns immediately. The worker drains on either a periodic tick or once depth crosses the high-water mark, retries transient failures with exponential backoff, drops permanent 4xx (other than 429), and evicts the oldest item under sustained back-pressure.

Constant Summary collapse

MAX_BUFFER_SIZE =
1000
WATERMARK =
50
FLUSH_INTERVAL =
5.0
MAX_ATTEMPTS =
5
INITIAL_BACKOFF =
0.25
MAX_BACKOFF =
8.0

Instance Method Summary collapse

Constructor Details

#initialize(api) ⇒ EventBuffer

Returns a new instance of EventBuffer.



21
22
23
24
25
26
27
28
29
30
# File 'lib/smplkit/audit/buffer.rb', line 21

def initialize(api)
  @api = api
  @queue = []
  @mutex = Mutex.new
  @cond = ConditionVariable.new
  @closed = false
  @dropped_count = 0
  @worker = Thread.new { run }
  @worker.report_on_exception = false
end

Instance Method Details

#close(timeout: 5.0) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/smplkit/audit/buffer.rb', line 64

def close(timeout: 5.0)
  flush(timeout: timeout)
  @mutex.synchronize do
    @closed = true
    @cond.broadcast
  end
  @worker.join(timeout)
end

#enqueue(body, idempotency_key) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/smplkit/audit/buffer.rb', line 32

def enqueue(body, idempotency_key)
  depth = nil
  @mutex.synchronize do
    return if @closed

    if @queue.size >= MAX_BUFFER_SIZE
      @queue.shift
      @dropped_count += 1
      warn "[smplkit.audit] buffer full (size=#{MAX_BUFFER_SIZE}); " \
           "dropped oldest event (total dropped=#{@dropped_count})"
    end
    @queue.push(PendingEvent.new(body, idempotency_key))
    depth = @queue.size
    @cond.signal if depth >= WATERMARK
  end
end

#flush(timeout: 5.0) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/smplkit/audit/buffer.rb', line 49

def flush(timeout: 5.0)
  deadline = monotonic_now + timeout
  loop do
    empty = @mutex.synchronize { @queue.empty? }
    return if empty

    if monotonic_now >= deadline
      warn "[smplkit.audit] flush timed out (timeout=#{timeout}s)"
      return
    end
    @mutex.synchronize { @cond.signal }
    sleep 0.05
  end
end