| 1 | class TokenBucket: |
| 2 | """See README.md; the bucket starts full at the first allow() timestamp.""" |
| 3 | |
| 4 | def __init__(self, capacity, refill_per_sec): |
| 5 | if capacity <= 0 or refill_per_sec <= 0: |
| 6 | raise ValueError("capacity and refill_per_sec must be positive") |
| 7 | self.capacity = float(capacity) |
| 8 | self.refill_per_sec = float(refill_per_sec) |
| 9 | self._tokens = self.capacity |
| 10 | self._last_t = None |
| 11 | |
| 12 | def allow(self, t): |
| 13 | if self._last_t is not None: |
| 14 | if t < self._last_t: |
| 15 | raise ValueError("timestamps must be monotonically non-decreasing") |
| 16 | self._tokens = min( |
| 17 | self.capacity, self._tokens + (t - self._last_t) * self.refill_per_sec |
| 18 | ) |
| 19 | self._last_t = t |
| 20 | if self._tokens >= 1: |
| 21 | self._tokens -= 1 |
| 22 | return True |
| 23 | return False |
| 24 |