tessl install tessl/pypi-pyrate-limiter@3.9.0Python Rate-Limiter using Leaky-Bucket Algorithm for controlling request rates in applications with multiple backend storage options.
Agent Success
Agent success rate when using this tile
81%
Improvement
Agent success rate improvement when using this tile compared to baseline
1.45x
Baseline
Agent success rate without this tile
56%
Build a custom storage backend for a rate limiting system that persists rate limit data to JSON files. The implementation should support basic rate limiting operations with file-based persistence.
Your implementation must provide a storage backend that:
Create a JSONFileBucket class that stores rate items as timestamps in a JSON file, loads existing data on initialization, saves data after modifications, uses locking for thread safety, and implements context manager support.
@generates
from typing import List, Optional, Union
from threading import RLock
import json
class JSONFileBucket:
"""
A file-based storage backend that persists rate limit data to JSON files.
This bucket stores rate items as timestamps in a JSON file, providing
persistence across application restarts with thread-safe operations.
"""
def __init__(self, rates: List, file_path: str):
"""
Initialize the JSON file bucket.
Parameters:
- rates: List of Rate objects defining rate limits
- file_path: Path to the JSON file for storing data
"""
pass
def put(self, item) -> bool:
"""
Attempt to add an item to the bucket.
Parameters:
- item: RateItem to add
Returns:
- True if item was added successfully, False if rate limit exceeded
"""
pass
def leak(self, current_timestamp: Optional[int] = None) -> int:
"""
Remove expired items from the bucket.
Parameters:
- current_timestamp: Current time in milliseconds (optional)
Returns:
- Number of items removed
"""
pass
def flush(self) -> None:
"""
Remove all items from the bucket and clear the file.
"""
pass
def count(self) -> int:
"""
Get the number of items currently in the bucket.
Returns:
- Number of items
"""
pass
def peek(self, index: int) -> Optional:
"""
View an item at a specific index without removing it.
Parameters:
- index: Index of the item to view
Returns:
- RateItem at the index, or None if index is out of bounds
"""
pass
def waiting(self, item) -> int:
"""
Calculate how long to wait (in milliseconds) before the bucket has space.
Parameters:
- item: RateItem to check
Returns:
- Wait time in milliseconds, or 0 if space is available
"""
pass
def close(self) -> None:
"""
Release any resources held by the bucket.
"""
pass
def __enter__(self):
"""
Enter context manager.
Returns:
- self
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""
Exit context manager and cleanup resources.
"""
passProvides rate limiting functionality and core data structures.
@satisfied-by