Search code examples
ruby-on-railsrubysidekiqrack

How can I lookup / retrieve the Rack::Timeout timeout value that has been configured in Rails?


In our Rails application we are using rack-timeout 0.4.2 and have it configured in config/initializers/timeout.rb for prod and staging like so:

if Rails.env.production? || Rails.env.staging?
  Rack::Timeout.timeout = (ENV['RACKTIMEOUT'] || 25).to_i # seconds
end

When we upgrade the gem in the near future those values will probably be set as service_timout or wait_timeout.

I want to retrieve what this value is set to in the application to use as a default for any MySidekiqWorker.perform_in(CURRENT_TIMEOUT_VALUE, ...) call, instead of just writing (ENV['RACKTIMEOUT'] || 25).to_i everywhere it's needed. The problem I am trying to work around here is this sidekiq issue, where it can't find the Model yet because it hasn't been committed. It's not an option right now to refactor these calls into after_commit hooks.

this try gives the following:

0> Rack::Timeout.timeout
=> private method `timeout' called for Rack::Timeout:Class

and Rails.app.configuration only has Rails.app.configuration.middleware.includes? Rack::Timeout as true and doesn't give any values that I can see.


Solution

  • I assume you're talking about https://github.com/sharpstone/rack-timeout.

    0.4.2 allows reading the value using some backwards-compatible methods:

    Rack::Timeout.service_timeout
    => 25
    

    It seems like the wrong way to approach the issue. You're setting the value in Rails based off an environment variable, so just make sure it's defined in ENV:

    # config/initializers/timeout.rb
    if Rails.env.production? || Rails.env.staging?
      ENV['RACKTIMEOUT'] ||= '25'
      Rack::Timeout.timeout = ENV['RACKTIMEOUT'].to_i
    end
    

    And then you can read it from anywhere:

    MySidekiqWorker.perform_in(ENV['RACKTIMEOUT'].to_i, ...)
    

    It's probably best to break out the logic for ENV into a separate configuration using something like figaro to make it all a little more manageable.

    That'll make your life a bit easier if you ever decide to upgrade to newer versions of the gem. I'd recommend looking into it because 0.4.2 is about 4 years old now. 0.6.0 is the most recent version and the gem configures itself using some default environment variables so all you have to do is set ENV['RACK_TIMEOUT_SERVICE_TIMEOUT'] and then you can skip the initializer altogether.