libo11y 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "opentelemetry"
6
+
7
+ module Libo11y
8
+ # Instrumented Net::HTTP client helper that injects W3C headers without global monkey-patching.
9
+ class HttpClient
10
+ HTTP_DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0].freeze
11
+
12
+ def initialize(telemetry: nil, propagate_fn: nil, peer_service: nil)
13
+ @telemetry = telemetry
14
+ @propagate_fn = propagate_fn
15
+ @peer_service = peer_service
16
+ end
17
+
18
+ def request(method, url, headers: {}, body: nil, open_timeout: 5, read_timeout: 15)
19
+ uri = url.is_a?(URI) ? url : URI.parse(url.to_s)
20
+ verb = method.to_s.upcase
21
+ sanitized_url = strip_credentials(uri)
22
+
23
+ attrs = {
24
+ "http.request.method" => verb,
25
+ "url.full" => sanitized_url,
26
+ "server.address" => uri.host.to_s,
27
+ "server.port" => uri.port
28
+ }
29
+ attrs["peer.service"] = @peer_service.to_s if @peer_service && !@peer_service.to_s.empty?
30
+
31
+ tracer = @telemetry ? @telemetry.tracer("libo11y.http", Libo11y::VERSION) : OpenTelemetry.tracer_provider.tracer("libo11y.http", Libo11y::VERSION)
32
+ meter = @telemetry ? @telemetry.meter("libo11y.http", version: Libo11y::VERSION) : OpenTelemetry.meter_provider.meter("libo11y.http", version: Libo11y::VERSION)
33
+ @duration_hist ||= meter.create_histogram(
34
+ "http.client.request.duration",
35
+ unit: "s",
36
+ description: "Duration of HTTP client requests.",
37
+ explicit_bucket_boundaries: HTTP_DURATION_BUCKETS
38
+ )
39
+
40
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
41
+ tracer.in_span(verb, attributes: attrs, kind: :client) do |span|
42
+ req_headers = headers.transform_keys(&:to_s).transform_values(&:to_s)
43
+ if @propagate_fn.nil? || @propagate_fn.call(uri)
44
+ propagator = @telemetry ? @telemetry.propagator : OpenTelemetry.propagation
45
+ propagator.inject(req_headers)
46
+ end
47
+
48
+ http = Net::HTTP.new(uri.host, uri.port)
49
+ http.use_ssl = uri.scheme == "https"
50
+ http.open_timeout = open_timeout
51
+ http.read_timeout = read_timeout
52
+
53
+ req_class = Net::HTTP.const_get(verb.capitalize)
54
+ req = req_class.new(uri.request_uri)
55
+ req_headers.each { |k, v| req[k] = v }
56
+ req.body = body unless body.nil?
57
+
58
+ status = nil
59
+ error = nil
60
+ begin
61
+ resp = http.request(req)
62
+ status = resp.code.to_i
63
+ span.set_attribute("http.response.status_code", status)
64
+ if status >= 400
65
+ span.status = OpenTelemetry::Trace::Status.error("HTTP #{status}")
66
+ span.set_attribute("error.type", status.to_s)
67
+ end
68
+ resp
69
+ rescue StandardError => e
70
+ error = e
71
+ span.record_exception(e)
72
+ span.status = OpenTelemetry::Trace::Status.error(e.message)
73
+ span.set_attribute("error.type", e.class.name)
74
+ raise
75
+ ensure
76
+ duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
77
+ metric_attrs = {
78
+ "http.request.method" => verb,
79
+ "server.address" => uri.host.to_s,
80
+ "server.port" => uri.port
81
+ }
82
+ metric_attrs["http.response.status_code"] = status if status
83
+ metric_attrs["error.type"] = error ? error.class.name : status.to_s if error || (status && status >= 400)
84
+ @duration_hist.record(duration, attributes: metric_attrs)
85
+ end
86
+ end
87
+ end
88
+
89
+ private
90
+
91
+ def strip_credentials(uri)
92
+ clean = uri.dup
93
+ clean.user = nil
94
+ clean.password = nil
95
+ clean.to_s
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,427 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "opentelemetry/sdk"
4
+ require "opentelemetry-metrics-sdk"
5
+ require "opentelemetry-logs-sdk"
6
+ require "opentelemetry/exporter/otlp"
7
+ require "opentelemetry/exporter/otlp_metrics"
8
+ require "opentelemetry/exporter/otlp_logs"
9
+ require_relative "../errors"
10
+ require_relative "../options"
11
+ require_relative "../spec"
12
+ require_relative "env"
13
+ require_relative "policy"
14
+
15
+ module Libo11y
16
+ module Internal
17
+ module Bridges
18
+ # Wraps any span exporter so span, event, and link attributes pass through SensitivityPolicy once.
19
+ class PolicySpanExporter
20
+ def initialize(inner, policy)
21
+ @inner = inner
22
+ @policy = policy
23
+ end
24
+
25
+ def export(spans, timeout: nil)
26
+ redacted = spans.map { |sd| PolicySpanExporter.redact_span_data(sd, @policy) }
27
+ @inner.export(redacted, timeout: timeout)
28
+ end
29
+
30
+ def force_flush(timeout: nil)
31
+ @inner.force_flush(timeout: timeout)
32
+ end
33
+
34
+ def shutdown(timeout: nil)
35
+ @inner.shutdown(timeout: timeout)
36
+ end
37
+
38
+ def self.redact_span_data(sd, policy)
39
+ attrs, attrs_changed = policy.classify_flat(Spec::Signal::TRACES, sd.attributes)
40
+
41
+ events_changed = false
42
+ new_events = sd.events&.map do |ev|
43
+ ev_attrs, changed = policy.classify_flat(Spec::Signal::TRACES, ev.attributes)
44
+ if changed
45
+ events_changed = true
46
+ OpenTelemetry::SDK::Trace::Event.new(ev.name, ev_attrs, ev.timestamp)
47
+ else
48
+ ev
49
+ end
50
+ end
51
+
52
+ links_changed = false
53
+ new_links = sd.links&.map do |lk|
54
+ lk_attrs, changed = policy.classify_flat(Spec::Signal::TRACES, lk.attributes)
55
+ if changed
56
+ links_changed = true
57
+ OpenTelemetry::Trace::Link.new(lk.span_context, lk_attrs)
58
+ else
59
+ lk
60
+ end
61
+ end
62
+
63
+ return sd unless attrs_changed || events_changed || links_changed
64
+
65
+ OpenTelemetry::SDK::Trace::SpanData.new(
66
+ sd.name,
67
+ sd.kind,
68
+ sd.status,
69
+ sd.parent_span_id,
70
+ sd.total_recorded_attributes,
71
+ sd.total_recorded_events,
72
+ sd.total_recorded_links,
73
+ sd.start_timestamp,
74
+ sd.end_timestamp,
75
+ attrs,
76
+ new_links,
77
+ new_events,
78
+ sd.resource,
79
+ sd.instrumentation_scope,
80
+ sd.span_id,
81
+ sd.trace_id,
82
+ sd.trace_flags,
83
+ sd.tracestate,
84
+ sd.parent_span_is_remote
85
+ )
86
+ end
87
+ end
88
+
89
+ # Wraps an injected SpanProcessor so on_finish receives redacted span data.
90
+ class PolicySpanProcessor
91
+ def initialize(inner, policy)
92
+ @inner = inner
93
+ @policy = policy
94
+ end
95
+
96
+ def on_start(span, parent_context)
97
+ @inner.on_start(span, parent_context)
98
+ end
99
+
100
+ def on_finish(span)
101
+ redacted = RedactedSpanView.new(span, @policy)
102
+ @inner.on_finish(redacted)
103
+ end
104
+
105
+ def force_flush(timeout: nil)
106
+ @inner.force_flush(timeout: timeout)
107
+ end
108
+
109
+ def shutdown(timeout: nil)
110
+ @inner.shutdown(timeout: timeout)
111
+ end
112
+ end
113
+
114
+ # A finished span as an injected processor sees it. Every accessor that
115
+ # carries attributes (attributes, events, links, to_span_data) returns
116
+ # the redacted values, and the rest delegate to the span.
117
+ class RedactedSpanView
118
+ def initialize(span, policy)
119
+ @span = span
120
+ @policy = policy
121
+ end
122
+
123
+ def to_span_data
124
+ @to_span_data ||= PolicySpanExporter.redact_span_data(@span.to_span_data, @policy)
125
+ end
126
+
127
+ def attributes
128
+ to_span_data.attributes
129
+ end
130
+
131
+ def events
132
+ to_span_data.events
133
+ end
134
+
135
+ def links
136
+ to_span_data.links
137
+ end
138
+
139
+ def method_missing(name, ...)
140
+ @span.public_send(name, ...)
141
+ end
142
+
143
+ def respond_to_missing?(name, include_private = false)
144
+ @span.respond_to?(name, include_private)
145
+ end
146
+ end
147
+
148
+ # The first processor on the logger provider. It classifies the
149
+ # attributes of a record that reached the provider through the
150
+ # OpenTelemetry Logs API, in place, so every later processor sees the
151
+ # classified record. A record from the libo11y logger is already
152
+ # classified and counted, and its context says so.
153
+ class PolicyLogRecordProcessor
154
+ CLASSIFIED_KEY = OpenTelemetry::Context.create_key("libo11y-log-classified")
155
+
156
+ # Returns context marked as carrying a record the libo11y logger classified.
157
+ def self.mark_classified(context)
158
+ context.set_value(CLASSIFIED_KEY, true)
159
+ end
160
+
161
+ def initialize(policy)
162
+ @policy = policy
163
+ end
164
+
165
+ def on_emit(log_record, context)
166
+ return if context&.value(CLASSIFIED_KEY)
167
+
168
+ attrs = log_record.attributes
169
+ log_record.attributes = @policy.classify_log_attributes(attrs) unless attrs.nil? || attrs.empty?
170
+ end
171
+
172
+ def force_flush(timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
173
+ OpenTelemetry::SDK::Logs::Export::SUCCESS
174
+ end
175
+
176
+ def shutdown(timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
177
+ OpenTelemetry::SDK::Logs::Export::SUCCESS
178
+ end
179
+ end
180
+
181
+ # Policy-enforcing MeterProvider wrapper: classifies attributes before SDK recording so
182
+ # every derived View stream and every Exemplar receives filtered attributes (PII always dropped).
183
+ class PolicyMeterProvider
184
+ def initialize(inner, policy)
185
+ @inner = inner
186
+ @policy = policy
187
+ @mutex = Mutex.new
188
+ @meters = {}
189
+ end
190
+
191
+ def meter(name, version: nil, attributes: nil)
192
+ key = [name, version, attributes]
193
+ @mutex.synchronize do
194
+ @meters[key] ||= PolicyMeter.new(@inner.meter(name, version: version, attributes: attributes), @policy)
195
+ end
196
+ end
197
+
198
+ def add_metric_reader(reader)
199
+ @inner.add_metric_reader(reader)
200
+ end
201
+
202
+ def add_view(*, **)
203
+ @inner.add_view(*, **)
204
+ end
205
+
206
+ def resource
207
+ @inner.resource
208
+ end
209
+
210
+ def metric_readers
211
+ @inner.metric_readers
212
+ end
213
+
214
+ def exemplar_filter
215
+ @inner.exemplar_filter
216
+ end
217
+
218
+ def shutdown(timeout: nil)
219
+ @inner.shutdown(timeout: timeout)
220
+ end
221
+
222
+ def force_flush(timeout: nil)
223
+ @inner.force_flush(timeout: timeout)
224
+ end
225
+
226
+ def sdk_provider
227
+ @inner
228
+ end
229
+ end
230
+
231
+ class PolicyMeter
232
+ def initialize(inner, policy)
233
+ @inner = inner
234
+ @policy = policy
235
+ end
236
+
237
+ def create_counter(name, unit: nil, description: nil)
238
+ PolicySyncInstrument.new(@inner.create_counter(name, unit: unit, description: description), @policy)
239
+ end
240
+
241
+ def create_up_down_counter(name, unit: nil, description: nil)
242
+ PolicySyncInstrument.new(@inner.create_up_down_counter(name, unit: unit, description: description), @policy)
243
+ end
244
+
245
+ def create_histogram(name, unit: nil, description: nil, explicit_bucket_boundaries: nil)
246
+ inst = if explicit_bucket_boundaries
247
+ @inner.create_histogram(
248
+ name,
249
+ unit: unit,
250
+ description: description,
251
+ advisory: { explicit_bucket_boundaries: explicit_bucket_boundaries }
252
+ )
253
+ else
254
+ @inner.create_histogram(name, unit: unit, description: description)
255
+ end
256
+ PolicySyncInstrument.new(inst, @policy)
257
+ end
258
+
259
+ def create_gauge(name, unit: nil, description: nil)
260
+ PolicySyncInstrument.new(@inner.create_gauge(name, unit: unit, description: description), @policy)
261
+ end
262
+
263
+ # An observable instrument's callbacks take no argument and return a
264
+ # number, so its attributes come only through add_attributes and
265
+ # observe, which the wrapper classifies.
266
+ def create_observable_counter(name, callback: nil, unit: nil, description: nil)
267
+ PolicyAsyncInstrument.new(@inner.create_observable_counter(name, callback: callback, unit: unit, description: description), @policy)
268
+ end
269
+
270
+ def create_observable_up_down_counter(name, callback: nil, unit: nil, description: nil)
271
+ PolicyAsyncInstrument.new(
272
+ @inner.create_observable_up_down_counter(name, callback: callback, unit: unit, description: description), @policy
273
+ )
274
+ end
275
+
276
+ def create_observable_gauge(name, callback: nil, unit: nil, description: nil)
277
+ PolicyAsyncInstrument.new(@inner.create_observable_gauge(name, callback: callback, unit: unit, description: description), @policy)
278
+ end
279
+
280
+ def method_missing(name, ...)
281
+ @inner.public_send(name, ...)
282
+ end
283
+
284
+ def respond_to_missing?(name, include_private = false)
285
+ @inner.respond_to?(name, include_private)
286
+ end
287
+ end
288
+
289
+ # Wraps an observable instrument so the attributes it is given are
290
+ # classified before the SDK records them.
291
+ class PolicyAsyncInstrument
292
+ def initialize(inner, policy)
293
+ @inner = inner
294
+ @policy = policy
295
+ end
296
+
297
+ def add_attributes(attributes)
298
+ @inner.add_attributes(@policy.classify_metric_attrs(attributes))
299
+ end
300
+
301
+ def observe(timeout: nil, attributes: {})
302
+ @inner.observe(timeout: timeout, attributes: @policy.classify_metric_attrs(attributes))
303
+ end
304
+
305
+ def method_missing(name, ...)
306
+ @inner.public_send(name, ...)
307
+ end
308
+
309
+ def respond_to_missing?(name, include_private = false)
310
+ @inner.respond_to?(name, include_private)
311
+ end
312
+ end
313
+
314
+ class PolicySyncInstrument
315
+ def initialize(inner, policy)
316
+ @inner = inner
317
+ @policy = policy
318
+ end
319
+
320
+ def add(increment, attributes: {})
321
+ @inner.add(increment, attributes: @policy.classify_metric_attrs(attributes))
322
+ end
323
+
324
+ def record(amount, attributes: {})
325
+ @inner.record(amount, attributes: @policy.classify_metric_attrs(attributes))
326
+ end
327
+
328
+ def method_missing(name, ...)
329
+ @inner.public_send(name, ...)
330
+ end
331
+
332
+ def respond_to_missing?(name, include_private = false)
333
+ @inner.respond_to?(name, include_private)
334
+ end
335
+ end
336
+
337
+ module_function
338
+
339
+ def build_sampler(opt_sampler, env_map)
340
+ return opt_sampler unless opt_sampler.nil?
341
+
342
+ raw = env_map["OTEL_TRACES_SAMPLER"]
343
+ return OpenTelemetry::SDK::Trace::Samplers.parent_based(root: OpenTelemetry::SDK::Trace::Samplers::ALWAYS_ON) if raw.nil? || raw.strip.empty?
344
+
345
+ arg = env_map["OTEL_TRACES_SAMPLER_ARG"].to_s.strip
346
+ case raw.strip.downcase
347
+ when "always_on"
348
+ OpenTelemetry::SDK::Trace::Samplers::ALWAYS_ON
349
+ when "always_off"
350
+ OpenTelemetry::SDK::Trace::Samplers::ALWAYS_OFF
351
+ when "traceidratio"
352
+ OpenTelemetry::SDK::Trace::Samplers.trace_id_ratio_based(parse_ratio(arg))
353
+ when "parentbased_always_on"
354
+ OpenTelemetry::SDK::Trace::Samplers.parent_based(root: OpenTelemetry::SDK::Trace::Samplers::ALWAYS_ON)
355
+ when "parentbased_always_off"
356
+ OpenTelemetry::SDK::Trace::Samplers.parent_based(root: OpenTelemetry::SDK::Trace::Samplers::ALWAYS_OFF)
357
+ when "parentbased_traceidratio"
358
+ OpenTelemetry::SDK::Trace::Samplers.parent_based(
359
+ root: OpenTelemetry::SDK::Trace::Samplers.trace_id_ratio_based(parse_ratio(arg))
360
+ )
361
+ else
362
+ raise ExporterError, "o11y: unsupported trace sampler #{raw.inspect}"
363
+ end
364
+ end
365
+
366
+ def parse_ratio(arg)
367
+ val = Float(arg)
368
+ raise ExporterError, "o11y: invalid trace ratio #{arg.inspect}" if val.nan? || val.negative? || val > 1.0
369
+
370
+ val
371
+ rescue ArgumentError
372
+ raise ExporterError, "o11y: invalid trace ratio #{arg.inspect}"
373
+ end
374
+
375
+ def configure_exemplar_filter(meter_provider, filter_sym)
376
+ case filter_sym
377
+ when ExemplarFilter::ALWAYS_ON
378
+ meter_provider.enable_exemplar_filter(
379
+ exemplar_filter: OpenTelemetry::SDK::Metrics::Exemplar::AlwaysOnExemplarFilter
380
+ )
381
+ when ExemplarFilter::ALWAYS_OFF
382
+ meter_provider.disable_exemplar_filter
383
+ else
384
+ meter_provider.enable_exemplar_filter(
385
+ exemplar_filter: OpenTelemetry::SDK::Metrics::Exemplar::TraceBasedExemplarFilter
386
+ )
387
+ end
388
+ end
389
+
390
+ def build_otlp_trace_exporter(env_map)
391
+ Env.parse_protocol(env_map, "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")
392
+ tls = Env.signal_tls(env_map, "OTEL_EXPORTER_OTLP_TRACES")
393
+ OpenTelemetry::Exporter::OTLP::Exporter.new(
394
+ endpoint: Env.signal_endpoint(env_map, "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "/v1/traces"),
395
+ headers: Env.signal_headers(env_map, "OTEL_EXPORTER_OTLP_TRACES_HEADERS"),
396
+ compression: Env.signal_compression(env_map, "OTEL_EXPORTER_OTLP_TRACES_COMPRESSION"),
397
+ timeout: Env.signal_timeout(env_map, "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT"),
398
+ **tls
399
+ )
400
+ end
401
+
402
+ def build_otlp_metric_exporter(env_map)
403
+ Env.parse_protocol(env_map, "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL")
404
+ tls = Env.signal_tls(env_map, "OTEL_EXPORTER_OTLP_METRICS")
405
+ OpenTelemetry::Exporter::OTLP::Metrics::MetricsExporter.new(
406
+ endpoint: Env.signal_endpoint(env_map, "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "/v1/metrics"),
407
+ headers: Env.signal_headers(env_map, "OTEL_EXPORTER_OTLP_METRICS_HEADERS"),
408
+ compression: Env.signal_compression(env_map, "OTEL_EXPORTER_OTLP_METRICS_COMPRESSION"),
409
+ timeout: Env.signal_timeout(env_map, "OTEL_EXPORTER_OTLP_METRICS_TIMEOUT"),
410
+ **tls
411
+ )
412
+ end
413
+
414
+ def build_otlp_log_exporter(env_map)
415
+ Env.parse_protocol(env_map, "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")
416
+ tls = Env.signal_tls(env_map, "OTEL_EXPORTER_OTLP_LOGS")
417
+ OpenTelemetry::Exporter::OTLP::Logs::LogsExporter.new(
418
+ endpoint: Env.signal_endpoint(env_map, "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "/v1/logs"),
419
+ headers: Env.signal_headers(env_map, "OTEL_EXPORTER_OTLP_LOGS_HEADERS"),
420
+ compression: Env.signal_compression(env_map, "OTEL_EXPORTER_OTLP_LOGS_COMPRESSION"),
421
+ timeout: Env.signal_timeout(env_map, "OTEL_EXPORTER_OTLP_LOGS_TIMEOUT"),
422
+ **tls
423
+ )
424
+ end
425
+ end
426
+ end
427
+ end