libo11y 0.2.0 → 0.3.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.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +170 -21
  3. data/README.md +77 -8
  4. data/lib/libo11y/{proc.rb → child_process.rb} +12 -2
  5. data/lib/libo11y/db.rb +22 -10
  6. data/lib/libo11y/detached.rb +241 -29
  7. data/lib/libo11y/http_client.rb +48 -15
  8. data/lib/libo11y/internal/bridges.rb +3553 -255
  9. data/lib/libo11y/internal/endpoint.rb +7 -1
  10. data/lib/libo11y/internal/env.rb +177 -59
  11. data/lib/libo11y/internal/error_type.rb +17 -0
  12. data/lib/libo11y/internal/histogram_buckets.rb +42 -0
  13. data/lib/libo11y/internal/http_common.rb +2 -0
  14. data/lib/libo11y/internal/identity.rb +10 -1
  15. data/lib/libo11y/internal/injected.rb +178 -0
  16. data/lib/libo11y/internal/logging_device.rb +141 -32
  17. data/lib/libo11y/internal/path_match.rb +148 -0
  18. data/lib/libo11y/internal/pii.rb +185 -65
  19. data/lib/libo11y/internal/pipeline.rb +141 -34
  20. data/lib/libo11y/internal/policy.rb +556 -52
  21. data/lib/libo11y/internal/propagators.rb +29 -6
  22. data/lib/libo11y/internal/quiet_inspect.rb +20 -0
  23. data/lib/libo11y/internal/resource.rb +187 -52
  24. data/lib/libo11y/internal/sdk_load.rb +64 -0
  25. data/lib/libo11y/internal/sql_text.rb +365 -67
  26. data/lib/libo11y/internal/summary.rb +2 -1
  27. data/lib/libo11y/options.rb +159 -1
  28. data/lib/libo11y/rack.rb +257 -44
  29. data/lib/libo11y/record.rb +70 -7
  30. data/lib/libo11y/redact.rb +87 -21
  31. data/lib/libo11y/signals.rb +70 -29
  32. data/lib/libo11y/spec/app_registry.rb +97 -61
  33. data/lib/libo11y/spec/yaml_v3.rb +179 -111
  34. data/lib/libo11y/telemetry.rb +315 -53
  35. data/lib/libo11y/testing.rb +31 -19
  36. data/lib/libo11y/version.rb +1 -1
  37. data/lib/libo11y.rb +1 -1
  38. metadata +94 -39
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "openssl"
4
+ require_relative "../redact"
4
5
 
5
6
  module Libo11y
6
7
  module Internal
@@ -9,6 +10,8 @@ module Libo11y
9
10
  MAX_COMPOSITE_NODES = 2048
10
11
  CANONICAL_TRUNCATED = "truncated"
11
12
  MIN_PII_HASH_KEY_LEN = 32
13
+ # The length of a PII token: "hmac-sha256:" and 32 hex digits.
14
+ TOKEN_LENGTH = 44
12
15
 
13
16
  class Walk
14
17
  def initialize
@@ -23,6 +26,10 @@ module Libo11y
23
26
  true
24
27
  end
25
28
 
29
+ def budget_remaining?
30
+ @remaining.positive?
31
+ end
32
+
26
33
  def enter?(obj)
27
34
  oid = obj.object_id
28
35
  return false if @active.key?(oid)
@@ -59,17 +66,17 @@ module Libo11y
59
66
  if mant.include?(".")
60
67
  int_part, frac_part = mant.split(".", 2)
61
68
  digits_raw = int_part + frac_part
62
- stripped = digits_raw.sub(/\A0+/, "")
69
+ stripped = strip_leading_zeros(digits_raw)
63
70
  leading_zeros = digits_raw.length - stripped.length
64
71
  if int_part == "0"
65
72
  exp -= leading_zeros
66
73
  else
67
74
  exp += int_part.length - 1
68
75
  end
