Skip to content

Commit

Permalink
Improve compatibility with Faraday v1
Browse files Browse the repository at this point in the history
Fixes open-telemetry#1031

Faraday >= 1 changes where the #adapter method gets called, affecting
the RackBuilder patch in this gem.

Without this change, the tracer middleware gets added to the beginning
of the stack instead of the end, and explicitly adding the middleware
would cause it to get added twice.

This change patches `Connection#initialize` for Faraday >= 1 to preserve
the behavior we had with Faraday < 1. This is similar to the dd-trace-rb
change made in DataDog/dd-trace-rb#906.

There is some followup work here to explore moving the middleware to the
beginning of the stack instead of the end, but we can work on that
separately.
  • Loading branch information
composerinteralia committed Jun 20, 2024
1 parent 5b09f9b commit 548c7ab
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Instrumentation < OpenTelemetry::Instrumentation::Base

def require_dependencies
require_relative 'middlewares/tracer_middleware'
require_relative 'patches/connection'
require_relative 'patches/rack_builder'
end

Expand All @@ -37,7 +38,11 @@ def register_tracer_middleware
end

def use_middleware_by_default
::Faraday::RackBuilder.prepend(Patches::RackBuilder)
if Gem::Version.new(::Faraday::VERSION) >= Gem::Version.new('1')
::Faraday::Connection.prepend(Patches::Connection)
else
::Faraday::RackBuilder.prepend(Patches::RackBuilder)
end
end
end
end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# frozen_string_literal: true

# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0

module OpenTelemetry
module Instrumentation
module Faraday
module Patches
# Module to be prepended to force Faraday to use the middleware by
# default so the user doesn't have to call `use` for every connection.
module Connection
# Wraps Faraday::Connection#initialize:
# https://github.com/lostisland/faraday/blob/ff9dc1d1219a1bbdba95a9a4cf5d135b97247ee2/lib/faraday/connection.rb#L62-L92
def initialize(*args)
super.tap do
use(:open_telemetry) unless builder.handlers.any? do |handler|
handler.klass == Middlewares::TracerMiddleware
end
end
end
end
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -198,5 +198,18 @@
_(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR
end
end

describe 'when explicitly adding the tracer middleware' do
let(:client) do
Faraday.new do |builder|
builder.use :open_telemetry
end
end

it 'only adds the middleware once' do
tracers = client.builder.handlers.count(OpenTelemetry::Instrumentation::Faraday::Middlewares::TracerMiddleware)
_(tracers).must_equal 1
end
end
end
end

0 comments on commit 548c7ab

Please sign in to comment.