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,266 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "logger"
5
+ require "opentelemetry"
6
+ require_relative "../spec"
7
+ require_relative "bridges"
8
+
9
+ module Libo11y
10
+ FORCE_EMIT_FIBER_KEY = :libo11y_force_emit
11
+ REENTRY_FIBER_KEY = :libo11y_logging_reentry
12
+
13
+ def self.force_emit
14
+ prev = Thread.current[FORCE_EMIT_FIBER_KEY]
15
+ Thread.current[FORCE_EMIT_FIBER_KEY] = true
16
+ return true unless block_given?
17
+
18
+ begin
19
+ yield
20
+ ensure
21
+ Thread.current[FORCE_EMIT_FIBER_KEY] = prev
22
+ end
23
+ end
24
+
25
+ def self.force_emit?
26
+ Thread.current[FORCE_EMIT_FIBER_KEY] == true
27
+ end
28
+
29
+ module Internal
30
+ # Structured logging facade built on Ruby's standard ::Logger.
31
+ # Correlates every record with the active OpenTelemetry span context, applies attr_replacer
32
+ # followed by SensitivityPolicy, and fans out to JSON console, OTLP logs, and extra sinks.
33
+ class StructuredLogger < ::Logger
34
+ SEVERITY_TO_OTEL = {
35
+ ::Logger::DEBUG => [5, "DEBUG"],
36
+ ::Logger::INFO => [9, "INFO"],
37
+ ::Logger::WARN => [13, "WARN"],
38
+ ::Logger::ERROR => [17, "ERROR"],
39
+ ::Logger::FATAL => [21, "FATAL"],
40
+ ::Logger::UNKNOWN => [9, "INFO"]
41
+ }.freeze
42
+
43
+ def initialize(
44
+ policy:,
45
+ otel_logger: nil,
46
+ console_writer: $stdout,
47
+ console_enabled: true,
48
+ console_level: ::Logger::INFO,
49
+ attr_replacer: nil,
50
+ extra_sinks: []
51
+ )
52
+ super(nil)
53
+ @policy = policy
54
+ @otel_logger = otel_logger
55
+ @console_writer = console_writer
56
+ @console_enabled = console_enabled
57
+ @console_level = console_level
58
+ @attr_replacer = attr_replacer
59
+ @extra_sinks = Array(extra_sinks).dup
60
+ @mutex = Mutex.new
61
+ self.level = ::Logger::DEBUG
62
+ end
63
+
64
+ def add(severity, message = nil, progname = nil, &)
65
+ severity ||= ::Logger::UNKNOWN
66
+ return true if Thread.current[REENTRY_FIBER_KEY]
67
+
68
+ force = Libo11y.force_emit?
69
+ return true if !force && severity < @console_level && @otel_logger.nil? && @extra_sinks.empty?
70
+
71
+ if message.nil?
72
+ if block_given?
73
+ message = yield
74
+ else
75
+ message = progname
76
+ @progname
77
+ end
78
+ end
79
+
80
+ body, attrs = extract_message_and_attrs(message)
81
+ emit_record(
82
+ severity: severity,
83
+ body: body,
84
+ attrs: attrs,
85
+ event_name: nil,
86
+ force: force,
87
+ raise_on_sink_error: false
88
+ )
89
+ true
90
+ end
91
+
92
+ def log_with_attrs(severity, body, attrs = {}, event_name: nil, force: nil, raise_on_sink_error: false)
93
+ forced = force.nil? ? Libo11y.force_emit? : force
94
+ emit_record(
95
+ severity: severity,
96
+ body: body.to_s,
97
+ attrs: attrs || {},
98
+ event_name: event_name,
99
+ force: forced,
100
+ raise_on_sink_error: raise_on_sink_error
101
+ )
102
+ end
103
+
104
+ def debug(progname = nil, attrs = nil, &)
105
+ return log_with_attrs(::Logger::DEBUG, progname, attrs) if attrs.is_a?(Hash)
106
+
107
+ super(progname, &)
108
+ end
109
+
110
+ def info(progname = nil, attrs = nil, &)
111
+ return log_with_attrs(::Logger::INFO, progname, attrs) if attrs.is_a?(Hash)
112
+
113
+ super(progname, &)
114
+ end
115
+
116
+ def warn(progname = nil, attrs = nil, &)
117
+ return log_with_attrs(::Logger::WARN, progname, attrs) if attrs.is_a?(Hash)
118
+
119
+ super(progname, &)
120
+ end
121
+
122
+ def error(progname = nil, attrs = nil, &)
123
+ return log_with_attrs(::Logger::ERROR, progname, attrs) if attrs.is_a?(Hash)
124
+
125
+ super(progname, &)
126
+ end
127
+
128
+ def fatal(progname = nil, attrs = nil, &)
129
+ return log_with_attrs(::Logger::FATAL, progname, attrs) if attrs.is_a?(Hash)
130
+
131
+ super(progname, &)
132
+ end
133
+
134
+ private
135
+
136
+ def extract_message_and_attrs(message)
137
+ if message.is_a?(Hash)
138
+ dup = message.dup
139
+ body = dup.delete(:msg) || dup.delete("msg") || dup.delete(:message) || dup.delete("message") || ""
140
+ [body.to_s, dup]
141
+ else
142
+ [message.to_s, {}]
143
+ end
144
+ end
145
+
146
+ def emit_record(severity:, body:, attrs:, event_name:, force:, raise_on_sink_error:)
147
+ return if Thread.current[REENTRY_FIBER_KEY]
148
+
149
+ Thread.current[REENTRY_FIBER_KEY] = true
150
+ begin
151
+ now = Time.now.utc
152
+ sev_num, sev_text = SEVERITY_TO_OTEL.fetch(severity, [9, "INFO"])
153
+
154
+ span_ctx = OpenTelemetry::Trace.current_span.context
155
+ trace_id = span_ctx.valid? ? span_ctx.hex_trace_id : nil
156
+ span_id = span_ctx.valid? ? span_ctx.hex_span_id : nil
157
+
158
+ full_attrs = {}
159
+ attrs&.each { |k, v| full_attrs[k.to_s] = v }
160
+ full_attrs[Spec::EVENT_NAME_KEY] = event_name if event_name && !event_name.empty?
161
+
162
+ classified = @policy.classify_log_attributes(full_attrs, replacer: @attr_replacer)
163
+ # trace_id and span_id are reserved: they come from the active span
164
+ # only. Removed after the replacer, which could bring them back.
165
+ classified.delete("trace_id")
166
+ classified.delete("span_id")
167
+
168
+ # Console leg
169
+ if @console_enabled && @console_writer && (force || severity >= @console_level)
170
+ line = build_console_line(now, sev_text, body, trace_id, span_id, classified)
171
+ write_console(line, raise_on_sink_error: raise_on_sink_error)
172
+ end
173
+
174
+ # OTLP leg
175
+ if @otel_logger && (force || severity >= @console_level)
176
+ emit_otel(now, sev_num, sev_text, body, event_name, classified, raise_on_sink_error: raise_on_sink_error)
177
+ end
178
+
179
+ # Extra sinks
180
+ @extra_sinks.each do |sink|
181
+ next unless force || severity >= @console_level
182
+
183
+ record_hash = {
184
+ timestamp: now,
185
+ observed_timestamp: now,
186
+ severity_number: sev_num,
187
+ severity_text: sev_text,
188
+ body: body,
189
+ event_name: event_name,
190
+ trace_id: trace_id,
191
+ span_id: span_id,
192
+ attributes: classified
193
+ }
194
+ begin
195
+ if sink.respond_to?(:call)
196
+ sink.call(record_hash)
197
+ elsif sink.respond_to?(:emit)
198
+ sink.emit(record_hash)
199
+ end
200
+ rescue StandardError
201
+ raise if raise_on_sink_error
202
+ end
203
+ end
204
+ ensure
205
+ Thread.current[REENTRY_FIBER_KEY] = false
206
+ end
207
+ end
208
+
209
+ def build_console_line(now, sev_text, body, trace_id, span_id, attrs)
210
+ payload = {
211
+ "time" => now.iso8601(6),
212
+ "level" => sev_text,
213
+ "msg" => body
214
+ }
215
+ payload["trace_id"] = trace_id if trace_id
216
+ payload["span_id"] = span_id if span_id
217
+ attrs.each do |k, v|
218
+ next if %w[time level msg trace_id span_id].include?(k)
219
+
220
+ payload[k] = v
221
+ end
222
+ "#{JSON.generate(payload)}\n"
223
+ end
224
+
225
+ def write_console(line, raise_on_sink_error:)
226
+ @mutex.synchronize do
227
+ @console_writer.write(line)
228
+ end
229
+ rescue StandardError
230
+ raise if raise_on_sink_error
231
+ end
232
+
233
+ def emit_otel(now, sev_num, sev_text, body, event_name, classified, raise_on_sink_error:)
234
+ flat = flatten_for_otel(classified)
235
+ @otel_logger.on_emit(
236
+ timestamp: now,
237
+ observed_timestamp: now,
238
+ severity_number: sev_num,
239
+ severity_text: sev_text,
240
+ body: body,
241
+ attributes: flat,
242
+ event_name: event_name,
243
+ context: Bridges::PolicyLogRecordProcessor.mark_classified(OpenTelemetry::Context.current)
244
+ )
245
+ rescue StandardError
246
+ raise if raise_on_sink_error
247
+ end
248
+
249
+ def flatten_for_otel(hash, prefix = nil, out = {})
250
+ hash.each do |k, v|
251
+ full = prefix ? "#{prefix}.#{k}" : k.to_s
252
+ if v.is_a?(Hash)
253
+ flatten_for_otel(v, full, out)
254
+ elsif v.is_a?(Array)
255
+ out[full] = v.map { |el| el.is_a?(Hash) || el.is_a?(Array) ? JSON.generate(el) : el }
256
+ elsif v.is_a?(String) || v.is_a?(Integer) || v.is_a?(Float) || v.is_a?(TrueClass) || v.is_a?(FalseClass)
257
+ out[full] = v
258
+ elsif !v.nil?
259
+ out[full] = v.to_s
260
+ end
261
+ end
262
+ out
263
+ end
264
+ end
265
+ end
266
+ end
@@ -0,0 +1,198 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Libo11y
6
+ module Internal
7
+ module PII
8
+ MAX_COMPOSITE_DEPTH = 16
9
+ MAX_COMPOSITE_NODES = 2048
10
+ CANONICAL_TRUNCATED = "truncated"
11
+ MIN_PII_HASH_KEY_LEN = 32
12
+
13
+ class Walk
14
+ def initialize
15
+ @remaining = MAX_COMPOSITE_NODES
16
+ @active = {}
17
+ end
18
+
19
+ def spend?
20
+ return false if @remaining <= 0
21
+
22
+ @remaining -= 1
23
+ true
24
+ end
25
+
26
+ def enter?(obj)
27
+ oid = obj.object_id
28
+ return false if @active.key?(oid)
29
+
30
+ @active[oid] = true
31
+ true
32
+ end
33
+
34
+ def leave(obj)
35
+ @active.delete(obj.object_id)
36
+ end
37
+ end
38
+
39
+ module_function
40
+
41
+ def canonical_float(value)
42
+ return "NaN" if value.nan?
43
+ return value.positive? ? "+Inf" : "-Inf" if value.infinite?
44
+ if value.zero?
45
+ return (1.0 / value).negative? ? "-0" : "0"
46
+ end
47
+
48
+ neg = value.negative?
49
+ abs_val = neg ? -value : value
50
+ s = abs_val.to_s
51
+ if s.include?("e") || s.include?("E")
52
+ mant, exp_str = s.downcase.split("e", 2)
53
+ exp = exp_str.to_i
54
+ else
55
+ mant = s
56
+ exp = 0
57
+ end
58
+
59
+ if mant.include?(".")
60
+ int_part, frac_part = mant.split(".", 2)
61
+ digits_raw = int_part + frac_part
62
+ stripped = digits_raw.sub(/\A0+/, "")
63
+ leading_zeros = digits_raw.length - stripped.length
64
+ if int_part == "0"
65
+ exp -= leading_zeros
66
+ else
67
+ exp += int_part.length - 1
68
+ end
69
+ digits = stripped.sub(/0+\z/, "")
70
+ else
71
+ exp += mant.length - 1
72
+ digits = mant.sub(/0+\z/, "")
73
+ end
74
+
75
+ return neg ? "-0" : "0" if digits.empty?
76
+
77
+ prefix = neg ? "-" : ""
78
+ if exp < -4 || exp >= 6
79
+ body = digits.length == 1 ? digits : "#{digits[0]}.#{digits[1..]}"
80
+ sign = exp >= 0 ? "+" : "-"
81
+ abs_exp = exp.abs
82
+ exp_fmt = abs_exp < 100 ? format("%02d", abs_exp) : abs_exp.to_s
83
+ return "#{prefix}#{body}e#{sign}#{exp_fmt}"
84
+ end
85
+
86
+ if exp.negative?
87
+ "#{prefix}0.#{"0" * (-exp - 1)}#{digits}"
88
+ elsif exp + 1 >= digits.length
89
+ "#{prefix}#{digits}#{"0" * (exp + 1 - digits.length)}"
90
+ else
91
+ split = exp + 1
92
+ "#{prefix}#{digits[0, split]}.#{digits[split..]}"
93
+ end
94
+ end
95
+
96
+ 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
122
+ end
123
+ out << "\""
124
+ out
125
+ end
126
+
127
+ def render_json_node(node)
128
+ case node
129
+ when String
130
+ encode_json_string(node)
131
+ when Array
132
+ "[#{node.map { |el| render_json_node(el) }.join(",")}]"
133
+ when Hash
134
+ items = node.map { |k, v| "#{encode_json_string(k)}:#{render_json_node(v)}" }
135
+ "{#{items.join(",")}}"
136
+ else
137
+ encode_json_string(node.to_s)
138
+ end
139
+ end
140
+
141
+ def build_node(value, depth, walk)
142
+ return CANONICAL_TRUNCATED if depth > MAX_COMPOSITE_DEPTH || !walk.spend?
143
+
144
+ 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
153
+ end
154
+ when Hash
155
+ return CANONICAL_TRUNCATED unless walk.enter?(value)
156
+
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)
166
+ end
167
+ obj
168
+ ensure
169
+ walk.leave(value)
170
+ end
171
+ when Array
172
+ return CANONICAL_TRUNCATED unless walk.enter?(value)
173
+
174
+ begin
175
+ value.map { |el| build_node(el, depth + 1, walk) }
176
+ ensure
177
+ walk.leave(value)
178
+ end
179
+ else
180
+ value.to_s
181
+ end
182
+ end
183
+
184
+ def canonical_value(value)
185
+ node = build_node(value, 0, Walk.new)
186
+ return node if node.is_a?(String)
187
+
188
+ render_json_node(node)
189
+ end
190
+
191
+ def token(key, value)
192
+ canonical = canonical_value(value)
193
+ digest = OpenSSL::HMAC.digest("SHA256", key, canonical.encode(Encoding::UTF_8).b)
194
+ "hmac-sha256:#{digest.byteslice(0, 16).unpack1("H*")}"
195
+ end
196
+ end
197
+ end
198
+ end