boto-rb-telemetry 0.26.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 998c789e8ad36514570f19b0f3cc3f00b07ffcb5b670297b79f518f8f4a95ba0
4
+ data.tar.gz: f6465746f879e33954774f11a960f2f25614b53d30c95d611e8537a9139ec6a8
5
+ SHA512:
6
+ metadata.gz: 04ddf6c5364458f8134bd5c5afc41111c0c7e41f6d672f667d22f8d1d910fa12ea453797630be23a3f64dd6b600421019b469d17a66450df5b00d5025a00b24a
7
+ data.tar.gz: 27cff3bf43cb89c6dc7295d38c333f0f79a6cba533146a3da7cfc101e549f85475db186b60a9c27f3e5dca6efc9fbfe8fe6fbed535e379bfd6296ba5840ae553
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evo Tech Builder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ # Traces each request with an OpenTelemetry span, writes one JSON log line per request and,
6
+ # with metrics on, exports the process metrics through the same SDK.
7
+ class Telemetry < Boto::Plugin
8
+ scope :global
9
+
10
+ include Boto::Telemetry::Options
11
+
12
+ SERVICE_NAME = "OTEL_SERVICE_NAME"
13
+ TRACER_NAME = "boto"
14
+ METHOD_KEY = "REQUEST_METHOD"
15
+ PATH_KEY = "PATH_INFO"
16
+ QUERY_KEY = "QUERY_STRING"
17
+ ROUTE_KEY = "boto.route"
18
+ STATUS_INDEX = 0
19
+ CLOCK = Process::CLOCK_MONOTONIC
20
+
21
+ def call(env, app)
22
+ return app.call(env) unless @recording
23
+
24
+ started = monotonic_now
25
+ span = @spans.start(env, @tracer) if @tracer
26
+ response = measure(env) { span ? OpenTelemetry::Trace.with_span(span) { app.call(env) } : app.call(env) }
27
+ @spans.record(span, env, response[STATUS_INDEX]) if span
28
+ write_log(env, span, response[STATUS_INDEX], started) if @log
29
+ response
30
+ ensure
31
+ span&.finish
32
+ end
33
+
34
+ def start
35
+ return if @started
36
+
37
+ sdk.start(Process.pid) { configure_sdk }
38
+ exporting = sdk.configured?
39
+ metrics = @metrics && exporting && sdk_meter_provider?
40
+ Boto::Telemetry::OperationTracing.install(metrics: metrics, tracing: exporting)
41
+ # Looked up once: the provider's #tracer takes a lock and builds a key on every call.
42
+ @tracer = exporting ? OpenTelemetry.tracer_provider.tracer(TRACER_NAME) : nil
43
+ @request_metrics = metrics ? Boto::Telemetry::RequestMetrics.new(project: project_name) : nil
44
+ # Without an exporter and without the log there is nothing to record: requests go straight through.
45
+ @recording = !@tracer.nil? || @log
46
+ @started = true
47
+ end
48
+
49
+ # Safe to call twice: the SDK is shut down by the last plugin of the process that stops.
50
+ def stop
51
+ return unless @started
52
+
53
+ @started = false
54
+ sdk.stop(Process.pid) { OpenTelemetry.tracer_provider.shutdown }
55
+ end
56
+
57
+ private
58
+
59
+ # span_processor: and metric_reader: are for tests only; they replace the OTLP exporters that the environment would build.
60
+ def configure(filter: [], instrument: [], log: true, metrics: true, output: $stdout,
61
+ span_processor: nil, metric_reader: nil)
62
+ @filter = Boto::Telemetry::Filter.new(extra: list(:filter, filter))
63
+ @instrumentations = Boto::Telemetry::Instrumentation.prepare(list(:instrument, instrument))
64
+ @log = boolean(:log, log)
65
+ @metrics = boolean(:metrics, metrics)
66
+ @output = output
67
+ @span_processor = span_processor
68
+ @metric_reader = metric_reader
69
+ @spans = Boto::Telemetry::RequestSpan.new(filter: @filter, project: project_name)
70
+ @request_log = Boto::Telemetry::RequestLog.new(filter: @filter)
71
+ @project = project_name
72
+ @started = false
73
+ @recording = log
74
+ end
75
+
76
+ def configure_sdk
77
+ processor = @span_processor || Boto::Telemetry::Otlp.span_processor(env)
78
+ return false unless processor
79
+
80
+ reader = metric_reader
81
+ Boto::Telemetry::Aggregations.prefer(reader) if reader
82
+ OpenTelemetry::SDK.configure do |config|
83
+ config.service_name = env[SERVICE_NAME] || project_name
84
+ config.resource = Boto::Telemetry::Instance.resource
85
+ config.add_span_processor(processor)
86
+ # Without a reader the SDK builds its own exporter from OTEL_METRICS_EXPORTER; a base reader never exports.
87
+ config.add_metric_reader(reader || OpenTelemetry::SDK::Metrics::Export::MetricReader.new)
88
+ @instrumentations.each { |name| config.use(name) }
89
+ end
90
+ # The SDK installs its meter provider even without a reader; without metrics the API's no-op one goes back in.
91
+ OpenTelemetry.meter_provider = OpenTelemetry::Internal::ProxyMeterProvider.new unless reader
92
+ true
93
+ end
94
+
95
+ # nil when metrics are off or there is no endpoint.
96
+ def metric_reader
97
+ return unless @metrics
98
+
99
+ @metric_reader || Boto::Telemetry::Otlp.metric_reader(env)
100
+ end
101
+
102
+ # Without metrics the block runs as it is: no request is counted.
103
+ def measure(env, &)
104
+ return yield unless @request_metrics
105
+
106
+ @request_metrics.track(env, &)
107
+ end
108
+
109
+ def write_log(env, span, status, started)
110
+ context = @spans.valid_context(span)
111
+ @output.write(@request_log.line(
112
+ project: @project, method: env[METHOD_KEY], path: env[PATH_KEY], query: env[QUERY_KEY],
113
+ route: env[ROUTE_KEY], status: status, duration: monotonic_now - started,
114
+ time: Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond),
115
+ trace_id: context&.hex_trace_id, span_id: context&.hex_span_id
116
+ ))
117
+ # A piped stdout (a container's) is buffered: without the flush the lines only show up at exit.
118
+ @output.flush
119
+ end
120
+
121
+ def sdk_meter_provider? = OpenTelemetry.meter_provider.is_a?(OpenTelemetry::SDK::Metrics::MeterProvider)
122
+
123
+ def sdk = Boto::Telemetry::Sdk::SHARED
124
+
125
+ def project_name = File.basename(project_dir.to_s)
126
+
127
+ def monotonic_now = Process.clock_gettime(CLOCK)
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # The aggregation the metrics reader builds for histograms.
6
+ # - Histograms use the OpenTelemetry HTTP buckets, in seconds. The SDK ignores the instrument advice, and a
7
+ # view costs allocations on every record (it merges and checks the attributes each time), so the
8
+ # boundaries go in the reader's default histogram aggregation instead.
9
+ # - It updates an existing series directly: the SDK's update hashes the attributes again for the exemplar
10
+ # storage even when exemplars are off, and it runs on every request. The first record of a series (and
11
+ # any exemplar) still goes through the SDK.
12
+ # shortcut: depends on the HistogramDataPoint fields of opentelemetry-metrics-sdk 0.22 (the gemspec pins
13
+ # ~> 0.22.0); recheck SecondsHistogram#update when upgrading it.
14
+ module Aggregations
15
+ BOUNDARIES = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10].freeze
16
+ HISTOGRAM_KIND = :histogram
17
+
18
+ # The SDK builds it from the reader preference with only exemplar_reservoir:, so the boundaries are fixed here.
19
+ class SecondsHistogram < OpenTelemetry::SDK::Metrics::Aggregation::ExplicitBucketHistogram
20
+ def initialize(**options)
21
+ super(boundaries: BOUNDARIES, **options)
22
+ end
23
+
24
+ def update(amount, attributes, data_points, cardinality_limit, exemplar_offer: false)
25
+ point = data_points[attributes] unless exemplar_offer
26
+ return super unless point
27
+
28
+ record(point, amount)
29
+ nil
30
+ end
31
+
32
+ private
33
+
34
+ def record(point, amount)
35
+ if @record_min_max
36
+ point.max = amount if amount > point.max
37
+ point.min = amount if amount < point.min
38
+ end
39
+ point.sum += amount
40
+ point.count += 1
41
+ point.bucket_counts[@boundaries.bsearch_index { |bound| bound >= amount } || @boundaries.size] += 1
42
+ end
43
+ end
44
+
45
+ module_function
46
+
47
+ # Must run before the instruments are created: each one takes its aggregation from the reader when it registers.
48
+ def prefer(reader)
49
+ preferences = reader.default_aggregation if reader.respond_to?(:default_aggregation)
50
+ return reader unless preferences.is_a?(Hash) && !preferences.frozen?
51
+
52
+ preferences[HISTOGRAM_KIND] = SecondsHistogram
53
+ reader
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Boto
6
+ module Telemetry
7
+ # Masks the values of query parameters whose names look sensitive.
8
+ class Filter
9
+ FILTERED = "[FILTERED]"
10
+ DEFAULT_TERMS = %w[password passwd secret token authorization api_key apikey cookie session].freeze
11
+ PARAM_SEPARATOR = "&"
12
+ VALUE_SEPARATOR = "="
13
+
14
+ def initialize(extra: [])
15
+ @pattern = Regexp.union(DEFAULT_TERMS + extra.map { |term| normalize(term) })
16
+ end
17
+
18
+ def filtered?(name)
19
+ @pattern.match?(normalize(decode(name)))
20
+ end
21
+
22
+ def query(string)
23
+ return string if string.nil? || string.empty?
24
+
25
+ string.split(PARAM_SEPARATOR, -1).map { |pair| mask_pair(pair) }.join(PARAM_SEPARATOR)
26
+ end
27
+
28
+ private
29
+
30
+ def mask_pair(pair)
31
+ name, separator, _value = pair.partition(VALUE_SEPARATOR)
32
+ return pair if separator.empty? || !filtered?(name)
33
+
34
+ "#{name}#{VALUE_SEPARATOR}#{FILTERED}"
35
+ end
36
+
37
+ # Decoded only to match names like "%74oken"; the output keeps the raw name.
38
+ def decode(name)
39
+ URI.decode_www_form_component(name)
40
+ rescue ArgumentError
41
+ name
42
+ end
43
+
44
+ def normalize(name)
45
+ name.downcase.tr("-", "_")
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module Boto
6
+ module Telemetry
7
+ # Identifies one process of the service. Each forked worker exports its own series under its id,
8
+ # so the backend sums the instances instead of one worker overwriting the others.
9
+ module Instance
10
+ ID_KEY = "service.instance.id"
11
+
12
+ module_function
13
+
14
+ def resource
15
+ OpenTelemetry::SDK::Resources::Resource.create(ID_KEY => id)
16
+ end
17
+
18
+ def id(pid: Process.pid, hostname: Socket.gethostname) = "#{hostname}-#{pid}"
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # The official instrumentations that `instrument:` switches on, by symbol.
6
+ module Instrumentation
7
+ CLASSES = {
8
+ pg: "PG", mysql2: "Mysql2", trilogy: "Trilogy", net_http: "Net::HTTP", redis: "Redis", faraday: "Faraday"
9
+ }.freeze
10
+ NAMESPACE = "OpenTelemetry::Instrumentation"
11
+ GEM_PREFIX = "opentelemetry-instrumentation-"
12
+
13
+ module_function
14
+
15
+ # Checks the symbols and requires their gems; returns the names that the SDK's `use` expects.
16
+ def prepare(symbols)
17
+ symbols.map do |symbol|
18
+ name = name_for(symbol)
19
+ require_gem(symbol)
20
+ name
21
+ end
22
+ end
23
+
24
+ def name_for(symbol)
25
+ constant = CLASSES.fetch(symbol) { raise unknown(symbol) }
26
+ "#{NAMESPACE}::#{constant}"
27
+ end
28
+
29
+ def require_gem(symbol)
30
+ require "#{GEM_PREFIX}#{symbol}"
31
+ rescue LoadError
32
+ raise ArgumentError, "telemetry: instrument #{symbol.inspect} needs gem \"#{GEM_PREFIX}#{symbol}\" in the project's Gemfile"
33
+ end
34
+
35
+ def unknown(symbol)
36
+ ArgumentError.new("telemetry: unknown instrument #{symbol.inspect}, accepted: #{CLASSES.keys.join(", ")}")
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # Wraps each Boto::Operation.call in an internal span, child of the request span, and records its duration.
6
+ # Operations are called with `.call` on the class, so it is prepended to the singleton class; the core does
7
+ # not depend on OpenTelemetry. Helpers are module methods, so an operation's own class methods cannot shadow them.
8
+ module OperationTracing
9
+ SPAN_KIND = :internal
10
+ ANONYMOUS_NAME = "Boto::Operation"
11
+ DURATION_NAME = "boto.operation.duration"
12
+ OPERATION_KEY = "boto.operation"
13
+ PROJECT_KEY = "boto.project"
14
+ RESULT_KEY = "boto.operation.result"
15
+ FAILURE_KEY = "boto.operation.failure"
16
+ SUCCESS = "success"
17
+ FAILURE = "failure"
18
+ ERROR = "error"
19
+ CLOCK = Process::CLOCK_MONOTONIC
20
+
21
+ # Idempotent: the plugin calls it on every start, and the histogram is created again each time, so it
22
+ # belongs to the meter provider configured by then. Without metrics the duration is not recorded.
23
+ def self.install(metrics: true, tracing: true)
24
+ singleton = Boto::Operation.singleton_class
25
+ singleton.prepend(self) unless singleton.include?(self)
26
+ @duration = metrics ? create_duration : nil
27
+ @attributes = {}
28
+ # Looked up once: the provider's #tracer takes a lock and builds a key on every call.
29
+ @tracer = tracing ? OpenTelemetry.tracer_provider.tracer(Boto::Plugins::Telemetry::TRACER_NAME) : nil
30
+ @active = !@tracer.nil? || !@duration.nil?
31
+ end
32
+
33
+ # False when nothing is exported: the operation then runs without a span or a measurement.
34
+ def self.active? = @active
35
+
36
+ def self.trace(operation)
37
+ started = clock
38
+ result = tracer.in_span(span_name(operation), kind: SPAN_KIND) do |span|
39
+ record(span, yield)
40
+ end
41
+ record_duration(operation, outcome(result), started)
42
+ result
43
+ rescue StandardError
44
+ record_duration(operation, ERROR, started)
45
+ raise
46
+ end
47
+
48
+ def self.span_name(operation) = operation.name || ANONYMOUS_NAME
49
+
50
+ def self.record(span, result)
51
+ if result.success?
52
+ span.set_attribute(RESULT_KEY, SUCCESS)
53
+ else
54
+ span.set_attribute(RESULT_KEY, FAILURE)
55
+ span.set_attribute(FAILURE_KEY, result.failure.code.to_s)
56
+ end
57
+ result
58
+ end
59
+
60
+ def self.outcome(result) = result.success? ? SUCCESS : FAILURE
61
+
62
+ def self.record_duration(operation, outcome, started)
63
+ return unless @duration
64
+
65
+ @duration.record(clock - started, attributes: duration_attributes(operation, outcome))
66
+ end
67
+
68
+ # Built once per operation class and outcome: a call allocates no attribute hash.
69
+ def self.duration_attributes(operation, outcome)
70
+ by_outcome = (@attributes ||= {})[operation] ||= {}
71
+ by_outcome[outcome] ||= begin
72
+ attributes = { OPERATION_KEY => span_name(operation), RESULT_KEY => outcome }
73
+ project = project_name(operation)
74
+ attributes[PROJECT_KEY] = project if project
75
+ attributes
76
+ end
77
+ end
78
+
79
+ # nil when the operation's namespace is not a booted project (for example, in a console without it).
80
+ def self.project_name(operation)
81
+ operation.project_app.name
82
+ rescue Boto::ProjectApp::NotBootedError
83
+ nil
84
+ end
85
+
86
+ def self.create_duration
87
+ OpenTelemetry.meter_provider.meter(RequestMetrics::METER_NAME)
88
+ .create_histogram(DURATION_NAME, unit: "s", description: "Duration of Boto operations.",
89
+ exemplar_reservoir: RequestMetrics.no_exemplars)
90
+ end
91
+
92
+ def self.tracer = @tracer || OpenTelemetry.tracer_provider.tracer(Boto::Plugins::Telemetry::TRACER_NAME)
93
+
94
+ def self.clock = Process.clock_gettime(CLOCK)
95
+
96
+ def call(...)
97
+ return super unless OperationTracing.active?
98
+
99
+ OperationTracing.trace(self) { super }
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # Checks the :telemetry plugin options when the plugin is built, so a wrong type fails at boot.
6
+ module Options
7
+ module_function
8
+
9
+ def list(name, value)
10
+ return value if value.is_a?(Array)
11
+
12
+ raise ArgumentError, "telemetry: #{name} must be an Array, got #{value.inspect}"
13
+ end
14
+
15
+ def boolean(name, value)
16
+ return value if [true, false].include?(value)
17
+
18
+ raise ArgumentError, "telemetry: #{name} must be true or false, got #{value.inspect}"
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # The OTLP/HTTP exporters for the endpoint that the project's environment declares.
6
+ module Otlp
7
+ ENDPOINT = "OTEL_EXPORTER_OTLP_ENDPOINT"
8
+ HEADERS = "OTEL_EXPORTER_OTLP_HEADERS"
9
+ INTERVAL = "OTEL_METRIC_EXPORT_INTERVAL"
10
+ TRACES_PATH = "/v1/traces"
11
+ METRICS_PATH = "/v1/metrics"
12
+ DEFAULT_INTERVAL = "60000"
13
+ NO_HEADERS = {}.freeze
14
+
15
+ module_function
16
+
17
+ # nil without an endpoint: the SDK then stays unconfigured and no connection is opened.
18
+ def span_processor(env)
19
+ endpoint = env[ENDPOINT]
20
+ return if endpoint.to_s.empty?
21
+
22
+ exporter = OpenTelemetry::Exporter::OTLP::Exporter.new(
23
+ endpoint: traces_url(endpoint), headers: env[HEADERS] || NO_HEADERS
24
+ )
25
+ OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(exporter)
26
+ end
27
+
28
+ # nil without an endpoint, as span_processor. The reader exports on its own thread, every interval.
29
+ def metric_reader(env)
30
+ endpoint = env[ENDPOINT]
31
+ return if endpoint.to_s.empty?
32
+
33
+ exporter = OpenTelemetry::Exporter::OTLP::Metrics::MetricsExporter.new(
34
+ endpoint: metrics_url(endpoint), headers: env[HEADERS] || NO_HEADERS
35
+ )
36
+ OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader.new(
37
+ exporter: exporter, export_interval_millis: export_interval(env)
38
+ )
39
+ end
40
+
41
+ def traces_url(endpoint) = signal_url(endpoint, TRACES_PATH)
42
+
43
+ def metrics_url(endpoint) = signal_url(endpoint, METRICS_PATH)
44
+
45
+ # An explicit endpoint is used as it is, so the exporter does not add the signal path itself.
46
+ def signal_url(endpoint, path)
47
+ base = endpoint.delete_suffix("/")
48
+ base.end_with?(path) ? base : base + path
49
+ end
50
+
51
+ def export_interval(env)
52
+ value = env.fetch(INTERVAL, DEFAULT_INTERVAL)
53
+ millis = Integer(value, exception: false)
54
+ return millis if millis&.positive?
55
+
56
+ raise ArgumentError, "#{INTERVAL} must be a positive integer of milliseconds, got #{value.inspect}"
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Boto
6
+ module Telemetry
7
+ # Builds the one-line JSON log entry written for each request. It runs on every request, so the line is one
8
+ # string interpolation: the values that repeat (project, method, route, status, millisecond) are JSON-encoded
9
+ # once and reused, and only what the client sends (path, query) is escaped, and only when it needs it.
10
+ class RequestLog
11
+ SERVER_ERROR_STATUS = 500
12
+ MILLISECONDS = 1000.0
13
+ MS_PER_SECOND = 1000
14
+ SECOND_FORMAT = "%FT%T"
15
+ INFO = "info"
16
+ ERROR = "error"
17
+ NULL = "null"
18
+ NEEDS_ESCAPE = /["\\\x00-\x1f\x7f]/
19
+ MILLISECOND_TEXT = Array.new(MS_PER_SECOND) { format("%03d", _1).freeze }.freeze
20
+ CAPACITY = 256
21
+ TIME_OPEN = %({"time":")
22
+ DOT = "."
23
+ LEVEL_OPEN = %(Z","level":")
24
+ PROJECT_OPEN = %(","project":)
25
+ METHOD_OPEN = %(,"method":)
26
+ ROUTE_OPEN = %(,"route":)
27
+ PATH_OPEN = %(,"path":)
28
+ QUERY_OPEN = %(,"query":)
29
+ STATUS_OPEN = %(,"status":)
30
+ DURATION_OPEN = %(,"duration_ms":)
31
+ TRACE_OPEN = %(,"trace_id":")
32
+ SPAN_OPEN = %(","span_id":")
33
+ QUOTE = %(")
34
+ CLOSE = "}\n"
35
+ # Bounds the reused encodings of method and route; past it they are encoded on each line.
36
+ CACHE_LIMIT = 1024
37
+
38
+ def initialize(filter:)
39
+ @filter = filter
40
+ @second = nil
41
+ @second_text = nil
42
+ @encoded = {}
43
+ @statuses = {}
44
+ end
45
+
46
+ # time is the wall clock in milliseconds since the epoch; duration is in seconds. The line ends with "\n".
47
+ def line(project:, method:, path:, query:, route:, status:, duration:, trace_id:, span_id:, time:)
48
+ text = String.new(capacity: CAPACITY, encoding: Encoding::UTF_8)
49
+ text << TIME_OPEN << second_text(time / MS_PER_SECOND) << DOT << MILLISECOND_TEXT[time % MS_PER_SECOND]
50
+ text << LEVEL_OPEN << level(status) << PROJECT_OPEN << encoded(project) << METHOD_OPEN << encoded(method)
51
+ text << ROUTE_OPEN << encoded(route) << PATH_OPEN
52
+ append_escaped(text, path)
53
+ append_query(text, query)
54
+ text << STATUS_OPEN << status_text(status) << DURATION_OPEN << (duration * MILLISECONDS).round(1).to_s
55
+ text << TRACE_OPEN << trace_id << SPAN_OPEN << span_id << QUOTE if trace_id
56
+ text << CLOSE
57
+ end
58
+
59
+ private
60
+
61
+ def level(status) = status >= SERVER_ERROR_STATUS ? ERROR : INFO
62
+
63
+ def append_query(text, query)
64
+ masked = @filter.query(query)
65
+ return if masked.nil? || masked.empty?
66
+
67
+ text << QUERY_OPEN
68
+ append_escaped(text, masked)
69
+ end
70
+
71
+ # Values from a bounded set (project, method of a matched route, declared route), encoded once each.
72
+ def encoded(value)
73
+ return NULL if value.nil?
74
+
75
+ @encoded[value] || remember(@encoded, value, JSON.generate(value).freeze)
76
+ end
77
+
78
+ # Values from the client: copied as they are unless they hold a character JSON must escape.
79
+ def append_escaped(text, value)
80
+ return text << JSON.generate(value) if NEEDS_ESCAPE.match?(value)
81
+
82
+ text << QUOTE << value << QUOTE
83
+ end
84
+
85
+ def status_text(status) = @statuses[status] || remember(@statuses, status, status.to_s.freeze)
86
+
87
+ def remember(cache, key, value)
88
+ cache[key] = value if cache.size < CACHE_LIMIT
89
+ value
90
+ end
91
+
92
+ # Formatted once per second: the requests of the same second share it.
93
+ def second_text(second)
94
+ return @second_text if second == @second
95
+
96
+ @second = second
97
+ @second_text = Time.at(second).utc.strftime(SECOND_FORMAT)
98
+ end
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # The HTTP server metrics of one project: the requests in flight and how long each one took.
6
+ # Built after the SDK is configured; without it the instruments are the API's no-op ones.
7
+ # The attribute hashes are built once per method, route and status and reused, so a request allocates none.
8
+ class RequestMetrics
9
+ DURATION_NAME = "http.server.request.duration"
10
+ ACTIVE_NAME = "http.server.active_requests"
11
+ METER_NAME = "boto"
12
+ ERROR_TYPE = "error.type"
13
+ STATUS_INDEX = 0
14
+ CLOCK = Process::CLOCK_MONOTONIC
15
+ # The semantic convention names unknown methods _OTHER, which also bounds the cached attribute sets.
16
+ KNOWN_METHODS = %w[GET HEAD POST PUT PATCH DELETE OPTIONS QUERY TRACE CONNECT].freeze
17
+ OTHER_METHOD = "_OTHER"
18
+
19
+ # Exemplars read the clock and the context on every record; Boto does not export them.
20
+ def self.no_exemplars = OpenTelemetry::SDK::Metrics::Exemplar::NoopExemplarReservoir.new
21
+
22
+ def initialize(project:, meter_provider: OpenTelemetry.meter_provider)
23
+ meter = meter_provider.meter(METER_NAME)
24
+ @project = project
25
+ @duration = meter.create_histogram(DURATION_NAME, unit: "s", description: "Duration of HTTP server requests.",
26
+ exemplar_reservoir: self.class.no_exemplars)
27
+ @active = meter.create_up_down_counter(ACTIVE_NAME, unit: "{request}", description: "HTTP server requests in flight.",
28
+ exemplar_reservoir: self.class.no_exemplars)
29
+ @base = {}
30
+ @by_route = {}
31
+ end
32
+
33
+ def started(env)
34
+ @active.add(1, attributes: base_attributes(env[RequestSpan::METHOD_KEY]))
35
+ end
36
+
37
+ def finished(env, status, duration, error = nil)
38
+ method = env[RequestSpan::METHOD_KEY]
39
+ @active.add(-1, attributes: base_attributes(method))
40
+ @duration.record(duration, attributes: duration_attributes(env, method, status, error))
41
+ end
42
+
43
+ # Counts the request while the block runs and records it when the block ends, also when it raises.
44
+ def track(env)
45
+ started_at = clock
46
+ started(env)
47
+ status = RequestSpan::SERVER_ERROR
48
+ error = nil
49
+ begin
50
+ response = yield
51
+ status = response[STATUS_INDEX]
52
+ response
53
+ rescue StandardError => error
54
+ raise
55
+ ensure
56
+ finished(env, status, clock - started_at, error)
57
+ end
58
+ end
59
+
60
+ private
61
+
62
+ def base_attributes(method)
63
+ method = OTHER_METHOD unless KNOWN_METHODS.include?(method)
64
+ @base[method] ||= { RequestSpan::HTTP_METHOD => method, RequestSpan::PROJECT_ATTRIBUTE => @project }
65
+ end
66
+
67
+ def duration_attributes(env, method, status, error)
68
+ type = error_type(env, status, error)
69
+ return with_error(env, method, status, type) if type
70
+
71
+ method = OTHER_METHOD unless KNOWN_METHODS.include?(method)
72
+ route = env[RequestSpan::ROUTE_KEY]
73
+ by_status = (@by_route[method] ||= {})[route] ||= {}
74
+ by_status[status] ||= build_attributes(method, route, status)
75
+ end
76
+
77
+ # Errors are rare and their type is open-ended, so these attributes are not cached.
78
+ def with_error(env, method, status, type)
79
+ build_attributes(method, env[RequestSpan::ROUTE_KEY], status).merge(ERROR_TYPE => type)
80
+ end
81
+
82
+ def build_attributes(method, route, status)
83
+ attributes = base_attributes(method).merge(RequestSpan::HTTP_STATUS => status)
84
+ attributes[RequestSpan::HTTP_ROUTE] = route if route
85
+ attributes
86
+ end
87
+
88
+ # The exception class when there is one; a 5xx without exception is named by its status.
89
+ def error_type(env, status, error)
90
+ failure = error || env[RequestSpan::ERROR_KEY]
91
+ return failure.class.name if failure
92
+
93
+ status.to_s if status >= RequestSpan::SERVER_ERROR
94
+ end
95
+
96
+ def clock = Process.clock_gettime(CLOCK)
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # The server span of one request. It is named after the route once the app has matched one,
6
+ # and it records the status and the error that the app left in the Rack env.
7
+ class RequestSpan
8
+ ROUTE_KEY = "boto.route"
9
+ ERROR_KEY = "boto.error"
10
+ METHOD_KEY = "REQUEST_METHOD"
11
+ PATH_KEY = "PATH_INFO"
12
+ QUERY_KEY = "QUERY_STRING"
13
+ HTTP_METHOD = "http.request.method"
14
+ HTTP_ROUTE = "http.route"
15
+ HTTP_STATUS = "http.response.status_code"
16
+ URL_PATH = "url.path"
17
+ URL_QUERY = "url.query"
18
+ PROJECT_ATTRIBUTE = "boto.project"
19
+ SERVER_ERROR = 500
20
+ KIND = :server
21
+ # The propagators read these Rack keys; without any of them there is no incoming context to extract.
22
+ PROPAGATION_KEYS = %w[HTTP_TRACEPARENT HTTP_BAGGAGE].freeze
23
+
24
+ def initialize(filter:, project:)
25
+ @filter = filter
26
+ @project = project
27
+ @names = {}
28
+ end
29
+
30
+ def start(env, tracer)
31
+ tracer.start_span(env[METHOD_KEY], with_parent: parent_context(env), kind: KIND, attributes: attributes(env))
32
+ end
33
+
34
+ def record(span, env, status)
35
+ route = env[ROUTE_KEY]
36
+ name_after_route(span, env[METHOD_KEY], route) if route
37
+ span.set_attribute(HTTP_STATUS, status)
38
+ record_error(span, env[ERROR_KEY], status)
39
+ end
40
+
41
+ # Hex ids for the log line; nil when the span is not recording (no SDK configured).
42
+ # The span context for the log line; nil when there is no span or it is not recording (no SDK configured).
43
+ def valid_context(span)
44
+ context = span&.context
45
+ context if context&.valid?
46
+ end
47
+
48
+ private
49
+
50
+ # nil starts the span under the current context, which is what an extract without headers would give.
51
+ def parent_context(env)
52
+ return unless PROPAGATION_KEYS.any? { |key| env.key?(key) }
53
+
54
+ OpenTelemetry.propagation.extract(env, getter: OpenTelemetry::Common::Propagation.rack_env_getter)
55
+ end
56
+
57
+ def attributes(env)
58
+ query = @filter.query(env[QUERY_KEY])
59
+ attributes = { HTTP_METHOD => env[METHOD_KEY], URL_PATH => env[PATH_KEY], PROJECT_ATTRIBUTE => @project }
60
+ attributes[URL_QUERY] = query unless query.to_s.empty?
61
+ attributes
62
+ end
63
+
64
+ def name_after_route(span, method, route)
65
+ span.name = (@names[method] ||= {})[route] ||= "#{method} #{route}".freeze
66
+ span.set_attribute(HTTP_ROUTE, route)
67
+ end
68
+
69
+ # The exception is recorded as an event; the status carries only its class, not its message.
70
+ def record_error(span, error, status)
71
+ if error
72
+ span.record_exception(error)
73
+ span.status = OpenTelemetry::Trace::Status.error(error.class.name)
74
+ elsif status >= SERVER_ERROR
75
+ span.status = OpenTelemetry::Trace::Status.error
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ # Configures the OpenTelemetry SDK once per process. The tracer and meter providers are global to the
6
+ # process, so several :telemetry plugins share them; a forked worker has its own pid and configures its own.
7
+ class Sdk
8
+ def initialize
9
+ @pid = nil
10
+ @users = 0
11
+ @configured = false
12
+ end
13
+
14
+ # Runs the block on the first start of the pid, and on later starts until one of them configures.
15
+ # A block that raises is not counted, so a failed boot does not hold the shutdown back.
16
+ def start(pid)
17
+ reset_for(pid)
18
+ @configured ||= yield
19
+ @users += 1
20
+ end
21
+
22
+ # True once a start of this pid configured the SDK (an exporter was found).
23
+ def configured? = @configured
24
+
25
+ # The last stop of the pid runs the block (the shutdown), and only if the SDK was configured.
26
+ def stop(pid)
27
+ return unless pid == @pid && @users.positive?
28
+
29
+ @users -= 1
30
+ return unless @users.zero?
31
+
32
+ if @configured
33
+ yield
34
+ shutdown_meter_provider
35
+ end
36
+ @configured = false
37
+ end
38
+
39
+ private
40
+
41
+ # A forked child inherits the parent's count, but not its threads: it starts from zero.
42
+ def reset_for(pid)
43
+ return if pid == @pid
44
+
45
+ @pid = pid
46
+ @users = 0
47
+ @configured = false
48
+ end
49
+
50
+ # Drains the readers of the SDK's meter provider. Before configuration the global is a proxy, which has nothing to drain.
51
+ def shutdown_meter_provider
52
+ provider = OpenTelemetry.meter_provider
53
+ provider.shutdown if provider.is_a?(OpenTelemetry::SDK::Metrics::MeterProvider)
54
+ end
55
+
56
+ SHARED = new
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Telemetry
5
+ VERSION = "0.26.0"
6
+ end
7
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "boto"
4
+ require "opentelemetry/sdk"
5
+ require "opentelemetry/exporter/otlp"
6
+ require "opentelemetry-metrics-sdk"
7
+ require "opentelemetry-exporter-otlp-metrics"
8
+ require "zeitwerk"
9
+
10
+ loader = Zeitwerk::Loader.for_gem_extension(Boto)
11
+ loader.setup
12
+
13
+ module Boto
14
+ # OpenTelemetry traces, metrics and request logs for projects that enable the :telemetry plugin.
15
+ module Telemetry
16
+ end
17
+ end
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: boto-rb-telemetry
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.26.0
5
+ platform: ruby
6
+ authors:
7
+ - Evo Tech Builder
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: boto-rb
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - '='
17
+ - !ruby/object:Gem::Version
18
+ version: 0.26.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - '='
24
+ - !ruby/object:Gem::Version
25
+ version: 0.26.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: opentelemetry-sdk
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '1.13'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.13'
40
+ - !ruby/object:Gem::Dependency
41
+ name: opentelemetry-exporter-otlp
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '0.37'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '0.37'
54
+ - !ruby/object:Gem::Dependency
55
+ name: opentelemetry-metrics-api
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '0.10'
61
+ type: :runtime
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '0.10'
68
+ - !ruby/object:Gem::Dependency
69
+ name: opentelemetry-metrics-sdk
70
+ requirement: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: 0.22.0
75
+ type: :runtime
76
+ prerelease: false
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: 0.22.0
82
+ - !ruby/object:Gem::Dependency
83
+ name: opentelemetry-exporter-otlp-metrics
84
+ requirement: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - "~>"
87
+ - !ruby/object:Gem::Version
88
+ version: '0.15'
89
+ type: :runtime
90
+ prerelease: false
91
+ version_requirements: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '0.15'
96
+ executables: []
97
+ extensions: []
98
+ extra_rdoc_files: []
99
+ files:
100
+ - LICENSE
101
+ - lib/boto/plugins/telemetry.rb
102
+ - lib/boto/telemetry.rb
103
+ - lib/boto/telemetry/aggregations.rb
104
+ - lib/boto/telemetry/filter.rb
105
+ - lib/boto/telemetry/instance.rb
106
+ - lib/boto/telemetry/instrumentation.rb
107
+ - lib/boto/telemetry/operation_tracing.rb
108
+ - lib/boto/telemetry/options.rb
109
+ - lib/boto/telemetry/otlp.rb
110
+ - lib/boto/telemetry/request_log.rb
111
+ - lib/boto/telemetry/request_metrics.rb
112
+ - lib/boto/telemetry/request_span.rb
113
+ - lib/boto/telemetry/sdk.rb
114
+ - lib/boto/telemetry/version.rb
115
+ homepage: https://github.com/EvoTechBuilder/boto-rb
116
+ licenses:
117
+ - MIT
118
+ metadata:
119
+ rubygems_mfa_required: 'true'
120
+ source_code_uri: https://github.com/EvoTechBuilder/boto-rb
121
+ changelog_uri: https://github.com/EvoTechBuilder/boto-rb/blob/main/CHANGELOG.md
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '3.4'
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubygems_version: 4.0.20
137
+ specification_version: 4
138
+ summary: OpenTelemetry traces and request logs for Boto
139
+ test_files: []