Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set middleware_mutex when middleware/adapter classes are defined #1074

wants to merge 1 commit into
base: master


Copy link

technoweenie commented Nov 13, 2019

This is an attempt to fix #1065 by calling #middleware_mutex when the classes are defined. This should prevent @middleware_mutex from being undefined when a Faraday::Connection instance is used in a multi-threaded environment.

Right now, the proper way to build a Faraday::Connection for use in a multi-threaded environment should look something like this:

conn = "some-base-url") do |f|
  f.request :something
  f.response :or_other
  f.adapter :some_http_client

# The "rack app" wrapped in middleware. All requests are sent here.
# The builder is responsible for creating the app object. After this,
# the builder gets locked to ensure no further modifications are made
# to the middleware stack.
# Returns an object that responds to `call` and returns a Response.
def app
@app ||= begin

Faraday::Connection#app is delegated to Faraday::RackBuilder#app, which does the following:

  • Uses the Faraday::Request middleware registry to load :something
  • Uses the Faraday::Response middleware registry to load :or_other
  • Uses the Faraday::Adapter middleware registry to load :some_http_client
  • Locks the Faraday::RackBuilder instance from changing the middleware chain (conn.builder.handlers)
  • Instantiates all of the middleware instances
  • Builds the "app" instance from the loaded recursive middleware instances.

At this point, it should be safe to use shared connection object across multiple threads. But, I don't know how often it's used like this, so there are likely some more bugs.

I also have another larger solution in mind that requires some refactoring. I'll publish once I have it working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
1 participant
You can’t perform that action at this time.