foam-otel 3.0.0.alpha.12 → 3.0.0.alpha.13

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.
Files changed (32) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +103 -37
  3. data/lib/foam/otel/internal/before_send.rb +15 -8
  4. data/lib/foam/otel/internal/body_capture.rb +25 -6
  5. data/lib/foam/otel/internal/body_decoder.rb +6 -6
  6. data/lib/foam/otel/internal/body_redactor.rb +3 -3
  7. data/lib/foam/otel/internal/clients/excon.rb +16 -28
  8. data/lib/foam/otel/internal/clients/faraday.rb +15 -21
  9. data/lib/foam/otel/internal/clients/http_client.rb +9 -15
  10. data/lib/foam/otel/internal/clients/net_http.rb +12 -23
  11. data/lib/foam/otel/internal/constants.rb +3 -0
  12. data/lib/foam/otel/internal/exporters.rb +9 -9
  13. data/lib/foam/otel/internal/fork_hooks.rb +4 -5
  14. data/lib/foam/otel/internal/ignored_headers.rb +1 -1
  15. data/lib/foam/otel/internal/ignored_hosts.rb +0 -1
  16. data/lib/foam/otel/internal/ingest.rb +7 -6
  17. data/lib/foam/otel/internal/init.rb +74 -72
  18. data/lib/foam/otel/internal/instrumentations.rb +9 -3
  19. data/lib/foam/otel/internal/lifecycle.rb +14 -4
  20. data/lib/foam/otel/internal/log_record_processor.rb +5 -4
  21. data/lib/foam/otel/internal/otlp.rb +1 -0
  22. data/lib/foam/otel/internal/patch_resolver.rb +6 -7
  23. data/lib/foam/otel/internal/propagation.rb +15 -25
  24. data/lib/foam/otel/internal/que.rb +6 -6
  25. data/lib/foam/otel/internal/rails_middleware.rb +12 -8
  26. data/lib/foam/otel/internal/redactor.rb +75 -31
  27. data/lib/foam/otel/internal/resource.rb +3 -5
  28. data/lib/foam/otel/internal/safely.rb +7 -4
  29. data/lib/foam/otel/internal/state.rb +26 -35
  30. data/lib/foam/otel/version.rb +1 -1
  31. data/lib/foam/rack/middleware.rb +31 -18
  32. metadata +4 -4
@@ -34,12 +34,11 @@ module Foam
34
34
  instrument_default_connection
35
35
  end
36
36
 
37
- # Faraday.get, Faraday.post and the other class-level calls reuse a cached default
38
- # connection. If it was built before init (Datadog's integration does this),
39
- # OpenTelemetry's and our initialize patches never ran on it, so add the tracer and this
40
- # middleware now, matching what a new connection gets. Once that connection has sent a
41
- # request, Faraday freezes its middleware, so it is left as is, traced by the HTTP client
42
- # beneath it.
37
+ # `Faraday.get`, `Faraday.post` and the other class-level calls reuse a cached default
38
+ # connection. A connection built before init, as Datadog's integration does, missed the
39
+ # OpenTelemetry and Foam patches. This adds the tracer and this middleware to it, as a new
40
+ # connection gets them. Faraday locks the middleware after the first request.
41
+ # A locked connection stays as is, and the HTTP client under it traces its requests.
43
42
  def self.instrument_default_connection
44
43
  connection = ::Faraday.instance_variable_get(:@default_connection)
45
44
  return if connection.nil? || connection.builder.locked?
@@ -59,7 +58,7 @@ module Foam
59
58
  # returns nil by design. The transport patches beneath report to the owner what they
60
59
  # inflated, so the response is described as it was on the wire.
61
60
  def call(env)
62
- span = Safely.call("body capture") { BodyCapture.client_span }
61
+ span = BodyCapture.client_span
63
62
  return @app.call(env) unless span
64
63
 
65
64
  # The tracer names the handler under it as the adapter, which is now this middleware.
@@ -91,11 +90,7 @@ module Foam
91
90
  def capture_request(env, span, body)
92
91
  return unless body.is_a?(String)
93
92
 
94
- capture = BodyCapture.start(
95
- span, State.body_redactor, side: :client, direction: :request
96
- ) { request_headers(env, body) }
97
- capture&.observe(body)
98
- capture
93
+ BodyCapture.client_request(span, body) { request_headers(env, body) }
99
94
  end
