How to set timeout for a specific url in rails

I use rack-timeout and it works fine. But I could not figure out how to set the time for a specific URL.

Even if I like:

  map '/ foo / bar' do
   Rack :: Timeout.timeout = 10
 end

not only / foo / bar, but every action dies after 10 seconds.

Can I set a timeout for a specific URL? Or should I use a different solution than the rack timeout?

+4
source share
3 answers

If you worry that certain actions take too long, I would wrap the code in the anxiety block in a Timeout block, instead of trying to use timeouts at the URL level. You can easily combine the following into a helper method and use it with a variable timeout on all controllers.

require "timeout'" begin status = Timeout::timeout(10) { # Potentially long process here... } rescue Timeout::Error puts 'This is taking way too long.' end 
+3
source

Updated version of Jiten Kothari answer:

 module Rack class Timeout @excludes = [ '/statistics', ] class << self attr_accessor :excludes end def call_with_excludes(env) #puts 'BEGIN CALL' #puts env['REQUEST_URI'] #puts 'END CALL' if self.class.excludes.any? {|exclude_uri| /\A#{exclude_uri}/ =~ env['REQUEST_URI']} @app.call(env) else call_without_excludes(env) end end alias_method_chain :call, :excludes end end 
+2
source

put this code as timeout.rb in config / initializers folder and put your specific url to array exception

 require RUBY_VERSION < '1.9' && RUBY_PLATFORM != "java" ? 'system_timer' : 'timeout' SystemTimer ||= Timeout module Rack class Timeout @timeout = 30 @excludes = ['your url here', 'your url here' ] class << self attr_accessor :timeout, :excludes end def initialize(app) @app = app end def call(env) #puts 'BEGIN CALL' #puts env['REQUEST_URI'] #puts 'END CALL' if self.class.excludes.any? {|exclude_uri| /#{exclude_uri}/ =~ env['REQUEST_URI']} @app.call(env) else SystemTimer.timeout(self.class.timeout, ::Timeout::Error) { @app.call(env) } end end end end 
+1
source

Source: https://habr.com/ru/post/1479348/


All Articles