-
-
Save zaharinea/0722125cdb04cd909a95f0deebb33e03 to your computer and use it in GitHub Desktop.
Generic Cell Rate Algorithm example
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 RateLimit: | |
| def __init__(self, count: int, period: timedelta) -> None: | |
| self.count = count | |
| self.period = period | |
| @property | |
| def inverse(self) -> float: | |
| return self.period.total_seconds() / self.count | |
| class Store: | |
| def get_tat(self, key: str) -> datetime: | |
| # This should return a previous tat for the key or the current time. | |
| pass | |
| def set_tat(self, key: str, tat: datetime) -> None: | |
| pass | |
| def update(self, key: str, limit: RateLimit) -> bool: | |
| now = datetime.utcnow() | |
| tat = max(self.get_tat(key), now) | |
| separation = (tat - now).total_seconds() | |
| max_interval = limit.period.total_seconds() - limit.inverse | |
| if separation > max_interval: | |
| reject = True | |
| else: | |
| reject = False | |
| new_tat = max(tat, now) + timedelta(seconds=limit.inverse) | |
| self.set_tat(key, new_tat) | |
| return reject |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment