Class: Synthra::APIServer::Metrics
- Inherits:
-
Object
- Object
- Synthra::APIServer::Metrics
- Defined in:
- lib/synthra/api_server.rb
Overview
Simple metrics collector
Instance Method Summary collapse
-
#initialize ⇒ Metrics
constructor
A new instance of Metrics.
- #percentile(array, p) ⇒ Object private
- #record(path:, method:, status:, duration:) ⇒ Object
- #to_h ⇒ Object
Constructor Details
#initialize ⇒ Metrics
Returns a new instance of Metrics.
479 480 481 482 483 484 |
# File 'lib/synthra/api_server.rb', line 479 def initialize @requests = Hash.new(0) @durations = Hash.new { |h, k| h[k] = [] } @errors = Hash.new(0) @mutex = Mutex.new end |
Instance Method Details
#percentile(array, p) ⇒ Object (private)
515 516 517 518 519 520 |
# File 'lib/synthra/api_server.rb', line 515 def percentile(array, p) return 0 if array.empty? sorted = array.sort k = (p / 100.0 * (sorted.length - 1)).floor sorted[k] end |
#record(path:, method:, status:, duration:) ⇒ Object
486 487 488 489 490 491 492 493 |
# File 'lib/synthra/api_server.rb', line 486 def record(path:, method:, status:, duration:) @mutex.synchronize do key = "#{method} #{path}" @requests[key] += 1 @durations[key] << duration @errors[key] += 1 if status >= 400 end end |
#to_h ⇒ Object
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
# File 'lib/synthra/api_server.rb', line 495 def to_h @mutex.synchronize do { total_requests: @requests.values.sum, endpoints: @requests.map do |key, count| durations = @durations[key] { endpoint: key, requests: count, errors: @errors[key], avg_duration_ms: (durations.sum / durations.length * 1000).round(2), p99_duration_ms: (percentile(durations, 99) * 1000).round(2) } end } end end |