69
- digits = stripped.sub(/0+\z/, "")
76
+ digits = strip_trailing_zeros(stripped)
70
77
  else
71
78
  exp += mant.length - 1
72
- digits = mant.sub(/0+\z/, "")
79
+ digits = strip_trailing_zeros(mant)
73
80
  end
74
81
 
75
82
  return neg ? "-0" : "0" if digits.empty?
@@ -93,35 +100,100 @@ module Libo11y
93
100
  end
94
101
  end
95
102
 
103
+ # Encodes str as a JSON string matching Go's encoding/json: HTML characters
104
+ # (<, >, &) and U+2028/U+2029 are escaped, valid UTF-8 sequences (including
105
+ # a literal U+FFFD) pass through verbatim, and each invalid UTF-8 byte
106
+ # becomes the ASCII escape \ufffd.
96
107
  def encode_json_string(str)
97
- out = +"\""
98
- str.each_char do |ch|
99
- cp = ch.ord
100
- out << case ch
101
- when "\"" then "\\\""
102
- when "\\" then "\\\\"
103
- when "\b" then "\\b"
104
- when "\f" then "\\f"
105
- when "\n" then "\\n"
106
- when "\r" then "\\r"
107
- when "\t" then "\\t"
108
- when "<" then "\\u003c"
109
- when ">" then "\\u003e"
110
- when "&" then "\\u0026"
111
- else
112
- if cp == 0x2028
113
- "\\u2028"
114
- elsif cp == 0x2029
115
- "\\u2029"
116
- elsif cp < 0x20
117
- format("\\u%04x", cp)
118
- else
119
- ch
120
- end
121
- end
108
+ text = utf8_or_binary_bytes(str)
109
+ len = text.bytesize
110
+ out = +"\"".b
111
+ idx = 0
112
+ while idx < len
113
+ byte = text.getbyte(idx)
114
+ if byte < 0x80
115
+ out << encode_ascii_byte(byte)
116
+ idx += 1
117
+ else
118
+ width = utf8_char_width(text, idx, len)
119
+ if width.zero?
120
+ out << "\\ufffd"
121
+ idx += 1
122
+ elsif width == 3 && byte == 0xE2 && text.getbyte(idx + 1) == 0x80 && text.getbyte(idx + 2) == 0xA8
123
+ out << "\\u2028"
124
+ idx += 3
125
+ elsif width == 3 && byte == 0xE2 && text.getbyte(idx + 1) == 0x80 && text.getbyte(idx + 2) == 0xA9
126
+ out << "\\u2029"
127
+ idx += 3
128
+ else
129
+ out << text.byteslice(idx, width)
130
+ idx += width
131
+ end
132
+ end
122
133
  end
123
134
  out << "\""
