21
loading...
This website collects cookies to deliver better user experience
allowance
to allow the packet to pass through in the first second.current_time
is the current time frame that the rate-limiter is using.from time import time, sleep
class FixedWindow:
def __init__(self, capacity, forward_callback, drop_callback):
self.current_time = int(time())
self.allowance = capacity
self.capacity = capacity
self.forward_callback = forward_callback
self.drop_callback = drop_callback
handle()
where the magic happens.def handle(self, packet): #1
if (int(time()) != self.current_time): #2
self.current_time = int(time()) #3
self.allowance = self.capacity #3
if (self.allowance < 1): #4
return self.drop_callback(packet) #5
self.allowance -= 1 #6
return self.forward_callback(packet) #6
handle
accepts only 1 parameter: the packet.current_time
and reset the allowance
.from time import time, sleep
class FixedWindow:
def __init__(self, capacity, forward_callback, drop_callback):
self.current_time = int(time())
self.allowance = capacity
self.capacity = capacity
self.forward_callback = forward_callback
self.drop_callback = drop_callback
def handle(self, packet):
if (int(time()) != self.current_time):
self.current_time = int(time())
self.allowance = self.capacity
if (self.allowance < 1):
return self.drop_callback(packet)
self.allowance -= 1
return self.forward_callback(packet)
def forward(packet):
print("Packet Forwarded: " + str(packet))
def drop(packet):
print("Packet Dropped: " + str(packet))
throttle = FixedWindow(1, forward, drop)
packet = 0
while True:
sleep(0.2)
throttle.handle(packet)
packet += 1
Packet Forwarded: 0
Packet Dropped: 1
Packet Dropped: 2
Packet Forwarded: 3
Packet Dropped: 4
Packet Dropped: 5
Packet Dropped: 6
Packet Dropped: 7
Packet Forwarded: 8
Packet Dropped: 9
Packet Dropped: 10
Packet Dropped: 11
Packet Dropped: 12
Packet Forwarded: 13