thread_timeout: avoid a threading bug under 1.9
[rainbows.git] / lib / rainbows / thread_timeout.rb
blobb9f602580f596e4b5215aea6017d2eb8e1c20f50
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
77           # because of the lack of GVL-releasing syscalls in this branch
78           # of the thread loop, we need Thread.pass to ensure other threads
79           # get scheduled appropriately under 1.9.  This is likely a threading
80           # bug in 1.9 that warrants further investigation when we're in a
81           # better mood.
82           next_wake > 0 ? sleep(next_wake) : Thread.pass
83         else
84           sleep(@timeout)
85         end
87         # "active.size" is atomic in MRI 1.8 and 1.9
88         next if @threshold && @active.size < @threshold
90         now = Time.now
91         @lock.synchronize do
92           @active.delete_if do |thread, time|
93             time >= now and thread.raise(ExecutionExpired).nil?
94           end
95         end
96       end while true
97     end
98   end
99   # :startdoc: