Middleware and Thread Safety

I have the usual middleware used by my Rails 4 application. The middleware itself is only for the standard Accept and Content-Type headers for application/json , unless the client has provided reliable information (I'm working on an API). Therefore, before each request, it changes these headers, and after each request, it adds an X-Something-Media-Type user head with information about user media.

I would like to switch to Puma, so I'm a little worried about the thread safety of such middleware. I did not play with variable instances, except once for the regular @app.call that we come across in every middleware, but even here I reproduced something that I read in the RailsCasts comments:

 def initialize(app) @app = app end def call(env) dup._call(env) end def _call(env) ... status, headers, response = @app.call(env) ... 

Is dup._call useful for solving thread safety issues?

Except that the @app instance @app I only play with the current request created with the current env variable:

 request = Rack::Request.new(env) 

And I call env.update to update the header and form information.

Is it dangerous to expect some problems with this middleware when I switch from Webrick to a parallel web server like Puma ?

If so, do you know several ways to do some tests, isolate parts of my middleware that are not thread safe?

Thanks.

+6
source share
1 answer

Yes, dup middleware is required to be thread safe. That way, all the instance variables you set from _call will be set to the duped instance, not the original. You will notice that the web frameworks built into Rack work as follows:

One way to use the unit test is to assert that _call is called in the duplicate instance, and not in the original.

+2
source

All Articles