Class: Trevosdk::EventBatcher
- Inherits:
-
Object
- Object
- Trevosdk::EventBatcher
- Defined in:
- lib/trevosdk/batcher.rb
Overview
Bounded background delivery mirroring the node SDK's EventBatcher semantics.
Instance Method Summary collapse
- #enqueue(event) ⇒ Object
-
#flush ⇒ Object
Sends everything queued; raises on delivery failure so callers get a real guarantee.
-
#initialize(ingestion_url:, secret_key:, max_batch_size:, flush_interval_s:, transport:, on_error:) ⇒ EventBatcher
constructor
A new instance of EventBatcher.
-
#shutdown ⇒ Object
Stops the worker and flushes once; never raises — this runs from exit hooks.
- #start ⇒ Object
Constructor Details
#initialize(ingestion_url:, secret_key:, max_batch_size:, flush_interval_s:, transport:, on_error:) ⇒ EventBatcher
Returns a new instance of EventBatcher.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/trevosdk/batcher.rb', line 11 def initialize(ingestion_url:, secret_key:, max_batch_size:, flush_interval_s:, transport:, on_error:) @ingestion_url = ingestion_url @secret_key = secret_key @batch_size = [max_batch_size, SERVER_MAX_BATCH_SIZE].min @flush_interval_s = flush_interval_s @transport = transport @on_error = on_error @queue = [] @mutex = Mutex.new @send_mutex = Mutex.new @wake_mutex = Mutex.new @wake_cv = ConditionVariable.new @wake_flag = false @stopped = false @dropped = 0 @worker = nil end |
Instance Method Details
#enqueue(event) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/trevosdk/batcher.rb', line 36 def enqueue(event) first_drop = false over_batch = false @mutex.synchronize do return if @stopped if @queue.length >= MAX_QUEUE_SIZE # Drop oldest: an outage should cost the stalest events, not the newest. @queue.shift @dropped += 1 first_drop = @dropped == 1 end @queue.push(event) over_batch = @queue.length >= @batch_size end if first_drop @on_error.call(RuntimeError.new("Trevo event queue full at #{MAX_QUEUE_SIZE}; dropping oldest events")) end wake! if over_batch end |
#flush ⇒ Object
Sends everything queued; raises on delivery failure so callers get a real guarantee.
57 58 59 |
# File 'lib/trevosdk/batcher.rb', line 57 def flush @send_mutex.synchronize { drain } end |
#shutdown ⇒ Object
Stops the worker and flushes once; never raises — this runs from exit hooks.
62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/trevosdk/batcher.rb', line 62 def shutdown @mutex.synchronize { @stopped = true } wake! @worker&.join(@flush_interval_s + 1) @worker = nil begin flush rescue => error @on_error.call(error) end end |
#start ⇒ Object
30 31 32 33 34 |
# File 'lib/trevosdk/batcher.rb', line 30 def start return unless @worker.nil? @worker = Thread.new { run } @worker.name = "trevosdk-batcher" end |