thread_timeout: de-Struct-ify
[rainbows.git] / lib / rainbows / thread_timeout.rb
blobf34c0d4117b94b9ca7f29ab03596c283572ea082
1 # -*- encoding: binary -*-
2 require 'thread'
4 # Soft timeout middleware for thread-based concurrency models in \Rainbows!
5 # This timeout only includes application dispatch, and will not take into
6 # account the (rare) response bodies that are dynamically generated while
7 # they are being written out to the client.
9 # In your rackup config file (config.ru), the following line will
10 # cause execution to timeout in 1.5 seconds.
12 #    use Rainbows::ThreadTimeout, :timeout => 1.5
13 #    run MyApplication.new
15 # You may also specify a threshold, so the timeout does not take
16 # effect until there are enough active clients.  It does not make
17 # sense to set a +:threshold+ higher or equal to the
18 # +worker_connections+ \Rainbows! configuration parameter.
19 # You may specify a negative threshold to be an absolute
20 # value relative to the +worker_connections+ parameter, thus
21 # if you specify a threshold of -1, and have 100 worker_connections,
22 # ThreadTimeout will only activate when there are 99 active requests.
24 #    use Rainbows::ThreadTimeout, :timeout => 1.5, :threshold => -1
25 #    run MyApplication.new
27 # This middleware only affects elements below it in the stack, so
28 # it can be configured to ignore certain endpoints or middlewares.
30 # Timed-out requests will cause this middleware to return with a
31 # "408 Request Timeout" response.
33 class Rainbows::ThreadTimeout
35   # :stopdoc:
36   class ExecutionExpired < ::Exception
37   end
39   def initialize(app, opts)
40     @timeout = opts[:timeout]
41     Numeric === @timeout or
42       raise TypeError, "timeout=#{@timeout.inspect} is not numeric"
44     if @threshold = opts[:threshold]
45       Integer === @threshold or
46         raise TypeError, "threshold=#{@threshold.inspect} is not an integer"
47       @threshold == 0 and
48         raise ArgumentError, "threshold=0 does not make sense"
49       @threshold < 0 and
50         @threshold += Rainbows::G.server.worker_connections
51     end
52     @app = app
53     @active = {}
54     @lock = Mutex.new
55   end
57   def call(env)
58     @lock.synchronize do
59       start_watchdog unless @watchdog
60       @active[Thread.current] = Time.now + @timeout
61     end
62     begin
63       @app.call(env)
64     ensure
65       @lock.synchronize { @active.delete(Thread.current) }
66     end
67     rescue ExecutionExpired
68       [ 408, { 'Content-Type' => 'text/plain', 'Content-Length' => '0' }, [] ]
69   end
71   def start_watchdog
72     @watchdog = Thread.new do
73       begin
74         if next_wake = @lock.synchronize { @active.values }.min
75           next_wake -= Time.now
76           sleep(next_wake) if next_wake > 0
77         else
78           sleep(@timeout)
79         end
81         # "active.size" is atomic in MRI 1.8 and 1.9
82         next if @threshold && @active.size < @threshold
84         now = Time.now
85         @lock.synchronize do
86           @active.delete_if do |thread, time|
87             time >= now and thread.raise(ExecutionExpired).nil?
88           end
89         end
90       end while true
91     end
92   end
93   # :startdoc:
94 end