File size: 38,192 Bytes
8cbe6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
"""
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__)


@dataclass
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


@dataclass
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")