# `TokenBucket`

`TokenBucket` is an in-memory rate limiter. A new bucket starts full, so it can accept an initial burst up to `capacity` tokens. Each successful acquisition spends tokens, and elapsed time restores them at `rate` tokens per second, up to `capacity`. Refills are calculated when you call an acquisition method; there is no background worker.

Use `try_acquire()` to decide immediately whether to proceed, or `acquire()` to wait for tokens. By default, each call requests one token, so a rate of 5 means five one-token operations per second over time, not a hard limit of five operations in every one-second window.

## API reference

### `TokenBucket(rate, capacity=None, clock=time.monotonic)`

| Parameter | Description |
| --- | --- |
| `rate` | Refill rate in tokens per second. A rate less than or equal to zero raises `ValueError`. |
| `capacity` | Maximum number of tokens the bucket can hold, and its initial balance. Defaults to `rate`. |
| `clock` | No-argument callable returning time in seconds. Defaults to `time.monotonic`. Used for refill calculations and timeout checks. |

The constructor stores `rate` and `capacity` as floats. Fractional rates, capacities, and request sizes are supported.

### `try_acquire(n=1) -> bool`

Attempts to spend `n` tokens. Returns `True` and deducts `n` if enough tokens are available; otherwise returns `False` without spending any. It does not sleep for tokens, but may briefly wait for the bucket's lock. Raises `ValueError` if `n` exceeds `capacity`.

### `acquire(n=1, timeout=None) -> bool`

Attempts to spend `n` tokens immediately. If there are not enough tokens, it estimates how long replenishment will take, releases the lock, sleeps, and tries again. Returns `True` once it deducts `n` tokens.

`timeout` is in seconds. With `None`, there is no deadline. With a timeout, the method returns `False` without spending tokens if, after a failed attempt, the estimated next wait would extend past the deadline. In particular, `timeout=0` with the default clock still allows an immediate success but does not wait for replenishment.

## Examples

These examples assume `TokenBucket` is already imported or defined.

### Wait briefly for a token

```python
bucket = TokenBucket(rate=5, capacity=10)

if bucket.acquire(timeout=0.25):
    print("Proceed with one operation")
else:
    print("Rate limited; try again later")
```

The bucket allows a burst of ten one-token operations when full. Once empty, it takes about 0.2 seconds to refill one token, provided another caller doesn't take it first.

### Test burst and refill behavior without sleeping

```python
now = 0.0
bucket = TokenBucket(rate=2, capacity=3, clock=lambda: now)

assert bucket.try_acquire(3)        # Spend the initial burst.
assert not bucket.try_acquire()    # No tokens left.

now += 0.5                         # Two tokens/second × half a second.
assert bucket.try_acquire()        # One token has refilled.
```

## Caveats

- **Validate inputs at the call site.** Use finite positive values for `rate`, `capacity`, and `n`, with `n <= capacity`, and a finite nonnegative timeout or `None`. The implementation does not enforce all of these conditions: a negative `n` can add tokens, and `acquire()` does not reject `n > capacity`. Such an oversized request can wait indefinitely without a timeout. If `rate < 1` and you omit `capacity`, the default one-token request is oversized; set `capacity=1` or higher if you want to use that request size.
- **Timeouts are not hard deadlines.** Sleep and lock contention can delay a call. The deadline is checked only after an unsuccessful attempt, so `acquire()` can still return `True` after the deadline if it wakes up late and finds enough tokens.
- **Threads share the bucket, not a queue.** The lock protects refill and spending on a single instance, but there is no FIFO ordering or reservation. A caller that wakes up may find another thread has already spent the tokens. Separate instances and processes do not share a limit. `acquire()` is synchronous and can block an async event loop.
- **Use a monotonic clock.** Backward jumps contribute zero elapsed time for that refill, but the bucket still records the new timestamp. A custom clock does not replace `time.sleep()`; a frozen test clock will not refill the bucket during a real sleep. Token calculations use floating-point arithmetic, so exact fractional boundaries can be affected by rounding.