124
- out
135
+ out.force_encoding(Encoding::UTF_8)
136
+ end
137
+
138
+ def utf8_or_binary_bytes(str)
139
+ return str.b if [Encoding::UTF_8, Encoding::BINARY].include?(str.encoding)
140
+
141
+ str.encode(Encoding::UTF_8, invalid: :replace, undef: :replace).b
142
+ rescue EncodingError
143
+ str.b
144
+ end
145
+
146
+ def encode_ascii_byte(byte)
147
+ case byte
148
+ when 0x22 then "\\\""
149
+ when 0x5C then "\\\\"
150
+ when 0x08 then "\\b"
151
+ when 0x0C then "\\f"
152
+ when 0x0A then "\\n"
153
+ when 0x0D then "\\r"
154
+ when 0x09 then "\\t"
155
+ when 0x3C then "\\u003c"
156
+ when 0x3E then "\\u003e"
157
+ when 0x26 then "\\u0026"
158
+ else
159
+ byte < 0x20 ? format("\\u%04x", byte) : byte.chr
160
+ end
161
+ end
162
+
163
+ def utf8_char_width(bytes, idx, len)
164
+ lead = bytes.getbyte(idx)
165
+ return 0 if idx + 1 >= len
166
+
167
+ second = bytes.getbyte(idx + 1)
168
+ return (second & 0xC0) == 0x80 ? 2 : 0 if lead.between?(0xC2, 0xDF)
169
+ return 0 if idx + 2 >= len
170
+
171
+ third = bytes.getbyte(idx + 2)
172
+ return utf8_three_byte?(lead, second, third) ? 3 : 0 if lead.between?(0xE0, 0xEF)
173
+ return 0 if idx + 3 >= len || !lead.between?(0xF0, 0xF4)
174
+
175
+ fourth = bytes.getbyte(idx + 3)
176
+ utf8_four_byte?(lead, second, third, fourth) ? 4 : 0
177
+ end
178
+
179
+ def utf8_three_byte?(lead, second, third)
180
+ return false unless (third & 0xC0) == 0x80
181
+
182
+ case lead
183
+ when 0xE0 then second.between?(0xA0, 0xBF)
184
+ when 0xED then second.between?(0x80, 0x9F)
185
+ else (second & 0xC0) == 0x80
186
+ end
187
+ end
188
+
189
+ def utf8_four_byte?(lead, second, third, fourth)
190
+ return false unless (third & 0xC0) == 0x80 && (fourth & 0xC0) == 0x80
191
+
192
+ case lead
193
+ when 0xF0 then second.between?(0x90, 0xBF)
194
+ when 0xF4 then second.between?(0x80, 0x8F)
195
+ else (second & 0xC0) == 0x80
196
+ end
125
197
  end
126
198
 
127
199
  def render_json_node(node)
@@ -138,59 +210,107 @@ module Libo11y
138
210
  end
139
211
  end
140
212
 
141
- def build_node(value, depth, walk)
213
+ def build_node(value, depth, walk, floor = :passthrough)
142
214
  return CANONICAL_TRUNCATED if depth > MAX_COMPOSITE_DEPTH || !walk.spend?
215
+ return Redact::REDACTED if floor == :redact
143
216
 
144
217
  case value
145
- when true then "true"
146
- when false then "false"
147
- when Float then canonical_float(value)
148
- when String
149
- if value.encoding == Encoding::BINARY
150
- [value].pack("m0")
151
- else
152
- value
218
+ when nil then ""
219
+ when Redact::Secret then Redact::REDACTED
220
+ when Redact::Masked then value.to_s
221
+ when Redact::Fields then build_fields_node(value, depth, walk, floor)
222
+ when Hash then build_hash_node(value, depth, walk, floor)
223
+ when Array then build_array_node(value, depth, walk, floor)
224
+ else
225
+ return Redact.mask_string(value) if floor == :mask
226
+
227
+ case value
228
+ when true then "true"
229
+ when false then "false"
230
+ when Float then canonical_float(value)
231
+ when String then value.encoding == Encoding::BINARY ? [value].pack("m0") : value
232
+ else value.to_s
153
233
  end
154
- when Hash
155
- return CANONICAL_TRUNCATED unless walk.enter?(value)
234
+ end
235
+ end
156
236
 
157
- begin
158
- pairs = value.map do |k, v|
159
- ks = k.is_a?(String) ? k : k.to_s
160
- [ks.encode(Encoding::UTF_8, invalid: :replace, undef: :replace).b, ks, v]
161
- end
162
- pairs.sort_by!(&:first)
163
- obj = {}
164
- pairs.each do |_, ks, v|
165
- obj[ks] = build_node(v, depth + 1, walk)
237
+ def build_fields_node(value, depth, walk, floor)
238
+ return CANONICAL_TRUNCATED unless walk.enter?(value)
239
+
240
+ begin
241
+ specs = Redact.field_specs(value, floor).map do |name, next_floor|
242
+ ks = name.to_s
243
+ [utf8_or_binary_bytes(ks), ks, name, next_floor]
244
+ end
245
+ specs.sort_by!(&:first)
246
+ obj = {}
247
+ specs.each do |_, ks, name, next_floor|
248
+ if depth + 1 > MAX_COMPOSITE_DEPTH || !walk.budget_remaining?
249
+ obj[ks] = CANONICAL_TRUNCATED
250
+ elsif next_floor == :redact
251
+ walk.spend?
252
+ obj[ks] = Redact::REDACTED
253
+ else
254
+ obj[ks] = build_node(Redact.read_field(value, name), depth + 1, walk, next_floor)
166
255
  end
