Spaces:
Runtime error
Runtime error
Download voice_control/rate_limiter.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 38.2 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/rate_limiter.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/rate_limiter.py
-
curl -L -o rate_limiter.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/rate_limiter.py
38.2 kB
| """ | |
| Rate Limiter implementation for the voice control optimization system. | |
| This module implements sophisticated rate limiting and quota management | |
| with sliding window tracking, provider-specific limits, and automatic | |
| provider switching capabilities. | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| from typing import Dict, List, Optional, Set, Tuple, Any | |
| from datetime import datetime, timedelta, timezone | |
| from collections import defaultdict, deque | |
| from dataclasses import dataclass, field | |
| import json | |
| from .interfaces import RateLimiterInterface | |
| from .models import QuotaStatus, QuotaType, UsageStats, ProviderConfig | |
| from .exceptions import QuotaExceededError, RateLimitExceededError, ConfigurationError | |
| logger = logging.getLogger(__name__) | |
| class TimeWindow: | |
| """Represents a time window for rate limiting.""" | |
| duration: int # Duration in seconds | |
| max_requests: int | |
| max_audio_duration: float | |
| reset_schedule: Optional[str] = None # "hourly", "daily", "monthly", or None for sliding | |
| class WindowUsage: | |
| """Tracks usage within a time window.""" | |
| requests: deque = field(default_factory=deque) # Timestamps of requests | |
| audio_durations: deque = field(default_factory=deque) # (timestamp, duration) tuples | |
| total_requests: int = 0 | |
| total_audio_duration: float = 0.0 | |
| last_reset: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | |
| class RateLimiter(RateLimiterInterface): | |
| """ | |
| Implements multi-window rate limiting with sliding window tracking. | |
| Features: | |
| - Sliding window rate limiting for requests per minute/hour/day | |
| - Audio duration quota tracking across multiple time windows | |
| - Provider-specific limit enforcement | |
| - Automatic quota resets based on provider schedules | |
| - Exponential backoff for rate limit violations | |
| """ | |
| def __init__(self, redis_url: Optional[str] = None, cleanup_interval: int = 300): | |
| """ | |
| Initialize the rate limiter. | |
| Args: | |
| redis_url: Redis URL for distributed rate limiting (None for in-memory) | |
| cleanup_interval: Interval in seconds for cleaning up old data | |
| """ | |
| self._redis_url = redis_url | |
| self._cleanup_interval = cleanup_interval | |
| # In-memory storage (used when Redis is not available) | |
| self._provider_windows: Dict[str, Dict[str, TimeWindow]] = {} | |
| self._provider_usage: Dict[str, Dict[str, WindowUsage]] = defaultdict(lambda: defaultdict(WindowUsage)) | |
| # Provider configurations | |
| self._provider_configs: Dict[str, ProviderConfig] = {} | |
| # Backoff tracking | |
| self._backoff_state: Dict[str, Dict[str, Any]] = defaultdict(dict) | |
| # Background tasks | |
| self._cleanup_task: Optional[asyncio.Task] = None | |
| self._reset_scheduler_task: Optional[asyncio.Task] = None | |
| # Lock for thread safety | |
| self._lock = asyncio.Lock() | |
| # Redis client (will be initialized if redis_url is provided) | |
| self._redis_client = None | |
| # Reset scheduler configuration | |
| self._reset_check_interval = 60 # Check for resets every minute | |
| logger.info(f"RateLimiter initialized (redis_url: {redis_url is not None})") | |
| async def initialize(self) -> None: | |
| """Initialize the rate limiter and start background tasks.""" | |
| if self._redis_url: | |
| await self._initialize_redis() | |
| # Start background tasks | |
| self._cleanup_task = asyncio.create_task(self._cleanup_loop()) | |
| self._reset_scheduler_task = asyncio.create_task(self._reset_scheduler_loop()) | |
| logger.info("RateLimiter initialization complete") | |
| async def _initialize_redis(self) -> None: | |
| """Initialize Redis client for distributed rate limiting.""" | |
| try: | |
| import redis.asyncio as redis | |
| self._redis_client = redis.from_url(self._redis_url) | |
| await self._redis_client.ping() | |
| logger.info("Redis client initialized successfully") | |
| except ImportError: | |
| logger.warning("Redis not available, falling back to in-memory rate limiting") | |
| self._redis_client = None | |
| except Exception as e: | |
| logger.error(f"Failed to initialize Redis client: {e}") | |
| self._redis_client = None | |
| async def configure_provider(self, provider_config: ProviderConfig) -> None: | |
| """ | |
| Configure rate limits for a provider. | |
| Args: | |
| provider_config: Provider configuration with rate limits | |
| """ | |
| async with self._lock: | |
| provider_name = provider_config.name | |
| self._provider_configs[provider_name] = provider_config | |
| # Initialize time windows based on provider configuration | |
| windows = {} | |
| # Standard rate limit windows | |
| rate_limits = provider_config.rate_limits | |
| if "requests_per_minute" in rate_limits: | |
| windows["requests_per_minute"] = TimeWindow( | |
| duration=60, | |
| max_requests=rate_limits["requests_per_minute"], | |
| max_audio_duration=float('inf') | |
| ) | |
| if "requests_per_hour" in rate_limits: | |
| windows["requests_per_hour"] = TimeWindow( | |
| duration=3600, | |
| max_requests=rate_limits["requests_per_hour"], | |
| max_audio_duration=float('inf') | |
| ) | |
| if "requests_per_day" in rate_limits: | |
| windows["requests_per_day"] = TimeWindow( | |
| duration=86400, | |
| max_requests=rate_limits["requests_per_day"], | |
| max_audio_duration=float('inf'), | |
| reset_schedule="daily" | |
| ) | |
| # Audio duration limits from free tier limits | |
| free_tier = provider_config.free_tier_limits | |
| if "audio_minutes_per_day" in free_tier: | |
| windows["audio_minutes_per_day"] = TimeWindow( | |
| duration=86400, | |
| max_requests=float('inf'), | |
| max_audio_duration=free_tier["audio_minutes_per_day"] * 60.0, # Convert to seconds | |
| reset_schedule="daily" | |
| ) | |
| if "audio_minutes_per_month" in free_tier: | |
| windows["audio_minutes_per_month"] = TimeWindow( | |
| duration=30 * 86400, # 30 days | |
| max_requests=float('inf'), | |
| max_audio_duration=free_tier["audio_minutes_per_month"] * 60.0, # Convert to seconds | |
| reset_schedule="monthly" | |
| ) | |
| self._provider_windows[provider_name] = windows | |
| # Initialize usage tracking for each window | |
| for window_name in windows: | |
| if window_name not in self._provider_usage[provider_name]: | |
| self._provider_usage[provider_name][window_name] = WindowUsage() | |
| logger.info(f"Configured rate limits for provider {provider_name}: {list(windows.keys())}") | |
| async def check_quota( | |
| self, | |
| provider: str, | |
| audio_duration: float | |
| ) -> QuotaStatus: | |
| """ | |
| Check if a request would exceed quota limits. | |
| Args: | |
| provider: Provider name | |
| audio_duration: Duration of audio in seconds | |
| Returns: | |
| QuotaStatus indicating current usage and limits | |
| """ | |
| if provider not in self._provider_windows: | |
| # No limits configured for this provider | |
| return QuotaStatus( | |
| provider=provider, | |
| quota_type=QuotaType.REQUESTS_PER_MINUTE, | |
| current_usage=0.0, | |
| limit=float('inf'), | |
| remaining=float('inf'), | |
| reset_time=datetime.now(timezone.utc) + timedelta(hours=1), | |
| percentage_used=0.0 | |
| ) | |
| async with self._lock: | |
| # Check all configured windows for this provider | |
| most_restrictive_status = None | |
| highest_usage_percentage = 0.0 | |
| for window_name, window in self._provider_windows[provider].items(): | |
| usage = self._provider_usage[provider][window_name] | |
| # Clean up old entries for sliding windows | |
| if window.reset_schedule is None: | |
| await self._cleanup_sliding_window(provider, window_name, window.duration) | |
| # Calculate current usage | |
| current_requests = len(usage.requests) | |
| current_audio_duration = sum(duration for _, duration in usage.audio_durations) | |
| # Check request limits | |
| if window.max_requests != float('inf'): | |
| requests_percentage = current_requests / window.max_requests | |
| if requests_percentage > highest_usage_percentage: | |
| highest_usage_percentage = requests_percentage | |
| quota_type = self._window_name_to_quota_type(window_name) | |
| most_restrictive_status = QuotaStatus( | |
| provider=provider, | |
| quota_type=quota_type, | |
| current_usage=current_requests, | |
| limit=window.max_requests, | |
| remaining=max(0, window.max_requests - current_requests), | |
| reset_time=self._calculate_reset_time(window), | |
| percentage_used=requests_percentage | |
| ) | |
| # Check audio duration limits | |
| if window.max_audio_duration != float('inf'): | |
| # Check if adding this request would exceed the limit | |
| projected_duration = current_audio_duration + audio_duration | |
| duration_percentage = projected_duration / window.max_audio_duration | |
| if duration_percentage > highest_usage_percentage: | |
| highest_usage_percentage = duration_percentage | |
| quota_type = self._window_name_to_quota_type(window_name) | |
| # Create QuotaStatus with projected usage to properly reflect if limit would be exceeded | |
| most_restrictive_status = QuotaStatus( | |
| provider=provider, | |
| quota_type=quota_type, | |
| current_usage=projected_duration / 60.0, # Use projected duration in minutes | |
| limit=window.max_audio_duration / 60.0, # Convert to minutes | |
| remaining=max(0, (window.max_audio_duration - projected_duration) / 60.0), | |
| reset_time=self._calculate_reset_time(window), | |
| percentage_used=0.0 # Will be recalculated in __post_init__ | |
| ) | |
| # Return the most restrictive quota status | |
| if most_restrictive_status is None: | |
| # No limits configured | |
| return QuotaStatus( | |
| provider=provider, | |
| quota_type=QuotaType.REQUESTS_PER_MINUTE, | |
| current_usage=0.0, | |
| limit=float('inf'), | |
| remaining=float('inf'), | |
| reset_time=datetime.now(timezone.utc) + timedelta(hours=1), | |
| percentage_used=0.0 | |
| ) | |
| return most_restrictive_status | |
| async def consume_quota( | |
| self, | |
| provider: str, | |
| audio_duration: float, | |
| request_count: int = 1 | |
| ) -> bool: | |
| """ | |
| Consume quota for a request. | |
| Args: | |
| provider: Provider name | |
| audio_duration: Duration of audio in seconds | |
| request_count: Number of requests (default 1) | |
| Returns: | |
| True if quota was consumed successfully, False if exceeded | |
| Raises: | |
| QuotaExceededError: If quota would be exceeded | |
| """ | |
| # First check if the request would exceed limits | |
| quota_status = await self.check_quota(provider, audio_duration) | |
| if quota_status.is_exceeded: | |
| # Check if we should apply backoff (only on repeated attempts) | |
| backoff_key = f"{provider}:{quota_status.quota_type.value}" | |
| if backoff_key in self._backoff_state: | |
| await self._apply_backoff(provider, quota_status.quota_type.value) | |
| else: | |
| # First time hitting the limit, just record it for future backoff | |
| self._backoff_state[backoff_key] = { | |
| "attempts": 1, | |
| "last_attempt": time.time(), | |
| "backoff_duration": 1.0 | |
| } | |
| raise QuotaExceededError(provider, quota_status.quota_type.value, quota_status.current_usage, quota_status.limit) | |
| # Check if we're near the limit and should warn | |
| if quota_status.is_near_limit(threshold=0.9): | |
| logger.warning(f"Provider {provider} approaching quota limit: {quota_status.percentage_used:.1%} used") | |
| # Consume the quota | |
| async with self._lock: | |
| if provider not in self._provider_windows: | |
| return True # No limits configured | |
| current_time = time.time() | |
| for window_name in self._provider_windows[provider]: | |
| usage = self._provider_usage[provider][window_name] | |
| # Add request timestamps | |
| for _ in range(request_count): | |
| usage.requests.append(current_time) | |
| # Add audio duration | |
| if audio_duration > 0: | |
| usage.audio_durations.append((current_time, audio_duration)) | |
| # Update totals | |
| usage.total_requests += request_count | |
| usage.total_audio_duration += audio_duration | |
| # Reset backoff on successful consumption | |
| if provider in self._backoff_state: | |
| # Clear backoff for this provider | |
| keys_to_remove = [key for key in self._backoff_state.keys() if key.startswith(f"{provider}:")] | |
| for key in keys_to_remove: | |
| del self._backoff_state[key] | |
| logger.debug(f"Consumed quota for {provider}: {request_count} requests, {audio_duration:.2f}s audio") | |
| return True | |
| async def get_usage_stats( | |
| self, | |
| provider: str, | |
| time_window: str | |
| ) -> UsageStats: | |
| """ | |
| Get usage statistics for a provider and time window. | |
| Args: | |
| provider: Provider name | |
| time_window: Time window ("minute", "hour", "day", "month") | |
| Returns: | |
| UsageStats for the specified period | |
| """ | |
| # Map time window to actual window name used in tracking | |
| window_mapping = { | |
| "minute": "requests_per_minute", | |
| "hour": "requests_per_hour", | |
| "day": "requests_per_day", | |
| "month": "audio_minutes_per_month" | |
| } | |
| window_name = window_mapping.get(time_window, "requests_per_minute") | |
| async with self._lock: | |
| if provider not in self._provider_usage or window_name not in self._provider_usage[provider]: | |
| # No usage data available | |
| now = datetime.now(timezone.utc) | |
| return UsageStats( | |
| provider=provider, | |
| requests_count=0, | |
| audio_minutes=0.0, | |
| estimated_cost=0.0, | |
| success_rate=1.0, | |
| average_latency=0.0, | |
| time_window=time_window, | |
| window_start=now, | |
| window_end=now | |
| ) | |
| usage = self._provider_usage[provider][window_name] | |
| # Calculate window boundaries using current time | |
| current_time = time.time() | |
| if time_window == "minute": | |
| window_start_timestamp = current_time - 60 | |
| elif time_window == "hour": | |
| window_start_timestamp = current_time - 3600 | |
| elif time_window == "day": | |
| window_start_timestamp = current_time - 86400 | |
| elif time_window == "month": | |
| window_start_timestamp = current_time - (30 * 86400) | |
| else: | |
| window_start_timestamp = current_time - 3600 | |
| # Count requests and audio duration in the window | |
| requests_in_window = sum(1 for timestamp in usage.requests if timestamp >= window_start_timestamp) | |
| audio_in_window = sum(duration for timestamp, duration in usage.audio_durations if timestamp >= window_start_timestamp) | |
| # Convert back to datetime for return value | |
| now = datetime.now(timezone.utc) | |
| window_start = datetime.fromtimestamp(window_start_timestamp, tz=timezone.utc) | |
| # Estimate cost | |
| provider_config = self._provider_configs.get(provider) | |
| estimated_cost = 0.0 | |
| if provider_config: | |
| estimated_cost = (audio_in_window / 60.0) * provider_config.cost_per_minute | |
| return UsageStats( | |
| provider=provider, | |
| requests_count=requests_in_window, | |
| audio_minutes=audio_in_window / 60.0, | |
| estimated_cost=estimated_cost, | |
| success_rate=1.0, # We don't track failures here | |
| average_latency=0.0, # We don't track latency here | |
| time_window=time_window, | |
| window_start=window_start, | |
| window_end=now | |
| ) | |
| async def reset_quota(self, provider: str, quota_type: str) -> None: | |
| """ | |
| Reset quota counters for a provider. | |
| Args: | |
| provider: Provider name | |
| quota_type: Type of quota to reset | |
| """ | |
| async with self._lock: | |
| if provider not in self._provider_usage: | |
| return | |
| # Find matching windows | |
| windows_to_reset = [] | |
| for window_name in self._provider_usage[provider]: | |
| if quota_type in window_name: | |
| windows_to_reset.append(window_name) | |
| # Reset usage for matching windows | |
| for window_name in windows_to_reset: | |
| usage = self._provider_usage[provider][window_name] | |
| usage.requests.clear() | |
| usage.audio_durations.clear() | |
| usage.total_requests = 0 | |
| usage.total_audio_duration = 0.0 | |
| usage.last_reset = datetime.now(timezone.utc) | |
| logger.info(f"Reset quota for provider {provider}, type {quota_type}") | |
| async def _cleanup_sliding_window(self, provider: str, window_name: str, window_duration: int) -> None: | |
| """ | |
| Clean up old entries from a sliding window. | |
| Args: | |
| provider: Provider name | |
| window_name: Name of the window | |
| window_duration: Duration of the window in seconds | |
| """ | |
| usage = self._provider_usage[provider][window_name] | |
| current_time = time.time() | |
| cutoff_time = current_time - window_duration | |
| # Remove old request timestamps | |
| while usage.requests and usage.requests[0] < cutoff_time: | |
| usage.requests.popleft() | |
| # Remove old audio duration entries | |
| while usage.audio_durations and usage.audio_durations[0][0] < cutoff_time: | |
| usage.audio_durations.popleft() | |
| def _window_name_to_quota_type(self, window_name: str) -> QuotaType: | |
| """Convert window name to QuotaType enum.""" | |
| if "requests_per_minute" in window_name: | |
| return QuotaType.REQUESTS_PER_MINUTE | |
| elif "requests_per_hour" in window_name: | |
| return QuotaType.REQUESTS_PER_HOUR | |
| elif "requests_per_day" in window_name: | |
| return QuotaType.REQUESTS_PER_DAY | |
| elif "audio_minutes_per_day" in window_name: | |
| return QuotaType.AUDIO_MINUTES_PER_DAY | |
| elif "audio_minutes_per_month" in window_name: | |
| return QuotaType.AUDIO_MINUTES_PER_MONTH | |
| else: | |
| return QuotaType.REQUESTS_PER_MINUTE | |
| def _calculate_reset_time(self, window: TimeWindow) -> datetime: | |
| """Calculate when the window will reset.""" | |
| now = datetime.now(timezone.utc) | |
| if window.reset_schedule == "hourly": | |
| # Reset at the top of the next hour | |
| next_reset = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) | |
| elif window.reset_schedule == "daily": | |
| # Reset at midnight | |
| next_reset = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1) | |
| elif window.reset_schedule == "weekly": | |
| # Reset at the beginning of next week (Monday) | |
| days_until_monday = (7 - now.weekday()) % 7 | |
| if days_until_monday == 0: # If today is Monday, reset next Monday | |
| days_until_monday = 7 | |
| next_reset = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=days_until_monday) | |
| elif window.reset_schedule == "monthly": | |
| # Reset at the beginning of next month | |
| if now.month == 12: | |
| next_reset = now.replace(year=now.year + 1, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) | |
| else: | |
| next_reset = now.replace(month=now.month + 1, day=1, hour=0, minute=0, second=0, microsecond=0) | |
| else: | |
| # Sliding window - reset continuously | |
| next_reset = now + timedelta(seconds=window.duration) | |
| return next_reset | |
| async def _apply_backoff(self, provider: str, quota_type: str) -> None: | |
| """ | |
| Apply exponential backoff for rate limit violations. | |
| Args: | |
| provider: Provider name | |
| quota_type: Type of quota that was exceeded | |
| """ | |
| backoff_key = f"{provider}:{quota_type}" | |
| if backoff_key not in self._backoff_state: | |
| self._backoff_state[backoff_key] = { | |
| "attempts": 0, | |
| "last_attempt": time.time(), | |
| "backoff_duration": 1.0 # Start with 1 second | |
| } | |
| backoff_info = self._backoff_state[backoff_key] | |
| current_time = time.time() | |
| # Check if enough time has passed since last attempt | |
| time_since_last = current_time - backoff_info["last_attempt"] | |
| if time_since_last < backoff_info["backoff_duration"]: | |
| remaining_wait = backoff_info["backoff_duration"] - time_since_last | |
| raise RateLimitExceededError(provider, quota_type, remaining_wait) | |
| # Update backoff state | |
| backoff_info["attempts"] += 1 | |
| backoff_info["last_attempt"] = current_time | |
| backoff_info["backoff_duration"] = min(300, backoff_info["backoff_duration"] * 2) # Max 5 minutes | |
| logger.warning(f"Applied exponential backoff for {provider}:{quota_type}, next attempt in {backoff_info['backoff_duration']}s") | |
| async def _cleanup_loop(self) -> None: | |
| """Background task for periodic cleanup of old data.""" | |
| while True: | |
| try: | |
| await asyncio.sleep(self._cleanup_interval) | |
| await self._perform_cleanup() | |
| except asyncio.CancelledError: | |
| logger.info("Rate limiter cleanup loop cancelled") | |
| break | |
| except Exception as e: | |
| logger.error(f"Error in rate limiter cleanup loop: {e}") | |
| async def _reset_scheduler_loop(self) -> None: | |
| """Background task for scheduled quota resets.""" | |
| while True: | |
| try: | |
| await asyncio.sleep(self._reset_check_interval) | |
| await self._check_and_perform_resets() | |
| except asyncio.CancelledError: | |
| logger.info("Rate limiter reset scheduler loop cancelled") | |
| break | |
| except Exception as e: | |
| logger.error(f"Error in rate limiter reset scheduler loop: {e}") | |
| async def _perform_cleanup(self) -> None: | |
| """Perform cleanup of old rate limiting data.""" | |
| async with self._lock: | |
| current_time = time.time() | |
| for provider in list(self._provider_usage.keys()): | |
| for window_name in list(self._provider_usage[provider].keys()): | |
| if provider in self._provider_windows and window_name in self._provider_windows[provider]: | |
| window = self._provider_windows[provider][window_name] | |
| # Only cleanup sliding windows | |
| if window.reset_schedule is None: | |
| await self._cleanup_sliding_window(provider, window_name, window.duration) | |
| # Cleanup old backoff state | |
| for backoff_key in list(self._backoff_state.keys()): | |
| backoff_info = self._backoff_state[backoff_key] | |
| if current_time - backoff_info["last_attempt"] > 3600: # 1 hour | |
| del self._backoff_state[backoff_key] | |
| logger.debug("Rate limiter cleanup completed") | |
| async def _check_and_perform_resets(self) -> None: | |
| """Check for scheduled resets and perform them if needed.""" | |
| async with self._lock: | |
| current_time = datetime.now(timezone.utc) | |
| for provider in list(self._provider_usage.keys()): | |
| if provider not in self._provider_windows: | |
| continue | |
| for window_name, window in self._provider_windows[provider].items(): | |
| # Only process windows with scheduled resets | |
| if window.reset_schedule is None: | |
| continue | |
| usage = self._provider_usage[provider][window_name] | |
| # Check if reset is due | |
| if self._is_reset_due(window, usage.last_reset, current_time): | |
| # Perform the reset | |
| usage.requests.clear() | |
| usage.audio_durations.clear() | |
| usage.total_requests = 0 | |
| usage.total_audio_duration = 0.0 | |
| usage.last_reset = current_time | |
| logger.info(f"Scheduled reset performed for {provider}:{window_name} ({window.reset_schedule})") | |
| logger.debug("Reset scheduler check completed") | |
| def _is_reset_due(self, window: TimeWindow, last_reset: datetime, current_time: datetime) -> bool: | |
| """ | |
| Check if a scheduled reset is due for a window. | |
| Args: | |
| window: The time window configuration | |
| last_reset: When the window was last reset | |
| current_time: Current time | |
| Returns: | |
| True if reset is due, False otherwise | |
| """ | |
| if window.reset_schedule == "hourly": | |
| # Reset at the top of each hour | |
| last_reset_hour = last_reset.replace(minute=0, second=0, microsecond=0) | |
| current_hour = current_time.replace(minute=0, second=0, microsecond=0) | |
| return current_hour > last_reset_hour | |
| elif window.reset_schedule == "daily": | |
| # Reset at midnight each day | |
| last_reset_day = last_reset.replace(hour=0, minute=0, second=0, microsecond=0) | |
| current_day = current_time.replace(hour=0, minute=0, second=0, microsecond=0) | |
| return current_day > last_reset_day | |
| elif window.reset_schedule == "monthly": | |
| # Reset at the beginning of each month | |
| last_reset_month = last_reset.replace(day=1, hour=0, minute=0, second=0, microsecond=0) | |
| current_month = current_time.replace(day=1, hour=0, minute=0, second=0, microsecond=0) | |
| return current_month > last_reset_month | |
| elif window.reset_schedule == "weekly": | |
| # Reset at the beginning of each week (Monday) | |
| days_since_monday = current_time.weekday() | |
| current_week_start = current_time.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=days_since_monday) | |
| last_reset_days_since_monday = last_reset.weekday() | |
| last_reset_week_start = last_reset.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=last_reset_days_since_monday) | |
| return current_week_start > last_reset_week_start | |
| # Unknown schedule type, don't reset | |
| return False | |
| async def get_provider_quota_status(self, provider: str) -> Dict[str, QuotaStatus]: | |
| """ | |
| Get quota status for all windows of a provider. | |
| Args: | |
| provider: Provider name | |
| Returns: | |
| Dictionary mapping window names to quota status | |
| """ | |
| if provider not in self._provider_windows: | |
| return {} | |
| quota_statuses = {} | |
| for window_name, window in self._provider_windows[provider].items(): | |
| # Use a small audio duration for checking current status | |
| quota_status = await self.check_quota(provider, 0.1) | |
| quota_statuses[window_name] = quota_status | |
| return quota_statuses | |
| async def is_provider_available(self, provider: str, audio_duration: float = 0.0) -> bool: | |
| """ | |
| Check if a provider is available (not rate limited). | |
| Args: | |
| provider: Provider name | |
| audio_duration: Duration of audio to check (optional) | |
| Returns: | |
| True if provider is available, False if rate limited | |
| """ | |
| try: | |
| quota_status = await self.check_quota(provider, audio_duration) | |
| return not quota_status.is_exceeded | |
| except (QuotaExceededError, RateLimitExceededError): | |
| return False | |
| async def is_provider_approaching_limit(self, provider: str, audio_duration: float = 0.0, threshold: float = 0.8) -> bool: | |
| """ | |
| Check if a provider is approaching its quota limits. | |
| Args: | |
| provider: Provider name | |
| audio_duration: Duration of audio to check (optional) | |
| threshold: Percentage threshold to consider "approaching" (default 0.8 = 80%) | |
| Returns: | |
| True if provider is approaching limits, False otherwise | |
| """ | |
| try: | |
| quota_status = await self.check_quota(provider, audio_duration) | |
| return quota_status.is_near_limit(threshold) | |
| except (QuotaExceededError, RateLimitExceededError): | |
| return True # Already at limit | |
| async def get_providers_by_availability(self, audio_duration: float = 0.0) -> Dict[str, bool]: | |
| """ | |
| Get availability status for all configured providers. | |
| Args: | |
| audio_duration: Duration of audio to check (optional) | |
| Returns: | |
| Dictionary mapping provider names to availability status | |
| """ | |
| availability = {} | |
| for provider in self._provider_configs.keys(): | |
| availability[provider] = await self.is_provider_available(provider, audio_duration) | |
| return availability | |
| async def configure_reset_schedule(self, provider: str, window_name: str, reset_schedule: str) -> None: | |
| """ | |
| Configure a custom reset schedule for a specific provider window. | |
| Args: | |
| provider: Provider name | |
| window_name: Name of the window to configure | |
| reset_schedule: Reset schedule ("hourly", "daily", "weekly", "monthly", or None for sliding) | |
| """ | |
| async with self._lock: | |
| if provider not in self._provider_windows: | |
| raise ValueError(f"Provider {provider} not configured") | |
| if window_name not in self._provider_windows[provider]: | |
| raise ValueError(f"Window {window_name} not found for provider {provider}") | |
| # Validate reset schedule | |
| valid_schedules = ["hourly", "daily", "weekly", "monthly", None] | |
| if reset_schedule not in valid_schedules: | |
| raise ValueError(f"Invalid reset schedule: {reset_schedule}. Must be one of {valid_schedules}") | |
| # Update the window configuration | |
| window = self._provider_windows[provider][window_name] | |
| old_schedule = window.reset_schedule | |
| window.reset_schedule = reset_schedule | |
| # Reset the usage tracking to start fresh with new schedule | |
| if window_name in self._provider_usage[provider]: | |
| usage = self._provider_usage[provider][window_name] | |
| usage.requests.clear() | |
| usage.audio_durations.clear() | |
| usage.total_requests = 0 | |
| usage.total_audio_duration = 0.0 | |
| usage.last_reset = datetime.now(timezone.utc) | |
| logger.info(f"Updated reset schedule for {provider}:{window_name} from {old_schedule} to {reset_schedule}") | |
| async def get_reset_schedule_info(self, provider: str) -> Dict[str, Dict[str, Any]]: | |
| """ | |
| Get reset schedule information for all windows of a provider. | |
| Args: | |
| provider: Provider name | |
| Returns: | |
| Dictionary with window names as keys and reset info as values | |
| """ | |
| if provider not in self._provider_windows: | |
| return {} | |
| reset_info = {} | |
| current_time = datetime.now(timezone.utc) | |
| for window_name, window in self._provider_windows[provider].items(): | |
| usage = self._provider_usage[provider].get(window_name) | |
| info = { | |
| "reset_schedule": window.reset_schedule, | |
| "last_reset": usage.last_reset if usage else None, | |
| "next_reset": self._calculate_reset_time(window) if window.reset_schedule else None, | |
| "is_sliding_window": window.reset_schedule is None | |
| } | |
| # Add time until next reset | |
| if info["next_reset"]: | |
| time_until_reset = info["next_reset"] - current_time | |
| info["seconds_until_reset"] = max(0, int(time_until_reset.total_seconds())) | |
| else: | |
| info["seconds_until_reset"] = None | |
| reset_info[window_name] = info | |
| return reset_info | |
| async def should_switch_provider(self, provider: str, audio_duration: float = 0.0, threshold: float = 0.9) -> bool: | |
| """ | |
| Determine if we should switch away from a provider due to quota concerns. | |
| Args: | |
| provider: Current provider name | |
| audio_duration: Duration of audio to process | |
| threshold: Percentage threshold for switching (default 0.9 = 90%) | |
| Returns: | |
| True if should switch to alternative provider, False otherwise | |
| """ | |
| if provider not in self._provider_configs: | |
| return False | |
| # Check if provider is approaching limits | |
| if await self.is_provider_approaching_limit(provider, audio_duration, threshold): | |
| logger.info(f"Provider {provider} approaching quota limit, recommending switch") | |
| return True | |
| # Check if provider is in backoff state | |
| for backoff_key in self._backoff_state.keys(): | |
| if backoff_key.startswith(f"{provider}:"): | |
| backoff_info = self._backoff_state[backoff_key] | |
| current_time = time.time() | |
| time_since_last = current_time - backoff_info["last_attempt"] | |
| if time_since_last < backoff_info["backoff_duration"]: | |
| logger.info(f"Provider {provider} in backoff state, recommending switch") | |
| return True | |
| return False | |
| async def shutdown(self) -> None: | |
| """Shutdown the rate limiter and cleanup resources.""" | |
| logger.info("Shutting down RateLimiter") | |
| # Cancel background tasks | |
| if self._cleanup_task: | |
| self._cleanup_task.cancel() | |
| try: | |
| await self._cleanup_task | |
| except asyncio.CancelledError: | |
| pass | |
| if self._reset_scheduler_task: | |
| self._reset_scheduler_task.cancel() | |
| try: | |
| await self._reset_scheduler_task | |
| except asyncio.CancelledError: | |
| pass | |
| # Close Redis connection if available | |
| if self._redis_client: | |
| await self._redis_client.close() | |
| # Clear all data | |
| async with self._lock: | |
| self._provider_windows.clear() | |
| self._provider_usage.clear() | |
| self._provider_configs.clear() | |
| self._backoff_state.clear() | |
| logger.info("RateLimiter shutdown complete") |