Class: Tracekit::Metrics::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/tracekit/metrics/registry.rb

Overview

Registry for managing metrics and exporting them to TraceKit Implements automatic buffering and periodic export (100 metrics or 10 seconds)

Constant Summary collapse

MAX_BUFFER_SIZE =
100
FLUSH_INTERVAL_SECONDS =
10

Instance Method Summary collapse

Constructor Details

#initialize(endpoint, api_key, service_name) ⇒ Registry

Returns a new instance of Registry.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/tracekit/metrics/registry.rb', line 14

def initialize(endpoint, api_key, service_name)
  @endpoint = endpoint
  @api_key = api_key
  @service_name = service_name
  @buffer = Concurrent::Array.new
  @exporter = Exporter.new(endpoint, api_key, service_name)
  @flush_mutex = Mutex.new

  # Start periodic flush timer
  @flush_task = Concurrent::TimerTask.new(execution_interval: FLUSH_INTERVAL_SECONDS) do
    flush
  end
  @flush_task.execute
end

Instance Method Details

#flushObject

Flushes all buffered metrics



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/tracekit/metrics/registry.rb', line 45

def flush
  return if @buffer.empty?

  @flush_mutex.synchronize do
    return if @buffer.empty?

    data_points = @buffer.dup
    @buffer.clear

    begin
      @exporter.export(data_points)
    rescue => e
      warn "Failed to export metrics: #{e.message}"
    end
  end
end

#record_metric(name, type, value, tags) ⇒ Object

Records a metric data point



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/tracekit/metrics/registry.rb', line 30

def record_metric(name, type, value, tags)
  data_point = MetricDataPoint.new(
    name: name,
    type: type,
    value: value,
    tags: tags.dup
  )

  @buffer << data_point

  # Auto-flush if buffer is full
  flush if @buffer.size >= MAX_BUFFER_SIZE
end

#shutdownObject

Shuts down the registry and flushes remaining metrics



63
64
65
66
# File 'lib/tracekit/metrics/registry.rb', line 63

def shutdown
  @flush_task&.shutdown
  flush
end