""" Provider Manager implementation for the voice control optimization system. This module implements the ProviderManager class that orchestrates multiple speech-to-text providers with intelligent selection, fallback, and health monitoring. """ import asyncio import logging from typing import Dict, List, Optional, AsyncIterator, Set from datetime import datetime, timedelta from collections import defaultdict from .interfaces import ProviderManagerInterface, STTProvider, RateLimiterInterface, CacheManagerInterface from .models import ( ProviderConfig, TranscriptionResult, ProviderStatus, QuotaStatus, QuotaType ) from .exceptions import ( ProviderError, ProviderUnavailableError, NoProvidersAvailableError, QuotaExceededError, RateLimitExceededError, UnsupportedFormatError, UnsupportedLanguageError, CircuitBreakerError ) logger = logging.getLogger(__name__) class ProviderManager(ProviderManagerInterface): """ Manages multiple STT providers with intelligent selection and fallback. The ProviderManager implements: - Provider registration and discovery - Priority-based provider ordering with free-tier prioritization - Health checking and status tracking - Automatic fallback on provider failures - Circuit breaker pattern for failing providers """ def __init__( self, rate_limiter: Optional[RateLimiterInterface] = None, cache_manager: Optional[CacheManagerInterface] = None ): """ Initialize the provider manager. Args: rate_limiter: Optional rate limiter for quota management cache_manager: Optional cache manager for transcription caching """ self._providers: Dict[str, STTProvider] = {} self._provider_status: Dict[str, ProviderStatus] = {} self._rate_limiter = rate_limiter self._cache_manager = cache_manager # Health check configuration self._health_check_interval = 60 # seconds self._health_check_timeout = 10 # seconds self._health_check_task: Optional[asyncio.Task] = None # Circuit breaker configuration self._circuit_breaker_threshold = 5 # consecutive failures self._circuit_breaker_timeout = 300 # seconds (5 minutes) # Provider metrics tracking self._provider_metrics: Dict[str, Dict[str, float]] = defaultdict(dict) # Lock for thread-safe operations self._lock = asyncio.Lock() logger.info("ProviderManager initialized") async def register_provider(self, provider: STTProvider) -> None: """ Register a new STT provider. Args: provider: STTProvider instance to register Raises: ValueError: If provider name already exists """ async with self._lock: if provider.name in self._providers: raise ValueError(f"Provider '{provider.name}' is already registered") self._providers[provider.name] = provider # Initialize provider status self._provider_status[provider.name] = ProviderStatus( name=provider.name, available=True, current_load=0.0, quota_remaining={}, last_error=None, response_time_avg=0.0, circuit_breaker_state="CLOSED", consecutive_failures=0 ) # Initialize metrics self._provider_metrics[provider.name] = { "total_requests": 0, "successful_requests": 0, "failed_requests": 0, "total_response_time": 0.0, "last_request_time": 0.0 } logger.info(f"Registered provider: {provider.name} (type: {provider.provider_type})") # Start health checking if this is the first provider if len(self._providers) == 1 and self._health_check_task is None: self._health_check_task = asyncio.create_task(self._health_check_loop()) async def unregister_provider(self, provider_name: str) -> None: """ Unregister an STT provider. Args: provider_name: Name of provider to unregister Raises: KeyError: If provider is not registered """ async with self._lock: if provider_name not in self._providers: raise KeyError(f"Provider '{provider_name}' is not registered") del self._providers[provider_name] del self._provider_status[provider_name] del self._provider_metrics[provider_name] logger.info(f"Unregistered provider: {provider_name}") # Stop health checking if no providers remain if not self._providers and self._health_check_task: self._health_check_task.cancel() self._health_check_task = None async def update_provider_config( self, provider_name: str, config: ProviderConfig ) -> bool: """ Update configuration for a provider. Args: provider_name: Name of provider to update config: New configuration Returns: True if update was successful, False otherwise """ async with self._lock: if provider_name not in self._providers: logger.warning(f"Cannot update config for unregistered provider: {provider_name}") return False try: # Update provider configuration provider = self._providers[provider_name] provider.config = config # Reset circuit breaker if provider was re-enabled if config.enabled and self._provider_status[provider_name].circuit_breaker_state == "OPEN": self._provider_status[provider_name].circuit_breaker_state = "CLOSED" self._provider_status[provider_name].consecutive_failures = 0 logger.info(f"Reset circuit breaker for provider: {provider_name}") logger.info(f"Updated configuration for provider: {provider_name}") return True except Exception as e: logger.error(f"Failed to update config for provider {provider_name}: {e}") return False async def get_provider_status(self) -> Dict[str, ProviderStatus]: """ Get status of all registered providers. Returns: Dictionary mapping provider names to their status """ async with self._lock: return self._provider_status.copy() async def transcribe_audio( self, audio_data: bytes, format: str, language: str = "en-US", preferred_provider: Optional[str] = None ) -> TranscriptionResult: """ Transcribe audio using the best available provider with cache optimization. This method implements cache hit optimization by: 1. First checking the cache for existing transcription results 2. Only calling STT providers if no cached result is found 3. Caching successful transcription results for future use Args: audio_data: Raw audio bytes format: Audio format language: Language code preferred_provider: Preferred provider name (optional) Returns: TranscriptionResult from cache or the selected provider Raises: NoProvidersAvailableError: If no providers are available UnsupportedFormatError: If no provider supports the format UnsupportedLanguageError: If no provider supports the language """ # Step 1: Check cache first to avoid API calls (Requirement 4.3) audio_fingerprint = None if self._cache_manager: try: audio_fingerprint = await self._cache_manager.generate_audio_fingerprint(audio_data) cached_result = await self._cache_manager.get_cached_transcription(audio_fingerprint) if cached_result is not None: logger.info(f"Cache hit for audio fingerprint: {audio_fingerprint[:16]}... " f"(provider: {cached_result.provider})") return cached_result logger.debug(f"Cache miss for audio fingerprint: {audio_fingerprint[:16]}...") except Exception as e: logger.warning(f"Cache lookup failed, proceeding with provider transcription: {e}") # Step 2: No cached result found, proceed with provider transcription # Estimate audio duration for quota checking audio_duration = len(audio_data) / (44100 * 2) # Rough estimate # Get ordered list of providers to try providers_to_try = await self._get_ordered_providers( format=format, language=language, preferred_provider=preferred_provider, audio_duration=audio_duration ) if not providers_to_try: raise NoProvidersAvailableError() last_error = None attempted_providers = [] for provider_name in providers_to_try: provider = self._providers[provider_name] attempted_providers.append(provider_name) try: # Check if provider is available if not await self._is_provider_available(provider_name, format, language): continue # Check rate limits if rate limiter is available if self._rate_limiter: # Check if we should switch away from this provider due to quota concerns if await self._rate_limiter.should_switch_provider(provider_name, audio_duration): logger.info(f"Switching away from provider {provider_name} due to quota concerns") continue quota_status = await self._rate_limiter.check_quota(provider_name, audio_duration) if quota_status.is_exceeded: logger.warning(f"Provider {provider_name} quota exceeded, trying next provider") continue # Attempt transcription start_time = datetime.utcnow() result = await provider.transcribe_audio(audio_data, format, language) end_time = datetime.utcnow() # Update metrics and status processing_time = (end_time - start_time).total_seconds() await self._update_provider_metrics(provider_name, True, processing_time) # Consume quota if rate limiter is available if self._rate_limiter: await self._rate_limiter.consume_quota(provider_name, result.audio_duration) # Step 3: Cache successful transcription result for future use if self._cache_manager and audio_fingerprint: try: cache_success = await self._cache_manager.cache_transcription( audio_fingerprint, result ) if cache_success: logger.debug(f"Cached transcription result for fingerprint: {audio_fingerprint[:16]}...") else: logger.warning(f"Failed to cache transcription result for fingerprint: {audio_fingerprint[:16]}...") except Exception as e: logger.warning(f"Cache storage failed: {e}") logger.info(f"Successfully transcribed audio using provider: {provider_name}") return result except (QuotaExceededError, RateLimitExceededError) as e: logger.warning(f"Provider {provider_name} quota/rate limit exceeded: {e}") await self._update_provider_metrics(provider_name, False, 0.0) last_error = e continue except (ProviderUnavailableError, CircuitBreakerError) as e: logger.warning(f"Provider {provider_name} unavailable: {e}") await self._update_provider_metrics(provider_name, False, 0.0) last_error = e continue except Exception as e: logger.error(f"Provider {provider_name} failed: {e}") await self._update_provider_metrics(provider_name, False, 0.0) await self._handle_provider_failure(provider_name, str(e)) last_error = e continue # All providers failed raise NoProvidersAvailableError(attempted_providers) async def transcribe_streaming( self, audio_stream: AsyncIterator[bytes], format: str, language: str = "en-US", preferred_provider: Optional[str] = None ) -> AsyncIterator[TranscriptionResult]: """ Transcribe streaming audio using the best available provider. Args: audio_stream: Async iterator of audio chunks format: Audio format language: Language code preferred_provider: Preferred provider name (optional) Yields: TranscriptionResult for each processed chunk Raises: NoProvidersAvailableError: If no providers are available """ # Get the best provider for streaming providers_to_try = await self._get_ordered_providers( format=format, language=language, preferred_provider=preferred_provider ) if not providers_to_try: raise NoProvidersAvailableError() # Try providers in order until one works for provider_name in providers_to_try: provider = self._providers[provider_name] try: if not await self._is_provider_available(provider_name, format, language): continue # Stream transcription async for result in provider.transcribe_streaming(audio_stream, format, language): await self._update_provider_metrics(provider_name, True, result.processing_time) yield result # If we get here, streaming was successful return except Exception as e: logger.error(f"Streaming provider {provider_name} failed: {e}") await self._update_provider_metrics(provider_name, False, 0.0) await self._handle_provider_failure(provider_name, str(e)) continue raise NoProvidersAvailableError(providers_to_try) async def _get_ordered_providers( self, format: str, language: str, preferred_provider: Optional[str] = None, audio_duration: float = 0.0 ) -> List[str]: """ Get providers ordered by priority, availability, and free-tier preference. Args: format: Required audio format language: Required language preferred_provider: Preferred provider (gets highest priority) audio_duration: Audio duration for quota checking Returns: List of provider names in order of preference """ available_providers = [] for name, provider in self._providers.items(): # Skip disabled providers if not provider.config.enabled: continue # Check format and language support if not provider.supports_format(format): continue if not provider.supports_language(language): continue # Check circuit breaker state status = self._provider_status[name] if status.circuit_breaker_state == "OPEN": # Check if timeout has passed for half-open state if datetime.utcnow() - status.last_health_check > timedelta(seconds=self._circuit_breaker_timeout): status.circuit_breaker_state = "HALF_OPEN" logger.info(f"Circuit breaker for {name} moved to HALF_OPEN state") else: continue available_providers.append((name, provider)) if not available_providers: return [] # Pre-calculate quota priorities for all providers quota_priorities = {} if self._rate_limiter: for name, _ in available_providers: try: should_switch = await self._rate_limiter.should_switch_provider(name, audio_duration) quota_priorities[name] = 1 if should_switch else 0 except: # If quota check fails, treat as lower priority quota_priorities[name] = 1 else: for name, _ in available_providers: quota_priorities[name] = 0 # Sort providers by priority criteria def provider_sort_key(item): name, provider = item config = provider.config status = self._provider_status[name] # Preferred provider gets highest priority (lowest sort value) if preferred_provider and name == preferred_provider: return (0, 0, 0, 0, 0) # Free tier providers get priority over paid ones is_free = config.cost_per_minute == 0.0 free_priority = 0 if is_free else 1 # Use configured priority configured_priority = config.priority # Use pre-calculated quota priority quota_priority = quota_priorities[name] # Prefer providers with better availability and response times availability_score = 1.0 - (status.current_load if status.available else 1.0) response_time_score = status.response_time_avg # If quota is a concern, prioritize it over free/paid preference # This allows paid providers to be selected when free providers are approaching limits if quota_priority == 1: # Provider should be switched away from return (1, configured_priority, quota_priority, -availability_score, response_time_score) else: return (0, free_priority, configured_priority, -availability_score, response_time_score) # Sort and return provider names sorted_providers = sorted(available_providers, key=provider_sort_key) provider_names = [name for name, _ in sorted_providers] logger.debug(f"Provider order for format={format}, language={language}: {provider_names}") return provider_names async def _is_provider_available( self, provider_name: str, format: str, language: str ) -> bool: """ Check if a provider is available for the given format and language. Args: provider_name: Name of the provider format: Audio format language: Language code Returns: True if provider is available, False otherwise """ if provider_name not in self._providers: return False provider = self._providers[provider_name] status = self._provider_status[provider_name] # Check basic availability if not status.available or not provider.config.enabled: return False # Check circuit breaker if status.circuit_breaker_state == "OPEN": return False # Check format and language support if not provider.supports_format(format) or not provider.supports_language(language): return False return True async def _update_provider_metrics( self, provider_name: str, success: bool, response_time: float ) -> None: """ Update metrics for a provider after a request. Args: provider_name: Name of the provider success: Whether the request was successful response_time: Response time in seconds """ if provider_name not in self._provider_metrics: return metrics = self._provider_metrics[provider_name] status = self._provider_status[provider_name] # Update request counts metrics["total_requests"] += 1 if success: metrics["successful_requests"] += 1 status.consecutive_failures = 0 else: metrics["failed_requests"] += 1 status.consecutive_failures += 1 # Update response time if response_time > 0: metrics["total_response_time"] += response_time metrics["last_request_time"] = response_time # Calculate moving average of response time successful_requests = metrics["successful_requests"] if successful_requests > 0: status.response_time_avg = metrics["total_response_time"] / successful_requests # Update current load (simple metric based on recent activity) total_requests = metrics["total_requests"] if total_requests > 0: success_rate = metrics["successful_requests"] / total_requests status.current_load = 1.0 - success_rate logger.debug(f"Updated metrics for {provider_name}: success={success}, response_time={response_time}") async def _handle_provider_failure(self, provider_name: str, error_message: str) -> None: """ Handle a provider failure and update circuit breaker state. Args: provider_name: Name of the failed provider error_message: Error message from the failure """ if provider_name not in self._provider_status: return status = self._provider_status[provider_name] status.last_error = error_message status.last_health_check = datetime.utcnow() # Check if circuit breaker should be opened if status.consecutive_failures >= self._circuit_breaker_threshold: if status.circuit_breaker_state != "OPEN": status.circuit_breaker_state = "OPEN" logger.warning(f"Circuit breaker OPENED for provider {provider_name} after {status.consecutive_failures} failures") async def _health_check_loop(self) -> None: """Background task for periodic health checks of all providers.""" while True: try: await asyncio.sleep(self._health_check_interval) await self._perform_health_checks() except asyncio.CancelledError: logger.info("Health check loop cancelled") break except Exception as e: logger.error(f"Error in health check loop: {e}") async def _perform_health_checks(self) -> None: """Perform health checks on all registered providers.""" if not self._providers: return logger.debug("Performing health checks on all providers") # Create health check tasks for all providers health_check_tasks = [] for provider_name, provider in self._providers.items(): task = asyncio.create_task(self._check_provider_health(provider_name, provider)) health_check_tasks.append(task) # Wait for all health checks to complete (with timeout) try: await asyncio.wait_for( asyncio.gather(*health_check_tasks, return_exceptions=True), timeout=self._health_check_timeout ) except asyncio.TimeoutError: logger.warning("Health check timeout exceeded") async def _check_provider_health(self, provider_name: str, provider: STTProvider) -> None: """ Check the health of a single provider. Args: provider_name: Name of the provider provider: Provider instance """ try: # Perform health check is_healthy = await provider.check_health() # Update provider status status = self._provider_status[provider_name] status.available = is_healthy status.last_health_check = datetime.utcnow() if is_healthy: # If provider is healthy and circuit breaker is half-open, close it if status.circuit_breaker_state == "HALF_OPEN": status.circuit_breaker_state = "CLOSED" status.consecutive_failures = 0 logger.info(f"Circuit breaker CLOSED for provider {provider_name}") # Update quota information try: quota_status = await provider.get_quota_status() status.quota_remaining = { quota_type.value: quota.remaining for quota_type, quota in quota_status.items() } except Exception as e: logger.debug(f"Failed to get quota status for {provider_name}: {e}") else: logger.warning(f"Provider {provider_name} failed health check") await self._handle_provider_failure(provider_name, "Health check failed") except Exception as e: logger.error(f"Health check error for provider {provider_name}: {e}") await self._handle_provider_failure(provider_name, f"Health check error: {e}") async def get_provider_metrics(self) -> Dict[str, Dict[str, float]]: """ Get performance metrics for all providers. Returns: Dictionary mapping provider names to their metrics """ return { name: metrics.copy() for name, metrics in self._provider_metrics.items() } async def get_cache_stats(self) -> Optional[Dict[str, Any]]: """ Get cache performance statistics if cache manager is available. Returns: Cache statistics dictionary or None if no cache manager """ if not self._cache_manager: return None try: cache_stats = await self._cache_manager.get_cache_stats() return { "total_requests": cache_stats.total_requests, "cache_hits": cache_stats.cache_hits, "cache_misses": cache_stats.cache_misses, "hit_rate": cache_stats.hit_rate, "total_size_bytes": cache_stats.total_size_bytes, "entry_count": cache_stats.entry_count, "evictions": cache_stats.evictions } except Exception as e: logger.error(f"Failed to get cache statistics: {e}") return None async def get_system_stats(self) -> Dict[str, Any]: """ Get comprehensive system statistics including providers and cache. Returns: Dictionary with provider metrics, cache stats, and system overview """ stats = { "providers": await self.get_provider_metrics(), "provider_status": await self.get_provider_status(), "cache": await self.get_cache_stats(), "system_overview": { "total_providers": len(self._providers), "available_providers": sum( 1 for status in self._provider_status.values() if status.available and status.circuit_breaker_state != "OPEN" ), "cache_enabled": self._cache_manager is not None, "rate_limiting_enabled": self._rate_limiter is not None } } # Calculate aggregate metrics total_requests = sum( metrics.get("total_requests", 0) for metrics in stats["providers"].values() ) total_successful = sum( metrics.get("successful_requests", 0) for metrics in stats["providers"].values() ) if total_requests > 0: stats["system_overview"]["overall_success_rate"] = total_successful / total_requests else: stats["system_overview"]["overall_success_rate"] = 0.0 return stats async def reset_provider_circuit_breaker(self, provider_name: str) -> bool: """ Manually reset a provider's circuit breaker. Args: provider_name: Name of the provider Returns: True if reset was successful, False otherwise """ if provider_name not in self._provider_status: return False status = self._provider_status[provider_name] status.circuit_breaker_state = "CLOSED" status.consecutive_failures = 0 status.last_error = None logger.info(f"Manually reset circuit breaker for provider: {provider_name}") return True async def get_alternative_provider( self, current_provider: str, format: str, language: str = "en-US", audio_duration: float = 0.0 ) -> Optional[str]: """ Get the best alternative provider when the current one is approaching limits. Args: current_provider: Current provider that should be avoided format: Required audio format language: Required language audio_duration: Audio duration for quota checking Returns: Name of best alternative provider, or None if no alternatives available """ # Get ordered providers excluding the current one all_providers = await self._get_ordered_providers(format, language, audio_duration=audio_duration) # Filter out the current provider alternative_providers = [p for p in all_providers if p != current_provider] if not alternative_providers: return None # Return the best alternative (first in the ordered list) best_alternative = alternative_providers[0] # Verify the alternative is actually available if await self._is_provider_available(best_alternative, format, language): if self._rate_limiter: # Check if alternative has quota available if not await self._rate_limiter.should_switch_provider(best_alternative, audio_duration): return best_alternative else: return best_alternative # If best alternative is not available, try the next ones for provider_name in alternative_providers[1:]: if await self._is_provider_available(provider_name, format, language): if self._rate_limiter: if not await self._rate_limiter.should_switch_provider(provider_name, audio_duration): return provider_name else: return provider_name return None async def recommend_provider_switch( self, current_provider: str, format: str, language: str = "en-US", audio_duration: float = 0.0 ) -> Optional[Dict[str, Any]]: """ Recommend a provider switch if the current provider is approaching limits. Args: current_provider: Current provider name format: Required audio format language: Required language audio_duration: Audio duration for quota checking Returns: Dictionary with switch recommendation, or None if no switch needed """ if not self._rate_limiter: return None # Check if current provider should be switched should_switch = await self._rate_limiter.should_switch_provider(current_provider, audio_duration) if not should_switch: return None # Get alternative provider alternative = await self.get_alternative_provider(current_provider, format, language, audio_duration) if alternative is None: return { "should_switch": True, "reason": "Current provider approaching limits", "alternative_provider": None, "recommendation": "Wait for quota reset or reduce usage" } # Get quota status for both providers current_quota = await self._rate_limiter.check_quota(current_provider, audio_duration) alternative_quota = await self._rate_limiter.check_quota(alternative, audio_duration) return { "should_switch": True, "reason": f"Current provider {current_provider} at {current_quota.percentage_used:.1%} of quota", "alternative_provider": alternative, "current_quota_status": current_quota, "alternative_quota_status": alternative_quota, "recommendation": f"Switch to {alternative} for better quota availability" } async def shutdown(self) -> None: """Shutdown the provider manager and cleanup resources.""" logger.info("Shutting down ProviderManager") # Cancel health check task if self._health_check_task: self._health_check_task.cancel() try: await self._health_check_task except asyncio.CancelledError: pass # Clear all providers and status async with self._lock: self._providers.clear() self._provider_status.clear() self._provider_metrics.clear() logger.info("ProviderManager shutdown complete")