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,201 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require "opentelemetry"
5
+ require_relative "record"
6
+ require_relative "spec"
7
+
8
+ module Libo11y
9
+ # Rack middleware (Rails, Sinatra, Hanami, Roda) emitting stable HTTP semconv spans,
10
+ # http.server.request.duration histograms with exemplars, Server-Timing, and canonical lines.
11
+ module Rack
12
+ 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
13
+ ROUTE_FIBER_KEY = :libo11y_http_route
14
+
15
+ def self.set_route(route)
16
+ Thread.current[ROUTE_FIBER_KEY] = route.to_s
17
+ end
18
+
19
+ def self.match_glob?(pattern, path)
20
+ File.fnmatch?(pattern, path, File::FNM_PATHNAME)
21
+ end
22
+
23
+ class Middleware
24
+ def initialize(
25
+ app,
26
+ telemetry: nil,
27
+ route: nil,
28
+ public_endpoint: false,
29
+ ignore_paths: [],
30
+ filter: nil,
31
+ server_timing: false,
32
+ canonical_line: false
33
+ )
34
+ @app = app
35
+ @telemetry = telemetry
36
+ @route_fn = route
37
+ @public_endpoint = public_endpoint
38
+ @ignore_paths = Array(ignore_paths)
39
+ @filter = filter
40
+ @server_timing = server_timing
41
+ @canonical_line = canonical_line
42
+ end
43
+
44
+ def call(env)
45
+ raw_path = env["PATH_INFO"].to_s
46
+ decoded_path = decode_path(raw_path)
47
+
48
+ return @app.call(env) if ignored?(decoded_path, env)
49
+
50
+ method = env["REQUEST_METHOD"].to_s.upcase
51
+ scheme = env["rack.url_scheme"].to_s
52
+ scheme = "http" if scheme.empty?
53
+
54
+ propagator = @telemetry ? @telemetry.propagator : OpenTelemetry.propagation
55
+ headers = extract_rack_headers(env)
56
+ extracted_ctx = propagator.extract(headers, context: OpenTelemetry::Context.empty)
57
+
58
+ parent_ctx = extracted_ctx
59
+ links = nil
60
+ if @public_endpoint
61
+ remote_sc = OpenTelemetry::Trace.current_span(extracted_ctx).context
62
+ links = [OpenTelemetry::Trace::Link.new(remote_sc)] if remote_sc.valid?
63
+ parent_ctx = OpenTelemetry::Context.empty
64
+ end
65
+
66
+ resolved_route = resolve_route(env)
67
+ span_name = resolved_route ? "#{method} #{resolved_route}" : method
68
+
69
+ attrs = {
70
+ "http.request.method" => method,
71
+ "url.path" => raw_path,
72
+ "url.scheme" => scheme
73
+ }
74
+ attrs["http.route"] = resolved_route if resolved_route
75
+ attrs["server.address"] = env["SERVER_NAME"].to_s unless env["SERVER_NAME"].to_s.empty?
76
+ attrs["server.port"] = env["SERVER_PORT"].to_i unless env["SERVER_PORT"].to_s.empty?
77
+
78
+ tracer = @telemetry ? @telemetry.tracer("libo11y.rack", Libo11y::VERSION) : OpenTelemetry.tracer_provider.tracer("libo11y.rack", Libo11y::VERSION)
79
+ meter = if @telemetry
80
+ @telemetry.meter("libo11y.rack",
81
+ version: Libo11y::VERSION)
82
+ else
83
+ OpenTelemetry.meter_provider.meter("libo11y.rack", version: Libo11y::VERSION)
84
+ end
85
+ @duration_hist ||= meter.create_histogram(
86
+ "http.server.request.duration",
87
+ unit: "s",
88
+ description: "Duration of HTTP server requests.",
89
+ explicit_bucket_boundaries: HTTP_DURATION_BUCKETS
90
+ )
91
+
92
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
93
+ prev_route = Thread.current[ROUTE_FIBER_KEY]
94
+ Thread.current[ROUTE_FIBER_KEY] = nil
95
+
96
+ status = 500
97
+ resp_headers = {}
98
+ body = nil
99
+ error = nil
100
+
101
+ OpenTelemetry::Context.with_current(parent_ctx) do
102
+ tracer.in_span(span_name, attributes: attrs, links: links, kind: :server) do |span|
103
+ Libo11y.start_record do |rec|
104
+ status, resp_headers, body = @app.call(env)
105
+ status = status.to_i
106
+ rescue StandardError => e
107
+ error = e
108
+ span.record_exception(e)
109
+ span.status = OpenTelemetry::Trace::Status.error(e.message)
110
+ span.set_attribute("error.type", e.class.name)
111
+ raise
112
+ ensure
113
+ final_route = Thread.current[ROUTE_FIBER_KEY] || resolved_route || resolve_route(env)
114
+ if final_route && !final_route.empty?
115
+ span.set_attribute("http.route", final_route)
116
+ span.name = "#{method} #{final_route}"
117
+ end
118
+ span.set_attribute("http.response.status_code", status)
119
+ if status >= 500 && error.nil?
120
+ span.status = OpenTelemetry::Trace::Status.error("HTTP #{status}")
121
+ span.set_attribute("error.type", status.to_s)
122
+ end
123
+
124
+ duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
125
+ metric_attrs = {
126
+ "http.request.method" => method,
127
+ "http.response.status_code" => status,
128
+ "url.scheme" => scheme
129
+ }
130
+ metric_attrs["http.route"] = final_route if final_route && !final_route.empty?
131
+ metric_attrs["error.type"] = error ? error.class.name : status.to_s if error || status >= 500
132
+ @duration_hist.record(duration, attributes: metric_attrs)
133
+
134
+ if @server_timing && resp_headers.is_a?(Hash) && error.nil?
135
+ sc = span.context
136
+ if sc.valid?
137
+ flags = sc.trace_flags.sampled? ? "01" : "00"
138
+ tp = "00-#{sc.hex_trace_id}-#{sc.hex_span_id}-#{flags}"
139
+ resp_headers = resp_headers.dup
140
+ existing = resp_headers["server-timing"] || resp_headers["Server-Timing"]
141
+ entry = "traceparent;desc=\"#{tp}\""
142
+ resp_headers["server-timing"] = existing ? "#{existing}, #{entry}" : entry
143
+ end
144
+ end
145
+
146
+ if @canonical_line && @telemetry
147
+ summary_attrs = rec.attributes.merge(
148
+ "http.request.method" => method,
149
+ "http.response.status_code" => status,
150
+ "url.path" => raw_path,
151
+ Spec::ATTR_DURATION => duration,
152
+ Spec::ATTR_OUTCOME => error || status >= 500 ? Spec::Outcome::FAILURE : Spec::Outcome::SUCCESS
153
+ )
154
+ summary_attrs["http.route"] = final_route if final_route && !final_route.empty?
155
+ summary_attrs["error.type"] = error.class.name if error
156
+ @telemetry.event(Spec::EVENT_REQUEST_SUMMARY, summary_attrs)
157
+ end
158
+ end
159
+ end
160
+ end
161
+
162
+ [status, resp_headers, body]
163
+ ensure
164
+ Thread.current[ROUTE_FIBER_KEY] = prev_route
165
+ end
166
+
167
+ private
168
+
169
+ def ignored?(decoded_path, env)
170
+ return true if @ignore_paths.any? { |pat| Rack.match_glob?(pat, decoded_path) }
171
+ return true if @filter && !@filter.call(env)
172
+
173
+ false
174
+ end
175
+
176
+ def decode_path(raw)
177
+ URI.decode_www_form_component(raw.gsub("+", "%2B"))
178
+ rescue StandardError
179
+ raw
180
+ end
181
+
182
+ def extract_rack_headers(env)
183
+ headers = {}
184
+ env.each do |k, v|
185
+ next unless k.is_a?(String) && k.start_with?("HTTP_")
186
+
187
+ header_name = k.delete_prefix("HTTP_").downcase.tr("_", "-")
188
+ headers[header_name] = v.to_s
189
+ end
190
+ headers
191
+ end
192
+
193
+ def resolve_route(env)
194
+ return @route_fn.call(env) if @route_fn.respond_to?(:call)
195
+
196
+ # Sinatra / Rails route conventions
197
+ env["sinatra.route"]&.split(" ", 2)&.last || env["action_dispatch.route_uri_pattern"]
198
+ end
199
+ end
200
+ end
201
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Libo11y
4
+ # Wide event accumulator attached to the current Fiber/execution context.
5
+ class Record
6
+ def initialize
7
+ @mutex = Mutex.new
8
+ @attrs = {}
9
+ end
10
+
11
+ def set(key, value)
12
+ @mutex.synchronize { @attrs[key.to_s] = value }
13
+ self
14
+ end
15
+
16
+ def set_all(hash)
17
+ return self if hash.nil?
18
+
19
+ @mutex.synchronize do
20
+ hash.each { |k, v| @attrs[k.to_s] = v }
21
+ end
22
+ self
23
+ end
24
+
25
+ def add(key, delta = 1)
26
+ k = key.to_s
27
+ @mutex.synchronize do
28
+ cur = @attrs[k]
29
+ @attrs[k] = (cur.is_a?(Numeric) ? cur : 0) + delta
30
+ end
31
+ self
32
+ end
33
+
34
+ def attributes
35
+ @mutex.synchronize { @attrs.dup }
36
+ end
37
+
38
+ def emit_event(telemetry, name, extra = nil)
39
+ merged = attributes
40
+ extra&.each { |k, v| merged[k.to_s] = v }
41
+ telemetry.event(name, merged)
42
+ end
43
+ end
44
+
45
+ RECORD_FIBER_KEY = :libo11y_current_record
46
+
47
+ def self.current_record
48
+ Thread.current[RECORD_FIBER_KEY]
49
+ end
50
+
51
+ def self.start_record
52
+ rec = Record.new
53
+ prev = Thread.current[RECORD_FIBER_KEY]
54
+ Thread.current[RECORD_FIBER_KEY] = rec
55
+ return rec unless block_given?
56
+
57
+ begin
58
+ yield rec
59
+ ensure
60
+ Thread.current[RECORD_FIBER_KEY] = prev
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,224 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Libo11y
6
+ # Capture-time redaction, so a sensitive value never reaches to_s, inspect,
7
+ # JSON or a log record in the clear. Three protections exist: mask (a run of
8
+ # X as long as the value), redact (the literal REDACTED) and omit (the field
9
+ # is absent). The strictest protection wins through nesting.
10
+ module Redact
11
+ REDACTED = "REDACTED"
12
+ VALID_TAGS = %i[mask redact omit confidential secret].freeze
13
+
14
+ # Nesting deeper than this renders as REDACTED.
15
+ MAX_DEPTH = 32
16
+
17
+ PASSTHROUGH = 0
18
+ MASK = 1
19
+ REDACT = 2
20
+ OMIT = 3
21
+ LEVELS = { mask: MASK, confidential: MASK, redact: REDACT, secret: REDACT, omit: OMIT }.freeze
22
+ TAG_OF = { MASK => :mask, REDACT => :redact, OMIT => :omit }.freeze
23
+ private_constant :PASSTHROUGH, :MASK, :REDACT, :OMIT, :LEVELS, :TAG_OF
24
+
25
+ def self.mask_string(value)
26
+ "X" * value.to_s.length
27
+ end
28
+
29
+ # Returns the protection a tag names: :mask, :redact or :omit.
30
+ # confidential is a synonym of mask and secret of redact.
31
+ def self.normalize_tag(tag)
32
+ TAG_OF.fetch(level_for(tag))
33
+ end
34
+
35
+ # @api private
36
+ def self.level_for(tag)
37
+ sym = tag.is_a?(Symbol) ? tag : tag.to_s.to_sym
38
+ LEVELS.fetch(sym) do
39
+ raise ArgumentError, "libo11y: unknown redact tag #{tag.inspect} (expected mask, redact, omit, confidential, or secret)"
40
+ end
41
+ end
42
+
43
+ # Wraps a secret value. It always renders as "REDACTED".
44
+ class Secret
45
+ def initialize(value)
46
+ @value = value
47
+ end
48
+
49
+ # Returns the wrapped value.
50
+ def reveal
51
+ @value
52
+ end
53
+
54
+ def to_s
55
+ REDACTED
56
+ end
57
+
58
+ def inspect
59
+ REDACTED.inspect
60
+ end
61
+
62
+ def to_json(*)
63
+ REDACTED.to_json(*)
64
+ end
65
+
66
+ def as_redacted
67
+ REDACTED
68
+ end
69
+
70
+ def ==(other)
71
+ other.is_a?(Secret) && @value == other.reveal
72
+ end
73
+ end
74
+
75
+ # Wraps a value that renders as a run of X of the same length.
76
+ class Masked
77
+ def initialize(value)
78
+ @value = value
79
+ end
80
+
81
+ # Returns the wrapped value.
82
+ def reveal
83
+ @value
84
+ end
85
+
86
+ def to_s
87
+ Redact.mask_string(@value)
88
+ end
89
+
90
+ def inspect
91
+ to_s.inspect
92
+ end
93
+
94
+ def to_json(*)
95
+ to_s.to_json(*)
96
+ end
97
+
98
+ def as_redacted
99
+ to_s
100
+ end
101
+
102
+ def ==(other)
103
+ other.is_a?(Masked) && @value == other.reveal
104
+ end
105
+ end
106
+
107
+ # Mixin for a Struct or class that declares a protection per field when
108
+ # the class is defined:
109
+ #
110
+ # Account = Struct.new(:id, :ssn, :token) do
111
+ # include Libo11y::Redact::Fields
112
+ #
113
+ # redact_field :ssn, :mask
114
+ # redact_field :token, :secret
115
+ # end
116
+ #
117
+ # A subclass keeps its parent's rules. It can add rules and make one
118
+ # stricter, and it cannot make one weaker.
119
+ module Fields
120
+ def self.included(base)
121
+ base.extend(ClassMethods)
122
+ end
123
+
124
+ module ClassMethods
125
+ # Declares the protection of one field. An unknown tag raises
126
+ # ArgumentError here, when the class is defined.
127
+ def redact_field(name, tag)
128
+ level = Redact.level_for(tag)
129
+ (@o11y_redact_levels ||= {})[name.to_sym] = level
130
+ end
131
+
132
+ # The protection of every declared field, the parent's included, as
133
+ # :mask, :redact or :omit.
134
+ def o11y_redact_rules
135
+ o11y_redact_levels.transform_values { |level| TAG_OF.fetch(level) }
136
+ end
137
+
138
+ # @api private
139
+ def o11y_redact_levels
140
+ inherited = superclass.respond_to?(:o11y_redact_levels) ? superclass.o11y_redact_levels : {}
141
+ inherited.merge(@o11y_redact_levels || {}) { |_name, parent, own| [parent, own].max }
142
+ end
143
+ end
144
+
145
+ # The fields as a Hash with string keys, with each field's protection
146
+ # applied.
147
+ def redacted_hash
148
+ Redact.render(self)
149
+ end
150
+
151
+ def to_s
152
+ redacted_hash.inspect
153
+ end
154
+
155
+ def inspect
156
+ "#<#{self.class.name || "struct"} #{redacted_hash.map { |k, v| "#{k}=#{v.inspect}" }.join(" ")}>"
157
+ end
158
+
159
+ def to_json(*)
160
+ redacted_hash.to_json(*)
161
+ end
162
+
163
+ def as_redacted
164
+ redacted_hash
165
+ end
166
+ end
167
+
168
+ def self.redactable?(value)
169
+ value.is_a?(Secret) || value.is_a?(Masked) || value.is_a?(Fields)
170
+ end
171
+
172
+ # Returns value with every Secret, Masked and Fields object inside it
173
+ # rendered. Hashes and Arrays are walked. Nesting past MAX_DEPTH and a
174
+ # reference back into the value being walked render as REDACTED.
175
+ def self.render(value)
176
+ protect(value, PASSTHROUGH, 0, {}.compare_by_identity)
177
+ end
178
+
179
+ # floor is the strictest protection of the fields that hold value.
180
+ def self.protect(value, floor, depth, active)
181
+ return REDACTED if floor >= REDACT || depth > MAX_DEPTH
182
+
183
+ case value
184
+ when nil then nil
185
+ when Secret then REDACTED
186
+ when Masked then value.to_s
187
+ when Fields, Hash, Array then protect_composite(value, floor, depth, active)
188
+ else floor == MASK ? mask_string(value) : value
189
+ end
190
+ end
191
+
192
+ def self.protect_composite(value, floor, depth, active)
193
+ return REDACTED if active.key?(value)
194
+
195
+ active[value] = true
196
+ begin
197
+ case value
198
+ when Fields then protect_fields(value, floor, depth, active)
199
+ when Hash then value.to_h { |k, v| [k.to_s, protect(v, floor, depth + 1, active)] }
200
+ else value.map { |v| protect(v, floor, depth + 1, active) }
201
+ end
202
+ ensure
203
+ active.delete(value)
204
+ end
205
+ end
206
+
207
+ def self.protect_fields(value, floor, depth, active)
208
+ levels = value.class.o11y_redact_levels
209
+ names = value.respond_to?(:members) ? value.members : value.instance_variables.map { |iv| iv.to_s.delete_prefix("@").to_sym }
210
+ names.each_with_object({}) do |name, out|
211
+ level = [levels.fetch(name.to_sym, PASSTHROUGH), floor].max
212
+ next if level == OMIT
213
+
214
+ out[name.to_s] = if level == REDACT
215
+ REDACTED
216
+ else
217
+ field = value.respond_to?(name) ? value.public_send(name) : value.instance_variable_get(:"@#{name}")
218
+ protect(field, level, depth + 1, active)
219
+ end
220
+ end
221
+ end
222
+ private_class_method :protect, :protect_composite, :protect_fields
223
+ end
224
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Libo11y
4
+ module Signals
5
+ module_function
6
+
7
+ # Block until SIGINT or SIGTERM arrives, restore default handlers, run optional
8
+ # before_shutdown callback, and flush telemetry under one shared deadline.
9
+ def shutdown_on_signals(telemetry, timeout: nil, signals: %w[INT TERM], before_shutdown: nil)
10
+ deadline_secs = timeout || telemetry.shutdown_timeout
11
+ read_io, write_io = IO.pipe
12
+ previous = {}
13
+
14
+ signals.each do |sig|
15
+ previous[sig] = Signal.trap(sig) do
16
+ write_io.write_nonblock("x")
17
+ rescue StandardError
18
+ nil
19
+ end
20
+ end
21
+
22
+ begin
23
+ read_io.read(1)
24
+ ensure
25
+ previous.each do |sig, handler|
26
+ Signal.trap(sig, handler || "DEFAULT")
27
+ rescue StandardError
28
+ nil
29
+ end
30
+ read_io.close unless read_io.closed?
31
+ write_io.close unless write_io.closed?
32
+ end
33
+
34
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
35
+ if before_shutdown
36
+ begin
37
+ before_shutdown.call
38
+ rescue StandardError
39
+ nil
40
+ end
41
+ end
42
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
43
+ remaining = [deadline_secs - elapsed, 0.05].max
44
+ telemetry.shutdown(timeout: remaining)
45
+ end
46
+ end
47
+ end