100
95
 
101
96
  # The safe request headers. content-length is still missing at this point, because the
@@ -114,9 +109,9 @@ module Foam
114
109
  body = env.body
115
110
  return if env.request.stream_response? || !body.is_a?(String)
116
111
 
117
- capture = BodyCapture.start(
118
- span, State.body_redactor, side: :client, direction: :response
119
- ) { body_headers(env, body, owner) }
112
+ capture = BodyCapture.start(span, side: :client, direction: :response) do
113
+ body_headers(env, body, owner)
114
+ end
120
115
  return unless capture
121
116
 
122
117
  capture.observe(body)
@@ -132,10 +127,10 @@ module Foam
132
127
  found
133
128
  end
134
129
 
135
- # The safe response headers for the body capture. When an adapter Foam does not patch
136
- # inflates the body, content-encoding still names the compression and the capture would
137
- # try to inflate plain text, so it is dropped unless the body still starts like
138
- # compressed data. A body a patched transport inflated keeps it.
130
+ # The safe response headers for the body capture. An adapter Foam does not patch can
131
+ # inflate the body but keep `content-encoding`, and the capture would then try to inflate
132
+ # plain text. This drops `content-encoding` unless the body starts like compressed data.
133
+ # A body that a patched transport inflated keeps the header.
139
134
  def body_headers(env, body, owner)
140
135
  found = sent_headers(env, owner)
141
136
  return found if owner.encoding
@@ -148,8 +143,7 @@ module Foam
148
143
  # Faraday's headers answer to any case, so the app's own spelling of a name is found. Excon
149
144
  # blanks content-encoding once it has inflated the body, so an empty value counts as unset.
150
145
  def headers(hash)
151
- Constants::SAFE_NETWORK_HEADERS.to_h { |name| [name, hash[name]] }
152
- .reject { |_name, value| value.nil? || value.empty? }
146
+ BodyCapture.safe_headers { |name| hash[name] }.reject { |_name, value| value.empty? }
153
147
  end
154
148
  end
155
149
  end
@@ -10,7 +10,6 @@ module Foam
10
10
  # exchange, so both methods run inside it whatever the prepend order.
11
11
  module HttpClient
12
12
  INSTRUMENTATION = "OpenTelemetry::Instrumentation::HttpClient"
13
- INFLATED_ENCODINGS = %w[gzip x-gzip deflate].freeze
14
13
 
15
14
  def self.install
16
15
  return unless Instrumentations.installed?(INSTRUMENTATION)
@@ -21,7 +20,7 @@ module Foam
21
20
  # Sends the request, capturing a String body. The headers are read after the send,
22
21
  # once Content-Length is set.
23
22
  def query(req)
24
- span = Safely.call("body capture") { BodyCapture.client_span }
23
+ span = BodyCapture.client_span
25
24
  return super unless span
26
25
 
27
26
  capture = Safely.call("request body capture") { capture_request(req, span) }
@@ -41,7 +40,7 @@ module Foam
41
40
  # size on the wire; when a middleware above owns the request, it is told what was inflated.
42
41
  def get_body(&block)
43
42
  @foam_wire_bytes = 0
44
- span = Safely.call("body capture") { BodyCapture.client_span }
43
+ span = BodyCapture.client_span
45
44
  unless span
46
45
  return super.tap do
47
46
  Safely.call("response body capture") do
@@ -77,11 +76,7 @@ module Foam
77
76
  body = req.http_body.content
78
77
  return unless body.is_a?(String)
79
78
 
80
- capture = BodyCapture.start(
81
- span, State.body_redactor, side: :client, direction: :request
82
- ) { request_headers(req) }
83
- capture&.observe(body)
84
- capture
79
+ BodyCapture.client_request(span, body) { request_headers(req) }
85
80
  end
86
81
 
87
82
  # Counts the compressed bytes of each piece before the session inflates it.
@@ -96,23 +91,22 @@ module Foam
96
91
  end
97
92
 
98
93
  def start_response(span)
99
- BodyCapture.start(span, State.body_redactor, side: :client, direction: :response) do
100
- response_headers
101
- end
94
+ BodyCapture.start(span, side: :client, direction: :response) { response_headers }
102
95
  end
103
96
 
104
97
  def request_headers(req)
