-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
90 lines (70 loc) · 1.99 KB
/
init.lua
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
-- from incredible-gmod.ru with <3
-- https://github.com/Be1zebub/Leaky-Bucket.lua
-- https://en.wikipedia.org/wiki/Leaky_bucket
--[[
local LeakyBucket = require("leaky-bucket")(1000, 50) -- 1 liter capacity, 50 milliliters per second bandwidth
function webserver:onRequestReceive(request, response)
LeakyBucket:Add(request.headers.length, function()
response.headers.code = 200
response.body = "pong!"
response()
end)
end
while true do
LeakyBucket()
webserver.listen()
end
]]--
local LeakyBucket = {}
function LeakyBucket:GetCapacity()
return self.capacity
end
function LeakyBucket:GetBandwidth()
return self.bandwidth
end
function LeakyBucket:GetValue()
return self.content
end
function LeakyBucket:GetLevel()
return self.content / self.capacity
end
function LeakyBucket:IsFull()
return self.content == self.capacity
end
function LeakyBucket:CanFit(size)
return self.content + size <= self.capacity
end
function LeakyBucket:Add(size, cback)
if self:CanFit(size) == false then return false end -- overflow leak
self.content = self.content + size
self.contents[#self.contents + 1] = {
size = size,
cback = cback
}
return true
end
function LeakyBucket:__call()
local incoming = self.contents[1]
if incoming == nil then return end
local time = os.time()
if time == self.lastLeak then return end
local change = (time - self.lastLeak) * self.bandwidth
self.content = math.max(0, self.content - change)
incoming.size = incoming.size - change
if incoming.size <= 0 then
if incoming.cback then incoming.cback() end
table.remove(self.contents, 1)
end
self.lastLeak = time
end
return setmetatable(LeakyBucket, {
__call = function(self, capacity, bandwidth)
return setmetatable({
capacity = capacity, -- can fit X liters
bandwidth = bandwidth, -- leak rate per second
content = 0, -- inner x liters
contents = {}, -- fluids queue
lastLeak = os.time()
}, self)
end
})