167
- obj
168
- ensure
169
- walk.leave(value)
170
256
  end
171
- when Array
172
- return CANONICAL_TRUNCATED unless walk.enter?(value)
257
+ obj
258
+ ensure
259
+ walk.leave(value)
260
+ end
261
+ end
262
+
263
+ def build_hash_node(value, depth, walk, floor)
264
+ return CANONICAL_TRUNCATED unless walk.enter?(value)
173
265
 
174
- begin
175
- value.map { |el| build_node(el, depth + 1, walk) }
176
- ensure
177
- walk.leave(value)
266
+ begin
267
+ pairs = value.map do |k, v|
268
+ ks = k.is_a?(String) ? k : k.to_s
269
+ [utf8_or_binary_bytes(ks), ks, v]
178
270
  end
179
- else
180
- value.to_s
271
+ pairs.sort_by!(&:first)
272
+ obj = {}
273
+ pairs.each do |_, ks, v|
274
+ obj[ks] = build_node(v, depth + 1, walk, floor)
275
+ end
276
+ obj
277
+ ensure
278
+ walk.leave(value)
279
+ end
280
+ end
281
+
282
+ def build_array_node(value, depth, walk, floor)
283
+ return CANONICAL_TRUNCATED unless walk.enter?(value)
284
+
285
+ begin
286
+ value.map { |el| build_node(el, depth + 1, walk, floor) }
287
+ ensure
288
+ walk.leave(value)
181
289
  end
182
290
  end
183
291
 
184
- def canonical_value(value)
185
- node = build_node(value, 0, Walk.new)
292
+ def strip_leading_zeros(str)
293
+ idx = 0
294
+ idx += 1 while idx < str.bytesize && str.getbyte(idx) == 48
295
+ str.byteslice(idx, str.bytesize - idx)
296
+ end
297
+
298
+ def strip_trailing_zeros(str)
299
+ stop = str.bytesize
300
+ stop -= 1 while stop.positive? && str.getbyte(stop - 1) == 48
301
+ str.byteslice(0, stop)
302
+ end
303
+
304
+ def canonical_value(value, floor: :passthrough)
305
+ node = build_node(value, 0, Walk.new, floor)
186
306
  return node if node.is_a?(String)
187
307
 
188
308
  render_json_node(node)
189
309
  end
190
310
 
191
- def token(key, value)
192
- canonical = canonical_value(value)
193
- digest = OpenSSL::HMAC.digest("SHA256", key, canonical.encode(Encoding::UTF_8).b)
311
+ def token(key, value, floor: :passthrough)
312
+ canonical = canonical_value(value, floor: floor)
313
+ digest = OpenSSL::HMAC.digest("SHA256", key, utf8_or_binary_bytes(canonical))
194
314
  "hmac-sha256:#{digest.byteslice(0, 16).unpack1("H*")}"
195
315
  end
196
316
  end
@@ -1,11 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "opentelemetry/sdk"
4
- require "opentelemetry-metrics-sdk"
5
- require "opentelemetry-logs-sdk"
3
+ require_relative "sdk_load"
6
4
  require_relative "bridges"
7
5
  require_relative "env"
8
6
  require_relative "histogram_buckets"
7
+ require_relative "injected"
8
+ require_relative "quiet_inspect"
9
9
  require_relative "runtime_metrics"
10
10
 
11
11
  module Libo11y
@@ -15,6 +15,8 @@ module Libo11y
15
15
  # wrapped so that its failures are observed and what it sends is
16
16
  # classified by the sensitivity policy.
