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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +170 -21
- data/README.md +77 -8
- data/lib/libo11y/{proc.rb → child_process.rb} +12 -2
- data/lib/libo11y/db.rb +22 -10
- data/lib/libo11y/detached.rb +241 -29
- data/lib/libo11y/http_client.rb +48 -15
- data/lib/libo11y/internal/bridges.rb +3553 -255
- data/lib/libo11y/internal/endpoint.rb +7 -1
- data/lib/libo11y/internal/env.rb +177 -59
- data/lib/libo11y/internal/error_type.rb +17 -0
- data/lib/libo11y/internal/histogram_buckets.rb +42 -0
- data/lib/libo11y/internal/http_common.rb +2 -0
- data/lib/libo11y/internal/identity.rb +10 -1
- data/lib/libo11y/internal/injected.rb +178 -0
- data/lib/libo11y/internal/logging_device.rb +141 -32
- data/lib/libo11y/internal/path_match.rb +148 -0
- data/lib/libo11y/internal/pii.rb +185 -65
- data/lib/libo11y/internal/pipeline.rb +141 -34
- data/lib/libo11y/internal/policy.rb +556 -52
- data/lib/libo11y/internal/propagators.rb +29 -6
- data/lib/libo11y/internal/quiet_inspect.rb +20 -0
- data/lib/libo11y/internal/resource.rb +187 -52
- data/lib/libo11y/internal/sdk_load.rb +64 -0
- data/lib/libo11y/internal/sql_text.rb +365 -67
- data/lib/libo11y/internal/summary.rb +2 -1
- data/lib/libo11y/options.rb +159 -1
- data/lib/libo11y/rack.rb +257 -44
- data/lib/libo11y/record.rb +70 -7
- data/lib/libo11y/redact.rb +87 -21
- data/lib/libo11y/signals.rb +70 -29
- data/lib/libo11y/spec/app_registry.rb +97 -61
- data/lib/libo11y/spec/yaml_v3.rb +179 -111
- data/lib/libo11y/telemetry.rb +315 -53
- data/lib/libo11y/testing.rb +31 -19
- data/lib/libo11y/version.rb +1 -1
- data/lib/libo11y.rb +1 -1
- metadata +94 -39
data/lib/libo11y/options.rb
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "logger"
|
|
4
|
+
|
|
3
5
|
module Libo11y
|
|
4
6
|
# Sentinel passed to `env:` for hermetic mode (no ambient OTEL_* env vars read).
|
|
5
7
|
HERMETIC = Object.new.freeze
|
|
@@ -32,6 +34,135 @@ module Libo11y
|
|
|
32
34
|
end
|
|
33
35
|
end
|
|
34
36
|
|
|
37
|
+
# The options of Libo11y.setup and Libo11y.init. Each is a keyword of
|
|
38
|
+
# those methods, and nil for one means its default. An option that is not
|
|
39
|
+
# listed here raises ArgumentError.
|
|
40
|
+
#
|
|
41
|
+
# Identity
|
|
42
|
+
#
|
|
43
|
+
# @!attribute service_name
|
|
44
|
+
# @return [String] service.name. Without it, here or in
|
|
45
|
+
# OTEL_SERVICE_NAME or resource_attributes, the start raises
|
|
46
|
+
# NoServiceName.
|
|
47
|
+
# @!attribute version
|
|
48
|
+
# @return [String, nil] service.version. Default: the version in
|
|
49
|
+
# build_info, else "0.0.0-unknown".
|
|
50
|
+
# @!attribute environment
|
|
51
|
+
# @return [String] deployment.environment.name: production, staging,
|
|
52
|
+
# development or test, or one of extra_environments. Without it the
|
|
53
|
+
# start raises NoEnvironment, and for another value InvalidEnvironment.
|
|
54
|
+
# @!attribute service_namespace
|
|
55
|
+
# @return [String, nil] service.namespace.
|
|
56
|
+
# @!attribute service_instance_id
|
|
57
|
+
# @return [String, nil] service.instance.id. Default: derived from the
|
|
58
|
+
# Kubernetes pod when there is one, else one random UUID per process.
|
|
59
|
+
# @!attribute extra_environments
|
|
60
|
+
# @return [Array<String>] environment names allowed beside the four.
|
|
61
|
+
# Default: none.
|
|
62
|
+
# @!attribute strict_identity
|
|
63
|
+
# @return [Boolean] false starts without a service name or an allowed
|
|
64
|
+
# environment, and counts a violation for each. Default: true.
|
|
65
|
+
# @!attribute resource_attributes
|
|
66
|
+
# @return [Hash] further resource attributes. They beat
|
|
67
|
+
# OTEL_RESOURCE_ATTRIBUTES and lose to the named options. Default: none.
|
|
68
|
+
# @!attribute build_info
|
|
69
|
+
# @return [Hash, String, Pathname, nil] version, vcs_revision,
|
|
70
|
+
# build_time and build_modified, as a Hash or as the path of a JSON
|
|
71
|
+
# file that holds them.
|
|
72
|
+
# @!attribute build_info_enabled
|
|
73
|
+
# @return [Boolean] false ignores build_info. Default: true.
|
|
74
|
+
#
|
|
75
|
+
# Environment and policy
|
|
76
|
+
#
|
|
77
|
+
# @!attribute env
|
|
78
|
+
# @return [Hash, Object, nil] where OTEL_* settings come from: nil for
|
|
79
|
+
# the process environment, a Hash in its place, or Libo11y::HERMETIC
|
|
80
|
+
# for none, in which case a signal with nothing injected is off.
|
|
81
|
+
# Anything else raises ArgumentError.
|
|
82
|
+
# @!attribute pii_mode
|
|
83
|
+
# @return [Symbol] what happens to PII-classified values. PIIMode::DROP
|
|
84
|
+
# removes them from the resource, spans, logs and metrics. HASH puts
|
|
85
|
+
# an HMAC token in their place on the resource, spans and logs, and
|
|
86
|
+
# removes them from metrics. ALLOW keeps them on all four.
|
|
87
|
+
# Secret-classified values are removed whatever the mode. Default:
|
|
88
|
+
# DROP. Another value raises ArgumentError.
|
|
89
|
+
# @!attribute pii_hash_key
|
|
90
|
+
# @return [String, nil] the HMAC key of PIIMode::HASH, at least 32
|
|
91
|
+
# bytes. Too short or missing raises PIIHashKey.
|
|
92
|
+
# @!attribute app_registries
|
|
93
|
+
# @return [Array, nil] application attribute registries: YAML text, a
|
|
94
|
+
# path as a one-line String or a Pathname, or a compiled registry. One
|
|
95
|
+
# that does not parse or validate raises InvalidAppRegistry.
|
|
96
|
+
# @!attribute attr_replacer
|
|
97
|
+
# @return [#call, nil] called with (groups, key, value) for every log
|
|
98
|
+
# attribute before the policy. Returns [key, value], or nil to drop it.
|
|
99
|
+
#
|
|
100
|
+
# Propagation, sampling and metrics
|
|
101
|
+
#
|
|
102
|
+
# @!attribute propagators
|
|
103
|
+
# @return [Object, Array, nil] the propagator, or several. Default: W3C
|
|
104
|
+
# TraceContext and Baggage. OTEL_PROPAGATORS is not read.
|
|
105
|
+
# @!attribute baggage_egress_allow
|
|
106
|
+
# @return [#call, nil] called with a baggage key. Only the members it
|
|
107
|
+
# returns true for leave the process. Default: all leave.
|
|
108
|
+
# @!attribute sampler
|
|
109
|
+
# @return [Object, nil] an OpenTelemetry sampler. Default:
|
|
110
|
+
# OTEL_TRACES_SAMPLER, else parent-based always-on.
|
|
111
|
+
# @!attribute exemplar_filter
|
|
112
|
+
# @return [Symbol, nil] ExemplarFilter::TRACE_BASED, ALWAYS_ON or
|
|
113
|
+
# ALWAYS_OFF. Default: OTEL_METRICS_EXEMPLAR_FILTER, else TRACE_BASED.
|
|
114
|
+
# Another value raises ArgumentError.
|
|
115
|
+
# @!attribute histogram_buckets
|
|
116
|
+
# @return [Hash{String => Array<Numeric>}, nil] bucket boundaries by
|
|
117
|
+
# histogram name. An entry for one of libo11y's duration histograms
|
|
118
|
+
# replaces its boundaries.
|
|
119
|
+
# @!attribute views
|
|
120
|
+
# @return [Array<Hash>, nil] metric views, each the arguments of the
|
|
121
|
+
# SDK's MeterProvider#add_view with a :name. Each must name an
|
|
122
|
+
# :aggregation of the SDK, since the SDK records nothing through a
|
|
123
|
+
# view without one. A view that selects one of libo11y's duration
|
|
124
|
+
# histograms takes the place of its built-in view. A view's
|
|
125
|
+
# :attribute_keys are classified as metric attributes are. Two views
|
|
126
|
+
# that may select one instrument are refused when either has
|
|
127
|
+
# :attribute_keys, because the SDK would add them to both streams. A
|
|
128
|
+
# bad entry raises ArgumentError.
|
|
129
|
+
# @!attribute runtime_metrics
|
|
130
|
+
# @return [Boolean] Ruby runtime metrics. Default: true.
|
|
131
|
+
#
|
|
132
|
+
# Logging
|
|
133
|
+
#
|
|
134
|
+
# @!attribute console_writer
|
|
135
|
+
# @return [#write, nil] where the JSON console lines go. Default: $stdout.
|
|
136
|
+
# @!attribute console_enabled
|
|
137
|
+
# @return [Boolean] false turns the console off. Default: true.
|
|
138
|
+
# @!attribute log_level
|
|
139
|
+
# @return [Integer, Symbol, String] the level of Telemetry#logger, as a
|
|
140
|
+
# Logger constant or its name. It gates every sink. Default: INFO.
|
|
141
|
+
# @!attribute extra_log_sinks
|
|
142
|
+
# @return [Array] further sinks: each responds to call or emit and is
|
|
143
|
+
# given the classified record. Default: none.
|
|
144
|
+
#
|
|
145
|
+
# Injected parts. libo11y owns each from the start and shuts it down once.
|
|
146
|
+
#
|
|
147
|
+
# @!attribute span_exporter
|
|
148
|
+
# @return [Object, nil] a span exporter. With one, no exporter is built
|
|
149
|
+
# from the environment for traces.
|
|
150
|
+
# @!attribute span_processors
|
|
151
|
+
# @return [Array] span processors. They get a finished span that holds
|
|
152
|
+
# classified data only, and own the trace export path. Default: none.
|
|
153
|
+
# @!attribute metric_reader
|
|
154
|
+
# @return [Object, nil] a metric reader. With one, no exporter is built
|
|
155
|
+
# from the environment for metrics.
|
|
156
|
+
# @!attribute log_exporter
|
|
157
|
+
# @return [Object, nil] a log record exporter. With one, no exporter is
|
|
158
|
+
# built from the environment for logs.
|
|
159
|
+
# @!attribute log_processors
|
|
160
|
+
# @return [Array] log record processors. They see classified records
|
|
161
|
+
# and own the log export path. Default: none.
|
|
162
|
+
# @!attribute shutdown_timeout
|
|
163
|
+
# @return [Numeric] the seconds Telemetry#shutdown and #force_flush take
|
|
164
|
+
# at most when called without a timeout. Default: 5. A value that is
|
|
165
|
+
# not a finite number above 0 raises ArgumentError.
|
|
35
166
|
Options = Struct.new(
|
|
36
167
|
:service_name,
|
|
37
168
|
:version,
|
|
@@ -78,6 +209,32 @@ module Libo11y
|
|
|
78
209
|
new(**options.to_h, **kwargs)
|
|
79
210
|
end
|
|
80
211
|
|
|
212
|
+
# The options as text. A text, a number, a symbol or a boolean is shown
|
|
213
|
+
# as it is, and anything else by its size or its class: an env Hash may
|
|
214
|
+
# hold OTLP headers, and an injected exporter holds its own. The PII
|
|
215
|
+
# hash key is never shown.
|
|
216
|
+
def inspect
|
|
217
|
+
shown = to_h.compact.map do |name, value|
|
|
218
|
+
"#{name}=#{name == :pii_hash_key ? "[FILTERED]" : Options.summary_of(value)}"
|
|
219
|
+
end
|
|
220
|
+
"#<#{self.class.name} #{shown.join(", ")}>"
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
# @api private
|
|
224
|
+
def self.summary_of(value)
|
|
225
|
+
case value
|
|
226
|
+
when String, Symbol, Numeric, true, false then value.inspect
|
|
227
|
+
when Hash then "{#{value.size} entries}"
|
|
228
|
+
when Array then "[#{value.size} entries]"
|
|
229
|
+
else value.equal?(HERMETIC) ? "HERMETIC" : "#<#{value.class.name}>"
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
alias_method :to_s, :inspect
|
|
233
|
+
|
|
234
|
+
def pretty_print(printer)
|
|
235
|
+
printer.text(inspect)
|
|
236
|
+
end
|
|
237
|
+
|
|
81
238
|
def initialize(**kwargs)
|
|
82
239
|
unknown = kwargs.keys - self.class.members
|
|
83
240
|
raise ArgumentError, "libo11y: unknown option#{"s" if unknown.length > 1} #{unknown.join(", ")}" unless unknown.empty?
|
|
@@ -98,7 +255,8 @@ module Libo11y
|
|
|
98
255
|
log_processors: [],
|
|
99
256
|
shutdown_timeout: 5.0
|
|
100
257
|
}
|
|
101
|
-
|
|
258
|
+
# nil for an option means its default, as nil does for env and timeout.
|
|
259
|
+
super(**defaults.merge(kwargs.compact))
|
|
102
260
|
end
|
|
103
261
|
end
|
|
104
262
|
end
|
data/lib/libo11y/rack.rb
CHANGED
|
@@ -5,6 +5,8 @@ require "opentelemetry"
|
|
|
5
5
|
require_relative "record"
|
|
6
6
|
require_relative "spec"
|
|
7
7
|
require_relative "internal/http_common"
|
|
8
|
+
require_relative "internal/quiet_inspect"
|
|
9
|
+
require_relative "internal/path_match"
|
|
8
10
|
|
|
9
11
|
module Libo11y
|
|
10
12
|
# Rack middleware (Rails, Sinatra, Hanami, Roda). It records a server span
|
|
@@ -14,7 +16,8 @@ module Libo11y
|
|
|
14
16
|
module Rack
|
|
15
17
|
HTTP_DURATION_BUCKETS = Internal::HttpCommon::DURATION_BUCKETS
|
|
16
18
|
ROUTE_FIBER_KEY = :libo11y_http_route
|
|
17
|
-
|
|
19
|
+
private_constant :ROUTE_FIBER_KEY
|
|
20
|
+
SCOPE_NAME = Internal::HistogramBuckets::RACK_SCOPE
|
|
18
21
|
|
|
19
22
|
# Sets the route template of the request this thread is serving, such as
|
|
20
23
|
# "/orders/:id", for a router the middleware does not know.
|
|
@@ -23,12 +26,17 @@ module Libo11y
|
|
|
23
26
|
end
|
|
24
27
|
|
|
25
28
|
# Matches a path against an ignore pattern as Go's path.Match does: `*`
|
|
26
|
-
# stays within one path segment
|
|
29
|
+
# stays within one path segment, also when it is written twice, and it
|
|
30
|
+
# matches a leading dot. A malformed pattern matches nothing.
|
|
27
31
|
def self.match_glob?(pattern, path)
|
|
28
|
-
|
|
32
|
+
Internal::PathMatch.match?(pattern, path)
|
|
33
|
+
rescue Internal::PathMatch::BadPattern
|
|
34
|
+
false
|
|
29
35
|
end
|
|
30
36
|
|
|
31
37
|
class Middleware
|
|
38
|
+
include Internal::QuietInspect
|
|
39
|
+
|
|
32
40
|
# @param telemetry [Libo11y::Telemetry, nil] the handle to record
|
|
33
41
|
# through. Without one the middleware uses the global providers.
|
|
34
42
|
# @param route [#call, nil] returns the route template for a Rack env
|
|
@@ -57,11 +65,14 @@ module Libo11y
|
|
|
57
65
|
@canonical_line = canonical_line
|
|
58
66
|
@mutex = Mutex.new
|
|
59
67
|
@duration = nil
|
|
68
|
+
@duration_provider = nil
|
|
60
69
|
end
|
|
61
70
|
|
|
62
71
|
def call(env)
|
|
63
|
-
path
|
|
64
|
-
|
|
72
|
+
# The decoded path, as Go and Python record it: url.path, the
|
|
73
|
+
# summary and ignore_paths all see the same text.
|
|
74
|
+
path = decode_path(env["PATH_INFO"].to_s)
|
|
75
|
+
return @app.call(env) if ignored?(path, env)
|
|
65
76
|
|
|
66
77
|
previous_route = Thread.current[ROUTE_FIBER_KEY]
|
|
67
78
|
Thread.current[ROUTE_FIBER_KEY] = nil
|
|
@@ -74,13 +85,96 @@ module Libo11y
|
|
|
74
85
|
|
|
75
86
|
private
|
|
76
87
|
|
|
77
|
-
Request = Struct.new(:verb, :scheme, :path, :started, :status, :error)
|
|
78
|
-
|
|
88
|
+
Request = Struct.new(:verb, :original, :scheme, :path, :started, :status, :error)
|
|
89
|
+
# One request on its way to completion: what finish needs, and whether it ran.
|
|
90
|
+
Exchange = Struct.new(:span, :context, :record, :request, :route, :done)
|
|
91
|
+
private_constant :Request, :Exchange
|
|
92
|
+
|
|
93
|
+
# A response body that tells the middleware when the server has closed
|
|
94
|
+
# it and whether sending it raised. It answers what the body it wraps
|
|
95
|
+
# answers, so a server still sees an enumerable body, a streaming body
|
|
96
|
+
# or a file as what it is.
|
|
97
|
+
class Body
|
|
98
|
+
include Internal::QuietInspect
|
|
99
|
+
|
|
100
|
+
# @param within [Proc] runs its block in the request's context
|
|
101
|
+
def initialize(body, within, on_error, &on_close)
|
|
102
|
+
@body = body
|
|
103
|
+
@within = within
|
|
104
|
+
@on_error = on_error
|
|
105
|
+
@on_close = on_close
|
|
106
|
+
@closed = false
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def each(&)
|
|
110
|
+
produce { @body.each(&) }
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# A streaming body: the server calls it with the stream.
|
|
114
|
+
def call(stream)
|
|
115
|
+
produce { @body.call(stream) }
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# A body that names a file. The server may send the file itself, and
|
|
119
|
+
# still closes the body.
|
|
120
|
+
def to_path
|
|
121
|
+
produce { @body.to_path }
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# As Rack::BodyProxy: a caller that takes the Array has the whole body.
|
|
125
|
+
def to_ary
|
|
126
|
+
produce { @body.to_ary }
|
|
127
|
+
ensure
|
|
128
|
+
close
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def close
|
|
132
|
+
return if @closed
|
|
133
|
+
|
|
134
|
+
@closed = true
|
|
135
|
+
begin
|
|
136
|
+
produce { @body.close } if @body.respond_to?(:close)
|
|
137
|
+
ensure
|
|
138
|
+
@on_close.call
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# Runs a step of the body in the request's context, and reports an
|
|
143
|
+
# error it raises before raising it again.
|
|
144
|
+
def produce(&)
|
|
145
|
+
@within.call(&)
|
|
146
|
+
rescue StandardError => e
|
|
147
|
+
@on_error.call(e)
|
|
148
|
+
raise
|
|
149
|
+
end
|
|
150
|
+
private :produce
|
|
151
|
+
|
|
152
|
+
def respond_to?(name, include_all = false) # rubocop:disable Style/OptionalBooleanParameter -- Object#respond_to?'s own signature
|
|
153
|
+
return @body.respond_to?(name, include_all) if %i[each call to_ary to_path].include?(name.to_sym)
|
|
154
|
+
|
|
155
|
+
super
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def respond_to_missing?(name, include_all = false)
|
|
159
|
+
name.to_sym != :to_str && @body.respond_to?(name, include_all)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def method_missing(name, ...)
|
|
163
|
+
return super if name.to_sym == :to_str || !@body.respond_to?(name)
|
|
164
|
+
|
|
165
|
+
@body.public_send(name, ...)
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
private_constant :Body
|
|
169
|
+
|
|
170
|
+
# The status of a request whose connection the application took over.
|
|
171
|
+
HIJACKED_STATUS = 101
|
|
172
|
+
private_constant :HIJACKED_STATUS
|
|
79
173
|
|
|
80
174
|
def serve(env, path)
|
|
81
175
|
method, original = Internal::HttpCommon.normalize_method(env["REQUEST_METHOD"].to_s)
|
|
82
176
|
scheme = env["rack.url_scheme"].to_s
|
|
83
|
-
request = Request.new(method, scheme.empty? ? "http" : scheme, path, Internal::HttpCommon.monotonic, 500, nil)
|
|
177
|
+
request = Request.new(method, original, scheme.empty? ? "http" : scheme, path, Internal::HttpCommon.monotonic, 500, nil)
|
|
84
178
|
parent, links = parent_context(env)
|
|
85
179
|
route = resolve_route(env)
|
|
86
180
|
|
|
@@ -90,32 +184,124 @@ module Libo11y
|
|
|
90
184
|
attrs["server.address"] = env["SERVER_NAME"].to_s unless env["SERVER_NAME"].to_s.empty?
|
|
91
185
|
attrs["server.port"] = env["SERVER_PORT"].to_i unless env["SERVER_PORT"].to_s.empty?
|
|
92
186
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
187
|
+
taken, restore_hijack = watch_hijack(env)
|
|
188
|
+
begin
|
|
189
|
+
OpenTelemetry::Context.with_current(parent) do
|
|
190
|
+
span = tracer.start_span(Internal::HttpCommon.span_name(method, route), attributes: attrs, links: links, kind: :server)
|
|
191
|
+
# The request's context: the caller's, with the server span current.
|
|
192
|
+
exchange = Exchange.new(span, OpenTelemetry::Trace.context_with_span(span), nil, request, route, false)
|
|
193
|
+
dispatch(env, exchange, taken)
|
|
194
|
+
end
|
|
195
|
+
ensure
|
|
196
|
+
restore_hijack&.call
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def dispatch(env, exchange, taken)
|
|
201
|
+
returned = false
|
|
202
|
+
begin
|
|
203
|
+
response = OpenTelemetry::Trace.with_span(exchange.span) do
|
|
204
|
+
Libo11y.start_record do |record|
|
|
205
|
+
exchange.record = record
|
|
206
|
+
@app.call(env)
|
|
107
207
|
end
|
|
108
|
-
response = with_server_timing(response, span) if @server_timing
|
|
109
|
-
ensure
|
|
110
|
-
span.finish
|
|
111
208
|
end
|
|
209
|
+
exchange.request.status = response[0].to_i unless taken.call
|
|
210
|
+
returned = true
|
|
211
|
+
rescue StandardError => e
|
|
212
|
+
exchange.request.error = e
|
|
213
|
+
raise
|
|
214
|
+
ensure
|
|
215
|
+
# After a full hijack the server sends no status of its own,
|
|
216
|
+
# whatever the application returns or raises. The request is
|
|
217
|
+
# recorded as 101 Switching Protocols, as in Go.
|
|
218
|
+
exchange.request.status = HIJACKED_STATUS if taken.call
|
|
219
|
+
# Read here: the route a router set is cleared when call returns.
|
|
220
|
+
exchange.route = Thread.current[ROUTE_FIBER_KEY] || exchange.route || resolve_route(env)
|
|
221
|
+
# The application raised or was unwound, so no body follows.
|
|
222
|
+
complete(exchange) unless returned
|
|
223
|
+
end
|
|
224
|
+
if taken.call
|
|
225
|
+
complete(exchange)
|
|
226
|
+
return response
|
|
112
227
|
end
|
|
113
|
-
response
|
|
228
|
+
response = with_server_timing(response, exchange.span) if @server_timing
|
|
229
|
+
deliver(response, exchange)
|
|
114
230
|
end
|
|
115
231
|
|
|
116
|
-
#
|
|
232
|
+
# The response the server gets. An Array body is complete when the
|
|
233
|
+
# application returns, so the request ends here, as it does for no
|
|
234
|
+
# body and for a partial hijack. Any other body is produced while the
|
|
235
|
+
# server sends it: it is wrapped, and the request ends when the server
|
|
236
|
+
# closes it, as the Rack specification requires of a server. The body
|
|
237
|
+
# is produced in the request's context, with the span, the baggage and
|
|
238
|
+
# the wide record current, so what it logs is correlated. The time it
|
|
239
|
+
# takes counts, and an error it raises is recorded.
|
|
240
|
+
def deliver(response, exchange)
|
|
241
|
+
status, headers, body = response
|
|
242
|
+
# Nothing of these is produced later: an Array is whole, a 204 or a
|
|
243
|
+
# HEAD response may have no body, and after a partial hijack the
|
|
244
|
+
# server runs the response callback and ignores the body.
|
|
245
|
+
if body.is_a?(Array) || body.nil? || (headers.is_a?(Hash) && headers.key?("rack.hijack"))
|
|
246
|
+
complete(exchange)
|
|
247
|
+
return response
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
failed = ->(error) { exchange.request.error ||= error }
|
|
251
|
+
[status, headers, Body.new(body, ->(&work) { resume(exchange, &work) }, failed) { complete(exchange) }]
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# Puts a wrapper around the request's hijack callback and returns a
|
|
255
|
+
# callable that says whether the application called it, plus a
|
|
256
|
+
# restorer for env["rack.hijack"]. After a full hijack the server
|
|
257
|
+
# ignores the response and closes no body, so the request ends when
|
|
258
|
+
# the application returns.
|
|
259
|
+
def watch_hijack(env)
|
|
260
|
+
hijack = env["rack.hijack"]
|
|
261
|
+
return [-> { false }, nil] unless hijack.respond_to?(:call)
|
|
262
|
+
|
|
263
|
+
called = false
|
|
264
|
+
wrapper = lambda do |*arguments, **keywords, &block|
|
|
265
|
+
# A hijack that raises leaves the connection with the server.
|
|
266
|
+
hijack.call(*arguments, **keywords, &block).tap { called = true }
|
|
267
|
+
end
|
|
268
|
+
env["rack.hijack"] = wrapper
|
|
269
|
+
restore = -> { env["rack.hijack"] = hijack if env["rack.hijack"].equal?(wrapper) }
|
|
270
|
+
[-> { called }, restore]
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# Runs the block in the request's context, as while the application
|
|
274
|
+
# ran: the span, the baggage and the wide record are current, and a
|
|
275
|
+
# route the block sets with Rack.set_route becomes the request's.
|
|
276
|
+
def resume(exchange, &work)
|
|
277
|
+
previous_route = Thread.current[ROUTE_FIBER_KEY]
|
|
278
|
+
Thread.current[ROUTE_FIBER_KEY] = nil
|
|
279
|
+
begin
|
|
280
|
+
OpenTelemetry::Context.with_current(exchange.context) { Libo11y.with_record(exchange.record, &work) }
|
|
281
|
+
ensure
|
|
282
|
+
exchange.route = Thread.current[ROUTE_FIBER_KEY] || exchange.route
|
|
283
|
+
Thread.current[ROUTE_FIBER_KEY] = previous_route
|
|
284
|
+
end
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
# Ends the request once: the span's last attributes, the duration and
|
|
288
|
+
# the canonical line, written with the span current so that the
|
|
289
|
+
# measurement's exemplar and the line name it.
|
|
290
|
+
def complete(exchange)
|
|
291
|
+
return if exchange.done
|
|
292
|
+
|
|
293
|
+
exchange.done = true
|
|
294
|
+
begin
|
|
295
|
+
OpenTelemetry::Context.with_current(exchange.context) do
|
|
296
|
+
finish(exchange.span, exchange.record, exchange.request, exchange.route)
|
|
297
|
+
end
|
|
298
|
+
ensure
|
|
299
|
+
exchange.span.finish
|
|
300
|
+
end
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# Sets the span's last attributes, records the duration and writes the canonical line.
|
|
117
304
|
def finish(span, record, request, route)
|
|
118
|
-
route = Thread.current[ROUTE_FIBER_KEY] || route
|
|
119
305
|
route = nil if route.to_s.empty?
|
|
120
306
|
if route
|
|
121
307
|
span.set_attribute("http.route", route)
|
|
@@ -123,7 +309,7 @@ module Libo11y
|
|
|
123
309
|
end
|
|
124
310
|
span.set_attribute("http.response.status_code", request.status)
|
|
125
311
|
|
|
126
|
-
error_type = request.error
|
|
312
|
+
error_type = Internal::ErrorType.of(request.error) if request.error
|
|
127
313
|
error_type ||= request.status.to_s if request.status >= 500
|
|
128
314
|
if error_type
|
|
129
315
|
span.record_exception(request.error) if request.error
|
|
@@ -139,27 +325,36 @@ module Libo11y
|
|
|
139
325
|
|
|
140
326
|
return unless @canonical_line
|
|
141
327
|
|
|
142
|
-
summary =
|
|
328
|
+
summary = {
|
|
143
329
|
"http.request.method" => request.verb,
|
|
144
330
|
"http.response.status_code" => request.status,
|
|
145
331
|
"url.path" => request.path,
|
|
146
332
|
Spec::ATTR_DURATION => elapsed,
|
|
147
333
|
Spec::ATTR_OUTCOME => error_type ? Spec::Outcome::FAILURE : Spec::Outcome::SUCCESS
|
|
148
|
-
|
|
334
|
+
}
|
|
335
|
+
summary["http.request.method_original"] = request.original if request.original
|
|
149
336
|
summary["http.route"] = route if route
|
|
150
337
|
summary["error.type"] = error_type if error_type
|
|
151
|
-
@telemetry
|
|
338
|
+
record.emit_event(@telemetry, Spec::EVENT_REQUEST_SUMMARY, summary)
|
|
152
339
|
end
|
|
153
340
|
|
|
154
341
|
# The context the server span starts in, and its links. A public
|
|
155
|
-
# endpoint starts a new trace and links the caller's span.
|
|
342
|
+
# endpoint starts a new trace and links the caller's span. It keeps
|
|
343
|
+
# the rest of the caller's context, the baggage included, as the Go
|
|
344
|
+
# and Python middleware do.
|
|
156
345
|
def parent_context(env)
|
|
157
346
|
propagator = @telemetry ? @telemetry.propagator : OpenTelemetry.propagation
|
|
158
|
-
extracted =
|
|
347
|
+
extracted = begin
|
|
348
|
+
propagator.extract(request_headers(env), context: OpenTelemetry::Context.empty)
|
|
349
|
+
rescue StandardError => e
|
|
350
|
+
OpenTelemetry.handle_error(exception: e, message: "libo11y: #{propagator.class} raised in extract")
|
|
351
|
+
OpenTelemetry::Context.empty
|
|
352
|
+
end
|
|
159
353
|
return [extracted, nil] unless @public_endpoint
|
|
160
354
|
|
|
161
355
|
remote = OpenTelemetry::Trace.current_span(extracted).context
|
|
162
|
-
|
|
356
|
+
rootless = OpenTelemetry::Trace.context_with_span(OpenTelemetry::Trace::Span::INVALID, parent_context: extracted)
|
|
357
|
+
[rootless, remote.valid? ? [OpenTelemetry::Trace::Link.new(remote)] : nil]
|
|
163
358
|
end
|
|
164
359
|
|
|
165
360
|
# Returns the response with a Server-Timing entry that names the server
|
|
@@ -184,9 +379,10 @@ module Libo11y
|
|
|
184
379
|
[status, headers, body]
|
|
185
380
|
end
|
|
186
381
|
|
|
382
|
+
# Whether the Content-Type's media type is text/html, whatever its parameters.
|
|
187
383
|
def html?(headers)
|
|
188
384
|
key = header_key(headers, "content-type")
|
|
189
|
-
!key.nil? && Array(headers[key]).first.to_s.strip.
|
|
385
|
+
!key.nil? && Array(headers[key]).first.to_s.split(";", 2).first.to_s.strip.casecmp?("text/html")
|
|
190
386
|
end
|
|
191
387
|
|
|
192
388
|
# Rack 3 header names are lower case. Rack 2 applications use any case.
|
|
@@ -201,9 +397,16 @@ module Libo11y
|
|
|
201
397
|
end
|
|
202
398
|
|
|
203
399
|
def decode_path(raw)
|
|
204
|
-
|
|
400
|
+
# Bytes that are not UTF-8 are replaced: one such attribute value
|
|
401
|
+
# fails a whole OTLP export. A server gives the path as binary, in
|
|
402
|
+
# which no byte is invalid, so it is read as UTF-8 first.
|
|
403
|
+
as_utf8(URI.decode_www_form_component(raw.gsub("+", "%2B")))
|
|
205
404
|
rescue ArgumentError
|
|
206
|
-
raw
|
|
405
|
+
as_utf8(raw)
|
|
406
|
+
end
|
|
407
|
+
|
|
408
|
+
def as_utf8(text)
|
|
409
|
+
text.dup.force_encoding(Encoding::UTF_8).scrub
|
|
207
410
|
end
|
|
208
411
|
|
|
209
412
|
def request_headers(env)
|
|
@@ -214,26 +417,36 @@ module Libo11y
|
|
|
214
417
|
end
|
|
215
418
|
end
|
|
216
419
|
|
|
420
|
+
# The route template, or nil. A route callable that raises is reported and
|
|
421
|
+
# read as giving none: it must not replace the application's own
|
|
422
|
+
# error, nor keep the request from ending.
|
|
217
423
|
def resolve_route(env)
|
|
218
424
|
return @route_fn.call(env) if @route_fn.respond_to?(:call)
|
|
219
425
|
|
|
220
|
-
# Sinatra
|
|
221
|
-
|
|
426
|
+
# Sinatra gives "GET /orders/:id". Rails gives "/orders/:id(.:format)",
|
|
427
|
+
# whose optional format is the router's notation and no part of the
|
|
428
|
+
# route template.
|
|
429
|
+
env["sinatra.route"]&.split(" ", 2)&.last || env["action_dispatch.route_uri_pattern"]&.delete_suffix("(.:format)")
|
|
430
|
+
rescue StandardError => e
|
|
431
|
+
OpenTelemetry.handle_error(exception: e, message: "libo11y: the route resolver raised")
|
|
432
|
+
nil
|
|
222
433
|
end
|
|
223
434
|
|
|
224
435
|
def tracer
|
|
225
436
|
provider = @telemetry ? @telemetry.tracer_provider : OpenTelemetry.tracer_provider
|
|
226
|
-
provider.tracer(SCOPE_NAME, Libo11y::VERSION)
|
|
437
|
+
provider.tracer(name: SCOPE_NAME, version: Libo11y::VERSION)
|
|
227
438
|
end
|
|
228
439
|
|
|
229
440
|
def duration
|
|
441
|
+
provider = @telemetry ? @telemetry.meter_provider : OpenTelemetry.meter_provider
|
|
230
442
|
@mutex.synchronize do
|
|
231
|
-
@
|
|
232
|
-
|
|
233
|
-
provider.meter(SCOPE_NAME, version: Libo11y::VERSION).create_histogram(
|
|
443
|
+
unless @duration_provider.equal?(provider)
|
|
444
|
+
@duration = provider.meter(SCOPE_NAME, version: Libo11y::VERSION).create_histogram(
|
|
234
445
|
"http.server.request.duration", unit: "s", description: "Duration of HTTP server requests."
|
|
235
446
|
)
|
|
447
|
+
@duration_provider = provider
|
|
236
448
|
end
|
|
449
|
+
@duration
|
|
237
450
|
end
|
|
238
451
|
end
|
|
239
452
|
end
|