105
- Constants::SAFE_NETWORK_HEADERS.to_h { |name| [name, req.header[name].first] }.compact
98
+ BodyCapture.safe_headers { |name| req.header[name].first }
106
99
  end
107
100
 
108
- # The safe response headers, as the server sent them.
101
+ # The safe response headers, as the server sent them. The session keeps them as an array
102
+ # of name and value pairs.
109
103
  def response_headers
110
- @headers.to_h { |name, value| [name.downcase, value] }.slice(*Constants::SAFE_NETWORK_HEADERS)
104
+ BodyCapture.safe_headers(@headers.to_h)
111
105
  end
112
106
 
113
107
  # Whether the session inflates the body before handing it over.
114
108
  def inflated?
115
- @transparent_gzip_decompression && INFLATED_ENCODINGS.include?(@content_encoding)
109
+ @transparent_gzip_decompression && Constants::INFLATED_ENCODINGS.include?(@content_encoding)
116
110
  end
117
111
  end
118
112
  end
@@ -39,7 +39,7 @@ module Foam
39
39
  # instrumentation opens the client span before calling this, so the span is current here
40
40
  # whatever the prepend order.
41
41
  def transport_request(req)
42
- span = Safely.call("body capture") { BodyCapture.client_span }
42
+ span = BodyCapture.client_span
43
43
  unless span
44
44
  # A middleware above, such as Faraday, may own the request; tell it what was inflated.
45
45
  return super.tap do |res|
@@ -49,10 +49,7 @@ module Foam
49
49
  end
50
50
  end
51
51
 
52
- body_redactor = State.body_redactor
53
- request = Safely.call("request body capture") do
54
- capture_request(req, span, body_redactor)
55
- end
52
+ request = Safely.call("request body capture") { capture_request(req, span) }
56
53
  res = nil
57
54
  sent = nil
58
55
  begin
@@ -73,7 +70,7 @@ module Foam
73
70
  end
74
71
  end
75
72
  Safely.call("response body capture") do
76
- capture_response(res, span, body_redactor, sent || body_headers(res))
73
+ capture_response(res, span, sent || body_headers(res))
77
74
  end
78
75
  res
79
76
  end
@@ -81,35 +78,27 @@ module Foam
81
78
  # A String body is observed in one piece. A body_stream is wrapped in a ReadTee, which
82
79
  # observes each chunk as Net::HTTP copies it to the socket; transport_request unwraps it
83
80
  # afterwards. Multipart form data is not captured.
84
- def capture_request(req, span, body_redactor)
81
+ def capture_request(req, span)
85
82
  body = req.body
86
- stream = req.body_stream
87
- return unless body.is_a?(String) || stream.respond_to?(:read)
83
+ return BodyCapture.client_request(span, body) { body_headers(req) } if body.is_a?(String)
88
84
 
89
- capture = BodyCapture.start(span, body_redactor, side: :client, direction: :request) do
90
- body_headers(req)
91
- end
92
- return unless capture
85
+ stream = req.body_stream
86
+ return unless stream.respond_to?(:read)
93
87
 
94
- if body
95
- capture.observe(body)
96
- else
97
- req.body_stream = ReadTee.new(stream, capture)
98
- end
88
+ capture = BodyCapture.start(span, side: :client, direction: :request) { body_headers(req) }
89
+ req.body_stream = ReadTee.new(stream, capture) if capture
99
90
  capture
100
91
  end
101
92
 
102
93
  # Captures the response body once it was read into a String, under the headers as sent. A
103
94
  # missing body (HEAD, 204, 304) is captured as empty; a body read in a block or into an IO
104
95
  # has already gone to the caller and is skipped.
105
- def capture_response(res, span, body_redactor, sent)
96
+ def capture_response(res, span, sent)
106
97
  body = res.body
107
98
  return unless body.nil? || body.is_a?(String)
108
99
 
109
100
  complete = response_complete?(res, body)
110
- capture = BodyCapture.start(span, body_redactor, side: :client, direction: :response) do
111
- sent
112
- end
101
+ capture = BodyCapture.start(span, side: :client, direction: :response) { sent }
113
102
  return unless capture
114
103
 
115
104
  capture.observe(body) if body
@@ -127,7 +116,7 @@ module Foam
127
116
  end
128
117
 
129
118
  def body_headers(message)
130
- Constants::SAFE_NETWORK_HEADERS.to_h { |name| [name, message[name]] }.compact
119
+ BodyCapture.safe_headers { |name| message[name] }
131
120
  end
