Class: MetrixWire::Transport

Inherits:
Object
  • Object
show all
Defined in:
lib/metrixwire/transport.rb

Overview

Batches finished traces on an in-memory Queue and flushes them to the ingest endpoint from a background daemon Thread. Every network path is wrapped so a dead or slow MetrixWire API can never crash or block the host app: short timeout, all errors swallowed, sends happen off the request path. A final flush runs at_exit.

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Transport

Returns a new instance of Transport.



15
16
17
18
19
20
21
22
23
# File 'lib/metrixwire/transport.rb', line 15

def initialize(config)
  @config = config
  @queue = Queue.new
  @buffer = []
  @mutex = Mutex.new
  @thread = nil
  @stopping = false
  @uri = safe_uri(config.endpoint)
end

Instance Method Details

#enqueue(trace) ⇒ Object

Enqueue a finished trace. Non-blocking. Flushes immediately once the batch threshold is reached.



41
42
43
44
45
46
47
48
# File 'lib/metrixwire/transport.rb', line 41

def enqueue(trace)
  return unless @config.enabled

  @queue << trace
  @signal_flush = true if @queue.size >= @config.max_batch
rescue StandardError
  # swallow — monitoring must never break the app
end

#flush_syncObject

Synchronous flush of everything currently queued. Safe to call anytime.



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/metrixwire/transport.rb', line 51

def flush_sync
  drain_queue
  batch = nil
  @mutex.synchronize do
    return if @buffer.empty?

    batch = @buffer.slice!(0, @buffer.length)
  end
  send_batch(batch) if batch && !batch.empty?
rescue StandardError
  # swallow
end

#startObject



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/metrixwire/transport.rb', line 25

def start
  return unless @config.enabled
  return if @thread&.alive?

  @thread = Thread.new { run_loop }
  @thread.name = "metrixwire-transport" if @thread.respond_to?(:name=)
  @thread.abort_on_exception = false

  # Last-chance flush on process exit.
  at_exit { flush_sync }
rescue StandardError
  # never let startup break the host app
end