17
17
  class Pipeline
18
+ include QuietInspect
19
+
18
20
  SIGNALS = %i[traces metrics logs].freeze
19
21
  EXPORTER_VARIABLES = {
20
22
  traces: "OTEL_TRACES_EXPORTER", metrics: "OTEL_METRICS_EXPORTER", logs: "OTEL_LOGS_EXPORTER"
@@ -26,8 +28,11 @@ module Libo11y
26
28
 
27
29
  # @param built [Array] receives each provider as it is created, so the
28
30
  # caller can stop the ones that exist when a later step raises
29
- def initialize(options:, env_map:, hermetic:, policy:, resource:, violations:, built:)
31
+ # @param injected [InjectedParts] told which signals' injected parts a
32
+ # provider now owns
33
+ def initialize(options:, env_map:, hermetic:, policy:, resource:, violations:, built:, injected:)
30
34
  @options = options
35
+ @injected = injected
31
36
  @env = env_map
32
37
  @hermetic = hermetic
33
38
  # OTEL_SDK_DISABLED beats every exporter, reader and processor, the injected ones included.
@@ -44,9 +49,60 @@ module Libo11y
44
49
  build_traces
45
50
  build_metrics
46
51
  build_logs
52
+ warn_of_refused_limits
53
+ warn_of_cut_tokens
47
54
  self
48
55
  end
49
56
 
57
+ # Says which limit variables of the env hold a value libo11y cannot
58
+ # hand to the OpenTelemetry Ruby SDK, and what applies in their place.
59
+ # A limit is read in base 10, as Go reads it. Go and Python apply a
60
+ # value length limit under 32. The Ruby SDK accepts none, so Ruby
61
+ # applies no limit there.
62
+ def warn_of_refused_limits
63
+ return if @disabled
64
+
65
+ Env.refused_limits(@env).each do |name, value, kind|
66
+ effect = if kind == :length
67
+ "a whole number of #{Env::MIN_VALUE_LENGTH} or more, the least value length limit " \
68
+ "the OpenTelemetry Ruby SDK takes, so no limit applies"
69
+ else
70
+ "a whole number of 1 or more, so the default of 128 applies"
71
+ end
72
+ OpenTelemetry.logger.warn("libo11y: #{name} is #{value.inspect}, which is not #{effect}")
73
+ end
74
+ end
75
+
76
+ # Says what a value length limit does to the tokens of PIIMode::HASH.
77
+ # The limit is the operator's, so libo11y says so and applies it.
78
+ #
79
+ # A span and a record emitted through the OpenTelemetry Logs API are
80
+ # classified after the SDK has cut their values, so a value longer than
81
+ # the limit gets a token of what the SDK left of it (ending in "...").
82
+ # On log records (both Telemetry#logger and the OpenTelemetry Logs API),
83
+ # a limit under a token's 44 characters also cuts the token itself when
84
+ # the SDK writes the record's attributes.
85
+ def warn_of_cut_tokens
86
+ return if @disabled || @policy.pii_mode != PIIMode::HASH
87
+
88
+ log = Env.length_limit_source(@env, Env::LOG_RECORD_LIMIT_VARIABLES.fetch(:attribute_length_limit))
89
+ spans = Env::SPAN_LIMIT_VARIABLES.values_at(:attribute_length_limit, :event_attribute_length_limit)
90
+ .filter_map { |names| Env.length_limit_source(@env, names) }.uniq
91
+ warnings = spans.map do |name, limit|
92
+ "#{name} is #{limit}, and the SDK cuts a longer span value before libo11y hashes it, " \
93
+ "so under pii_mode hash its token is not the one a Telemetry#logger record carries for the same value"
94
+ end
95
+ if log
96
+ warnings << "#{log.first} is #{log.last}, and the SDK cuts a longer OpenTelemetry Logs API attribute value " \
97
+ "before libo11y hashes it, so under pii_mode hash its token is not the one Telemetry#logger or the console carries"
98
+ if log.last < PII::TOKEN_LENGTH
99
+ warnings << "#{log.first} is #{log.last}, under the #{PII::TOKEN_LENGTH} characters of a PII token, " \
100
+ "so the SDK cuts the tokens of pii_mode hash on log records"
101
+ end
102
+ end
103
+ warnings.each { |text| OpenTelemetry.logger.warn("libo11y: #{text}") }
104
+ end
105
+
50
106
  def runtime_metrics?
51
107
  @options.runtime_metrics && !@disabled ? true : false
52
108
  end
@@ -75,11 +131,15 @@ module Libo11y
75
131
  end
76
132
  end
77
133
 
134
+ # The batch size is capped at the queue size, as the OpenTelemetry
135
+ # SDKs of other languages cap it. The Ruby processors raise for a
136
+ # batch larger than the queue.
78
137
  def batch_settings(prefix, schedule_delay:)
138
+ queue = Env.parse_int(@env, "OTEL_#{prefix}_MAX_QUEUE_SIZE", 2048)
79
139
  {
80
140
  schedule_delay: Env.parse_int(@env, "OTEL_#{prefix}_SCHEDULE_DELAY", schedule_delay),
81
- max_queue_size: Env.parse_int(@env, "OTEL_#{prefix}_MAX_QUEUE_SIZE", 2048),
82
- max_export_batch_size: Env.parse_int(@env, "OTEL_#{prefix}_MAX_EXPORT_BATCH_SIZE", 512),
141
+ max_queue_size: queue,
142
+ max_export_batch_size: [Env.parse_int(@env, "OTEL_#{prefix}_MAX_EXPORT_BATCH_SIZE", 512), queue].min,
83
143
  exporter_timeout: Env.parse_int(@env, "OTEL_#{prefix}_EXPORT_TIMEOUT", 30_000),
84
144
  start_thread_on_boot: Env.start_thread_on_boot?(@env, "OTEL_RUBY_#{prefix}_START_THREAD_ON_BOOT")
85
145
  }
@@ -91,7 +151,8 @@ module Libo11y
91
151
  if @disabled
92
152
  Bridges::NoopTracerProvider.new
93
153
  else
94
- OpenTelemetry::SDK::Trace::TracerProvider.new(sampler: sampler, resource: @resource, span_limits: Env.span_limits(@env))
154
+ Bridges::PolicyTracerProvider.new(policy: @policy, failures: @failures.fetch(:traces), owner: @injected, sampler: sampler,
155
+ resource: @resource, span_limits: Env.span_limits(@env))
95
156
  end
96
157
  )
