/
sf6.rb
66 lines (54 loc) · 1.2 KB
/
sf6.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
module SF6
class Unavailable < StandardError
end
module Base
def reset!(attr)
data[:timestamps][attr] = 0
data[:counts][attr] = 0
end
private
def data
@data ||= {:counts => Hash.new(0), :timestamps => Hash.new(0)}
end
def stamp(attr, bucket)
timestamp = Time.now.to_i / bucket
data[:counts][attr] = 0 unless data[:timestamps][attr] == timestamp
timestamp
end
def increment(attr, timestamp)
data[:timestamps][attr] = timestamp
data[:counts][attr] += 1
end
def test(attr, value, &blk)
if value == 0 || data[:counts][attr] < value
yield
else
raise(Unavailable, attr)
end
end
end
module Limiter
extend Base
def self.check(attr, value, bucket, &blk)
timestamp = stamp(attr, bucket)
increment(attr, timestamp)
test(attr, value) do
yield
end
end
end
module Breaker
extend Base
def self.check(attr, value, bucket, &blk)
timestamp = stamp(attr, bucket)
test(attr, value) do
begin
yield
rescue => e
increment(attr, timestamp)
raise
end
end
end
end
end