Module: MetrixWire::Instrument::Helpers
- Defined in:
- lib/metrixwire/instrument/helpers.rb
Overview
Shared helpers used by every low-level patch (PG, mysql2, Net::HTTP, …). These attach spans to the current trace only; if there's no active trace (work outside a request), they no-op. Never throw.
Class Method Summary collapse
-
.add_span(type, description, duration_ms, meta: nil, source_location: :auto) ⇒ Object
Add a span to the active trace.
-
.db_query(sql) ⇒ Object
Time a block, then record a db_query span.
-
.extract_row_count(result) ⇒ Object
Best-effort row count across PG::Result / Mysql2::Result / Array / etc.
- .row_count_meta(result) ⇒ Object
Class Method Details
.add_span(type, description, duration_ms, meta: nil, source_location: :auto) ⇒ Object
Add a span to the active trace. duration_ms is a float; description is
e.g. the SQL text or "GET https://host/path".
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/metrixwire/instrument/helpers.rb', line 13 def add_span(type, description, duration_ms, meta: nil, source_location: :auto) trace = Context.current return if trace.nil? || description.nil? || description.to_s.empty? loc = source_location == :auto ? SourceLocation.nearest : source_location span = Span.new( type: type, description: description.to_s, started_at: MetrixWire.iso8601(Time.now - (duration_ms / 1000.0)), duration_ms: [duration_ms, 0].max.round, source_location: loc, meta: ( && !.empty? ? : nil) ) trace.add_span(span) rescue StandardError # instrumentation must never throw end |
.db_query(sql) ⇒ Object
Time a block, then record a db_query span. Returns the block's result.
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/metrixwire/instrument/helpers.rb', line 32 def db_query(sql) return yield if Context.current.nil? t0 = MetrixWire.monotonic_ms result = yield add_span("db_query", sql, MetrixWire.monotonic_ms - t0, meta: (result)) result rescue StandardError raise end |
.extract_row_count(result) ⇒ Object
Best-effort row count across PG::Result / Mysql2::Result / Array / etc.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/metrixwire/instrument/helpers.rb', line 51 def extract_row_count(result) if result.respond_to?(:cmd_tuples) && result.respond_to?(:ntuples) # PG::Result: prefer affected rows for writes, tuple count for reads. nt = result.ntuples return nt if nt && nt > 0 ct = result.cmd_tuples return ct if ct && ct >= 0 nt elsif result.respond_to?(:count) && !result.is_a?(String) result.count elsif result.respond_to?(:size) result.size end rescue StandardError nil end |
.row_count_meta(result) ⇒ Object
43 44 45 46 47 48 |
# File 'lib/metrixwire/instrument/helpers.rb', line 43 def (result) n = extract_row_count(result) n.nil? ? nil : { rowCount: n } rescue StandardError nil end |