132
121
  end
133
122
  end
@@ -31,6 +31,9 @@ module Foam
31
31
  # How much body text one chunk record carries.
32
32
  BODY_CHUNK_BYTES = 64 * 1024 # 64 KiB
33
33
 
34
+ # The content encodings that the body decoder and the HTTP clients inflate.
35
+ INFLATED_ENCODINGS = %w[gzip x-gzip deflate].freeze
36
+
34
37
  # How far a compressed body may inflate before it is dropped. Only text is captured, and text
35
38
  # inflates well under 16x, so anything past that is a zip bomb rather than a body worth reading.
36
39
  BODY_DECODE_BYTES = 16 * BODY_CAPTURE_BYTES # 16 MiB
@@ -24,11 +24,10 @@ module Foam
24
24
  )
25
25
  end
26
26
 
27
- # The encoder groups items by resource object, so items sharing one must share its
28
- # redacted copy, and each resource is redacted once per batch.
29
- # A batch the hook emptied is done here; the SDK exporter would post an empty request.
30
- # A hook that raised is reported once for each error class in the batch, in the order they
31
- # first occurred, not once for each item.
27
+ # The encoder groups items by resource object. Items that share a resource share its redacted
28
+ # copy, and each resource is redacted once per batch. A batch the hook emptied ends here,
29
+ # because the SDK exporter would post an empty request. A hook that raised is reported once
30
+ # per error class in the batch, in first-seen order.
32
31
  def export(items, timeout: nil)
33
32
  resources = {}.compare_by_identity
34
33
  raised = Set.new
@@ -93,8 +92,8 @@ module Foam
93
92
  Encoder.as_encoded_etsr(span_data)
94
93
  end
95
94
 
96
- # The span as the hook left it, with its own, event, and link attributes and its status redacted; nil when
97
- # the hook dropped it.
95
+ # The span as the hook left it, with every attribute and the status description redacted;
96
+ # nil when the hook dropped it.
98
97
  def redacted_copy(span, resource, &on_raise)
99
98
  event = @before_send.event_to_export(hook_event(span), &on_raise) or return
100
99
 
@@ -192,9 +191,10 @@ module Foam
192
191
  end
193
192
  end
194
193
 
195
- # A body chunk's text was redacted by the body redactor when it was captured.
194
+ # A body chunk's text was redacted by the body redactor when it was captured. A chunk body the
195
+ # hook changed is redacted like any other log body.
196
196
  def redacted_body(record, body)
197
- return body if record.event_name == Constants::BODY_CHUNK_EVENT
197
+ return body if record.event_name == Constants::BODY_CHUNK_EVENT && body == record.body
198
198
 
199
199
  @redactor.redact_value(body)
200
200
  end
@@ -3,11 +3,10 @@
3
3
  module Foam
4
4
  module Otel
5
5
  module Internal
6
- # Runs State.after_fork in every child this process forks, by wrapping Process._fork, the
7
- # method fork and Process.fork call. Preforking servers init Foam in the master, and a
8
- # forked child gets the parent's memory but none of its threads, so the periodic metric
9
- # reader's export thread is gone and the child's metrics would never leave it, and the
10
- # providers' resource still names the parent process.
6
+ # Runs `State.after_fork` in each child this process forks. It wraps `Process._fork`, which
7
+ # `fork` and `Process.fork` both call. Preforking servers init Foam in the master. A forked
8
+ # child keeps the parent's memory but none of its threads. Without this hook, the child has
9
+ # no metric export thread, and its resource names the parent process.
11
10
  module ForkHooks
12
11
  def _fork
13
12
  parent = Process.pid
@@ -20,7 +20,7 @@ module Foam
20
20
  end
21
21
  end
22
22
 
23
- def request(req, body = nil, &block)
23
+ def request(req, body = nil)
24
24
  return super unless IgnoredHeaders.names.any? { |name| req.key?(name) }
25
25
 
26
26
  OpenTelemetry::Context.with_value(CONTEXT_KEY, true) { super }
@@ -52,7 +52,6 @@ module Foam
52
52
  def ignored?(kind, attributes)
53
53
  return false if attributes.nil? || INBOUND_KINDS.include?(kind)
54
54
 
55
- # The host and port the client instrumentation set, if it set them.
56
55
  host = attributes[HOST_KEY]
