-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
defer.rb
96 lines (82 loc) · 1.88 KB
/
defer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
module Scheduler
module Deferrable
def initialize
@async = !Rails.env.test?
@queue = Queue.new
@mutex = Mutex.new
@paused = false
@thread = nil
end
def pause
stop!
@paused = true
end
def resume
@paused = false
end
# for test
def async=(val)
@async = val
end
def later(desc = nil, db = RailsMultisite::ConnectionManagement.current_db, &blk)
if @async
start_thread unless (@thread && @thread.alive?) || @paused
@queue << [db, blk, desc]
else
blk.call
end
end
def stop!
@thread.kill if @thread && @thread.alive?
@thread = nil
end
# test only
def stopped?
!(@thread && @thread.alive?)
end
def do_all_work
while !@queue.empty?
do_work(_non_block = true)
end
end
private
def start_thread
@mutex.synchronize do
return if @thread && @thread.alive?
@thread = Thread.new {
while true
do_work
end
}
end
end
# using non_block to match Ruby #deq
def do_work(non_block = false)
db, job, desc = @queue.deq(non_block)
db ||= RailsMultisite::ConnectionManagement::DEFAULT
RailsMultisite::ConnectionManagement.with_connection(db) do
begin
job.call
rescue => ex
Discourse.handle_job_exception(ex, message: "Running deferred code '#{desc}'")
end
end
rescue => ex
Discourse.handle_job_exception(ex, message: "Processing deferred code queue")
ensure
ActiveRecord::Base.connection_handler.clear_active_connections!
end
end
class Defer
module Unicorn
def process_client(client)
Defer.pause
super(client)
Defer.do_all_work
Defer.resume
end
end
extend Deferrable
initialize
end
end