libo11y 0.1.0 → 0.2.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 +71 -1
- data/README.md +7 -4
- data/exe/libo11y +8 -4
- data/lib/libo11y/db.rb +2 -1
- data/lib/libo11y/detached.rb +158 -51
- data/lib/libo11y/http_client.rb +83 -61
- data/lib/libo11y/internal/bridges.rb +107 -3
- data/lib/libo11y/internal/env.rb +91 -16
- data/lib/libo11y/internal/histogram_buckets.rb +21 -0
- data/lib/libo11y/internal/http_common.rb +39 -0
- data/lib/libo11y/internal/logging_device.rb +81 -90
- data/lib/libo11y/internal/pipeline.rb +220 -0
- data/lib/libo11y/internal/policy.rb +36 -23
- data/lib/libo11y/internal/propagators.rb +8 -11
- data/lib/libo11y/internal/resource.rb +96 -92
- data/lib/libo11y/internal/runtime_metrics.rb +32 -46
- data/lib/libo11y/internal/summary.rb +55 -0
- data/lib/libo11y/options.rb +16 -2
- data/lib/libo11y/proc.rb +6 -6
- data/lib/libo11y/rack.rb +175 -135
- data/lib/libo11y/record.rb +11 -7
- data/lib/libo11y/spec/app_registry.rb +6 -5
- data/lib/libo11y/spec/yaml_v3.rb +81 -59
- data/lib/libo11y/telemetry.rb +185 -320
- data/lib/libo11y/testing.rb +105 -56
- data/lib/libo11y/version.rb +1 -1
- metadata +19 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9629b204a896f322453a963ce455749449dfba5b234a3af67cc5742e86e1be5a
|
|
4
|
+
data.tar.gz: 837b04f3203878ce5128a40db7ac7bedc1e129a4764c128b235e379f7d32daca
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 55fe7e3c7a4fed853d04aa645bd061bb372e925dfc948254bc74c3b702a9bd585ab7b0711b76edbc2c67c63f859a820b1e93283bc1418798e86acf6a248b7a5b
|
|
7
|
+
data.tar.gz: 6c6bb641fb3b9a715bdc767e057faba067f5762cc1e733593fe64956a146b58ea15c9418b3051e4be85be1482226fbe802c9c1b024746b041d4aaa5b9eecbeae
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,75 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.2.0] - 2026-11-28
|
|
11
|
+
|
|
12
|
+
This release fixes most of what the first review of 0.1.0 found. It changes an option name, a return type and the text form of a carrier, so read the "Changed" list before upgrading.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- The `console_level` option is now `log_level`, as in the other libo11y implementations. It sets the level of `Telemetry#logger`, which gates the console, OTLP and the extra sinks alike. In 0.1.0 setting `level` on the logger had no effect.
|
|
17
|
+
- `Telemetry#effective_config` returns one frozen line of `key=value` pairs, as Go and Python do. 0.1.0 returned a Hash.
|
|
18
|
+
- The `o11y.telemetry.configured` startup event carries the attributes the registry defines: `service.name`, `service.version`, `o11y.config.traces`, `o11y.config.metrics`, `o11y.config.logs`, `o11y.config.console`, `o11y.config.level`, `o11y.config.sampler`, `o11y.config.propagators`, `o11y.config.runtime_metrics`, `o11y.config.service_version_fallback` and the sanitized endpoints. 0.1.0 wrote keys such as `o11y.config.traces.exporter` that the registry does not define.
|
|
19
|
+
- `Detached::Carrier` writes and reads the URL-encoded text form of the other libo11y implementations (`baggage=...&traceparent=...&tracestate=...`), so a carrier crosses to a Go or Python worker. 0.1.0 wrote JSON, and a carrier that 0.1.0 serialized is not read. `Carrier` exposes `traceparent`, `tracestate`, `baggage`, `span_context` and `zero?` in place of `headers`. `start_linked` starts an `internal` span by default.
|
|
20
|
+
- `Proc.child_env` takes an empty base environment by default and maps `TRACEPARENT` and `TRACESTATE` to `nil` when the active span does not set them, so `Process.spawn` removes a stale value from the child.
|
|
21
|
+
- Explicit options and `resource_attributes` beat `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`. In 0.1.0 the environment beat `service.name` and `deployment.environment.name` given in `resource_attributes`.
|
|
22
|
+
- An injected span processor owns the export path, as an injected exporter does, so no exporter is built from the environment beside it.
|
|
23
|
+
- `Libo11y.force_emit` and `Libo11y.start_record` need a block and raise `ArgumentError` without one. In 0.1.0 a call without a block left its scope open for the rest of the thread.
|
|
24
|
+
- `Libo11y.setup` and `Libo11y.init` lay keywords over an `Options` object given with them, and raise `ArgumentError` for a keyword that is not an option. In 0.1.0 keywords beside an `Options` object were dropped without a word.
|
|
25
|
+
- In the `app_registries` option a `String` of one line is a path and a `Pathname` is always one. A path that does not exist raises `InvalidAppRegistry` with the missing file's name, where 0.1.0 reported a YAML type error.
|
|
26
|
+
- `Libo11y::InvalidEnvironment` names the value and the allowed set, and `Libo11y::CanaryRejected` says "rejected by log pipeline", as Go's errors do.
|
|
27
|
+
- `Rack::Middleware` adds the `Server-Timing` entry to HTML responses only, as the Go middleware does, and raises `ArgumentError` for `canonical_line: true` without `telemetry:`, where it used to emit nothing.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- `shutdown` reported success when the collector rejected a signal's final export. The `ShutdownReport` now names each signal that failed, missed the deadline, or had an export rejected, and an `o11y.telemetry.dropped` event for each goes to the console and the extra sinks.
|
|
32
|
+
- `shutdown` with a timeout that is not a number raised and left every later caller waiting. It now raises `ArgumentError` before it claims the shutdown.
|
|
33
|
+
- `force_flush` flushed the signals one after another and always returned `true`. It flushes them concurrently under one deadline and returns `false` when one fails.
|
|
34
|
+
- `Libo11y.setup` let two concurrent callers both build providers, and a start that failed left its workers running. It claims its place before it builds anything and stops what a failed start built.
|
|
35
|
+
- The startup canary did not fail `setup` when the log exporter answered with a failure or raised.
|
|
36
|
+
- Under `OTEL_SDK_DISABLED=true` the tracer provider recorded spans and minted trace ids. It records nothing and passes an inbound trace context through.
|
|
37
|
+
- An empty per-signal `OTEL_EXPORTER_OTLP_*` variable hid the general one.
|
|
38
|
+
- Percent escapes in `OTEL_RESOURCE_ATTRIBUTES` and in OTLP headers decode as UTF-8.
|
|
39
|
+
- A `Float::NAN` or infinite attribute raised out of the logging call. It is written to the console as `"NaN"`, `"+Inf"` or `"-Inf"`, and a console that fails no longer stops the other sinks.
|
|
40
|
+
- `Detached.capture` returns the zero carrier outside a span and drops the trace state and then the baggage to stay within 32 KiB. `Carrier.unmarshal_text` refuses text with no valid traceparent.
|
|
41
|
+
- `Detached.start_linked` dropped the caller's baggage. It merges the carrier's baggage into it.
|
|
42
|
+
- The baggage egress filter dropped the metadata of the members it let through.
|
|
43
|
+
- The Rack middleware and `HttpClient` record a request method outside the standard set as `_OTHER`, with the method as given in `http.request.method_original`, so a caller cannot grow the metric's series. `HttpClient` sends such a method, where it used to raise.
|
|
44
|
+
- A raised error is recorded on the span once, and the span status carries no error message. A 5xx response sets `error.type` on the span, the metric and the canonical line.
|
|
45
|
+
- The Rack middleware keeps an existing `Server-Timing` value in the form the application set it, a list included, and does not add a second header under another case.
|
|
46
|
+
- A request the middleware ignores no longer clears the route an enclosing middleware set. Ignore patterns match a leading dot, as Go's `path.Match` does.
|
|
47
|
+
- `HttpClient` replaces a propagation header the caller passed in another case.
|
|
48
|
+
- Threads that share a middleware or a client create its histogram once.
|
|
49
|
+
- OTLP payloads carry the specification's schema URL on the resource of every signal. The upstream exporters do not write it, so libo11y adds it as each request is sent.
|
|
50
|
+
- The HTTP and DB duration histograms use their latency boundaries. The SDK ignores the boundaries an instrument advises, so libo11y registers a view for each, and `histogram_buckets` replaces one by name.
|
|
51
|
+
- The `views` option is applied. It takes Hashes of `MeterProvider#add_view` arguments with a `:name`. In 0.1.0 it did nothing.
|
|
52
|
+
- With `env: Libo11y::HERMETIC` or an explicit `env`, the span and log record limits, the batch processors' worker switch, and the exporters' certificate files and certificate verification no longer come from the process environment.
|
|
53
|
+
- Two registries that declare one namespace are refused also when they are given as compiled registries.
|
|
54
|
+
- The registry parser checks the escapes of a double-quoted scalar that follows an apostrophe in a plain or block scalar. It used to treat the apostrophe as an open quote, so `"a \/ b"` was accepted there and `"it the log record and the exemplar were on different traces. It requires one trace with a span, a log record and an exemplar, and takes a metric name to look at one metric's exemplars.
|
|
55
|
+
- `Recorder#assert_conforms!` passed after the code under test emitted a secret, because the secret had been redacted. It now fails on any counted redaction of a secret, as Go's `AssertConforms` does, looks at metric data points too, and lists every problem it finds.
|
|
56
|
+
|
|
57
|
+
## [0.1.0] - 2026-11-28
|
|
58
|
+
|
|
59
|
+
### Added
|
|
60
|
+
|
|
61
|
+
- Core Ruby SDK (`Libo11y.setup`, `Libo11y.init`, `Options`, typed `Libo11y::Error` hierarchy, idempotent bounded concurrent shutdown, `shutdown_on_signals`).
|
|
62
|
+
- Generated spec constants, tables, and `GoPrint` ranges (`Libo11y::Spec`, spec 1.3.0) and strict `yaml.v3`-compatible application attribute registry validator passing all 46 shared conformance cases, plus `exe/libo11y registry check`.
|
|
63
|
+
- Single `SensitivityPolicy` across resource, spans, metrics (PII always dropped), and structured logs, matching all shared PII hash, instance ID, and endpoint sanitization conformance vectors. An injected span processor sees the redacted span through `attributes`, `events`, `links` and `to_span_data`. Observable instruments classify the attributes given to `add_attributes` and `observe`. A log record is classified once, so one PII value has one token on the console, on OTLP and on spans, and one violation is counted per record. The walk over nested log values drops what its depth bound, its budget of 2048 nodes or a cycle kept it from examining.
|
|
64
|
+
- Capture-time redaction (`Libo11y::Redact::Secret`, `Masked`, `Fields`), where the strictest protection wins through nesting and a subclass keeps its parent's field rules, wide events (`Record`), `force_emit`, detached propagation (`Libo11y::Detached`), child-process propagation (`Libo11y::Proc`), and zero-dependency Ruby/process runtime metrics.
|
|
65
|
+
- Integrations: `Libo11y::Rack::Middleware`, `Libo11y::HttpClient`, and `Libo11y::DB::Client`. The DB client removes literals and comments with the same dialect-aware lexer as `go/o11ysql` (PostgreSQL dollar quoting, escape strings and nested comments, MySQL backslash escapes, double-quoted strings, `#` and versioned comments, SQLite parameters), records `db.query.text` only for `postgresql`, `sqlite`, `mysql` and `mariadb`, capped at 4096 bytes, names the span after the operation and table, and never records a driver's error message.
|
|
66
|
+
- Hermetic test harness (`Libo11y::Testing::Recorder` and `OtlpHttpReceiver`). `OtlpHttpReceiver` serves through WEBrick, which the gem does not depend on. A consumer adds `gem "webrick"` to its test group.
|
|
67
|
+
|
|
68
|
+
[Unreleased]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.2.0...HEAD
|
|
69
|
+
[0.2.0]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.1.0...ruby/v0.2.0
|
|
70
|
+
[0.1.0]: https://github.com/jamesainslie/libo11y/releases/tag/ruby/v0.1.0
|
|
71
|
+
s"` was refused.
|
|
72
|
+
- `exe/libo11y` prints its usage on standard output and exits 0 for `-h`, `--help` and `help`, as the Go command does.
|
|
73
|
+
- Resident memory is computed with the system's page size, not a fixed 4 KiB.
|
|
74
|
+
- `OtlpHttpReceiver` returns copies of what it has received, taken under its lock.
|
|
75
|
+
- The gem declares its dependency on `logger`, which stops being a default gem in Ruby 3.5.
|
|
76
|
+
- `Recorder#assert_triangle!` passed when the log record and the exemplar were on different traces. It requires one trace with a span, a log record and an exemplar, and takes a metric name to look at one metric's exemplars.
|
|
77
|
+
- `Recorder#assert_conforms!` passed after the code under test emitted a secret, because the secret had been redacted. It now fails on any counted redaction of a secret, as Go's `AssertConforms` does, looks at metric data points too, and lists every problem it finds.
|
|
78
|
+
|
|
10
79
|
## [0.1.0] - 2026-11-28
|
|
11
80
|
|
|
12
81
|
### Added
|
|
@@ -18,5 +87,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
18
87
|
- Integrations: `Libo11y::Rack::Middleware`, `Libo11y::HttpClient`, and `Libo11y::DB::Client`. The DB client removes literals and comments with the same dialect-aware lexer as `go/o11ysql` (PostgreSQL dollar quoting, escape strings and nested comments, MySQL backslash escapes, double-quoted strings, `#` and versioned comments, SQLite parameters), records `db.query.text` only for `postgresql`, `sqlite`, `mysql` and `mariadb`, capped at 4096 bytes, names the span after the operation and table, and never records a driver's error message.
|
|
19
88
|
- Hermetic test harness (`Libo11y::Testing::Recorder` and `OtlpHttpReceiver`). `OtlpHttpReceiver` serves through WEBrick, which the gem does not depend on. A consumer adds `gem "webrick"` to its test group.
|
|
20
89
|
|
|
21
|
-
[Unreleased]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.
|
|
90
|
+
[Unreleased]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.2.0...HEAD
|
|
91
|
+
[0.2.0]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.1.0...ruby/v0.2.0
|
|
22
92
|
[0.1.0]: https://github.com/jamesainslie/libo11y/releases/tag/ruby/v0.1.0
|
data/README.md
CHANGED
|
@@ -29,6 +29,8 @@ end
|
|
|
29
29
|
|
|
30
30
|
`Libo11y.setup` installs the global tracer, meter, and logger providers, installs the W3C TraceContext + Baggage propagator wrapped in the baggage egress filter, and runs the startup canary (`o11y.telemetry.configured`). Passing a block guarantees bounded concurrent shutdown across all three signals when the block exits.
|
|
31
31
|
|
|
32
|
+
`tel.shutdown(timeout: 5)` runs once and returns a `ShutdownReport`. `report.ok?` is false, and `report.errors` names the signal, when a signal fails, misses the deadline, or has its final export rejected by the collector. Each such signal also gets an `o11y.telemetry.dropped` event on the console and the extra sinks. `tel.force_flush` returns `false` on the same failures.
|
|
33
|
+
|
|
32
34
|
Use `Libo11y.init(...)` for non-global handles in tests and dependency injection.
|
|
33
35
|
|
|
34
36
|
### Graceful shutdown on signals
|
|
@@ -47,11 +49,11 @@ bundle exec libo11y registry check o11y-registry.yaml
|
|
|
47
49
|
|
|
48
50
|
| Module | Notes |
|
|
49
51
|
|---|---|
|
|
50
|
-
| `Libo11y::Rack::Middleware` | Rack 3 middleware (Rails, Sinatra, Hanami); route templates (`set_route`, Sinatra/Rails keys), `http.server.request.duration` with exemplars, `public_endpoint`, `ignore_paths`, `filter`, `server_timing
|
|
52
|
+
| `Libo11y::Rack::Middleware` | Rack 3 middleware (Rails, Sinatra, Hanami); route templates (`set_route`, Sinatra/Rails keys), `http.server.request.duration` with exemplars, `public_endpoint`, `ignore_paths`, `filter`, `server_timing` (HTML responses), `canonical_line` (needs `telemetry:`). A method outside the standard set is recorded as `_OTHER` |
|
|
51
53
|
| `Libo11y::HttpClient` | Instrumented `Net::HTTP` client (no global monkey-patching); W3C injection, URL credential stripping, `propagate_fn`, `peer_service`, `http.client.request.duration` with exemplars |
|
|
52
54
|
| `Libo11y::DB::Client` | Parent-gated DB client spans named after the operation and table, `db.client.operation.duration` with exemplars, and sanitized `db.query.text` for `postgresql`, `sqlite`, `mysql` and `mariadb` only, capped at 4096 bytes (`query_text: false` turns it off). A failed call sets `error.type` to the SQLSTATE or the error class and never records the driver's message |
|
|
53
|
-
| `Libo11y::Detached` | 32 KiB
|
|
54
|
-
| `Libo11y::Proc` | `TRACEPARENT`/`TRACESTATE` env carriers (never baggage) and framed map `inject_frame`/`extract_frame` |
|
|
55
|
+
| `Libo11y::Detached` | `Carrier` with the URL-encoded text form every libo11y implementation reads (at most 32 KiB, the trace state and then the baggage dropped to fit), egress-filtered baggage, `capture`, `restore_baggage`, and `start_linked`, which starts a linked root span and merges the carrier's baggage into the caller's |
|
|
56
|
+
| `Libo11y::Proc` | `TRACEPARENT`/`TRACESTATE` env carriers (never baggage) and framed map `inject_frame`/`extract_frame`. Pass `Libo11y::Proc.child_env` as the environment argument of `Process.spawn`: it adds the current trace and removes a stale one the child would inherit |
|
|
55
57
|
| `Libo11y::Redact` | `Secret`, `Masked`, and `Fields` mixin (`mask`, `redact`, `omit`, `confidential`, `secret`) |
|
|
56
58
|
| `Libo11y::Testing` | Hermetic `Recorder` (`assert_conforms!`, `assert_correlated!`, `assert_triangle!`) and in-process `OtlpHttpReceiver`. The receiver serves through WEBrick, which the gem does not depend on, so add `gem "webrick"` to your test group to use it |
|
|
57
59
|
|
|
@@ -59,6 +61,7 @@ bundle exec libo11y registry check o11y-registry.yaml
|
|
|
59
61
|
|
|
60
62
|
- **Traces:** `PolicySpanExporter` and `PolicySpanProcessor` classify span, event, and link attributes before leaving the process. An injected span processor receives a redacted view at `on_finish` (`attributes`, `events`, `links`, `to_span_data`) and the live span at `on_start`.
|
|
61
63
|
- **Metrics:** `PolicyMeterProvider` classifies the attributes of synchronous measurements and of observable instruments (`add_attributes`, `observe`) before SDK recording (covering derived Views and exemplars). PII is always dropped on metrics even in `PIIMode::HASH`. Trace-based exemplars are on by default.
|
|
62
|
-
- **Logs:** `
|
|
64
|
+
- **Logs:** `tel.logger` is a `::Logger`. Its `level`, first set by the `log_level` option (`Logger::INFO` by default), gates the console, OTLP and the extra sinks alike. `Libo11y.force_emit { ... }` and `tel.event` pass it. `StructuredLogger` applies capture-time redaction, user `attr_replacer`, and `SensitivityPolicy` once per record, and writes the same classified attributes to console JSON, OTLP logs, and extra sinks. Nested values are walked to a depth of 16 within a budget of 2048 nodes, and what the walk did not examine, a cycle included, is dropped. A record from the OpenTelemetry Logs API is classified by the first processor on the logger provider, before any injected processor sees it.
|
|
63
65
|
- **Policy scope (shared across all languages):** Key-based classification does not inspect log message bodies, span names, span status descriptions, instrumentation scope attributes, map-valued span/metric members, attributes read at `on_start`, or baggage. Use `Libo11y::Redact` for values under unclassified keys.
|
|
66
|
+
- **Environment:** With `env: Libo11y::HERMETIC` or an explicit `env`, libo11y passes every setting it can to the SDK, so the process environment does not set limits, batch settings or certificate verification. Two variables remain that the upstream metrics SDK reads directly: `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` and `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION`.
|
|
64
67
|
- **Protocol support:** OTLP over `http/protobuf` is supported (gRPC and Prometheus exporters raise `Libo11y::UnsupportedProtocol`).
|
data/exe/libo11y
CHANGED
|
@@ -3,13 +3,17 @@
|
|
|
3
3
|
|
|
4
4
|
require "libo11y/spec"
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
USAGE = "usage: libo11y registry check FILE..."
|
|
7
|
+
|
|
8
|
+
if ARGV.length == 1 && %w[-h --help help].include?(ARGV[0])
|
|
9
|
+
puts USAGE
|
|
10
|
+
exit 0
|
|
11
|
+
end
|
|
12
|
+
if ARGV.length < 3 || ARGV[0] != "registry" || ARGV[1] != "check"
|
|
13
|
+
warn USAGE
|
|
8
14
|
exit 2
|
|
9
15
|
end
|
|
10
16
|
|
|
11
|
-
usage if ARGV.length < 3 || ARGV[0] != "registry" || ARGV[1] != "check"
|
|
12
|
-
|
|
13
17
|
files = ARGV[2..]
|
|
14
18
|
exit_code = 0
|
|
15
19
|
|
data/lib/libo11y/db.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "opentelemetry"
|
|
4
|
+
require_relative "internal/histogram_buckets"
|
|
4
5
|
require_relative "internal/sql_text"
|
|
5
6
|
|
|
6
7
|
module Libo11y
|
|
@@ -10,7 +11,7 @@ module Libo11y
|
|
|
10
11
|
# removed, and never the driver's error message, which often quotes
|
|
11
12
|
# statement values.
|
|
12
13
|
module DB
|
|
13
|
-
DB_DURATION_BUCKETS =
|
|
14
|
+
DB_DURATION_BUCKETS = Internal::HistogramBuckets::DB
|
|
14
15
|
SCOPE_NAME = "libo11y.db"
|
|
15
16
|
|
|
16
17
|
# The lexer for a db.system.name value, and whether that lexer is known to
|
data/lib/libo11y/detached.rb
CHANGED
|
@@ -1,90 +1,197 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "json"
|
|
4
3
|
require "opentelemetry"
|
|
5
4
|
require_relative "errors"
|
|
6
5
|
|
|
7
6
|
module Libo11y
|
|
8
|
-
#
|
|
7
|
+
# Trace propagation for work that runs detached from the request that
|
|
8
|
+
# caused it: a background job, a queue message, an outbox row. The request
|
|
9
|
+
# captures a Carrier, the carrier travels as text with the work, and the
|
|
10
|
+
# worker starts a new root span linked to the request's span.
|
|
9
11
|
module Detached
|
|
12
|
+
# The longest text form of a carrier, in bytes.
|
|
10
13
|
MAX_CARRIER_BYTES = 32 * 1024
|
|
11
14
|
|
|
15
|
+
# A captured span context and baggage. Its text form is the URL-encoded
|
|
16
|
+
# query every libo11y implementation writes, so a carrier a Ruby service
|
|
17
|
+
# captured starts a linked span in a Go or Python worker, and the other
|
|
18
|
+
# way round. The zero carrier, captured outside a span, has no
|
|
19
|
+
# traceparent and writes empty text.
|
|
12
20
|
class Carrier
|
|
13
|
-
attr_reader :
|
|
21
|
+
attr_reader :traceparent, :tracestate, :baggage
|
|
14
22
|
|
|
15
|
-
|
|
16
|
-
|
|
23
|
+
# Reads the text form. Empty text is the zero carrier.
|
|
24
|
+
#
|
|
25
|
+
# @raise [InvalidCarrier] when the text is longer than 32 KiB, is not a
|
|
26
|
+
# URL-encoded query, or holds no valid traceparent
|
|
27
|
+
def self.unmarshal_text(text)
|
|
28
|
+
raise InvalidCarrier, "o11y: invalid carrier: the text is nil" if text.nil?
|
|
29
|
+
return ZERO if text.empty?
|
|
30
|
+
if text.bytesize > MAX_CARRIER_BYTES
|
|
31
|
+
raise InvalidCarrier, "o11y: invalid carrier: #{text.bytesize} bytes exceeds the #{MAX_CARRIER_BYTES} byte limit"
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
fields = Query.parse(text)
|
|
35
|
+
context = new(fields["traceparent"].to_s, fields["tracestate"].to_s, "").span_context
|
|
36
|
+
raise InvalidCarrier, "o11y: invalid carrier: no valid traceparent" unless context.valid?
|
|
37
|
+
|
|
38
|
+
from_span_context(context, Baggage.valid_members(fields["baggage"].to_s))
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Builds the carrier of a span context and a baggage header value. To
|
|
42
|
+
# stay within 32 KiB it drops the trace state first and then the
|
|
43
|
+
# baggage, and always keeps the traceparent, so the link survives.
|
|
44
|
+
def self.from_span_context(span_context, baggage)
|
|
45
|
+
headers = {}
|
|
46
|
+
span = OpenTelemetry::Trace.non_recording_span(span_context)
|
|
47
|
+
context = OpenTelemetry::Trace.context_with_span(span, parent_context: OpenTelemetry::Context.empty)
|
|
48
|
+
OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.inject(headers, context: context)
|
|
49
|
+
|
|
50
|
+
carrier = new(headers["traceparent"].to_s, headers["tracestate"].to_s, baggage.to_s)
|
|
51
|
+
carrier = new(carrier.traceparent, "", carrier.baggage) if carrier.marshal_text.bytesize > MAX_CARRIER_BYTES
|
|
52
|
+
carrier = new(carrier.traceparent, "", "") if carrier.marshal_text.bytesize > MAX_CARRIER_BYTES
|
|
53
|
+
carrier
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def initialize(traceparent, tracestate, baggage)
|
|
57
|
+
@traceparent = traceparent.dup.freeze
|
|
58
|
+
@tracestate = tracestate.dup.freeze
|
|
59
|
+
@baggage = baggage.dup.freeze
|
|
60
|
+
freeze
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# True for the carrier captured outside a span.
|
|
64
|
+
def zero?
|
|
65
|
+
@traceparent.empty?
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# The captured span context. It is invalid for the zero carrier.
|
|
69
|
+
def span_context
|
|
70
|
+
headers = { "traceparent" => @traceparent, "tracestate" => @tracestate }.reject { |_, v| v.empty? }
|
|
71
|
+
context = OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.extract(headers, context: OpenTelemetry::Context.empty)
|
|
72
|
+
OpenTelemetry::Trace.current_span(context).context
|
|
17
73
|
end
|
|
18
74
|
|
|
75
|
+
# The text form: a URL-encoded query with its keys in order.
|
|
19
76
|
def marshal_text
|
|
20
|
-
|
|
21
|
-
raise InvalidCarrier, "o11y: carrier exceeds #{MAX_CARRIER_BYTES} byte limit" if text.bytesize > MAX_CARRIER_BYTES
|
|
77
|
+
return "" if zero?
|
|
22
78
|
|
|
23
|
-
|
|
79
|
+
fields = { "baggage" => @baggage, "traceparent" => @traceparent, "tracestate" => @tracestate }
|
|
80
|
+
fields.reject { |_, value| value.empty? }.map { |key, value| "#{key}=#{Query.escape(value)}" }.join("&")
|
|
24
81
|
end
|
|
82
|
+
alias to_s marshal_text
|
|
25
83
|
|
|
26
|
-
def
|
|
27
|
-
|
|
28
|
-
|
|
84
|
+
def ==(other)
|
|
85
|
+
other.is_a?(Carrier) && traceparent == other.traceparent && tracestate == other.tracestate && baggage == other.baggage
|
|
86
|
+
end
|
|
87
|
+
alias eql? ==
|
|
29
88
|
|
|
30
|
-
|
|
31
|
-
|
|
89
|
+
def hash
|
|
90
|
+
[traceparent, tracestate, baggage].hash
|
|
91
|
+
end
|
|
32
92
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
raise InvalidCarrier, "o11y: carrier entries must be strings" unless k.is_a?(String) && v.is_a?(String)
|
|
93
|
+
ZERO = new("", "", "")
|
|
94
|
+
end
|
|
36
95
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
96
|
+
# URL query encoding as Go's net/url writes and reads it, so the text
|
|
97
|
+
# form is the same bytes in every implementation.
|
|
98
|
+
module Query
|
|
99
|
+
module_function
|
|
100
|
+
|
|
101
|
+
def escape(value)
|
|
102
|
+
value.b.gsub(/[^A-Za-z0-9\-_.~]/n) { |byte| byte == " " ? "+" : format("%%%02X", byte.ord) }
|
|
42
103
|
end
|
|
43
104
|
|
|
44
|
-
def
|
|
45
|
-
|
|
105
|
+
def unescape(text)
|
|
106
|
+
raise InvalidCarrier, "o11y: invalid carrier: invalid URL escape #{text[/%.{0,2}/].inspect}" if text.match?(/%(?![0-9A-Fa-f]{2})/)
|
|
107
|
+
|
|
108
|
+
text.tr("+", " ").b.gsub(/%([0-9A-Fa-f]{2})/) { Regexp.last_match(1).hex.chr }.force_encoding(Encoding::UTF_8).scrub
|
|
46
109
|
end
|
|
47
110
|
|
|
48
|
-
|
|
49
|
-
|
|
111
|
+
# The first value of each key.
|
|
112
|
+
def parse(text)
|
|
113
|
+
raise InvalidCarrier, "o11y: invalid carrier: invalid semicolon separator in query" if text.include?(";")
|
|
114
|
+
|
|
115
|
+
text.split("&").each_with_object({}) do |pair, fields|
|
|
116
|
+
next if pair.empty?
|
|
117
|
+
|
|
118
|
+
key, value = pair.split("=", 2)
|
|
119
|
+
fields[unescape(key)] ||= unescape(value.to_s)
|
|
120
|
+
end
|
|
50
121
|
end
|
|
51
122
|
end
|
|
123
|
+
private_constant :Query
|
|
124
|
+
|
|
125
|
+
# W3C baggage header values.
|
|
126
|
+
module Baggage
|
|
127
|
+
MEMBER = /\A\s*[!#$%&'*+\-.^_`|~0-9A-Za-z]+\s*=\s*[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\s*(;.*)?\z/
|
|
128
|
+
private_constant :MEMBER
|
|
129
|
+
|
|
130
|
+
module_function
|
|
131
|
+
|
|
132
|
+
# The members of a baggage value that are valid on their own, in
|
|
133
|
+
# order, the first of each key.
|
|
134
|
+
def valid_members(header)
|
|
135
|
+
seen = {}
|
|
136
|
+
kept = header.split(",").select do |member|
|
|
137
|
+
next false unless MEMBER.match?(member)
|
|
138
|
+
|
|
139
|
+
key = member.split("=", 2).first.strip
|
|
140
|
+
next false if seen[key]
|
|
141
|
+
|
|
142
|
+
seen[key] = true
|
|
143
|
+
end
|
|
144
|
+
kept.join(",")
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
private_constant :Baggage
|
|
52
148
|
|
|
53
149
|
module_function
|
|
54
150
|
|
|
55
|
-
#
|
|
151
|
+
# Captures the active span and the baggage the egress filter lets out.
|
|
152
|
+
# Outside a span it returns the zero carrier.
|
|
153
|
+
#
|
|
154
|
+
# @param telemetry [Libo11y::Telemetry, nil] the handle whose propagator
|
|
155
|
+
# filters the baggage. Without one the global propagator does.
|
|
56
156
|
def capture(telemetry: nil, context: OpenTelemetry::Context.current)
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
propagator.inject(carrier, context: context)
|
|
60
|
-
Carrier.new(carrier)
|
|
61
|
-
end
|
|
157
|
+
span_context = OpenTelemetry::Trace.current_span(context).context
|
|
158
|
+
return Carrier::ZERO unless span_context.valid?
|
|
62
159
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
extracted = propagator.extract(carrier.headers, context: OpenTelemetry::Context.empty)
|
|
67
|
-
values = OpenTelemetry::Baggage.values(context: extracted)
|
|
68
|
-
ctx = context
|
|
69
|
-
values.each do |k, v|
|
|
70
|
-
ctx = OpenTelemetry::Baggage.set_value(k, v, context: ctx)
|
|
71
|
-
end
|
|
72
|
-
ctx
|
|
160
|
+
headers = {}
|
|
161
|
+
propagator(telemetry).inject(headers, context: context)
|
|
162
|
+
Carrier.from_span_context(span_context, headers["baggage"].to_s)
|
|
73
163
|
end
|
|
74
164
|
|
|
75
|
-
#
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
parent_sc = OpenTelemetry::Trace.current_span(extracted).context
|
|
165
|
+
# Returns context with the carrier's baggage merged over its own. The
|
|
166
|
+
# carrier's span is not adopted.
|
|
167
|
+
def restore_baggage(carrier, context: OpenTelemetry::Context.current)
|
|
168
|
+
return context if carrier.baggage.empty?
|
|
80
169
|
|
|
81
|
-
|
|
82
|
-
|
|
170
|
+
OpenTelemetry::Baggage::Propagation.text_map_propagator.extract({ "baggage" => carrier.baggage }, context: context)
|
|
171
|
+
end
|
|
83
172
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
173
|
+
# Starts a new root span linked to the carrier's span, with the carrier's
|
|
174
|
+
# baggage merged into the caller's, and runs the block inside it. The
|
|
175
|
+
# zero carrier gives a root span with no link.
|
|
176
|
+
#
|
|
177
|
+
# @param telemetry [Libo11y::Telemetry, nil] the handle to trace through.
|
|
178
|
+
# Without one the global tracer provider is used.
|
|
179
|
+
def start_linked(carrier, span_name, tracer_name: "libo11y.detached", telemetry: nil, kind: :internal, attributes: nil, &)
|
|
180
|
+
linked = carrier.span_context
|
|
181
|
+
links = linked.valid? ? [OpenTelemetry::Trace::Link.new(linked)] : nil
|
|
182
|
+
# The caller's span is taken out of the context, so the new span is a root.
|
|
183
|
+
context = restore_baggage(carrier)
|
|
184
|
+
context = OpenTelemetry::Trace.context_with_span(OpenTelemetry::Trace::Span::INVALID, parent_context: context)
|
|
185
|
+
|
|
186
|
+
provider = telemetry ? telemetry.tracer_provider : OpenTelemetry.tracer_provider
|
|
187
|
+
OpenTelemetry::Context.with_current(context) do
|
|
188
|
+
provider.tracer(tracer_name, Libo11y::VERSION).in_span(span_name, links: links, kind: kind, attributes: attributes, &)
|
|
87
189
|
end
|
|
88
190
|
end
|
|
191
|
+
|
|
192
|
+
def propagator(telemetry)
|
|
193
|
+
telemetry ? telemetry.propagator : OpenTelemetry.propagation
|
|
194
|
+
end
|
|
195
|
+
private_class_method :propagator
|
|
89
196
|
end
|
|
90
197
|
end
|
data/lib/libo11y/http_client.rb
CHANGED
|
@@ -3,96 +3,118 @@
|
|
|
3
3
|
require "net/http"
|
|
4
4
|
require "uri"
|
|
5
5
|
require "opentelemetry"
|
|
6
|
+
require_relative "internal/http_common"
|
|
6
7
|
|
|
7
8
|
module Libo11y
|
|
8
|
-
#
|
|
9
|
+
# An instrumented Net::HTTP client. It records a client span and the
|
|
10
|
+
# http.client.request.duration histogram for each request and injects the
|
|
11
|
+
# trace context into the request headers. It patches nothing globally.
|
|
9
12
|
class HttpClient
|
|
10
|
-
HTTP_DURATION_BUCKETS =
|
|
13
|
+
HTTP_DURATION_BUCKETS = Internal::HttpCommon::DURATION_BUCKETS
|
|
14
|
+
SCOPE_NAME = "libo11y.http"
|
|
11
15
|
|
|
16
|
+
# @param telemetry [Libo11y::Telemetry, nil] the handle to record
|
|
17
|
+
# through. Without one the client uses the global providers.
|
|
18
|
+
# @param propagate_fn [#call, nil] returns false for a URI that must not
|
|
19
|
+
# receive the trace context, such as a third party's
|
|
20
|
+
# @param peer_service [String, nil] the peer.service of the callee
|
|
12
21
|
def initialize(telemetry: nil, propagate_fn: nil, peer_service: nil)
|
|
13
22
|
@telemetry = telemetry
|
|
14
23
|
@propagate_fn = propagate_fn
|
|
15
24
|
@peer_service = peer_service
|
|
25
|
+
@mutex = Mutex.new
|
|
26
|
+
@duration = nil
|
|
16
27
|
end
|
|
17
28
|
|
|
29
|
+
# Sends one request and returns the Net::HTTPResponse.
|
|
30
|
+
#
|
|
31
|
+
# @param method [Symbol, String] the request method, such as :get. A
|
|
32
|
+
# method outside the standard set is sent as given and recorded as
|
|
33
|
+
# _OTHER.
|
|
18
34
|
def request(method, url, headers: {}, body: nil, open_timeout: 5, read_timeout: 15)
|
|
19
35
|
uri = url.is_a?(URI) ? url : URI.parse(url.to_s)
|
|
20
36
|
verb = method.to_s.upcase
|
|
21
|
-
|
|
37
|
+
normalized, original = Internal::HttpCommon.normalize_method(verb)
|
|
22
38
|
|
|
23
|
-
attrs = {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
attrs["peer.service"] = @peer_service.to_s if @peer_service && !@peer_service.to_s.empty?
|
|
39
|
+
attrs = { "http.request.method" => normalized, "server.address" => uri.host.to_s, "server.port" => uri.port }
|
|
40
|
+
metric_attrs = attrs.dup
|
|
41
|
+
attrs["http.request.method_original"] = original if original
|
|
42
|
+
attrs["url.full"] = without_credentials(uri)
|
|
43
|
+
attrs["peer.service"] = @peer_service.to_s unless @peer_service.to_s.empty?
|
|
30
44
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
|
45
|
+
started = Internal::HttpCommon.monotonic
|
|
46
|
+
span = tracer.start_span(Internal::HttpCommon.span_name(normalized), attributes: attrs, kind: :client)
|
|
47
|
+
begin
|
|
48
|
+
OpenTelemetry::Trace.with_span(span) do
|
|
49
|
+
response = send_request(uri, verb, outbound_headers(headers, uri), body, open_timeout: open_timeout, read_timeout: read_timeout)
|
|
50
|
+
status = response.code.to_i
|
|
63
51
|
span.set_attribute("http.response.status_code", status)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
end
|
|
68
|
-
resp
|
|
52
|
+
metric_attrs["http.response.status_code"] = status
|
|
53
|
+
failed(span, metric_attrs, status.to_s) if status >= 400
|
|
54
|
+
response
|
|
69
55
|
rescue StandardError => e
|
|
70
|
-
error = e
|
|
71
56
|
span.record_exception(e)
|
|
72
|
-
span
|
|
73
|
-
span.set_attribute("error.type", e.class.name)
|
|
57
|
+
failed(span, metric_attrs, e.class.name)
|
|
74
58
|
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
59
|
end
|
|
60
|
+
ensure
|
|
61
|
+
duration.record(Internal::HttpCommon.monotonic - started, attributes: metric_attrs)
|
|
62
|
+
span.finish
|
|
86
63
|
end
|
|
87
64
|
end
|
|
88
65
|
|
|
89
66
|
private
|
|
90
67
|
|
|
91
|
-
def
|
|
68
|
+
def failed(span, metric_attrs, error_type)
|
|
69
|
+
span.set_attribute("error.type", error_type)
|
|
70
|
+
span.status = OpenTelemetry::Trace::Status.error
|
|
71
|
+
metric_attrs["error.type"] = error_type
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# The caller's headers with the trace context of the active span. A
|
|
75
|
+
# propagation header the caller passed, in any case, is replaced.
|
|
76
|
+
def outbound_headers(headers, uri)
|
|
77
|
+
out = headers.to_h { |key, value| [key.to_s, value.to_s] }
|
|
78
|
+
return out unless @propagate_fn.nil? || @propagate_fn.call(uri)
|
|
79
|
+
|
|
80
|
+
propagator = @telemetry ? @telemetry.propagator : OpenTelemetry.propagation
|
|
81
|
+
injected = {}
|
|
82
|
+
propagator.inject(injected)
|
|
83
|
+
out.reject { |key, _| injected.keys.any? { |name| name.casecmp?(key) } }.merge(injected)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def send_request(uri, verb, headers, body, open_timeout:, read_timeout:)
|
|
87
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
88
|
+
http.use_ssl = uri.scheme == "https"
|
|
89
|
+
http.open_timeout = open_timeout
|
|
90
|
+
http.read_timeout = read_timeout
|
|
91
|
+
|
|
92
|
+
# A generic request, so a method Net::HTTP has no class for is sent too.
|
|
93
|
+
request = Net::HTTPGenericRequest.new(verb, !body.nil?, verb != "HEAD", uri.request_uri, headers)
|
|
94
|
+
http.request(request, body)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def without_credentials(uri)
|
|
92
98
|
clean = uri.dup
|
|
93
99
|
clean.user = nil
|
|
94
100
|
clean.password = nil
|
|
95
101
|
clean.to_s
|
|
96
102
|
end
|
|
103
|
+
|
|
104
|
+
def tracer
|
|
105
|
+
provider = @telemetry ? @telemetry.tracer_provider : OpenTelemetry.tracer_provider
|
|
106
|
+
provider.tracer(SCOPE_NAME, Libo11y::VERSION)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def duration
|
|
110
|
+
@mutex.synchronize do
|
|
111
|
+
@duration ||= begin
|
|
112
|
+
provider = @telemetry ? @telemetry.meter_provider : OpenTelemetry.meter_provider
|
|
113
|
+
provider.meter(SCOPE_NAME, version: Libo11y::VERSION).create_histogram(
|
|
114
|
+
"http.client.request.duration", unit: "s", description: "Duration of HTTP client requests."
|
|
115
|
+
)
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
end
|
|
97
119
|
end
|
|
98
120
|
end
|