interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / rate_limiter.py

58 lines · 2079 bytes Raw Blame History
1import time
2
3
4class RateLimiter:
5 """A sliding window rate limiter that tracks requests per client.
6
7 Limits the number of requests a client can make within a
8 configurable time window.
9
10 Args:
11 max_requests: Maximum number of requests allowed within the window.
12 window_seconds: Duration of the sliding window in seconds.
13 """
14
15 def __init__(self, max_requests, window_seconds):
16 self.max_requests = max_requests
17 self.window_seconds = window_seconds
18 self.requests = {}
19
20 def allow_request(self, client_id):
21 """Check whether a request from the given client should be allowed.
22
23 Prunes expired timestamps for the client and, if the request
24 count is below the limit, records the current time and returns
25 ``True``.
26
27 Args:
28 client_id: Unique identifier for the client making the request.
29
30 Returns:
31 True if the request is allowed; False if the client has
32 exceeded the rate limit.
33 """
34 now = time.time()
35 if client_id not in self.requests:
36 self.requests[client_id] = []
37 self.requests[client_id] = [t for t in self.requests[client_id] if now - t < self.window_seconds]
38 if len(self.requests[client_id]) >= self.max_requests:
39 return False
40 self.requests[client_id].append(now)
41 return True
42
43 def get_remaining(self, client_id):
44 """Return the number of requests remaining for the client.
45
46 Args:
47 client_id: Unique identifier for the client.
48
49 Returns:
50 The number of additional requests the client can make
51 within the current window. Returns ``max_requests`` if
52 the client has not yet made any requests.
53 """
54 now = time.time()
55 if client_id not in self.requests:
56 return self.max_requests
57 self.requests[client_id] = [t for t in self.requests[client_id] if now - t < self.window_seconds]
58 return max(0, self.max_requests - len(self.requests[client_id]))