57
56
  port = attributes[PORT_KEY]
58
57
  # The rest-client gem's instrumentation sets no host, only the URL.
@@ -75,9 +75,9 @@ module Foam
75
75
  inert(signal)
76
76
  end
77
77
 
78
- # What a factory returns when it cannot build the real component, because a value it was given
79
- # cannot be used or something inside Foam failed: the OpenTelemetry base component for the
80
- # signal's slot, which the app's provider takes and which exports nothing.
78
+ # The component a factory returns when it cannot build the real one: a value it got is
79
+ # unusable, or something inside Foam failed. It is the OpenTelemetry base component for the
80
+ # signal's slot. The app's provider accepts it, and it exports nothing.
81
81
  def inert(signal)
82
82
  {
83
83
  traces: OpenTelemetry::SDK::Trace::SpanProcessor,
@@ -108,11 +108,12 @@ module Foam
108
108
  State.record_provider(:logger, provider)
109
109
  end
110
110
 
111
- # Foam flushes and shuts down what it built, as it does its own providers, so the last batch
112
- # still leaves when the app never shuts its provider down or its provider fails to.
111
+ # Records an attached ingest component and registers `Foam.shutdown` at exit. Foam flushes
112
+ # and shuts down what it builds, as it does for its own providers. The last batch then
113
+ # leaves even when the app's provider never shuts down or fails to shut down.
113
114
  def attached(signal, component, label, name, environment, token)
114
115
  State.record_ingest(signal, component)
115
- at_exit { Foam.shutdown }
116
+ Lifecycle.shutdown_at_exit
116
117
  Report.call(
117
118
  severity: :info,
118
119
  message: "ingest #{label} attached",
@@ -19,36 +19,11 @@ module Foam
19
19
  identity = options.slice(:name, :environment, :token)
20
20
 
21
21
  # Recorded before the checks, so state names the app after a disabled or failed init too.
22
- # The token stays out of state on purpose; it is read by health checks and tests.
22
+ # The token stays out, since health checks and tests read state.
23
23
  State.record_params(options.slice(:name, :environment))
24
24
 
25
- # Teams may turn the SDK off in specific environments, with the option or with the
26
- # SDK's own switch, which OpenTelemetry reads as a case-insensitive boolean.
27
- disabled = !options[:enabled] || ENV["OTEL_SDK_DISABLED"].to_s.strip.casecmp?("true")
28
- if disabled
29
- Report.call(severity: :info, message: "SDK disabled", **identity)
30
- return
31
- end
32
-
33
- if Internal.blank?(options[:token])
34
- Report.call(severity: :error, message: "Parameter token not provided", **identity)
35
- return
36
- end
37
-
38
- # A second configure would install a second pipeline next to the first.
39
- if State.initialized?
40
- Report.call(severity: :warn, message: "SDK already initialized", **identity)
41
- return
42
- end
43
-
44
- if Internal.blank?(options[:name]) || Internal.blank?(options[:environment])
45
- Report.call(severity: :error, message: "Parameters name and environment not provided", **identity)
46
- return
47
- end
48
-
49
- # Stops on an unusable option value rather than guessing what was meant, so the mistake shows at boot.
50
- if (problem = invalid_option(**options))
51
- Report.call(severity: :error, message: problem, **identity)
25
+ if (failed = check_preconditions(options))
26
+ Report.call(**failed, **identity)
52
27
  return
53
28
  end
54
29
 
@@ -57,12 +32,13 @@ module Foam
57
32
  OpenTelemetry.logger = Diagnostics.logger
58
33
  OpenTelemetry.error_handler = Diagnostics.error_handler
59
34
 
60
- # Require instrumentation here, not at gem load because apps that only use the ingest components don't need them
35
+ # Loaded here, not with the gem: an app that uses only the ingest components doesn't need it.
61
36
  require "opentelemetry/instrumentation/all"
62
37
  require "opentelemetry/instrumentation/logger"
63
38
  instrumentation_config = Instrumentations.config_map(
64
39
  options[:additional_instrumentations],
65
- disable_log_sending: options[:disable_log_sending]
40
+ disable_log_sending: options[:disable_log_sending],
41
+ network_capture: options[:network_capture]
66
42
  )
67
43
 
68
44
  # An ingest factory may have built a logger provider for log; the pipeline replaces it.
@@ -73,42 +49,11 @@ module Foam
73
49
  instrumentation_config: instrumentation_config, redactor: redactor, **options
74
50
  )
75
51
  begin
76
- ForkHooks.attach
77
-
78
- # Where another SDK's patch and an instrumentation's define the same helper on a class,
79
- # each keeps its own, whichever of the two came first.
80
- Safely.call("patch resolver") { PatchResolver.install }
81
-
82
- # Drops the spans of the requests carrying an ignored header, in every capture mode.
83
- IgnoredHeaders.install(options[:ignored_outbound_headers])
52
+ install_patches(options)
84
53
 
85
- # Writes the W3C headers last on the requests Foam instruments, in every capture mode.
86
- Reinject.install
87
-
88
- # The logger instrumentation emits a record from inside every Logger call, and that emit
89
- # reads the current OpenTelemetry context. An SDK that supplies its own context can raise
90
- # there while it boots, which would make every app log line raise. LoggerBridge is
91
- # prepended after the instrumentation's patch, so it sits in front of it and drops just
92
- # the record whose emit failed.
93
- ::Logger.prepend(LoggerBridge) if Instrumentations.installed?(Instrumentations::LOGGER)
94
-
95
- # The client patches set the safe headers on every client span and, in advanced mode,
96
- # capture bodies too. Bodies are redacted by the same rules as attributes, so only
97
- # advanced builds a body redactor; its presence is what switches body capture on.
54
+ # Only advanced mode builds a body redactor, and the redactor turns body capture on. It
55
+ # masks bodies by the same rules as attributes.
98
56
  body_redactor = BodyRedactor.new(redactor) if options[:network_capture] == :advanced
99
- install_client_patches unless options[:network_capture] == :off
100
-
101
- # Adds faas.trigger for the event sources the aws_lambda instrumentation skips, and flushes
102
- # Foam's logger provider where it flushes the tracer and meter providers.
103
- Safely.call("aws_lambda") { AwsLambda.install }
104
-
105
- # Leaves out a propagation header Que would refuse as a job tag, so the app's enqueue
106
- # does not raise on a long baggage.
107
- Safely.call("que") { Que.install }
108
-
109
- # A Rails app cannot add the middleware in config.ru the way a plain Rack app does, so
110
- # Foam adds it through Rails itself.
111
- Safely.call("rails middleware") { RailsMiddleware.install } unless options[:network_capture] == :off
112
57
 
113
58
  # Recorded last so a failed init leaves the state uninitialized.
114
59
  State.record_init(
@@ -124,8 +69,7 @@ module Foam
124
69
  raise
125
70
  end
126
71
 
127
- # Flush whatever the batch processors still hold before the process exits.
128
- at_exit { Foam.shutdown }
72
+ Lifecycle.shutdown_at_exit
129
73
  Report.call(severity: :info, message: "SDK initialized", **identity)
130
74
  nil
131
75
  rescue => e
@@ -133,6 +77,68 @@ module Foam
133
77
  nil
134
78
  end
135
79
 
80
+ # Checks whether init goes on. Returns the severity and message of the report for the first
81
+ # check that fails, or nil when every check passes.
82
+ def check_preconditions(options)
83
+ # Teams may turn the SDK off in specific environments, with the option or with the
84
+ # SDK's own switch, which OpenTelemetry reads as a case-insensitive boolean.
85
+ if !options[:enabled] || ENV["OTEL_SDK_DISABLED"].to_s.strip.casecmp?("true")
86
+ return {severity: :info, message: "SDK disabled"}
87
+ end
88
+
89
+ return {severity: :error, message: "Parameter token not provided"} if Internal.blank?(options[:token])
90
+
91
+ # A second configure would install a second pipeline next to the first.
92
+ return {severity: :warn, message: "SDK already initialized"} if State.initialized?
93
+
94
+ if Internal.blank?(options[:name]) || Internal.blank?(options[:environment])
95
+ return {severity: :error, message: "Parameters name and environment not provided"}
96
+ end
97
+
98
+ # Stops on an unusable option value rather than guessing what was meant, so the mistake shows at boot.
99
+ problem = invalid_option(**options)
100
+ {severity: :error, message: problem} if problem
101
+ end
102
+
103
+ # Installs Foam's patches on the libraries the app loaded. Init calls it after configure, so
104
+ # each patch finds its instrumentation installed.
105
+ def install_patches(options)
106
+ ForkHooks.attach
107
+
108
+ # Where another SDK's patch and an instrumentation's define the same helper on a class,
109
+ # each keeps its own, whichever of the two came first.
110
+ Safely.call("patch resolver") { PatchResolver.install }
111
+
112
+ # Drops the spans of the requests carrying an ignored header, in every capture mode.
113
+ IgnoredHeaders.install(options[:ignored_outbound_headers])
114
+
115
+ # Writes the W3C headers last on the requests Foam instruments, in every capture mode.
116
+ Reinject.install
117
+
118
+ # The logger instrumentation emits a record from inside every Logger call, and that emit
119
+ # reads the current OpenTelemetry context. An SDK that supplies its own context can raise
120
+ # there while it boots, which would make every app log line raise. LoggerBridge is
121
+ # prepended after the instrumentation's patch, so it sits in front of it and drops just
122
+ # the record whose emit failed.
123
+ ::Logger.prepend(LoggerBridge) if Instrumentations.installed?(Instrumentations::LOGGER)
124
+
125
+ # The client patches set the safe headers on every client span and, in advanced mode,
126
+ # capture bodies too.
127
+ install_client_patches unless options[:network_capture] == :off
128
+
129
+ # Adds faas.trigger for the event sources the aws_lambda instrumentation skips, and flushes
130
+ # Foam's logger provider where it flushes the tracer and meter providers.
131
+ Safely.call("aws_lambda") { AwsLambda.install }
132
+
133
+ # Leaves out a propagation header Que would refuse as a job tag, so the app's enqueue
134
+ # does not raise on a long baggage.
135
+ Safely.call("que") { Que.install }
136
+
137
+ # A Rails app cannot add the middleware in config.ru the way a plain Rack app does, so
138
+ # Foam adds it through Rails itself.
139
+ Safely.call("rails middleware") { RailsMiddleware.install } unless options[:network_capture] == :off
140
+ end
141
+
136
142
  # Builds Foam's pipelines and claims the global slots the API still holds itself. Returns
137
143
  # the providers built, by kind, and the slots claimed, by signal.
138
144
  def configure(
@@ -266,7 +272,7 @@ module Foam
266
272
  raise ArgumentError, "ignored_outbound_hosts must be an array of hostnames, each with an optional :port, got #{hosts.inspect}"
267
273
  end
268
274
 
269
- Set.new(hosts) << URI(Endpoint.current).host
275
+ [*hosts, URI(Endpoint.current).host]
270
276
  end
271
277
 
272
278
  # The first option holding a value init cannot use, described as "<option> must be ..., got
@@ -290,11 +296,7 @@ module Foam
290
296
  return "ignored_outbound_headers must be an array of header names, got #{ignored_outbound_headers.inspect}"
291
297
  end
292
298
 
293
- if (problem = Redactor.invalid_option(redact) || BeforeSend.invalid_option(before_send))
294
- return problem
295
- end
296
-
297
- nil
299
+ Redactor.invalid_option(redact) || BeforeSend.invalid_option(before_send)
298
300
  end
299
301
  end
300
302
  end
@@ -8,6 +8,9 @@ module Foam
8
8
  # bridge is its own gem.
9
9
  LOGGER = "OpenTelemetry::Instrumentation::Logger"
10
10
 
11
+ # The GenAI instrumentation whose prompt and completion capture follows network_capture.
12
+ OPENAI = "OpenTelemetry::Instrumentation::OpenAI"
13
+
11
14
  # Every instrumentation the bundle registers -> short name (the gem name minus
12
15
  # opentelemetry-instrumentation-): opentelemetry-instrumentation-all's list, then the logger
13
16
  # bridge. Pinned by a spec, so a bundle change shows up here.
@@ -42,6 +45,7 @@ module Foam
42
45
  "OpenTelemetry::Instrumentation::Mongo" => "mongo",
43
46
  "OpenTelemetry::Instrumentation::Mysql2" => "mysql2",
44
47
  "OpenTelemetry::Instrumentation::Net::HTTP" => "net_http",
48
+ OPENAI => "openai",
45
49
  "OpenTelemetry::Instrumentation::PG" => "pg",
46
50
  "OpenTelemetry::Instrumentation::Que" => "que",
47
51
  "OpenTelemetry::Instrumentation::Racecar" => "racecar",
@@ -89,11 +93,13 @@ module Foam
89
93
  module_function
90
94
 
91
95
  # The instrumentation configs init installs, by name: the bundle, then the caller's entries,
92
- # which override it. Disabling log sending disables the logger bridge. An entry naming an
93
- # instrumentation that is not loaded fails init before anything is built.
94
- def config_map(additional, disable_log_sending: false)
96
+ # which override it. Disabling log sending disables the logger bridge. Advanced network
97
+ # capture turns on GenAI content capture. An entry naming an instrumentation that is not
98
+ # loaded fails init before anything is built.
99
+ def config_map(additional, disable_log_sending: false, network_capture: :basic)
95
100
  bundle = TABLE.keys.to_h { |name| [name, nil] }.merge(CONFIG)
96
101
  bundle[LOGGER] = {enabled: false} if disable_log_sending
102
+ bundle[OPENAI] = {capture_content: true} if network_capture == :advanced
97
103
  additional.each_with_object(bundle) do |entry, map|
98
104
  name, config = entry
99
105
  raise ArgumentError, "additional_instrumentations entry #{name.inspect} names no loaded instrumentation" unless instance(name)
@@ -4,7 +4,8 @@ module Foam
4
4
  module Otel
5
5
  module Internal
6
6
  module Lifecycle
7
- TIMEOUT = OpenTelemetry::SDK::Trace::Export::TIMEOUT
7
+ # The result code of a flush or shutdown that ran out of time.
8
+ TIMED_OUT = OpenTelemetry::SDK::Trace::Export::TIMEOUT
8
9
 
9
10
  module_function
10
11
 
@@ -14,11 +15,20 @@ module Foam
14
15
 
15
16
  # Taking the providers and ingest components out of State makes a second call a no-op.
16
17
  def shutdown(timeout:)
17
- components = State.take_providers + State.take_ingest_components
18
+ components = State.take_components
18
19
  Metrics.reset
19
20
  each(:shutdown, components, timeout: timeout)
20
21
  end
21
22
 
23
+ # Registers an exit hook that shuts Foam down, so the batch processors send what they hold.
24
+ # A later call adds no second hook.
25
+ def shutdown_at_exit
26
+ return if @shutdown_at_exit
27
+
28
+ @shutdown_at_exit = true
29
+ at_exit { Foam.shutdown }
30
+ end
31
+
22
32
  # Providers, processors, and readers all flush and shut down the same way; each in its own
23
33
  # thread, so one that hangs or fails holds up neither the others nor the caller. The caller is
24
34
  # back within one shared timeout; a thread still running then finishes on its own.
@@ -33,10 +43,10 @@ module Foam
33
43
  end
34
44
  threads.each do |component, thread|
35
45
  remaining = OpenTelemetry::Common::Utilities.maybe_timeout(timeout, start)
36
- code = thread.join(remaining) ? thread.value : TIMEOUT
46
+ code = thread.join(remaining) ? thread.value : TIMED_OUT
37
47
 
38
48
  # Failures are logged by the exporter or provider themselves; a timeout is silent upstream.
39
- Diagnostics.warn("#{operation}: #{component.class.name} timed out") if code == TIMEOUT
49
+ Diagnostics.warn("#{operation}: #{component.class.name} timed out") if code == TIMED_OUT
40
50
  rescue => e
41
51
  Diagnostics.warn("#{operation} failed: #{e.class}: #{e.message}")
42
52
  end
@@ -17,10 +17,11 @@ module Foam
17
17
 
18
18
  private
19
19
 
20
- # Every batch goes through here, from the timer and from force_flush, and the SDK reports its
21
- # result here too. The flag is shared by Foam's processors, so a record one processor's export
22
- # causes stays out of all of them; restoring it keeps it set for the rest of an export that
23
- # flushes another Foam processor on its way, for example from a before_send hook.
20
+ # Every batch goes through here, from the timer and from `force_flush`. The SDK also reports
21
+ # a failed export from inside this call. The flag is shared, so a record caused by one Foam
22
+ # processor's export stays out of all of them. An export can flush another Foam processor,
23
+ # such as from a `before_send` hook. Restoring the old value then keeps the flag set for the
24
+ # rest of the outer export.
24
25
  def export_batch(...)
25
26
  exporting = Thread.current[EXPORTING]
26
27
  Thread.current[EXPORTING] = true