Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respond a Rails request within a configurable timeout

I want to achieve the following behavior in my controllers' action without the usage of Timeout module:

class AdminController < ApplicationController
  def example
    Timeout.timeout(params[:timeout].to_i) do
      ... # try to process the request within params[:timeout] seconds
    end
  rescue Timeout::Error
    render nothing: true, status: :gateway_timeout
  end
end

I want to avoid the usage of Timeout because it's causing many bugs in my application, including database connection leaks. Some other problems reported at: http://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/

like image 338
barbolo Avatar asked Oct 18 '15 01:10

barbolo


2 Answers

Don't use ruby for this. The problem is that the timeout module is going to abort the code somewhere, anywhere in your executing code, which is going to result in open and dangling sockets, connections and files or worse. (This isn't really a problem if you're firing up an external script or shelling out for each job, I guess, but in those cases just use the unix/linux native io timeout)

This is pretty much why ruby CI servers never took off (Jenkins is java). I'd design this with a separate service that handles running jobs that you can ping with an API; then, in your view, ping it every few seconds so they can see continual updates. The rails app in this case wouldn't need to have any polluting timeout code in it.

edit: since you're doing HTTP requests in that block, just use the timeout setting built into the http library (e.g. https://github.com/lostisland/faraday )

like image 159
court3nay Avatar answered Nov 11 '22 03:11

court3nay


You can use gem "rack-timeout" https://github.com/heroku/rack-timeout for full fill your requirement.

# Gemfile

gem "rack-timeout"

# config/initializers/rack_timeout.rb
Rack::Timeout.timeout = 5  # seconds

Hope this will help you.

like image 24
hgsongra Avatar answered Nov 11 '22 03:11

hgsongra