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
|
# File 'lib/status_workflow.rb', line 25
def status_transition!(intermediate_to_status, final_to_status)
intermediate_to_status = intermediate_to_status&.to_s
final_to_status = final_to_status&.to_s
lock_obtained_at = nil
lock_key = "status_workflow/#{self.class.name}/#{id}"
Timeout.timeout(LOCK_ACQUISITION_TIMEOUT, nil, "#{lock_key} timeout waiting for lock") do
until StatusWorkflow.redis.set(lock_key, true, nx: true, ex: LOCK_EXPIRY)
sleep LOCK_CHECK_RATE
end
lock_obtained_at = Time.now
end
heartbeat = nil
initial_to_status = intermediate_to_status || final_to_status
begin
send "can_enter_#{initial_to_status}?", true
raise TooSlow, "#{lock_key} lost lock after checking status" if Time.now - lock_obtained_at > LOCK_EXPIRY
if intermediate_to_status
update_columns status: intermediate_to_status, status_changed_at: Time.now
raise TooSlow, "#{lock_key} lost lock after setting intermediate status #{intermediate_to_status}" if Time.now - lock_obtained_at > LOCK_EXPIRY
end
if block_given?
begin
heartbeat = Thread.new do
loop do
StatusWorkflow.redis.expire lock_key, LOCK_EXPIRY
lock_obtained_at = Time.now
sleep LOCK_EXPIRY/2
end
end
yield
rescue
error = (["#{$!.class} #{$!.message}"] + $!.backtrace).join("\n")
update_columns status: 'error', status_changed_at: Time.now, error: error
raise
end
end
if intermediate_to_status
send "can_enter_#{final_to_status}?", true
raise TooSlow, "#{lock_key} lost lock after checking final status" if Time.now - lock_obtained_at > LOCK_EXPIRY
end
update_columns status: final_to_status, status_changed_at: Time.now
ensure
raise TooSlow, "#{lock_key} lost lock" if Time.now - lock_obtained_at > LOCK_EXPIRY
StatusWorkflow.redis.del lock_key
heartbeat.kill if heartbeat
end
true
end
|