97
158
  # An injected processor owns the export path, as an injected exporter
@@ -101,14 +162,15 @@ module Libo11y
101
162
  return if @disabled
102
163
 
103
164
  exporting = span_export_processor(mode)
104
- @tracer_provider.add_span_processor(exporting) if exporting
105
- # An injected processor gets a redacted view of the finished span. A
106
- # span's violations are counted once: by the exporter path when there
107
- # is one, else by the first injected processor.
108
- processors.each_with_index do |processor, index|
109
- policy = exporting.nil? && index.zero? ? @policy : @policy.silent
110
- @tracer_provider.add_span_processor(Bridges::PolicySpanProcessor.new(processor, policy))
165
+ if exporting
166
+ @tracer_provider.register(Bridges::IsolatedSpanProcessor.new(exporting, @failures.fetch(:traces)))
167
+ # A span's violations are counted once: by the exporter path when
168
+ # there is one, else by the group of injected processors.
169
+ @tracer_provider.export_path_counts!
111
170
  end
171
+ # The provider puts them behind the policy, each once.
172
+ processors.each { |processor| @tracer_provider.add_span_processor(processor) }
173
+ @injected.hand_over(:traces)
112
174
  end
113
175
 
114
176
  def span_export_processor(mode)
@@ -132,13 +194,29 @@ module Libo11y
132
194
  filter = @disabled ? ExemplarFilter::ALWAYS_OFF : Env.parse_exemplar_filter(@options.exemplar_filter, @env)
