diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 286a5a13fc..d0be8ed75b 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -23,6 +23,8 @@ components: - johnnyshields instrumentation/racecar: - chrisholmes + instrumentation/rage: + - rsamoilov instrumentation/rspec: - chrisholmes instrumentation/que: diff --git a/.github/workflows/ci-instrumentation-full.yml b/.github/workflows/ci-instrumentation-full.yml index 5f0dce4378..d2179ced24 100644 --- a/.github/workflows/ci-instrumentation-full.yml +++ b/.github/workflows/ci-instrumentation-full.yml @@ -37,6 +37,7 @@ on: - 'instrumentation/logger/**' - 'instrumentation/net_http/**' - 'instrumentation/rack/**' + - 'instrumentation/rage/**' - 'instrumentation/rails/**' - 'instrumentation/restclient/**' - 'instrumentation/rspec/**' @@ -97,6 +98,7 @@ jobs: - logger - net_http - rack + - rage - rails - restclient - rspec @@ -147,6 +149,7 @@ jobs: [[ "${{ matrix.gem }}" == "koala" ]] && echo "skip=true" >> $GITHUB_OUTPUT [[ "${{ matrix.gem }}" == "lmdb" ]] && echo "skip=true" >> $GITHUB_OUTPUT [[ "${{ matrix.gem }}" == "rack" ]] && echo "skip=true" >> $GITHUB_OUTPUT + [[ "${{ matrix.gem }}" == "rage" ]] && echo "skip=true" >> $GITHUB_OUTPUT [[ "${{ matrix.gem }}" == "rails" ]] && echo "skip=true" >> $GITHUB_OUTPUT [[ "${{ matrix.gem }}" == "grpc" ]] && echo "skip=true" >> $GITHUB_OUTPUT [[ "${{ matrix.gem }}" == "gruf" ]] && echo "skip=true" >> $GITHUB_OUTPUT diff --git a/.toys/.data/releases.yml b/.toys/.data/releases.yml index ac110d17c4..f2a02795a1 100644 --- a/.toys/.data/releases.yml +++ b/.toys/.data/releases.yml @@ -221,6 +221,10 @@ gems: directory: instrumentation/rack version_constant: [OpenTelemetry, Instrumentation, Rack, VERSION] + - name: opentelemetry-instrumentation-rage + directory: instrumentation/rage + version_constant: [OpenTelemetry, Instrumentation, Rage, VERSION] + - name: opentelemetry-instrumentation-rails directory: instrumentation/rails version_constant: [OpenTelemetry, Instrumentation, Rails, VERSION] @@ -295,4 +299,4 @@ gems: - name: opentelemetry-sampler-xray directory: sampler/xray - version_constant: [OpenTelemetry, Sampler, XRay, VERSION] \ No newline at end of file + version_constant: [OpenTelemetry, Sampler, XRay, VERSION] diff --git a/instrumentation/rage/.rubocop.yml b/instrumentation/rage/.rubocop.yml new file mode 100644 index 0000000000..1248a2f825 --- /dev/null +++ b/instrumentation/rage/.rubocop.yml @@ -0,0 +1 @@ +inherit_from: ../../.rubocop.yml diff --git a/instrumentation/rage/.yardopts b/instrumentation/rage/.yardopts new file mode 100644 index 0000000000..97ec84cf97 --- /dev/null +++ b/instrumentation/rage/.yardopts @@ -0,0 +1,9 @@ +--no-private +--title=OpenTelemetry Rage Instrumentation +--markup=markdown +--main=README.md +./lib/opentelemetry/instrumentation/**/*.rb +./lib/opentelemetry/instrumentation.rb +- +README.md +CHANGELOG.md diff --git a/instrumentation/rage/Appraisals b/instrumentation/rage/Appraisals new file mode 100644 index 0000000000..5eda89af12 --- /dev/null +++ b/instrumentation/rage/Appraisals @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +appraise 'rage-1.0' do + gem 'rage-rb', github: 'rage-rb/rage', branch: 'main' +end diff --git a/instrumentation/rage/CHANGELOG.md b/instrumentation/rage/CHANGELOG.md new file mode 100644 index 0000000000..cbc891876a --- /dev/null +++ b/instrumentation/rage/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History: opentelemetry-instrumentation-rage + +### v0.1.0 / 2026-01-04 + +Initial release. diff --git a/instrumentation/rage/Gemfile b/instrumentation/rage/Gemfile new file mode 100644 index 0000000000..14ac2c87dc --- /dev/null +++ b/instrumentation/rage/Gemfile @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +source 'https://rubygems.org' + +gemspec + +group :test do + gem 'opentelemetry-instrumentation-base', path: '../base' + gem 'opentelemetry-instrumentation-rack', path: '../rack' + gem 'appraisal', '~> 2.5' + gem 'bundler', '~> 2.4' + gem 'minitest', '~> 5.0' + gem 'opentelemetry-sdk', '~> 1.0' + gem 'opentelemetry-test-helpers', '~> 0.3' + gem 'rake', '~> 13.0' + gem 'rubocop', '~> 1.81.1' + gem 'rubocop-performance', '~> 1.26.0' + gem 'simplecov', '~> 0.17.1' + gem 'webmock', '~> 3.24' + gem 'yard', '~> 0.9' + gem 'rspec-mocks' +end diff --git a/instrumentation/rage/LICENSE b/instrumentation/rage/LICENSE new file mode 100644 index 0000000000..1ef7dad2c5 --- /dev/null +++ b/instrumentation/rage/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright The OpenTelemetry Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/instrumentation/rage/README.md b/instrumentation/rage/README.md new file mode 100644 index 0000000000..1463713a13 --- /dev/null +++ b/instrumentation/rage/README.md @@ -0,0 +1,59 @@ +# OpenTelemetry Rage Instrumentation + +The OpenTelemetry Rage instrumentation provides automatic observability for [Rage](https://github.com/rage-rb/rage), a fiber-based framework with Rails-compatible syntax. + +This instrumentation enables comprehensive tracing and logging for Rage applications: + +* Creates spans for HTTP requests, WebSocket messages, event subscribers, and deferred tasks +* Propagates OpenTelemetry context across fibers created via `Fiber.schedule` and deferred tasks +* Enriches logs with trace and span IDs for correlated observability + +## How do I get started? + +Install the gem using: + +```console +gem install opentelemetry-instrumentation-rage +``` + +Or, if you use [bundler][bundler-home], include `opentelemetry-instrumentation-rage` in your `Gemfile`. + +## Usage + +To use the instrumentation, call `use` with the name of the instrumentation: + +```ruby +OpenTelemetry::SDK.configure do |c| + c.use 'OpenTelemetry::Instrumentation::Rage' +end +``` + +Alternatively, you can also call `use_all` to install all the available instrumentation. + +```ruby +OpenTelemetry::SDK.configure do |c| + c.use_all +end +``` + +## Examples + +Example usage can be seen in the [`./example/trace_demonstration.ru` file](https://github.com/open-telemetry/opentelemetry-ruby-contrib/blob/main/instrumentation/rage/example/trace_demonstration.ru) + +## How can I get involved? + +The `opentelemetry-instrumentation-rage` gem source is [on github][repo-github], along with related gems including `opentelemetry-api` and `opentelemetry-sdk`. + +The OpenTelemetry Ruby gems are maintained by the OpenTelemetry Ruby special interest group (SIG). You can get involved by joining us on our [GitHub Discussions][discussions-url], [Slack Channel][slack-channel] or attending our weekly meeting. See the [meeting calendar][community-meetings] for dates and times. For more information on this and other language SIGs, see the OpenTelemetry [community page][ruby-sig]. + +## License + +The `opentelemetry-instrumentation-rage` gem is distributed under the Apache 2.0 license. See [LICENSE][license-github] for more information. + +[bundler-home]: https://bundler.io +[repo-github]: https://github.com/open-telemetry/opentelemetry-ruby +[license-github]: https://github.com/open-telemetry/opentelemetry-ruby-contrib/blob/main/LICENSE +[ruby-sig]: https://github.com/open-telemetry/community#ruby-sig +[community-meetings]: https://github.com/open-telemetry/community#community-meetings +[slack-channel]: https://cloud-native.slack.com/archives/C01NWKKMKMY +[discussions-url]: https://github.com/open-telemetry/opentelemetry-ruby/discussions diff --git a/instrumentation/rage/Rakefile b/instrumentation/rage/Rakefile new file mode 100644 index 0000000000..1a64ba842e --- /dev/null +++ b/instrumentation/rage/Rakefile @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'bundler/gem_tasks' +require 'rake/testtask' +require 'yard' +require 'rubocop/rake_task' + +RuboCop::RakeTask.new + +Rake::TestTask.new :test do |t| + t.libs << 'test' + t.libs << 'lib' + t.test_files = FileList['test/**/*_test.rb'] +end + +YARD::Rake::YardocTask.new do |t| + t.stats_options = ['--list-undoc'] +end + +if RUBY_ENGINE == 'truffleruby' + task default: %i[test] +else + task default: %i[test rubocop yard] +end diff --git a/instrumentation/rage/example/trace_demonstration.ru b/instrumentation/rage/example/trace_demonstration.ru new file mode 100644 index 0000000000..1b4c100dd9 --- /dev/null +++ b/instrumentation/rage/example/trace_demonstration.ru @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'bundler/inline' + +gemfile(true) do + source 'https://rubygems.org' + + gem 'rage-rb' + gem 'opentelemetry-sdk' + gem 'opentelemetry-instrumentation-rage' +end + +require 'rage/all' + +ENV['OTEL_TRACES_EXPORTER'] ||= 'console' + +OpenTelemetry::SDK.configure do |c| + c.use 'OpenTelemetry::Instrumentation::Rage' +end + +class BaseController < RageController::API + def index + render plain: "Hello from OpenTelemetry!" + end +end + +Rage.routes.draw do + root to: "base#index" +end + +run Rage.application + +# To run this example: +# 1. Install the `rage-rb` gem: +# gem install rage-rb +# 2. Start the server: +# rage s -c trace_demonstration.ru +# 3. Navigate to http://localhost:3000/ +# Spans for the requests will appear in the console diff --git a/instrumentation/rage/lib/opentelemetry-instrumentation-rage.rb b/instrumentation/rage/lib/opentelemetry-instrumentation-rage.rb new file mode 100644 index 0000000000..c034f140f8 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry-instrumentation-rage.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require_relative 'opentelemetry/instrumentation' diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation.rb b/instrumentation/rage/lib/opentelemetry/instrumentation.rb new file mode 100644 index 0000000000..824ab13d6d --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +# OpenTelemetry is an open source observability framework, providing a +# general-purpose API, SDK, and related tools required for the instrumentation +# of cloud-native software, frameworks, and libraries. +# +# The OpenTelemetry module provides global accessors for telemetry objects. +# See the documentation for the `opentelemetry-api` gem for details. +module OpenTelemetry + # Instrumentation should be able to handle the case when the library is not installed on a user's system. + module Instrumentation + end +end + +require 'opentelemetry-instrumentation-rack' +require_relative 'instrumentation/rage' diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage.rb new file mode 100644 index 0000000000..d2437856f1 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'opentelemetry' +require 'opentelemetry-instrumentation-base' + +module OpenTelemetry + module Instrumentation + # Contains the OpenTelemetry instrumentation for the Rage gem + module Rage + end + end +end + +require_relative 'rage/instrumentation' +require_relative 'rage/version' diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/cable.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/cable.rb new file mode 100644 index 0000000000..54c3ee1a71 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/cable.rb @@ -0,0 +1,148 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'opentelemetry/semconv/incubating/code' +require 'opentelemetry/semconv/incubating/messaging' + +module OpenTelemetry + module Instrumentation + module Rage + module Handlers + # The class customizes the initial Rack span used for WebSocket handshakes and wraps subsequent + # Cable connection and action processing in spans linked to the handshake span. + class Cable < ::Rage::Telemetry::Handler + HANDSHAKE_CONTEXT = 'otel.rage.handshake_context' + private_constant :HANDSHAKE_CONTEXT + + HANDSHAKE_LINK = 'otel.rage.handshake_link' + private_constant :HANDSHAKE_LINK + + handle 'cable.websocket.handshake', with: :save_context + + handle 'cable.connection.process', with: :create_connection_span + handle 'cable.action.process', with: :create_channel_span + handle 'cable.stream.broadcast', with: :create_broadcast_span + + # @param env [Hash] the Rack env + def self.save_context(env:) + span = OpenTelemetry::Instrumentation::Rack.current_span + return yield unless span.recording? + + request = ::Rack::Request.new(env) + span.name = "#{request.request_method} #{request.path}" + + env[HANDSHAKE_CONTEXT] = OpenTelemetry::Context.current + env[HANDSHAKE_LINK] = [OpenTelemetry::Trace::Link.new(span.context)] + + yield + end + + # @param env [Hash] the Rack env + # @param action [:connect, :disconnect] the name of the action being processed + # @param connection [Rage::Cable::Connection] the connection instance + def self.create_connection_span(env:, action:, connection:) + handshake_context = env[HANDSHAKE_CONTEXT] + handshake_link = env[HANDSHAKE_LINK] + + OpenTelemetry::Context.with_current(handshake_context) do + attributes = { + 'websocket.framework' => 'rage.cable', + 'websocket.direction' => 'inbound', + 'websocket.handler' => connection.class.name, + 'websocket.action' => action.to_s + } + + kind = action == :connect ? :server : :internal + + span = Rage::Instrumentation.instance.tracer.start_root_span( + "#{connection.class} #{action}", + links: handshake_link, + kind:, + attributes: + ) + + OpenTelemetry::Trace.with_span(span) do + result = yield + + if result.error? + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + ensure + span.finish + end + end + end + + # @param env [Hash] the Rack env + # @param action [Symbol] the name of the action being processed + # @param channel [Rage::Cable::Channel] the channel instance + def self.create_channel_span(env:, action:, channel:) + handshake_context = env[HANDSHAKE_CONTEXT] + handshake_link = env[HANDSHAKE_LINK] + + OpenTelemetry::Context.with_current(handshake_context) do + attributes = { + 'websocket.framework' => 'rage.cable', + 'websocket.direction' => 'inbound', + 'websocket.channel' => channel.class.name, + 'websocket.action' => action.to_s + } + + attributes[SemConv::Incubating::MESSAGING::MESSAGING_OPERATION_TYPE] = 'process' unless action == :unsubscribed + + span_name = if action == :subscribed + "#{channel.class} subscribe" + elsif action == :unsubscribed + "#{channel.class} unsubscribe" + else + "#{channel.class} receive" + end + + kind = action == :unsubscribed ? :internal : :server + + span = Rage::Instrumentation.instance.tracer.start_root_span( + span_name, + links: handshake_link, + kind:, + attributes: + ) + + OpenTelemetry::Trace.with_span(span) do + result = yield + + if result.error? + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + ensure + span.finish + end + end + end + + # @param stream [String] the name of the stream + def self.create_broadcast_span(stream:) + attributes = { + 'websocket.framework' => 'rage.cable', + 'websocket.direction' => 'outbound', + 'websocket.stream' => stream + } + + Rage::Instrumentation.instance.tracer.in_span('Rage::Cable broadcast', kind: :producer, attributes:) do |span| + result = yield + + if result.error? + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + end + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/deferred.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/deferred.rb new file mode 100644 index 0000000000..ca663e83fe --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/deferred.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'opentelemetry/semconv/incubating/code' +require 'opentelemetry/semconv/incubating/messaging' + +module OpenTelemetry + module Instrumentation + module Rage + module Handlers + # The class propagates OpenTelemetry context to deferred tasks and wraps the + # enqueuing and processing of deferred tasks in spans. + class Deferred < ::Rage::Telemetry::Handler + handle 'deferred.task.enqueue', with: :create_enqueue_span + handle 'deferred.task.process', with: :create_perform_span + + # @param task_class [Class] the class of the deferred task + # @param task_context [Hash] the context for the deferred task + def self.create_enqueue_span(task_class:, task_context:) + Rage::Instrumentation.instance.tracer.in_span("#{task_class} enqueue", kind: :producer) do |span| + OpenTelemetry.propagation.inject(task_context) + + result = yield + + if result.error? + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + end + end + + # @param task_class [Class] the class of the deferred task + # @param task [Rage::Deferred::Task] the deferred task instance + # @param task_context [Hash] the context for the deferred task + def self.create_perform_span(task_class:, task:, task_context:) + otel_context = OpenTelemetry.propagation.extract(task_context) + + OpenTelemetry::Context.with_current(otel_context) do + attributes = { + 'workflow.platform.name' => 'rage.deferred', + 'workflow.execution.result' => 'success', + 'workflow.execution.attempt' => task.meta.attempts + } + + parent_span_context = OpenTelemetry::Trace.current_span(otel_context).context + links = [OpenTelemetry::Trace::Link.new(parent_span_context)] if parent_span_context.valid? + + span = Rage::Instrumentation.instance.tracer.start_root_span( + "#{task_class} perform", + attributes:, + links:, + kind: :consumer + ) + + OpenTelemetry::Trace.with_span(span) do + result = yield + + if result.error? + span.set_attribute('workflow.execution.result', 'failure') + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + ensure + span.finish + end + end + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/events.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/events.rb new file mode 100644 index 0000000000..0f9ce0c6b1 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/events.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'opentelemetry/semconv/incubating/code' +require 'opentelemetry/semconv/incubating/messaging' + +module OpenTelemetry + module Instrumentation + module Rage + module Handlers + # The class records the publishing of Rage events and wraps event subscribers in spans. + class Events < ::Rage::Telemetry::Handler + handle 'events.event.publish', with: :create_publisher_span + handle 'events.subscriber.process', with: :create_subscriber_span + + # @param event [Object] the event being published + def self.create_publisher_span(event:, &) + current_span = OpenTelemetry::Trace.current_span + return yield unless current_span.recording? + + kind = :producer + attributes = { + SemConv::Incubating::MESSAGING::MESSAGING_SYSTEM => 'rage.events', + SemConv::Incubating::MESSAGING::MESSAGING_OPERATION_TYPE => 'send', + SemConv::Incubating::MESSAGING::MESSAGING_DESTINATION_NAME => event.class.name + } + + Rage::Instrumentation.instance.tracer.in_span("#{event.class} publish", kind:, attributes:, &) + end + + # @param event [Object] the event being processed + # @param subscriber [Rage::Events::Subscriber] the subscriber processing the event + def self.create_subscriber_span(event:, subscriber:) + # deferred subscribers will be wrapped into spans by the `Handlers::Deferred` handler + return yield if subscriber.class.deferred? + + kind = :consumer + attributes = { + SemConv::Incubating::MESSAGING::MESSAGING_SYSTEM => 'rage.events', + SemConv::Incubating::MESSAGING::MESSAGING_OPERATION_TYPE => 'process', + SemConv::Incubating::MESSAGING::MESSAGING_DESTINATION_NAME => event.class.name + } + + Rage::Instrumentation.instance.tracer.in_span("#{subscriber.class} process", kind:, attributes:) do |span| + result = yield + + if result.error? + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + end + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/fiber.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/fiber.rb new file mode 100644 index 0000000000..470197cb3b --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/fiber.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Rage + module Handlers + # The class uses Fiber storage to propagate OpenTelemetry context between fibers. + class Fiber < ::Rage::Telemetry::Handler + # Save the current OpenTelemetry context into Fiber local storage. + # Application-level fibers spawned via `Fiber.schedule` will automatically inherit the storage. + module Patch + def schedule(&) + ::Fiber[:__rage_otel_context] = OpenTelemetry::Context.current + super + end + end + + def initialize + super + ::Fiber.singleton_class.prepend(Patch) + end + + handle 'core.fiber.spawn', with: :propagate_otel_context + + def propagate_otel_context(&) + OpenTelemetry::Context.with_current(::Fiber[:__rage_otel_context], &) + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/request.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/request.rb new file mode 100644 index 0000000000..40a9b072b1 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/handlers/request.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'opentelemetry/semconv/http' +require 'opentelemetry/semconv/incubating/code' + +module OpenTelemetry + module Instrumentation + module Rage + module Handlers + # The class updates the name of the Rack span, adds relevant attributes, and records + # exceptions if any occur during the processing of a controller action. + class Request < ::Rage::Telemetry::Handler + handle 'controller.action.process', with: :enrich_request_span + + # @param controller [RageController::API] the controller processing the request + # @param request [Rage::Request] the request being processed + def self.enrich_request_span(controller:, request:) + span = OpenTelemetry::Instrumentation::Rack.current_span + return yield unless span.recording? + + http_route = request.route_uri_pattern + span.name = "#{request.method} #{http_route}" + span.set_attribute(SemConv::HTTP::HTTP_ROUTE, http_route) + + result = yield + return unless result.error? + + span.record_exception(result.exception) + span.status = OpenTelemetry::Trace::Status.error + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/instrumentation.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/instrumentation.rb new file mode 100644 index 0000000000..adfa6cb7da --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/instrumentation.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Rage + # The Instrumentation class contains logic to detect and install the Rage instrumentation + class Instrumentation < OpenTelemetry::Instrumentation::Base + install do |_config| + unless OpenTelemetry::Instrumentation::Rack::Instrumentation.instance.installed? + ENV['OTEL_SEMCONV_STABILITY_OPT_IN'] ||= 'http' + OpenTelemetry::Instrumentation::Rack::Instrumentation.instance.install({ use_rack_events: false }) + end + + require_dependencies + install_instrumentation + end + + present do + defined?(::Rage) + end + + compatible do + is_compatible = gem_version >= Gem::Version.new('1.20.0') && gem_version < Gem::Version.new('2') + OpenTelemetry.logger.warn("Rage version #{::Rage::VERSION} is not supported by the OpenTelemetry Rage instrumentation. Supported versions are >= 1.20.0 and < 2.0.0.") unless is_compatible + + is_compatible + end + + private + + def gem_version + Gem::Version.new(::Rage::VERSION) + end + + def require_dependencies + require_relative 'log_context' + + require_relative 'handlers/cable' + require_relative 'handlers/deferred' + require_relative 'handlers/events' + require_relative 'handlers/fiber' + require_relative 'handlers/request' + end + + def install_instrumentation + ::Rage.configure do + # install Rack middleware that creates spans for incoming requests + config.middleware.insert_after(0, *OpenTelemetry::Instrumentation::Rack::Instrumentation.instance.middleware_args) + + # install telemetry handler to update request span name and attributes + config.telemetry.use Handlers::Request + + # install telemetry handler to propagate context to application-level fibers + config.telemetry.use Handlers::Fiber.new + + # install telemetry handlers for Rage components + config.telemetry.use Handlers::Cable + config.telemetry.use Handlers::Deferred + config.telemetry.use Handlers::Events + + # install log context to add tracing info to logs + config.log_context << LogContext + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/log_context.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/log_context.rb new file mode 100644 index 0000000000..115c992122 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/log_context.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Rage + # The class provides a custom log context to enrich Rage logs with + # the current OpenTelemetry trace and span IDs. + class LogContext + class << self + def call + current_span = OpenTelemetry::Trace.current_span + return unless current_span.recording? + + { + trace_id: current_span.context.hex_trace_id, + span_id: current_span.context.hex_span_id + } + rescue StandardError => e + OpenTelemetry.handle_error(exception: e) + nil + end + end + end + end + end +end diff --git a/instrumentation/rage/lib/opentelemetry/instrumentation/rage/version.rb b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/version.rb new file mode 100644 index 0000000000..a23097b1e4 --- /dev/null +++ b/instrumentation/rage/lib/opentelemetry/instrumentation/rage/version.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Rage + VERSION = '0.1.0' + end + end +end diff --git a/instrumentation/rage/opentelemetry-instrumentation-rage.gemspec b/instrumentation/rage/opentelemetry-instrumentation-rage.gemspec new file mode 100644 index 0000000000..01ab4b021c --- /dev/null +++ b/instrumentation/rage/opentelemetry-instrumentation-rage.gemspec @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +lib = File.expand_path('lib', __dir__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require 'opentelemetry/instrumentation/rage/version' + +Gem::Specification.new do |spec| + spec.name = 'opentelemetry-instrumentation-rage' + spec.version = OpenTelemetry::Instrumentation::Rage::VERSION + spec.authors = ['OpenTelemetry Authors'] + spec.email = ['cncf-opentelemetry-contributors@lists.cncf.io'] + + spec.summary = 'Rage instrumentation for the OpenTelemetry framework' + spec.description = 'Rage instrumentation for the OpenTelemetry framework' + spec.homepage = 'https://github.com/open-telemetry/opentelemetry-ruby-contrib' + spec.license = 'Apache-2.0' + + spec.files = Dir.glob('lib/**/*.rb') + + Dir.glob('*.md') + + ['LICENSE', '.yardopts'] + spec.require_paths = ['lib'] + spec.required_ruby_version = '>= 3.2' + + spec.add_dependency 'opentelemetry-instrumentation-rack', '~> 0.29' + spec.add_dependency 'opentelemetry-semantic_conventions', '>= 1.36.0' + + if spec.respond_to?(:metadata) + spec.metadata['changelog_uri'] = "https://rubydoc.info/gems/#{spec.name}/#{spec.version}/file/CHANGELOG.md" + spec.metadata['source_code_uri'] = 'https://github.com/open-telemetry/opentelemetry-ruby-contrib/tree/main/instrumentation/rage' + spec.metadata['bug_tracker_uri'] = 'https://github.com/open-telemetry/opentelemetry-ruby-contrib/issues' + spec.metadata['documentation_uri'] = "https://rubydoc.info/gems/#{spec.name}/#{spec.version}" + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/cable_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/cable_test.rb new file mode 100644 index 0000000000..b6c8e203d9 --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/cable_test.rb @@ -0,0 +1,285 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../../lib/opentelemetry/instrumentation/rage' +require_relative '../../../../../lib/opentelemetry/instrumentation/rage/handlers/cable' + +describe OpenTelemetry::Instrumentation::Rage::Handlers::Cable do + subject { OpenTelemetry::Instrumentation::Rage::Handlers::Cable } + + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + describe '.save_context' do + let(:env) { { 'REQUEST_METHOD' => 'POST', 'PATH_INFO' => '/cable' } } + + describe 'with no active span' do + it 'does not change env' do + subject.save_context(env:) {} + _(env.size).must_equal(2) + end + + it 'yields control' do + yielded = false + + subject.save_context(env:) do + yielded = true + end + + _(yielded).must_equal(true) + end + end + + describe 'with active span' do + before { instrumentation.install({}) } + after { instrumentation.instance_variable_set(:@installed, false) } + + it 'updates span name' do + instrumentation.tracer.in_span('test span') do |span| + context = OpenTelemetry::Instrumentation::Rack.context_with_span(span) + + OpenTelemetry::Context.with_current(context) do + subject.save_context(env:) {} + end + + _(span.name).must_equal('POST /cable') + end + end + + it 'updates env' do + instrumentation.tracer.in_span('test span') do |span| + context = OpenTelemetry::Instrumentation::Rack.context_with_span(span) + + OpenTelemetry::Context.with_current(context) do + subject.save_context(env:) {} + end + + _(env['otel.rage.handshake_context']).must_equal(context) + _(env['otel.rage.handshake_link'].first).must_be_instance_of(OpenTelemetry::Trace::Link) + end + end + + it 'yields control' do + instrumentation.tracer.in_span('test span') do |span| + context = OpenTelemetry::Instrumentation::Rack.context_with_span(span) + yielded = false + + OpenTelemetry::Context.with_current(context) do + subject.save_context(env:) do + yielded = true + end + end + + _(yielded).must_equal(true) + end + end + end + end + + describe '.create_connection_span' do + let(:link) { OpenTelemetry::Trace::Link.new(OpenTelemetry::Trace::SpanContext.new) } + let(:env) { { 'otel.rage.handshake_link' => [link] } } + let(:action) { :my_action } + let(:connection_class) { Class.new } + let(:connection) { connection_class.new } + let(:result) { double(error?: false) } + + let(:finished_spans) { EXPORTER.finished_spans } + let(:connection_span) { finished_spans.first } + + before do + instrumentation.install({}) + EXPORTER.reset + stub_const('MyConnection', connection_class) + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + it 'creates a span' do + subject.create_connection_span(env:, action:, connection:) { result } + + _(finished_spans.size).must_equal(1) + + _(connection_span.name).must_equal('MyConnection my_action') + _(connection_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + + _(connection_span.attributes['messaging.system']).must_equal('rage.cable') + _(connection_span.attributes['messaging.destination.name']).must_equal('MyConnection') + _(connection_span.attributes['code.function.name']).must_equal('MyConnection#my_action') + + _(connection_span.links.first).must_equal(link) + end + + describe 'with baggage' do + let(:context) { OpenTelemetry::Baggage.set_value('testing_baggage', 'it_worked') } + let(:env) { { 'otel.rage.handshake_context' => context } } + + it 'propagates baggage' do + subject.create_connection_span(env:, action:, connection:) do + _(OpenTelemetry::Baggage.value('testing_baggage')).must_equal('it_worked') + result + end + end + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + subject.create_connection_span(env:, action:, connection:) { result } + + _(connection_span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(connection_span.events.first.name).must_equal 'exception' + _(connection_span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + + describe 'with connect action' do + let(:action) { :connect } + + it 'sets span kind to server' do + subject.create_connection_span(env:, action:, connection:) { result } + _(connection_span.kind).must_equal(:server) + end + end + + describe 'with disconnect action' do + let(:action) { :disconnect } + + it 'sets span kind to internal' do + subject.create_connection_span(env:, action:, connection:) { result } + _(connection_span.kind).must_equal(:internal) + end + end + end + + describe '.create_channel_span' do + let(:link) { OpenTelemetry::Trace::Link.new(OpenTelemetry::Trace::SpanContext.new) } + let(:env) { { 'otel.rage.handshake_link' => [link] } } + let(:action) { :my_action } + let(:channel_class) { Class.new } + let(:channel) { channel_class.new } + + let(:result) { double(error?: false) } + + let(:finished_spans) { EXPORTER.finished_spans } + let(:channel_span) { finished_spans.first } + + before do + instrumentation.install({}) + EXPORTER.reset + stub_const('MyChannel', channel_class) + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + it 'creates a span' do + subject.create_channel_span(env:, action:, channel:) { result } + + _(finished_spans.size).must_equal(1) + + _(channel_span.name).must_equal('MyChannel receive') + _(channel_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + _(channel_span.kind).must_equal(:server) + + _(channel_span.attributes['messaging.system']).must_equal('rage.cable') + _(channel_span.attributes['messaging.destination.name']).must_equal('MyChannel') + _(channel_span.attributes['messaging.operation.type']).must_equal('receive') + _(channel_span.attributes['code.function.name']).must_equal('MyChannel#my_action') + + _(channel_span.links.first).must_equal(link) + end + + describe 'with baggage' do + let(:context) { OpenTelemetry::Baggage.set_value('testing_baggage', 'it_worked') } + let(:env) { { 'otel.rage.handshake_context' => context } } + + it 'propagates baggage' do + subject.create_channel_span(env:, action:, channel:) do + _(OpenTelemetry::Baggage.value('testing_baggage')).must_equal('it_worked') + result + end + end + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + subject.create_channel_span(env:, action:, channel:) { result } + + _(channel_span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(channel_span.events.first.name).must_equal 'exception' + _(channel_span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + + describe 'with subscribed action' do + let(:action) { :subscribed } + + it 'sets span kind to server' do + subject.create_channel_span(env:, action:, channel:) { result } + + _(channel_span.attributes['messaging.operation.type']).must_equal('receive') + _(channel_span.name).must_equal('MyChannel subscribe') + _(channel_span.kind).must_equal(:server) + end + end + + describe 'with unsubscribed action' do + let(:action) { :unsubscribed } + + it 'sets span kind to server' do + subject.create_channel_span(env:, action:, channel:) { result } + + _(channel_span.attributes['messaging.operation.type']).must_be_nil + _(channel_span.name).must_equal('MyChannel unsubscribe') + _(channel_span.kind).must_equal(:internal) + end + end + end + + describe '.create_broadcast_span' do + let(:result) { double(error?: false) } + + let(:finished_spans) { EXPORTER.finished_spans } + let(:broadcast_span) { finished_spans.first } + + before do + instrumentation.install({}) + EXPORTER.reset + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + it 'creates a span' do + subject.create_broadcast_span(stream: 'test-stream') { result } + + _(finished_spans.size).must_equal(1) + + _(broadcast_span.name).must_equal('Rage::Cable broadcast') + _(broadcast_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + _(broadcast_span.kind).must_equal(:producer) + + _(broadcast_span.attributes['messaging.system']).must_equal('rage.cable') + _(broadcast_span.attributes['messaging.operation.type']).must_equal('publish') + _(broadcast_span.attributes['messaging.destination.name']).must_equal('test-stream') + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + subject.create_broadcast_span(stream: 'test-stream') { result } + + _(broadcast_span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(broadcast_span.events.first.name).must_equal 'exception' + _(broadcast_span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/deferred_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/deferred_test.rb new file mode 100644 index 0000000000..aef58f4d6f --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/deferred_test.rb @@ -0,0 +1,149 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../../lib/opentelemetry/instrumentation/rage' +require_relative '../../../../../lib/opentelemetry/instrumentation/rage/handlers/deferred' + +describe OpenTelemetry::Instrumentation::Rage::Handlers::Deferred do + subject { OpenTelemetry::Instrumentation::Rage::Handlers::Deferred } + + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + let(:task_class) { Class.new } + let(:task_context) { {} } + + let(:result) { double(error?: false) } + + let(:finished_spans) { EXPORTER.finished_spans } + let(:task_span) { finished_spans.first } + + before do + instrumentation.install({}) + EXPORTER.reset + stub_const('MyTask', task_class) + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + describe '.create_enqueue_span' do + it 'creates a span' do + subject.create_enqueue_span(task_class:, task_context:) { result } + + _(finished_spans.size).must_equal(1) + + _(task_span.name).must_equal('MyTask enqueue') + _(task_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + _(task_span.kind).must_equal(:producer) + + _(task_span.attributes['messaging.system']).must_equal('rage.deferred') + _(task_span.attributes['messaging.operation.type']).must_equal('publish') + _(task_span.attributes['messaging.destination.name']).must_equal('MyTask') + _(task_span.attributes['code.function.name']).must_equal('MyTask.enqueue') + end + + it 'stores the context' do + subject.create_enqueue_span(task_class:, task_context:) { result } + _(task_context.key?('traceparent')).must_equal(true) + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + subject.create_enqueue_span(task_class:, task_context:) { result } + + _(task_span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(task_span.events.first.name).must_equal 'exception' + _(task_span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + end + + describe '.create_perform_span' do + let(:task) { double(meta: task_metadata) } + let(:task_metadata) { double(attempts: 0, retrying?: false) } + + it 'creates a span' do + subject.create_perform_span(task_class:, task:, task_context:) { result } + + _(finished_spans.size).must_equal(1) + + _(task_span.name).must_equal('MyTask perform') + _(task_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + _(task_span.kind).must_equal(:consumer) + + _(task_span.attributes['messaging.system']).must_equal('rage.deferred') + _(task_span.attributes['messaging.operation.type']).must_equal('process') + _(task_span.attributes['messaging.destination.name']).must_equal('MyTask') + _(task_span.attributes['code.function.name']).must_equal('MyTask#perform') + _(task_span.attributes['messaging.message.delivery_attempt']).must_be_nil + + _(task_span.links.nil?).must_equal(true) + end + + describe 'with retries' do + let(:task_metadata) { double(attempts: 3, retrying?: true) } + + it 'adds the retries attribute to the span' do + subject.create_perform_span(task_class:, task:, task_context:) { result } + + _(task_span.attributes['messaging.system']).must_equal('rage.deferred') + _(task_span.attributes['messaging.operation.type']).must_equal('process') + _(task_span.attributes['messaging.destination.name']).must_equal('MyTask') + _(task_span.attributes['code.function.name']).must_equal('MyTask#perform') + _(task_span.attributes['messaging.message.delivery_attempt']).must_equal(3) + end + end + + describe 'with root span' do + let(:task_span) { finished_spans.last } + + before do + instrumentation.tracer.in_span('test span') do |_span| + OpenTelemetry.propagation.inject(task_context) + end + end + + it 'links to root span' do + subject.create_perform_span(task_class:, task:, task_context:) { result } + + _(task_span.links.nil?).must_equal(false) + _(task_span.links.first).must_be_instance_of(OpenTelemetry::Trace::Link) + end + end + + describe 'with baggage' do + before do + context = OpenTelemetry::Baggage.set_value('testing_baggage', 'it_worked') + + OpenTelemetry::Context.with_current(context) do + OpenTelemetry.propagation.inject(task_context) + end + end + + it 'propagates baggage' do + subject.create_perform_span(task_class:, task:, task_context:) do + _(OpenTelemetry::Baggage.value('testing_baggage')).must_equal('it_worked') + result + end + end + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + subject.create_perform_span(task_class:, task:, task_context:) { result } + + _(task_span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(task_span.events.first.name).must_equal 'exception' + _(task_span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/events_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/events_test.rb new file mode 100644 index 0000000000..0e05540d89 --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/events_test.rb @@ -0,0 +1,152 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../../lib/opentelemetry/instrumentation/rage' +require_relative '../../../../../lib/opentelemetry/instrumentation/rage/handlers/events' + +describe OpenTelemetry::Instrumentation::Rage::Handlers::Events do + subject { OpenTelemetry::Instrumentation::Rage::Handlers::Events } + + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + let(:finished_spans) { EXPORTER.finished_spans } + let(:event_span) { finished_spans.first } + + before do + instrumentation.install({}) + EXPORTER.reset + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + describe '.create_publisher_span' do + let(:event_class) { Class.new } + let(:event) { event_class.new } + + before do + stub_const('MyEvent', event_class) + end + + describe 'with active span' do + it 'creates a span' do + instrumentation.tracer.in_span('test span') do + subject.create_publisher_span(event:) {} + end + + _(finished_spans.size).must_equal(2) + + _(event_span.name).must_equal('MyEvent publish') + _(event_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + _(event_span.kind).must_equal(:producer) + + _(event_span.attributes['messaging.system']).must_equal('rage.events') + _(event_span.attributes['messaging.operation.type']).must_equal('publish') + _(event_span.attributes['messaging.destination.name']).must_equal('MyEvent') + end + + it 'yields control' do + yielded = false + + subject.create_publisher_span(event:) do + yielded = true + end + + _(yielded).must_equal(true) + end + end + + describe 'without active span' do + it 'does not create a span' do + subject.create_publisher_span(event:) {} + _(finished_spans.size).must_equal(0) + end + + it 'yields control' do + yielded = false + + subject.create_publisher_span(event:) do + yielded = true + end + + _(yielded).must_equal(true) + end + end + end + + describe '.create_subscriber_span' do + let(:subscriber_class) do + Class.new do + def self.deferred?; end + end + end + let(:subscriber) { subscriber_class.new } + + let(:event_class) { Class.new } + let(:event) { event_class.new } + + let(:result) { double(error?: false) } + + before do + stub_const('MySubscriber', subscriber_class) + stub_const('MyEvent', event_class) + end + + describe 'with a synchronous subscriber' do + it 'creates a span' do + subscriber_class.stub(:deferred?, -> { false }) do + subject.create_subscriber_span(subscriber:, event:) { result } + end + + _(finished_spans.size).must_equal(1) + + _(event_span.name).must_equal('MySubscriber process') + _(event_span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + _(event_span.kind).must_equal(:consumer) + + _(event_span.attributes['messaging.system']).must_equal('rage.events') + _(event_span.attributes['messaging.operation.type']).must_equal('process') + _(event_span.attributes['messaging.destination.name']).must_equal('MyEvent') + _(event_span.attributes['code.function.name']).must_equal('MySubscriber#call') + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + subject.create_subscriber_span(subscriber:, event:) { result } + + _(event_span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(event_span.events.first.name).must_equal 'exception' + _(event_span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + end + + describe 'with an asynchronous subscriber' do + it 'does not create a span' do + subscriber_class.stub(:deferred?, -> { true }) do + subject.create_subscriber_span(subscriber:, event:) {} + end + + _(finished_spans.size).must_equal(0) + end + + it 'yields control' do + yielded = false + + subscriber_class.stub(:deferred?, -> { true }) do + subject.create_subscriber_span(subscriber:, event:) do + yielded = true + end + end + + _(yielded).must_equal(true) + end + end + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/fiber_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/fiber_test.rb new file mode 100644 index 0000000000..9629f874d3 --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/fiber_test.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../../lib/opentelemetry/instrumentation/rage' +require_relative '../../../../../lib/opentelemetry/instrumentation/rage/handlers/fiber' + +describe OpenTelemetry::Instrumentation::Rage::Handlers::Fiber do + subject { OpenTelemetry::Instrumentation::Rage::Handlers::Fiber } + + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + before do + instrumentation.install({}) + EXPORTER.reset + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + describe 'Patch' do + let(:klass) do + Class.new do + def self.schedule(&) + yield + end + end + end + + before do + klass.singleton_class.prepend(subject::Patch) + Fiber[:__rage_otel_context] = nil + end + + describe 'without active span' do + it 'saves context to fiber storage' do + _(Fiber[:__rage_otel_context]).must_be_nil + klass.schedule {} + _(Fiber[:__rage_otel_context]).must_be_instance_of(OpenTelemetry::Context) + end + end + + describe 'with active span' do + it 'saves context to fiber storage' do + _(Fiber[:__rage_otel_context]).must_be_nil + instrumentation.tracer.in_span('test span') do + klass.schedule {} + end + _(Fiber[:__rage_otel_context]).must_be_instance_of(OpenTelemetry::Context) + end + end + + it 'calls super' do + klass.stub(:schedule, -> { :test_schedule_result }) do + _(klass.schedule {}).must_equal(:test_schedule_result) + end + end + end + + describe '#initialize' do + it 'patches Fiber' do + expect(Fiber.singleton_class).to receive(:prepend).with(subject::Patch) + subject.new + end + end + + describe '#propagate_otel_context' do + before do + allow(Fiber.singleton_class).to receive(:prepend).with(subject::Patch) + end + + it 'propagates context' do + instrumentation.tracer.in_span('test span') do + Fiber[:__rage_otel_context] = OpenTelemetry::Context.current + end + + subject.new.propagate_otel_context do + _(OpenTelemetry::Trace.current_span.name).must_equal('test span') + end + end + + describe 'with baggage' do + it 'propagates baggage' do + Fiber[:__rage_otel_context] = OpenTelemetry::Baggage.set_value('testing_baggage', 'it_worked') + + subject.new.propagate_otel_context do + _(OpenTelemetry::Baggage.value('testing_baggage')).must_equal('it_worked') + end + end + end + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/request_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/request_test.rb new file mode 100644 index 0000000000..cb75a07039 --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/handlers/request_test.rb @@ -0,0 +1,90 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../../lib/opentelemetry/instrumentation/rage' +require_relative '../../../../../lib/opentelemetry/instrumentation/rage/handlers/request' + +describe OpenTelemetry::Instrumentation::Rage::Handlers::Request do + subject { OpenTelemetry::Instrumentation::Rage::Handlers::Request } + + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + before do + instrumentation.install({}) + EXPORTER.reset + end + + after { instrumentation.instance_variable_set(:@installed, false) } + + describe '.enrich_request_span' do + let(:controller_class) do + Class.new do + def action_name; end + end + end + let(:controller) { controller_class.new } + let(:request) { double(method: 'PUT', route_uri_pattern: '/api/test/:id') } + let(:result) { double(error?: false) } + + before do + stub_const('MyController', controller_class) + allow(controller).to receive(:action_name).and_return('my_action') + end + + it 'updates span name and attributes' do + instrumentation.tracer.in_span('test span') do |span| + context = OpenTelemetry::Instrumentation::Rack.context_with_span(span) + + OpenTelemetry::Context.with_current(context) do + subject.enrich_request_span(controller:, request:) { result } + end + + _(span.name).must_equal('PUT /api/test/:id') + + _(span.attributes['http.route']).must_equal('/api/test/:id') + _(span.attributes['code.function.name']).must_equal('MyController#my_action') + + _(span.status.code).must_equal(OpenTelemetry::Trace::Status::UNSET) + end + end + + describe 'with error' do + let(:result) { double(error?: true, exception: RuntimeError.new) } + + it 'handles returned exceptions' do + instrumentation.tracer.in_span('test span') do |span| + context = OpenTelemetry::Instrumentation::Rack.context_with_span(span) + + OpenTelemetry::Context.with_current(context) do + subject.enrich_request_span(controller:, request:) { result } + end + + _(span.status.code).must_equal(OpenTelemetry::Trace::Status::ERROR) + _(span.events.first.name).must_equal 'exception' + _(span.events.first.attributes['exception.type']).must_equal 'RuntimeError' + end + end + end + + describe 'with inactive span' do + it 'yields control' do + span = OpenTelemetry::Trace.non_recording_span(OpenTelemetry::Trace::SpanContext.new) + context = OpenTelemetry::Instrumentation::Rack.context_with_span(span) + yielded = false + + OpenTelemetry::Context.with_current(context) do + subject.enrich_request_span(controller:, request:) do + yielded = true + end + end + + _(yielded).must_equal(true) + end + end + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/instrumentation_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/instrumentation_test.rb new file mode 100644 index 0000000000..8d8d9cac49 --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/instrumentation_test.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../lib/opentelemetry/instrumentation/rage' + +describe OpenTelemetry::Instrumentation::Rage do + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + it 'has #name' do + _(instrumentation.name).must_equal 'OpenTelemetry::Instrumentation::Rage' + end + + it 'has #version' do + _(instrumentation.version).wont_be_nil + _(instrumentation.version).wont_be_empty + end + + describe '#install' do + after do + instrumentation.instance_variable_set(:@installed, false) + end + + it 'accepts argument' do + _(instrumentation.install({})).must_equal(true) + end + + it 'installs Rack middleware' do + expect(Rage.config.middleware).to receive(:insert_after) do |position, (middleware, _, _)| + _(position).must_equal(0) + _(middleware.name).must_match(/^OpenTelemetry::Instrumentation::Rack::Middlewares/) + end + + instrumentation.install({}) + end + + it 'installs observability components' do + expect(Rage.config.telemetry).to receive(:use).with(OpenTelemetry::Instrumentation::Rage::Handlers::Request) + expect(Rage.config.telemetry).to receive(:use).with(OpenTelemetry::Instrumentation::Rage::Handlers::Cable) + expect(Rage.config.telemetry).to receive(:use).with(OpenTelemetry::Instrumentation::Rage::Handlers::Deferred) + expect(Rage.config.telemetry).to receive(:use).with(OpenTelemetry::Instrumentation::Rage::Handlers::Events) + expect(Rage.config.telemetry).to receive(:use).with(instance_of(OpenTelemetry::Instrumentation::Rage::Handlers::Fiber)) + + expect(Rage.config.log_context).to receive(:<<).with(OpenTelemetry::Instrumentation::Rage::LogContext) + + instrumentation.install({}) + end + end + + describe '#compatible' do + describe 'with a compatible version' do + before do + stub_const('::Rage::VERSION', '1.22.1') + end + + it 'returns true' do + _(instrumentation.compatible?).must_equal(true) + end + + it 'logs a warning' do + expect(OpenTelemetry.logger).not_to receive(:warn) + instrumentation.compatible? + end + end + + describe 'with an incompatible version' do + before do + stub_const('::Rage::VERSION', '1.11.0') + end + + it 'returns false' do + _(instrumentation.compatible?).must_equal(false) + end + + it 'logs a warning' do + expect(OpenTelemetry.logger).to receive(:warn).with(/1.11.0 is not supported/) + instrumentation.compatible? + end + end + end +end diff --git a/instrumentation/rage/test/opentelemetry/instrumentation/rage/log_context_test.rb b/instrumentation/rage/test/opentelemetry/instrumentation/rage/log_context_test.rb new file mode 100644 index 0000000000..424dc9f327 --- /dev/null +++ b/instrumentation/rage/test/opentelemetry/instrumentation/rage/log_context_test.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../lib/opentelemetry/instrumentation/rage' +require_relative '../../../../lib/opentelemetry/instrumentation/rage/log_context' + +describe OpenTelemetry::Instrumentation::Rage::LogContext do + subject { OpenTelemetry::Instrumentation::Rage::LogContext.call } + + let(:instrumentation) { OpenTelemetry::Instrumentation::Rage::Instrumentation.instance } + + describe 'with no active span' do + it 'returns nil' do + _(subject).must_be_nil + end + end + + describe 'with active span' do + before { instrumentation.install({}) } + after { instrumentation.instance_variable_set(:@installed, false) } + + it 'returns a hash with trace_id and span_id' do + instrumentation.tracer.in_span('test span') do |span| + _(subject[:trace_id]).must_equal(span.context.hex_trace_id) + _(subject[:span_id]).must_equal(span.context.hex_span_id) + end + end + end + + describe 'with an exception' do + it 'handles raised exceptions' do + OpenTelemetry::Trace.stub(:current_span, ->(**) { raise 'Test Error' }) do + expect(OpenTelemetry).to receive(:handle_error).with(exception: instance_of(RuntimeError)) + _(subject).must_be_nil + end + end + end +end diff --git a/instrumentation/rage/test/test_helper.rb b/instrumentation/rage/test/test_helper.rb new file mode 100644 index 0000000000..9b2ae0c69b --- /dev/null +++ b/instrumentation/rage/test/test_helper.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'bundler/setup' +Bundler.require(:default, :development, :test) + +require 'minitest/autorun' +require 'webmock/minitest' +require 'rspec/mocks/minitest_integration' +require 'rage/all' + +# global opentelemetry-sdk setup: +EXPORTER = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new +span_processor = OpenTelemetry::SDK::Trace::Export::SimpleSpanProcessor.new(EXPORTER) + +OpenTelemetry::SDK.configure do |c| + c.error_handler = ->(exception:, message:) { raise(exception || message) } + c.logger = Logger.new($stderr, level: ENV.fetch('OTEL_LOG_LEVEL', 'fatal').to_sym) + c.add_span_processor span_processor +end diff --git a/releases/Gemfile b/releases/Gemfile index ef1f02d1ae..d9e336aa34 100644 --- a/releases/Gemfile +++ b/releases/Gemfile @@ -27,6 +27,7 @@ gem 'pg' gem 'que' gem 'racecar' gem 'rack' +gem 'rage-rb' gem 'rails' gem 'rake' gem 'rdkafka'