diff --git a/.github/workflows/ci-instrumentation-canary.yml b/.github/workflows/ci-instrumentation-canary.yml index 7dde977e0..e257bb255 100644 --- a/.github/workflows/ci-instrumentation-canary.yml +++ b/.github/workflows/ci-instrumentation-canary.yml @@ -25,6 +25,7 @@ jobs: - ethon - excon - faraday + - grape - graphql - http - http_client diff --git a/.github/workflows/ci-instrumentation.yml b/.github/workflows/ci-instrumentation.yml index d7d248d26..0a37533ac 100644 --- a/.github/workflows/ci-instrumentation.yml +++ b/.github/workflows/ci-instrumentation.yml @@ -29,6 +29,7 @@ jobs: - ethon - excon - faraday + - grape - graphql - http - http_client diff --git a/.toys/.data/releases.yml b/.toys/.data/releases.yml index 2401731bc..985a4ceda 100644 --- a/.toys/.data/releases.yml +++ b/.toys/.data/releases.yml @@ -29,6 +29,10 @@ commit_lint: # * changelog_path: Path to CHANGLEOG.md relative to the gem directory. # (Required only if it is not in the expected location.) gems: + - name: opentelemetry-instrumentation-grape + directory: instrumentation/grape + version_constant: [OpenTelemetry, Instrumentation, Grape, VERSION] + - name: opentelemetry-instrumentation-racecar directory: instrumentation/racecar version_constant: [OpenTelemetry, Instrumentation, Racecar, VERSION] diff --git a/instrumentation/all/Gemfile b/instrumentation/all/Gemfile index da7318213..636f92c50 100644 --- a/instrumentation/all/Gemfile +++ b/instrumentation/all/Gemfile @@ -8,5 +8,6 @@ source 'https://rubygems.org' gemspec +gem 'opentelemetry-instrumentation-grape', path: '../grape' gem 'opentelemetry-instrumentation-racecar', path: '../racecar' gem 'opentelemetry-instrumentation-rake', path: '../rake' diff --git a/instrumentation/all/lib/opentelemetry/instrumentation/all.rb b/instrumentation/all/lib/opentelemetry/instrumentation/all.rb index 71abefca9..32756451d 100644 --- a/instrumentation/all/lib/opentelemetry/instrumentation/all.rb +++ b/instrumentation/all/lib/opentelemetry/instrumentation/all.rb @@ -4,6 +4,7 @@ # # SPDX-License-Identifier: Apache-2.0 +require 'opentelemetry-instrumentation-grape' require 'opentelemetry-instrumentation-trilogy' require 'opentelemetry-instrumentation-active_support' require 'opentelemetry-instrumentation-action_pack' diff --git a/instrumentation/all/opentelemetry-instrumentation-all.gemspec b/instrumentation/all/opentelemetry-instrumentation-all.gemspec index ced5dc6ee..96ef79c2e 100644 --- a/instrumentation/all/opentelemetry-instrumentation-all.gemspec +++ b/instrumentation/all/opentelemetry-instrumentation-all.gemspec @@ -35,6 +35,7 @@ Gem::Specification.new do |spec| spec.add_dependency 'opentelemetry-instrumentation-ethon', '~> 0.20.0' spec.add_dependency 'opentelemetry-instrumentation-excon', '~> 0.20.0' spec.add_dependency 'opentelemetry-instrumentation-faraday', '~> 0.22.0' + spec.add_dependency 'opentelemetry-instrumentation-grape', '~> 0.1.0' spec.add_dependency 'opentelemetry-instrumentation-graphql', '~> 0.24.0' spec.add_dependency 'opentelemetry-instrumentation-http', '~> 0.21.0' spec.add_dependency 'opentelemetry-instrumentation-http_client', '~> 0.21.0' diff --git a/instrumentation/grape/.rubocop.yml b/instrumentation/grape/.rubocop.yml new file mode 100644 index 000000000..1248a2f82 --- /dev/null +++ b/instrumentation/grape/.rubocop.yml @@ -0,0 +1 @@ +inherit_from: ../../.rubocop.yml diff --git a/instrumentation/grape/.yardopts b/instrumentation/grape/.yardopts new file mode 100644 index 000000000..33496b784 --- /dev/null +++ b/instrumentation/grape/.yardopts @@ -0,0 +1,9 @@ +--no-private +--title=OpenTelemetry Grape Instrumentation +--markup=markdown +--main=README.md +./lib/opentelemetry/instrumentation/**/*.rb +./lib/opentelemetry/instrumentation.rb +- +README.md +CHANGELOG.md diff --git a/instrumentation/grape/Appraisals b/instrumentation/grape/Appraisals new file mode 100644 index 000000000..f12843271 --- /dev/null +++ b/instrumentation/grape/Appraisals @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +appraise 'grape-1.2' do + gem 'grape', '~> 1.2' +end + +appraise 'grape-1.3' do + gem 'grape', '~> 1.3' +end + +appraise 'grape-1.4' do + gem 'grape', '~> 1.4' +end + +appraise 'grape-1.5' do + gem 'grape', '~> 1.5' +end + +appraise 'grape-1.6' do + gem 'grape', '~> 1.6' +end + +appraise 'grape-1.7' do + gem 'grape', '~> 1.7' +end diff --git a/instrumentation/grape/CHANGELOG.md b/instrumentation/grape/CHANGELOG.md new file mode 100644 index 000000000..ba9491294 --- /dev/null +++ b/instrumentation/grape/CHANGELOG.md @@ -0,0 +1 @@ +# Release History: opentelemetry-instrumentation-grape diff --git a/instrumentation/grape/Gemfile b/instrumentation/grape/Gemfile new file mode 100644 index 000000000..ed1ec924e --- /dev/null +++ b/instrumentation/grape/Gemfile @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +source 'https://rubygems.org' + +# DO NOT ADD DEPENDENCIES HERE! +# Please declare a minimum development dependency in the gemspec, +# then target specific versions in the Appraisals file. + +gemspec + +group :test do + gem 'opentelemetry-instrumentation-base', path: '../base' + gem 'opentelemetry-instrumentation-rack', path: '../rack' +end diff --git a/instrumentation/grape/LICENSE b/instrumentation/grape/LICENSE new file mode 100644 index 000000000..1ef7dad2c --- /dev/null +++ b/instrumentation/grape/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/grape/README.md b/instrumentation/grape/README.md new file mode 100644 index 000000000..e1d091f15 --- /dev/null +++ b/instrumentation/grape/README.md @@ -0,0 +1,91 @@ +# OpenTelemetry Grape Instrumentation + +The Grape instrumentation is a community-maintained instrumentation for [Grape][grape], a REST-like API framework for Ruby. + +It relies on the Grape built-in support for `ActiveSupport::Notifications` (more info [here](https://github.com/ruby-grape/grape#active-support-instrumentation)) and the [OpenTelemetry Rack instrumentation](opentelemetry-rack-instrumentation). + +It currently supports the following events: + +- `endpoint_run.grape` +- `endpoint_render.grape` +- `endpoint_run_filters.grape` +- `format_response.grape` + +## How do I get started? + +Install the gem using: + +``` +gem install opentelemetry-instrumentation-grape +``` + +Or, if you use [bundler][bundler-home], include `opentelemetry-instrumentation-grape` 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::Grape' +end +``` + +Grape is "designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra". As a result, this instrumentation uses the Rack instrumentation and modifies the Rack spans, modifying the span name and adding Grape attributes and events. It is recommended to use it along with Rails and/or Sinatra instrumentations, if any of these frameworks are being used. + +Alternatively, you can also call `use_all` to install all the available instrumentation. + +```ruby +OpenTelemetry::SDK.configure do |c| + c.use_all +end +``` + +### Configuration options + +#### `:ignored_events` (array) + +Indicate if any events should not produce spans. + +- Accepted values: `:endpoint_render`, `:endpoint_run_filters`, `:format_response`. +- Defaults to `[]` (no ignored events). + +Example: + +```ruby +OpenTelemetry::SDK.configure do |c| + c.use 'OpenTelemetry::Instrumentation::Grape', { ignored_events: [:endpoint_run_filters] } +end +``` + +Note that the `endpoint_run` event cannot be ignored. If you need to disable the instrumentation, set `:enabled` to `false`: + +```ruby +OpenTelemetry::SDK.configure do |c| + config = { 'OpenTelemetry::Instrumentation::Grape' => { enabled: false } } + c.use_all(config) +end +``` + +## Examples + +Example usage can be seen in the `./example/trace_demonstration.rb` file [here](https://github.com/open-telemetry/opentelemetry-ruby-contrib/blob/main/instrumentation/grape/example/trace_demonstration.rb) + +## How can I get involved? + +The `opentelemetry-instrumentation-grape` 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 in [GitHub Discussions][discussions-url] 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-grape` 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 +[discussions-url]: https://github.com/open-telemetry/opentelemetry-ruby/discussions +[grape]: https://github.com/ruby-grape/grape +[opentelemetry-rack-instrumentation]: https://github.com/open-telemetry/opentelemetry-ruby-contrib/tree/main/instrumentation/rack diff --git a/instrumentation/grape/Rakefile b/instrumentation/grape/Rakefile new file mode 100644 index 000000000..1a64ba842 --- /dev/null +++ b/instrumentation/grape/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/grape/example/trace_demonstration.rb b/instrumentation/grape/example/trace_demonstration.rb new file mode 100644 index 000000000..ca93f5eea --- /dev/null +++ b/instrumentation/grape/example/trace_demonstration.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +require 'bundler/inline' + +gemfile(true) do + source 'https://rubygems.org' + gem 'opentelemetry-api' + gem 'opentelemetry-instrumentation-grape' + gem 'opentelemetry-sdk' + gem 'grape' +end + +require 'opentelemetry-instrumentation-rack' + +# Export traces to console +ENV['OTEL_TRACES_EXPORTER'] ||= 'console' + +OpenTelemetry::SDK.configure do |c| + c.service_name = 'trace_demonstration' + c.use_all # this will only require instrumentation gems it finds that are installed by bundler. +end + +# A basic Grape API example +class ExampleAPI < Grape::API + format :json + + desc 'Return a greeting message' + get :hello do + { message: 'Hello, world!' } + end + + desc 'Return information about a user' + # Filters + before { sleep(0.01) } + after { sleep(0.01) } + params do + requires :id, type: Integer, desc: 'User ID' + end + get 'users/:id' do + { id: params[:id], name: 'John Doe', email: 'johndoe@example.com' } + end +end + +# Set up fake Rack application +builder = Rack::Builder.app do + # Integration is automatic in web frameworks but plain Rack applications require this line. + # Enable it in your config.ru. + use OpenTelemetry::Instrumentation::Rack::Middlewares::TracerMiddleware + run ExampleAPI +end +app = Rack::MockRequest.new(builder) + +app.get('/hello') +app.get('/users/1') diff --git a/instrumentation/grape/lib/opentelemetry-instrumentation-grape.rb b/instrumentation/grape/lib/opentelemetry-instrumentation-grape.rb new file mode 100644 index 000000000..baceb3cb7 --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry-instrumentation-grape.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/grape/lib/opentelemetry/instrumentation.rb b/instrumentation/grape/lib/opentelemetry/instrumentation.rb new file mode 100644 index 000000000..2bb04e9a9 --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry/instrumentation.rb @@ -0,0 +1,19 @@ +# 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_relative './instrumentation/grape' diff --git a/instrumentation/grape/lib/opentelemetry/instrumentation/grape.rb b/instrumentation/grape/lib/opentelemetry/instrumentation/grape.rb new file mode 100644 index 000000000..59d8f737c --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry/instrumentation/grape.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 Grape gem + module Grape + end + end +end + +require_relative './grape/instrumentation' +require_relative './grape/version' diff --git a/instrumentation/grape/lib/opentelemetry/instrumentation/grape/event_handler.rb b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/event_handler.rb new file mode 100644 index 000000000..5665abd19 --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/event_handler.rb @@ -0,0 +1,111 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Grape + # Handles the events instrumented with ActiveSupport notifications. + # These handlers contain all the logic needed to create and connect spans. + class EventHandler + class << self + # Handles the start of the endpoint_run event, modifying the parent Rack span + # and recording it as a span event + def endpoint_run(_name, start, _finish, _id, payload) + span = OpenTelemetry::Instrumentation::Rack.current_span + return unless span.recording? + + endpoint = payload[:endpoint] + span.name = span_name(endpoint) + span.add_attributes(attributes_from_grape_endpoint(endpoint)) + + span.add_event('grape.endpoint_run', timestamp: start) + handle_payload_exception(span, payload[:exception_object]) if payload[:exception_object] + end + + # Handles the endpoint_render event, recording it as a span event + def endpoint_render(_name, start, _finish, _id, payload) + span = OpenTelemetry::Instrumentation::Rack.current_span + return unless span.recording? + + span.add_event('grape.endpoint_render', timestamp: start) + end + + # Handles the endpoint_run_filters events, recording them as a span event + def endpoint_run_filters(_name, start, finish, _id, payload) + span = OpenTelemetry::Instrumentation::Rack.current_span + return unless span.recording? + + filters = payload[:filters] + type = payload[:type] + + # Prevent submitting empty filters + return if (!filters || filters.empty?) || !type || (finish - start).zero? + + attributes = { 'grape.filter.type' => type.to_s } + span.add_event('grape.endpoint_run_filters', attributes: attributes, timestamp: start) + end + + # Handles the format_response event, recording it as a span event + def format_response(_name, start, _finish, _id, payload) + span = OpenTelemetry::Instrumentation::Rack.current_span + return unless span.recording? + + attributes = { + 'grape.formatter.type' => formatter_type(payload[:formatter]) + } + span.add_event('grape.format_response', attributes: attributes, timestamp: start) + handle_payload_exception(span, payload[:exception_object]) if payload[:exception_object] + end + + private + + def span_name(endpoint) + "HTTP #{request_method(endpoint)} #{path(endpoint)}" + end + + def attributes_from_grape_endpoint(endpoint) + { + OpenTelemetry::SemanticConventions::Trace::CODE_NAMESPACE => endpoint.options[:for]&.base.to_s, + OpenTelemetry::SemanticConventions::Trace::HTTP_ROUTE => path(endpoint) + } + end + + # ActiveSupport::Notifications will attach a `:exception_object` to the payload if there was + # an error raised during the execution of the &block associated to the Notification. + def handle_payload_exception(span, exception) + # Only record exceptions if they were not raised (i.e. do not have a status code in Grape) + # or do not have a 5xx status code. These exceptions are recorded by Rack. + # See instrumentation/rack/lib/opentelemetry/instrumentation/rack/middlewares/tracer_middleware.rb#L155 + return unless exception.respond_to?('status') && exception.status.to_i < 500 + + span.record_exception(exception) + span.status = OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{exception.class}") + end + + def request_method(endpoint) + endpoint.options[:method]&.first + end + + def path(endpoint) + return '' unless endpoint.routes + + namespace = endpoint.routes.first.namespace + version = endpoint.routes.first.options[:version] || '' + prefix = endpoint.routes.first.options[:prefix]&.to_s || '' + parts = [prefix, version] + namespace.split('/') + endpoint.options[:path] + parts.reject { |p| p.blank? || p.eql?('/') }.join('/').prepend('/') + end + + def formatter_type(formatter) + basename = formatter.name.split('::').last + # Convert from CamelCase to snake_case + basename.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase + end + end + end + end + end +end diff --git a/instrumentation/grape/lib/opentelemetry/instrumentation/grape/instrumentation.rb b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/instrumentation.rb new file mode 100644 index 000000000..d31def440 --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/instrumentation.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Grape + # The Instrumentation class contains logic to detect and install the Grape instrumentation + class Instrumentation < OpenTelemetry::Instrumentation::Base + # Minimum Grape version needed for compatibility with this instrumentation + MINIMUM_VERSION = Gem::Version.new('1.2.0') + + install do |_config| + install_rack_instrumentation + require_dependencies + subscribe + end + + present do + defined?(::Grape) + end + + compatible do + !defined?(::ActiveSupport::Notifications).nil? && gem_version >= MINIMUM_VERSION + end + + option :ignored_events, default: [], validate: :array + + private + + def gem_version + Gem::Version.new(::Grape::VERSION) + end + + def install_rack_instrumentation + OpenTelemetry::Instrumentation::Rack::Instrumentation.instance.install({}) + end + + def require_dependencies + require_relative 'subscriber' + end + + def subscribe + Subscriber.subscribe + end + end + end + end +end diff --git a/instrumentation/grape/lib/opentelemetry/instrumentation/grape/subscriber.rb b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/subscriber.rb new file mode 100644 index 000000000..004c558e5 --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/subscriber.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require_relative 'event_handler' + +module OpenTelemetry + module Instrumentation + module Grape + # Manages all subscriptions, both for custom subscribers and built-in notifications + class Subscriber + class << self + # Subscribe to all notifications (except those specified in the :ignored_events configs) + def subscribe + subscriptions = filter_ignored_events(SUBSCRIPTIONS) + subscriptions.each do |subscriber_method, event| + ::ActiveSupport::Notifications.subscribe(event) do |*args| + EventHandler.send(subscriber_method, *args) + end + end + end + + private + + # ActiveSupport::Notifications that can be subscribed to using the documented `.subscribe` interface. + # Reference: https://api.rubyonrails.org/classes/ActiveSupport/Notifications.html#method-c-subscribe + SUBSCRIPTIONS = { + endpoint_run: 'endpoint_run.grape', + endpoint_render: 'endpoint_render.grape', + endpoint_run_filters: 'endpoint_run_filters.grape', + format_response: 'format_response.grape' + }.freeze + + def filter_ignored_events(subscriptions) + # Do not ignore 'endpoint_run' event + ignored_events = config[:ignored_events] - [:endpoint_run] + subscriptions.reject { |event| ignored_events.include?(event) } + end + + def config + Grape::Instrumentation.instance.config + end + end + end + end + end +end diff --git a/instrumentation/grape/lib/opentelemetry/instrumentation/grape/version.rb b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/version.rb new file mode 100644 index 000000000..36d3a5f23 --- /dev/null +++ b/instrumentation/grape/lib/opentelemetry/instrumentation/grape/version.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +module OpenTelemetry + module Instrumentation + module Grape + # Current gem version + VERSION = '0.1.0' + end + end +end diff --git a/instrumentation/grape/opentelemetry-instrumentation-grape.gemspec b/instrumentation/grape/opentelemetry-instrumentation-grape.gemspec new file mode 100644 index 000000000..35838f115 --- /dev/null +++ b/instrumentation/grape/opentelemetry-instrumentation-grape.gemspec @@ -0,0 +1,54 @@ +# 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/grape/version' + +Gem::Specification.new do |spec| + spec.name = 'opentelemetry-instrumentation-grape' + spec.version = OpenTelemetry::Instrumentation::Grape::VERSION + spec.authors = ['OpenTelemetry Authors'] + spec.email = ['cncf-opentelemetry-contributors@lists.cncf.io'] + + spec.summary = 'Grape instrumentation for the OpenTelemetry framework' + spec.description = 'Grape 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.0' + + spec.add_dependency 'opentelemetry-api', '~> 1.1.0' + spec.add_dependency 'opentelemetry-instrumentation-base', '~> 0.21.1' + spec.add_dependency 'opentelemetry-instrumentation-rack', '~> 0.21' + + spec.add_development_dependency 'activesupport' + spec.add_development_dependency 'appraisal', '~> 2.2.0' + spec.add_development_dependency 'bundler', '~> 2.4' + spec.add_development_dependency 'grape', '~> 1.2' + spec.add_development_dependency 'minitest', '~> 5.0' + spec.add_development_dependency 'opentelemetry-sdk', '~> 1.0' + spec.add_development_dependency 'opentelemetry-test-helpers' + spec.add_development_dependency 'rack-test' + spec.add_development_dependency 'rake', '~> 13.0' + spec.add_development_dependency 'rspec-mocks' + spec.add_development_dependency 'rubocop', '~> 1.48.1' + spec.add_development_dependency 'simplecov', '~> 0.17.1' + spec.add_development_dependency 'webmock', '~> 3.7.6' + spec.add_development_dependency 'yard', '~> 0.9' + spec.add_development_dependency 'yard-doctest', '~> 0.1.6' + + 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/grape' + 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/grape/test/opentelemetry/instrumentation/grape/instrumentation_test.rb b/instrumentation/grape/test/opentelemetry/instrumentation/grape/instrumentation_test.rb new file mode 100644 index 000000000..b3119e2bd --- /dev/null +++ b/instrumentation/grape/test/opentelemetry/instrumentation/grape/instrumentation_test.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../../lib/opentelemetry/instrumentation/grape' + +describe OpenTelemetry::Instrumentation::Grape do + let(:instrumentation) { OpenTelemetry::Instrumentation::Grape::Instrumentation.instance } + + it 'has #name' do + _(instrumentation.name).must_equal 'OpenTelemetry::Instrumentation::Grape' + end + + it 'has #version' do + _(instrumentation.version).wont_be_nil + _(instrumentation.version).wont_be_empty + end + + describe '#install' do + it 'accepts argument' do + _(instrumentation.install({})).must_equal(true) + instrumentation.instance_variable_set(:@installed, false) + end + end + + describe '#compatible' do + it 'returns false for older gem versions' do + stub_const('::Grape::VERSION', '0.12.0') + _(instrumentation.compatible?).must_equal false + end + + it 'returns true for newer gem versions' do + stub_const('::Grape::VERSION', '1.7.0') + _(instrumentation.compatible?).must_equal true + end + end + + describe '#config' do + before do + # Simulate a fresh install + uninstall_and_cleanup + instrumentation.install(config) + end + + describe 'when configs are empty' do + let(:config) { {} } + + it 'is installed with default settings when configs are empty' do + _(instrumentation).must_be :installed? + _(instrumentation.config[:ignored_events]).must_be_empty + end + end + + describe 'when configs are not empty' do + let(:config) { { ignored_events: [:endpoint_render] } } + + it 'is installed with the specified configs' do + _(instrumentation).must_be :installed? + _(instrumentation.config[:ignored_events]).must_equal [:endpoint_render] + end + end + end +end diff --git a/instrumentation/grape/test/opentelemetry/instrumentation/grape_test.rb b/instrumentation/grape/test/opentelemetry/instrumentation/grape_test.rb new file mode 100644 index 000000000..1757f32da --- /dev/null +++ b/instrumentation/grape/test/opentelemetry/instrumentation/grape_test.rb @@ -0,0 +1,374 @@ +# frozen_string_literal: true + +# Copyright The OpenTelemetry Authors +# +# SPDX-License-Identifier: Apache-2.0 + +require 'test_helper' + +require_relative '../../../lib/opentelemetry/instrumentation/grape' + +describe OpenTelemetry::Instrumentation::Grape do + include Rack::Test::Methods + + let(:instrumentation) { OpenTelemetry::Instrumentation::Grape::Instrumentation.instance } + let(:exporter) { EXPORTER } + let(:spans) { exporter.finished_spans } + let(:span) { spans.first } + let(:config) { {} } + + before do + # Simulate fresh install + uninstall_and_cleanup + instrumentation.install(config) + end + + describe '#endpoint' do + describe 'when a basic API endpoint receives a request' do + class BasicAPI < Grape::API + format :json + get :hello do + { message: 'Hello, world!' } + end + end + + let(:app) { build_rack_app(BasicAPI) } + let(:request_path) { '/hello' } + let(:expected_span_name) { 'HTTP GET /hello' } + + before { app.get request_path } + + it 'produces a Rack span with the expected name and attributes' do + _(spans.length).must_equal 1 + + _(span.instrumentation_scope.name).must_equal 'OpenTelemetry::Instrumentation::Rack' + _(span.name).must_equal expected_span_name + _(span.attributes['code.namespace']).must_equal 'BasicAPI' + _(span.attributes['http.route']).must_equal '/hello' + end + + it 'adds an endpoint_run span event with the expected attributes' do + run_events = events_per_name('grape.endpoint_run') + + _(run_events.length).must_equal 1 + _(run_events.first.attributes).must_be_empty + end + + it 'adds an endpoint_render span event with the expected attributes' do + render_events = events_per_name('grape.endpoint_render') + + _(render_events.length).must_equal 1 + _(render_events.first.attributes).must_be_empty + end + + it 'does not add an endpoint_run_filters span' do + filter_events = events_per_name('grape.endpoint_run_filters') + + _(filter_events.length).must_equal 0 + end + + it 'adds a format_response span event with the expected attributes' do + format_events = events_per_name('grape.format_response') + + _(format_events.length).must_equal 1 + _(format_events.first.attributes['grape.formatter.type']).must_equal 'json' + end + end + + describe 'when an API endpoint with a route param receives a request' do + class RouteParamAPI < Grape::API + format :json + params do + requires :id, type: Integer, desc: 'User ID' + end + get 'users/:id' do + { id: params[:id], name: 'John Doe', email: 'johndoe@example.com' } + end + end + + let(:app) { build_rack_app(RouteParamAPI) } + let(:request_path) { '/users/1' } + let(:expected_span_name) { 'HTTP GET /users/:id' } + + before { app.get request_path } + + it 'sets the correct span name and adds the correct path attribute to the Rack span' do + _(span.name).must_equal expected_span_name + _(span.attributes['http.route']).must_equal '/users/:id' + end + end + + describe 'when an API endpoint with version and prefix receives a request' do + class VersionedWithPrefixAPI < Grape::API + prefix :api + version 'v1' + get :hello do + { message: 'Hello, world!' } + end + end + + let(:app) { build_rack_app(VersionedWithPrefixAPI) } + let(:request_path) { '/api/v1/hello' } + let(:expected_span_name) { 'HTTP GET /api/v1/hello' } + + before { app.get request_path } + + it 'sets the correct span name and adds the correct path attribute to the Rack span' do + _(span.name).must_equal expected_span_name + _(span.attributes['http.route']).must_equal '/api/v1/hello' + end + end + + describe 'when an API endpoint nested in a namespace receives a request' do + class NestedAPI < Grape::API + format :json + namespace :internal do + resource :users do + get do + { users: ['John Doe', 'Jane Doe'] } + end + end + end + end + + let(:app) { build_rack_app(NestedAPI) } + let(:request_path) { '/internal/users' } + let(:expected_span_name) { 'HTTP GET /internal/users' } + + before { app.get request_path } + + it 'sets the correct span name and adds the correct path attribute to the Rack span' do + _(span.name).must_equal expected_span_name + _(span.attributes['http.route']).must_equal '/internal/users' + end + end + + describe 'when a filtered API endpoint receives a request' do + class FilteredAPI < Grape::API + before { sleep(0.01) } + after { sleep(0.01) } + get :filtered do + 'OK' + end + end + + let(:app) { build_rack_app(FilteredAPI) } + let(:request_path) { '/filtered' } + let(:expected_span_name) { 'HTTP GET /filtered' } + + before { app.get request_path } + + it 'produces a Rack span with the expected name' do + _(spans.length).must_equal 1 + _(span.name).must_equal expected_span_name + end + + it 'adds two endpoint_run_filters events for before and after filters' do + filter_events = events_per_name('grape.endpoint_run_filters') + + _(filter_events.length).must_equal 2 + end + + it 'adds the before filter event with the expected attributes' do + event = events_per_name('grape.endpoint_run_filters').first + expected_attributes = { 'grape.filter.type' => 'before' } + + _(event.attributes).must_equal expected_attributes + end + + it 'adds the after filter event with the expected attributes' do + event = events_per_name('grape.endpoint_run_filters').last + expected_attributes = { 'grape.filter.type' => 'after' } + + _(event.attributes).must_equal expected_attributes + end + end + + describe 'when an API endpoint receives params that raise a validation error' do + class ValidationErrorAPI < Grape::API + format :json + before { sleep(0.01) } + params { requires :name, type: String } + post :new do + status 201 + end + end + + let(:app) { build_rack_app(ValidationErrorAPI) } + let(:request_path) { '/new' } + let(:expected_span_name) { 'HTTP POST /new' } + let(:headers) { { 'Content-Type' => 'application/json' } } + let(:expected_error_type) { 'Grape::Exceptions::ValidationErrors' } + + before { app.post request_path, headers: headers, params: {} } + + it 'sets span status to error' do + _(span.name).must_equal expected_span_name + _(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR + _(span.status.description).must_equal "Unhandled exception of type: #{expected_error_type}" + end + + it 'records the exception event' do + exception_events = events_per_name('exception') + + _(exception_events.length).must_equal 1 + _(exception_events.first.attributes['exception.type']).must_equal expected_error_type + _(exception_events.first.attributes['exception.message']).must_equal 'name is missing' + end + + it 'also records the filter event' do + filter_events = events_per_name('grape.endpoint_run_filters') + + _(filter_events.length).must_equal 1 + end + end + + describe 'when an API endpoint raises an error' do + class RaisedErrorAPI < Grape::API + before { sleep(0.01) } + get :failure do + raise StandardError, 'Oops!' + end + end + + let(:app) { build_rack_app(RaisedErrorAPI) } + let(:request_path) { '/failure' } + let(:expected_span_name) { 'HTTP GET /failure' } + let(:expected_error_type) { 'StandardError' } + + before do + expect { app.get request_path }.must_raise StandardError + end + + it 'sets span status to error' do + _(span.name).must_equal expected_span_name + _(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR + _(span.status.description).must_equal "Unhandled exception of type: #{expected_error_type}" + end + + it 'records the exception event' do + exception_events = events_per_name('exception') + + _(exception_events.length).must_equal 1 + _(exception_events.first.attributes['exception.type']).must_equal expected_error_type + _(exception_events.first.attributes['exception.message']).must_equal 'Oops!' + end + + it 'records events other than exceptions' do + _(events_per_name('grape.endpoint_run').length).must_equal 1 + _(events_per_name('grape.endpoint_run_filters').length).must_equal 1 + _(events_per_name('grape.endpoint_render').length).must_equal 1 + end + end + + describe 'when an API endpoint raises an error in the filters' do + class ErrorInFilterAPI < Grape::API + before { raise StandardError, 'Oops!' } + get :filtered do + 'OK' + end + end + + let(:app) { build_rack_app(ErrorInFilterAPI) } + let(:request_path) { '/filtered' } + let(:expected_span_name) { 'HTTP GET /filtered' } + let(:expected_error_type) { 'StandardError' } + + before do + expect { app.get request_path }.must_raise StandardError + end + + it 'records the filter event' do + filter_events = events_per_name('grape.endpoint_run_filters') + + _(filter_events.length).must_equal 1 + end + + it 'sets span status to error' do + _(span.name).must_equal expected_span_name + _(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR + _(span.status.description).must_equal "Unhandled exception of type: #{expected_error_type}" + end + + it 'records the exception event' do + exception_events = events_per_name('exception') + + _(exception_events.length).must_equal 1 + _(exception_events.first.attributes['exception.type']).must_equal expected_error_type + _(exception_events.first.attributes['exception.message']).must_equal 'Oops!' + end + end + + describe 'when an API endpoint raises an error when formatting the response' do + class ErrorInFormatterAPI < Grape::API + format :xml + get :bad_format do + 'Not OK' + end + end + + let(:app) { build_rack_app(ErrorInFormatterAPI) } + let(:request_path) { '/bad_format' } + let(:expected_span_name) { 'HTTP GET /bad_format' } + let(:expected_error_type) { 'Grape::Exceptions::InvalidFormatter' } + + before { app.get request_path } + + it 'sets span status to error' do + _(span.name).must_equal expected_span_name + _(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR + end + + it 'records the exception event' do + exception_events = events_per_name('exception') + + _(exception_events.length).must_equal 1 + _(exception_events.first.attributes['exception.type']).must_equal expected_error_type + _(exception_events.first.attributes['exception.message']).must_equal 'cannot convert String to xml' + end + end + + describe 'when an API endpoint returns an error without raising an exception' do + class ErrorResponseAPI < Grape::API + get :error_response do + error!('Not found', 404) + end + end + + let(:app) { build_rack_app(ErrorResponseAPI) } + let(:request_path) { '/error_response' } + let(:expected_span_name) { 'HTTP GET /error_response' } + + before { app.get request_path } + + it 'does not set span status to error' do + _(span.name).must_equal expected_span_name + _(span.status.code).wont_equal OpenTelemetry::Trace::Status::ERROR + end + end + + describe 'when an API endpoint receives a request and some events are ignored in the configs' do + class IgnoredEventAPI < Grape::API + get :success do + 'OK' + end + end + + let(:config) { { ignored_events: [:endpoint_render] } } + let(:app) { build_rack_app(IgnoredEventAPI) } + let(:request_path) { '/success' } + let(:expected_span_name) { 'HTTP GET /success' } + + before { app.get request_path } + + it 'produces a Rack span with the expected name' do + _(spans.length).must_equal 1 + _(span.name).must_equal expected_span_name + end + + it 'does not add the endpoint_render event to the span' do + _(events_per_name('grape.endpoint_render').length).must_equal 0 + end + end + end +end diff --git a/instrumentation/grape/test/test_helper.rb b/instrumentation/grape/test/test_helper.rb new file mode 100644 index 000000000..7bc0d82d9 --- /dev/null +++ b/instrumentation/grape/test/test_helper.rb @@ -0,0 +1,54 @@ +# 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' + +# 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 + +# Helper functions +def uninstall_and_cleanup + instrumentation.instance_variable_set('@installed', false) + unsubscribe + EXPORTER.reset +end + +def unsubscribe + subscriptions = [ + 'endpoint_run.grape', + 'endpoint_render.grape', + 'endpoint_run_filters.grape', + 'format_response.grape' + ] + subscriptions.each { |e| ActiveSupport::Notifications.unsubscribe(e) } +end + +def build_rack_app(api_class) + builder = Rack::Builder.app do + use OpenTelemetry::Instrumentation::Rack::Middlewares::TracerMiddleware + run api_class + end + Rack::MockRequest.new(builder) +end + +def events_per_name(name) + events = span.events + return [] if events.nil? + + events.select { |e| e.name == name } +end