133
195
  Bridges.configure_exemplar_filter(raw, filter)
134
196
  mode = exporter_mode(:metrics, @options.metric_reader)
197
+ add_views(raw) unless @disabled
198
+
199
+ # The histograms libo11y has a view for, which add_view may not select again.
200
+ bucketed = @disabled ? [] : HistogramBuckets::DEFAULTS.keys | (@options.histogram_buckets || {}).to_h.keys.map(&:to_s)
201
+ @meter_provider = Bridges::PolicyMeterProvider.new(raw, @policy, disabled: @disabled, bucketed: bucketed, views: @views || [],
202
+ failures: @failures.fetch(:metrics), owner: @injected)
203
+ @built.delete_if { |item| item.equal?(raw) }
204
+ track(@meter_provider)
135
205
  unless @disabled
136
206
  reader = metric_reader(mode)
137
- raw.add_metric_reader(reader) if reader
138
- add_views(raw)
207
+ if reader
208
+ begin
209
+ @meter_provider.add_metric_reader(reader)
210
+ rescue StandardError => e
211
+ # Owned by another provider, or already appended to @inner before raising.
212
+ owned_elsewhere = e.is_a?(ArgumentError) && e.message == Bridges::READER_OWNERSHIP_ERROR
213
+ @injected.hand_over(:metrics) if @options.metric_reader && (owned_elsewhere || @meter_provider.attached_reader?(reader))
214
+ raise
215
+ end
216
+ end
217
+ @injected.hand_over(:metrics)
139
218
  end
140
219
 
141
- @meter_provider = Bridges::PolicyMeterProvider.new(raw, @policy)
142
220
  count_violations(raw)
143
221
  RuntimeMetrics.register(@meter_provider) if runtime_metrics?
144
222
  end
@@ -159,49 +237,78 @@ module Libo11y
159
237
  )
160
238
  end
161
239
 
162
- # One view per histogram with boundaries: libo11y's own duration
163
- # histograms, then the histogram_buckets option, which wins for a name
164
- # both give. Then the views option.
240
+ # Registers the boundaries of libo11y's duration histograms and the
241
+ # views option. The SDK writes one stream per matching view, so a view
242
+ # of the caller that selects one of those histograms takes the place
243
+ # of the built-in one.
165
244
  def add_views(raw)
245
+ views = Array(@options.views).map { |view| checked_view(view) }
246
+ views.each_with_index { |view, index| Bridges.refuse_mixed_views(view, views.first(index)) }
247
+ @views = views
166
248
  buckets = HistogramBuckets::DEFAULTS.merge((@options.histogram_buckets || {}).to_h.transform_keys(&:to_s))
167
249
  buckets.each do |name, boundaries|
168
- aggregation = OpenTelemetry::SDK::Metrics::Aggregation::ExplicitBucketHistogram.new(boundaries: Array(boundaries))
169
- raw.add_view(name, type: :histogram, aggregation: aggregation)
250
+ next if views.any? { |view| HistogramBuckets.selected_by?(view, name) }
251
+
252
+ safe_bounds = Bridges.normalize_histogram_boundaries(boundaries, source: "histogram_buckets[#{name.inspect}]")
253
+ aggregation = OpenTelemetry::SDK::Metrics::Aggregation::ExplicitBucketHistogram.new(boundaries: safe_bounds)
254
+ # Selected by its meter too, so a histogram of the same name in
255
+ # the caller's own meter is not given these boundaries.
256
+ scope = HistogramBuckets::SCOPES[name]
257
+ raw.add_view(name, type: :histogram, aggregation: aggregation, **(scope ? { meter_name: scope } : {}))
170
258
  end
