This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class SlidingWindow: | |
| def __init__(self, window_size, max_requests): | |
| self.window_size = window_size | |
| self.max_requests = max_requests | |
| self.requests = deque() | |
| def allow_request(self): | |
| now = time.time() | |
| while self.requests and self.requests[0] <= now - self.window_size: | |
| self.requests.popleft() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FixedWindow: | |
| def __init__(self, window_size, max_requests): | |
| self.window_size = window_size | |
| self.max_requests = max_requests | |
| self.requests = 0 | |
| self.window_start = time.time() | |
| def allow_request(self): | |
| now = time.time() | |
| if now - self.window_start >= self.window_size: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LeakyBucket: | |
| def __init__(self, capacity, leak_rate): | |
| self.capacity = capacity # Maximum capacity of the bucket | |
| self.leak_rate = leak_rate # Rate at which the bucket leaks (units per second) | |
| self.bucket_size = 0 # Current size of the bucket | |
| self.last_updated = time.time() # Last time the bucket was updated | |
| def add_data(self, data_size): | |
| # Calculate time elapsed since last update | |
| current_time = time.time() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TokenBucket: | |
| def __init__(self, rate, capacity): | |
| self.rate = rate | |
| self.capacity = capacity | |
| self.tokens = capacity | |
| self.last_refill = time.time() | |
| def allow_request(self): | |
| now = time.time(); | |
| self.tokens += (now - self.last_refill) * self.rate |