171
- Array(@options.views).each do |view|
172
- arguments = view.is_a?(Hash) ? view.transform_keys(&:to_sym) : {}
173
- unless arguments[:name]
174
- raise ArgumentError, "libo11y: views takes Hashes of MeterProvider#add_view arguments with a :name, got #{view.inspect}"
175
- end
259
+ views.each { |view| raw.add_view(view[:name], **view.except(:name)) }
260
+ end
176
261
 
177
- raw.add_view(arguments[:name].to_s, **arguments.except(:name))
262
+ # One entry of the views option, with its added attributes classified.
263
+ #
264
+ # @raise [ArgumentError] for an entry without a :name, and for one
265
+ # Bridges.classified_view refuses
266
+ def checked_view(view)
267
+ arguments = view.is_a?(Hash) ? view.transform_keys(&:to_sym) : {}
268
+ unless arguments[:name]
269
+ raise ArgumentError, "libo11y: views takes Hashes of MeterProvider#add_view arguments with a :name, got #{view.inspect}"
178
270
  end
271
+
272
+ Bridges.classified_view(arguments.merge(name: arguments[:name].to_s), @policy)
179
273
  end
180
274
 
181
275
  # Feeds the o11y.schema.violations counter, the violations recorded
182
276
  # while the resource was built included. It is on the raw provider,
183
277
  # because its own attributes are not subject to the policy.
184
278
  def count_violations(raw)
279
+ unit = "{violation}"
280
+ description = "Specification and sensitivity policy violations."
185
281
  counter = raw.meter("libo11y", version: Libo11y::VERSION).create_counter(
186
- Spec::METRIC_SCHEMA_VIOLATIONS, unit: "{violation}", description: "Specification and sensitivity policy violations."
282
+ Spec::METRIC_SCHEMA_VIOLATIONS, unit: unit, description: description
187
283
  )
284
+ @meter_provider.track_internal_instrument(counter)
188
285
  @violations.attach(lambda do |signal, rule|
189
286
  counter.add(1, attributes: { Spec::ATTR_SIGNAL => signal.to_s, Spec::ATTR_RULE => rule.to_s })
190
287
  end)
191
288
  end
192
289
 
193
290
  def build_logs
291
+ provider = @disabled ? Bridges::DisabledLoggerProvider : Bridges::QuietLoggerProvider
194
292
  @logger_provider = track(
195
- OpenTelemetry::SDK::Logs::LoggerProvider.new(resource: @resource, log_record_limits: Env.log_record_limits(@env))
293
+ provider.new(failures: @failures.fetch(:logs), owner: @injected, resource: @resource, log_record_limits: Env.log_record_limits(@env))
196
294
  )
197
- mode = exporter_mode(:logs, @options.log_exporter)
295
+ # An injected processor owns the export path, as an injected
296
+ # exporter does, so no exporter is built from the environment beside it.
297
+ processors = Array(@options.log_processors)
298
+ mode = exporter_mode(:logs, @options.log_exporter || !processors.empty?)
198
299
  return if @disabled
199
300
 
200
301
  # First, so every later processor sees the classified record.
201
- @logger_provider.add_log_record_processor(Bridges::PolicyLogRecordProcessor.new(@policy))
302
+ @logger_provider.register(Bridges::PolicyLogRecordProcessor.new(@policy))
303
+ # The exporting processor and the injected ones go into the
304
+ # provider's group, which isolates them from one another and takes
305
+ # each once. The exporting processor receives a detached snapshot so
306
+ # later application processors cannot mutate records already queued.
202
307
  exporting = log_export_processor(mode)
203
- @logger_provider.add_log_record_processor(exporting) if exporting
204
- Array(@options.log_processors).each { |processor| @logger_provider.add_log_record_processor(processor) }
308
+ [exporting && Bridges::SnapshotLogRecordProcessor.new(exporting), *processors].compact.each do |processor|
309
+ @logger_provider.add_log_record_processor(processor)
310
+ end
311
+ @injected.hand_over(:logs)
205
312
  end
206
313
 
207
314
  def log_export_processor(mode)