reference-api-buddy 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,410 @@
1
+ """Database manager: connection pooling, schema, thread safety."""
2
+
3
+ import sqlite3
4
+ import threading
5
+ from datetime import datetime
6
+ from typing import Any, List
7
+
8
+ from reference_api_buddy.utils.logger import get_logger
9
+
10
+
11
+ def adapt_datetime_iso(val):
12
+ """Adapt datetime to ISO 8601 date."""
13
+ return val.isoformat()
14
+
15
+
16
+ def convert_datetime(val):
17
+ """Convert ISO 8601 datetime to datetime object."""
18
+ from datetime import datetime
19
+
20
+ return datetime.fromisoformat(val.decode())
21
+
22
+
23
+ def convert_timestamp(val):
24
+ """Convert timestamp to datetime object."""
25
+ from datetime import datetime
26
+
27
+ return datetime.fromisoformat(val.decode())
28
+
29
+
30
+ # Register adapters and converters to replace deprecated default ones
31
+ sqlite3.register_adapter(datetime, adapt_datetime_iso)
32
+ sqlite3.register_converter("datetime", convert_datetime)
33
+ sqlite3.register_converter("timestamp", convert_timestamp)
34
+
35
+ SCHEMA = [
36
+ # Cache entries table
37
+ """CREATE TABLE IF NOT EXISTS cache_entries (
38
+ cache_key TEXT PRIMARY KEY,
39
+ response_data BLOB NOT NULL,
40
+ headers TEXT NOT NULL,
41
+ status_code INTEGER NOT NULL,
42
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
43
+ ttl_seconds INTEGER NOT NULL,
44
+ access_count INTEGER DEFAULT 0,
45
+ last_accessed TIMESTAMP DEFAULT CURRENT_TIMESTAMP
46
+ );""",
47
+ # Metrics table
48
+ """CREATE TABLE IF NOT EXISTS metrics (
49
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
50
+ domain TEXT NOT NULL,
51
+ method TEXT NOT NULL,
52
+ cache_hit BOOLEAN NOT NULL,
53
+ response_time_ms INTEGER,
54
+ response_size_bytes INTEGER,
55
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
56
+ );""",
57
+ # Config history
58
+ """CREATE TABLE IF NOT EXISTS config_history (
59
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
60
+ config_data TEXT NOT NULL,
61
+ changed_by TEXT,
62
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
63
+ );""",
64
+ # Indexes
65
+ "CREATE INDEX IF NOT EXISTS idx_cache_created_ttl " "ON cache_entries(created_at, ttl_seconds);",
66
+ "CREATE INDEX IF NOT EXISTS idx_metrics_domain_timestamp " "ON metrics(domain, timestamp);",
67
+ "CREATE INDEX IF NOT EXISTS idx_cache_last_accessed " "ON cache_entries(last_accessed);",
68
+ ]
69
+
70
+
71
+ class DatabaseManager:
72
+ """Manages SQLite database operations with thread safety and connection pooling."""
73
+
74
+ def __init__(self, database_path: str):
75
+ self.logger = get_logger("api_buddy.database.manager")
76
+ # Use shared in-memory DB for ":memory:" or file::memory:?cache=shared
77
+ if database_path == ":memory:":
78
+ self.database_path = "file::memory:?cache=shared"
79
+ self._use_uri = True
80
+ else:
81
+ self.database_path = database_path
82
+ self._use_uri = database_path.startswith("file:")
83
+ self._lock = threading.Lock()
84
+ self._pool: List[sqlite3.Connection] = []
85
+ self._max_pool_size = 5
86
+ self._initialize_connections()
87
+ self._initialize_schema()
88
+
89
+ def _initialize_connections(self):
90
+ for _ in range(self._max_pool_size):
91
+ conn = sqlite3.connect(
92
+ self.database_path, check_same_thread=False, detect_types=sqlite3.PARSE_DECLTYPES, uri=self._use_uri
93
+ )
94
+ # Configure SQLite for better concurrency
95
+ # Enable WAL mode for better concurrency
96
+ conn.execute("PRAGMA journal_mode=WAL")
97
+ # Reduce I/O overhead
98
+ conn.execute("PRAGMA synchronous=NORMAL")
99
+ # Increase cache size
100
+ conn.execute("PRAGMA cache_size=10000")
101
+ # Use memory for temp tables
102
+ conn.execute("PRAGMA temp_store=memory")
103
+ # 5 second timeout on locks
104
+ conn.execute("PRAGMA busy_timeout=5000")
105
+ self._pool.append(conn)
106
+
107
+ def _initialize_schema(self):
108
+ conn = self.get_connection()
109
+ try:
110
+ cur = conn.cursor()
111
+ for stmt in SCHEMA:
112
+ cur.execute(stmt)
113
+ conn.commit()
114
+ finally:
115
+ self.return_connection(conn)
116
+
117
+ def get_connection(self) -> sqlite3.Connection:
118
+ with self._lock:
119
+ if self._pool:
120
+ return self._pool.pop()
121
+ conn = sqlite3.connect(
122
+ self.database_path, check_same_thread=False, detect_types=sqlite3.PARSE_DECLTYPES, uri=self._use_uri
123
+ )
124
+ # Configure SQLite for better concurrency
125
+ conn.execute("PRAGMA journal_mode=WAL")
126
+ conn.execute("PRAGMA synchronous=NORMAL")
127
+ conn.execute("PRAGMA cache_size=10000")
128
+ conn.execute("PRAGMA temp_store=memory")
129
+ conn.execute("PRAGMA busy_timeout=5000")
130
+ return conn
131
+
132
+ def return_connection(self, conn: sqlite3.Connection):
133
+ with self._lock:
134
+ if len(self._pool) < self._max_pool_size:
135
+ self._pool.append(conn)
136
+ else:
137
+ conn.close()
138
+
139
+ def execute_query(self, query: str, params: tuple = (), retries: int = 10, delay: float = 0.05) -> List[Any]:
140
+ import random
141
+ import time
142
+
143
+ for attempt in range(retries):
144
+ conn = self.get_connection()
145
+ try:
146
+ cur = conn.cursor()
147
+ cur.execute(query, params)
148
+ rows = cur.fetchall()
149
+ return rows
150
+ except sqlite3.OperationalError as e:
151
+ if "locked" in str(e).lower() and attempt < retries - 1:
152
+ # Exponential backoff with jitter to avoid thundering herd
153
+ backoff = delay * (2**attempt) + random.uniform(0, 0.1)
154
+ time.sleep(min(backoff, 1.0)) # Cap at 1 second
155
+ continue
156
+ raise
157
+ finally:
158
+ self.return_connection(conn)
159
+ return []
160
+
161
+ def execute_update(self, query: str, params: tuple = (), retries: int = 10, delay: float = 0.05) -> int:
162
+ import random
163
+ import time
164
+
165
+ for attempt in range(retries):
166
+ conn = self.get_connection()
167
+ try:
168
+ cur = conn.cursor()
169
+ cur.execute(query, params)
170
+ conn.commit()
171
+ return cur.rowcount
172
+ except sqlite3.OperationalError as e:
173
+ if "locked" in str(e).lower() and attempt < retries - 1:
174
+ # Exponential backoff with jitter to avoid thundering herd
175
+ backoff = delay * (2**attempt) + random.uniform(0, 0.1)
176
+ time.sleep(min(backoff, 1.0)) # Cap at 1 second
177
+ continue
178
+ raise
179
+ finally:
180
+ self.return_connection(conn)
181
+ return 0
182
+
183
+ def close(self):
184
+ """Close all pooled database connections."""
185
+ with self._lock:
186
+ while self._pool:
187
+ conn = self._pool.pop()
188
+ try:
189
+ conn.close()
190
+ except Exception:
191
+ pass
192
+
193
+ def store_upstream_metrics(
194
+ self,
195
+ domain: str,
196
+ method: str,
197
+ response_time_ms: int,
198
+ response_size_bytes: int,
199
+ cache_hit: bool,
200
+ status_code: int = 200,
201
+ ) -> bool:
202
+ """Store metrics for upstream requests.
203
+
204
+ Args:
205
+ domain: Domain that was contacted
206
+ method: HTTP method used
207
+ response_time_ms: Response time in milliseconds
208
+ response_size_bytes: Size of response body in bytes
209
+ cache_hit: Whether this was a cache hit or miss
210
+ status_code: HTTP status code returned
211
+
212
+ Returns:
213
+ True if metrics were stored successfully, False otherwise
214
+ """
215
+ try:
216
+ # First, ensure the metrics table has a status_code column
217
+ try:
218
+ # Check if status_code column exists
219
+ self.execute_query("SELECT status_code FROM metrics LIMIT 1")
220
+ except Exception as e:
221
+ # Add status_code column if it doesn't exist
222
+ self.execute_update("ALTER TABLE metrics ADD COLUMN status_code INTEGER DEFAULT 200")
223
+ self.logger.debug(f"Added status_code column to metrics table: {e}")
224
+
225
+ # Store metrics with proper status code
226
+ self.execute_update(
227
+ "INSERT INTO metrics (domain, method, cache_hit, response_time_ms, "
228
+ "response_size_bytes, status_code, timestamp) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
229
+ (domain, method, cache_hit, response_time_ms, response_size_bytes, status_code),
230
+ )
231
+
232
+ return True
233
+ except Exception as e:
234
+ self.logger.debug(f"Failed to store metrics: {e}")
235
+ return False
236
+
237
+ def get_upstream_metrics(self, domain: str = None, hours: int = 24) -> dict:
238
+ """Get upstream metrics for the specified time window.
239
+
240
+ Args:
241
+ domain: Optional domain filter. If None, gets metrics for all domains
242
+ hours: Number of hours back to look for metrics (default 24)
243
+
244
+ Returns:
245
+ Dictionary with overall stats and per-domain breakdowns including
246
+ response times, error rates, and request volumes
247
+ """
248
+ try:
249
+ # Base query conditions
250
+ where_conditions = ["datetime(timestamp) >= datetime('now', '-{} hours')".format(hours)]
251
+ params = []
252
+
253
+ if domain:
254
+ where_conditions.append("domain = ?")
255
+ params.append(domain)
256
+
257
+ where_clause = " AND ".join(where_conditions)
258
+
259
+ # Get overall metrics
260
+ overall_metrics = self._get_domain_metrics(where_clause, tuple(params))
261
+
262
+ # Get per-domain metrics if no specific domain was requested
263
+ domain_metrics = {}
264
+ if not domain:
265
+ # Get list of domains
266
+ domains_query = f"SELECT DISTINCT domain FROM metrics WHERE {where_conditions[0]} " "AND cache_hit = 0"
267
+ domains = [row[0] for row in self.execute_query(domains_query)]
268
+
269
+ # Get metrics for each domain
270
+ for domain_name in domains:
271
+ domain_where = where_conditions[0] + " AND domain = ?"
272
+ domain_params = (domain_name,)
273
+ domain_metrics[domain_name] = self._get_domain_metrics(domain_where, domain_params)
274
+
275
+ result = {"overall": overall_metrics}
276
+
277
+ if domain_metrics:
278
+ result["by_domain"] = domain_metrics
279
+
280
+ return result
281
+
282
+ except Exception as e:
283
+ return {
284
+ "overall": {
285
+ "response_times": {"average_ms": 0, "recent_samples": [], "total_samples": 0, "error": str(e)},
286
+ "error_rates": {
287
+ "total_requests": 0,
288
+ "error_count": 0,
289
+ "error_rate": 0.0,
290
+ "success_rate": 0.0,
291
+ "by_status_code": {},
292
+ },
293
+ "request_volumes": {
294
+ "total_requests_last_24h": 0,
295
+ "cache_hits_last_24h": 0,
296
+ "cache_hit_rate": 0.0,
297
+ "hourly_breakdown": [],
298
+ },
299
+ }
300
+ }
301
+
302
+ def _get_domain_metrics(self, where_clause: str, params: tuple) -> dict:
303
+ """Get metrics for a specific domain or overall.
304
+
305
+ Args:
306
+ where_clause: SQL WHERE clause for filtering
307
+ params: Parameters for the WHERE clause
308
+
309
+ Returns:
310
+ Dictionary with response times, error rates, and request volumes
311
+ """
312
+ try:
313
+ # Get response times for cache misses (actual upstream requests) - successful requests only
314
+ response_times_query = f"""
315
+ SELECT response_time_ms
316
+ FROM metrics
317
+ WHERE {where_clause} AND cache_hit = 0 AND status_code < 400
318
+ ORDER BY timestamp DESC
319
+ LIMIT 100
320
+ """
321
+ response_times = [row[0] for row in self.execute_query(response_times_query, params)]
322
+
323
+ # Calculate average response time
324
+ avg_response_time = sum(response_times) / len(response_times) if response_times else 0
325
+
326
+ # Get total requests (cache misses only - actual upstream requests)
327
+ total_requests_query = f"""
328
+ SELECT COUNT(*)
329
+ FROM metrics
330
+ WHERE {where_clause} AND cache_hit = 0
331
+ """
332
+ total_requests = self.execute_query(total_requests_query, params)[0][0]
333
+
334
+ # Get error breakdown by status code
335
+ error_breakdown_query = f"""
336
+ SELECT status_code, COUNT(*) as count
337
+ FROM metrics
338
+ WHERE {where_clause} AND cache_hit = 0 AND status_code >= 400
339
+ GROUP BY status_code
340
+ ORDER BY status_code
341
+ """
342
+ error_breakdown = {row[0]: row[1] for row in self.execute_query(error_breakdown_query, params)}
343
+
344
+ # Count total error responses
345
+ error_count = sum(error_breakdown.values())
346
+
347
+ # Get request volume by hour for the time window (cache misses only)
348
+ volume_query = f"""
349
+ SELECT strftime('%Y-%m-%d %H:00:00', timestamp) as hour_bucket,
350
+ COUNT(*) as request_count
351
+ FROM metrics
352
+ WHERE {where_clause} AND cache_hit = 0
353
+ GROUP BY hour_bucket
354
+ ORDER BY hour_bucket DESC
355
+ """
356
+ volume_data = self.execute_query(volume_query, params)
357
+
358
+ # Get cache hit ratio
359
+ cache_hits_query = f"""
360
+ SELECT COUNT(*)
361
+ FROM metrics
362
+ WHERE {where_clause} AND cache_hit = 1
363
+ """
364
+ cache_hits = self.execute_query(cache_hits_query, params)[0][0]
365
+
366
+ total_with_cache = total_requests + cache_hits
367
+ cache_hit_rate = cache_hits / total_with_cache if total_with_cache > 0 else 0.0
368
+
369
+ return {
370
+ "response_times": {
371
+ "average_ms": round(avg_response_time, 2),
372
+ "recent_samples": response_times[:10], # Last 10 response times
373
+ "total_samples": len(response_times),
374
+ },
375
+ "error_rates": {
376
+ "total_requests": total_requests,
377
+ "error_count": error_count,
378
+ "error_rate": round(error_count / total_requests if total_requests > 0 else 0.0, 4),
379
+ "success_rate": round(
380
+ (total_requests - error_count) / total_requests if total_requests > 0 else 0.0, 4
381
+ ),
382
+ "by_status_code": error_breakdown,
383
+ },
384
+ "request_volumes": {
385
+ "total_requests_last_24h": total_requests,
386
+ "cache_hits_last_24h": cache_hits,
387
+ "cache_hit_rate": round(cache_hit_rate, 4),
388
+ "hourly_breakdown": [{"hour": row[0], "requests": row[1]} for row in volume_data],
389
+ },
390
+ }
391
+ except Exception as e:
392
+ return {
393
+ "response_times": {"average_ms": 0, "recent_samples": [], "total_samples": 0, "error": str(e)},
394
+ "error_rates": {
395
+ "total_requests": 0,
396
+ "error_count": 0,
397
+ "error_rate": 0.0,
398
+ "success_rate": 0.0,
399
+ "by_status_code": {},
400
+ },
401
+ "request_volumes": {
402
+ "total_requests_last_24h": 0,
403
+ "cache_hits_last_24h": 0,
404
+ "cache_hit_rate": 0.0,
405
+ "hourly_breakdown": [],
406
+ },
407
+ }
408
+
409
+ def __del__(self):
410
+ self.close()
@@ -0,0 +1,61 @@
1
+ """Database models for Reference API Buddy."""
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import datetime
5
+ from typing import Dict, Optional
6
+
7
+
8
+ @dataclass
9
+ class CachedResponse:
10
+ """Represents a cached HTTP response."""
11
+
12
+ data: bytes
13
+ headers: Dict[str, str]
14
+ status_code: int
15
+ created_at: str
16
+ ttl_seconds: int
17
+ access_count: int = 0
18
+ last_accessed: Optional[str] = None
19
+
20
+
21
+ @dataclass
22
+ class ThrottleState:
23
+ """Tracks throttling state for a domain."""
24
+
25
+ violations: int = 0
26
+ delay_seconds: int = 1
27
+ last_violation: float = 0.0
28
+ total_requests: int = 0
29
+
30
+
31
+ @dataclass
32
+ class RequestMetrics:
33
+ """Metrics for a single request."""
34
+
35
+ domain: str
36
+ method: str
37
+ cache_hit: bool
38
+ response_time_ms: int
39
+ response_size_bytes: int
40
+ timestamp: datetime
41
+
42
+
43
+ @dataclass
44
+ class ProxyMetrics:
45
+ """Overall proxy performance metrics."""
46
+
47
+ total_requests: int = 0
48
+ cache_hits: int = 0
49
+ cache_misses: int = 0
50
+ total_response_time_ms: int = 0
51
+ domains_served: int = 0
52
+ uptime_seconds: float = 0.0
53
+
54
+ @property
55
+ def hit_rate(self) -> float:
56
+ total = self.cache_hits + self.cache_misses
57
+ return (self.cache_hits / total) if total > 0 else 0.0
58
+
59
+ @property
60
+ def average_response_time(self) -> float:
61
+ return (self.total_response_time_ms / self.total_requests) if self.total_requests > 0 else 0.0
@@ -0,0 +1,186 @@
1
+ """
2
+ MonitoringManager: Provides programmatic access to operational metrics
3
+ and health information for the caching proxy module.
4
+
5
+ Implements the design in 3.2.2 of the monitoring interface design document.
6
+ """
7
+
8
+ import os
9
+ import threading
10
+ import time
11
+ from typing import Any, Dict
12
+
13
+
14
+ class MonitoringManager:
15
+ def __init__(self, proxy, cache_engine, db_manager, throttle_manager):
16
+ """Initialize with references to core components."""
17
+ self.proxy = proxy
18
+ self.cache_engine = cache_engine
19
+ self.db_manager = db_manager
20
+ self.throttle_manager = throttle_manager
21
+ self.start_time = getattr(proxy, "start_time", time.time())
22
+
23
+ def get_cache_stats(self) -> Dict[str, Any]:
24
+ """Return cache entry counts, sizes, hit/miss rates, TTLs, and evictions."""
25
+ stats = {}
26
+ try:
27
+ if self.cache_engine and hasattr(self.cache_engine, "get_cache_performance"):
28
+ # Use existing cache performance method
29
+ perf_stats = self.cache_engine.get_cache_performance()
30
+ stats.update(perf_stats)
31
+
32
+ # Get raw stats for additional info
33
+ if hasattr(self.cache_engine, "get_stats"):
34
+ raw_stats = self.cache_engine.get_stats()
35
+ stats["hit_count"] = raw_stats.get("hits", "unavailable")
36
+ stats["miss_count"] = raw_stats.get("misses", "unavailable")
37
+ stats["miss_rate"] = 1.0 - stats.get("hit_rate", 0) if "hit_rate" in stats else "unavailable"
38
+ stats["sets"] = raw_stats.get("sets", "unavailable")
39
+ stats["compressed"] = raw_stats.get("compressed", "unavailable")
40
+ stats["decompressed"] = raw_stats.get("decompressed", "unavailable")
41
+ else:
42
+ # Fallback to unavailable if cache_engine is None or missing methods
43
+ stats = {
44
+ "total_entries": {"unavailable": {}},
45
+ "entries_per_domain": {"unavailable": {}},
46
+ "cache_size_bytes": {"unavailable": {}},
47
+ "cache_size_per_domain": {"unavailable": {}},
48
+ "hit_count": {"unavailable": {}},
49
+ "miss_count": {"unavailable": {}},
50
+ "hit_rate": {"unavailable": {}},
51
+ "miss_rate": {"unavailable": {}},
52
+ "ttl_distribution": {"unavailable": {}},
53
+ "expired_entries": {"unavailable": {}},
54
+ "evicted_entries": {"unavailable": {}},
55
+ }
56
+ except Exception as e:
57
+ stats["error"] = str(e)
58
+ return stats
59
+
60
+ def get_upstream_stats(self) -> Dict[str, Any]:
61
+ """Return upstream response times, error rates, and request volumes."""
62
+ stats = {}
63
+ try:
64
+ if self.db_manager and hasattr(self.db_manager, "get_upstream_metrics"):
65
+ # Get metrics from database for all domains - this now returns overall + per-domain breakdown
66
+ upstream_metrics = self.db_manager.get_upstream_metrics()
67
+
68
+ # Return the complete structure with overall and by_domain breakdowns
69
+ stats = upstream_metrics
70
+ else:
71
+ # Fallback to unavailable if no database or metrics method
72
+ stats = {
73
+ "overall": {
74
+ "response_times": "unavailable",
75
+ "error_rates": "unavailable",
76
+ "request_volumes": "unavailable",
77
+ }
78
+ }
79
+ except Exception as e:
80
+ stats["error"] = str(e)
81
+ stats = {
82
+ "overall": {
83
+ "response_times": "unavailable",
84
+ "error_rates": "unavailable",
85
+ "request_volumes": "unavailable",
86
+ }
87
+ }
88
+ return stats
89
+
90
+ def get_database_stats(self) -> Dict[str, Any]:
91
+ """Return database file path, size, memory usage, and health."""
92
+ stats = {}
93
+ try:
94
+ if self.db_manager:
95
+ # Get database file path from database_path attribute
96
+ db_path = getattr(self.db_manager, "database_path", None)
97
+ if db_path and ":memory:" not in db_path and "file::memory:" not in db_path:
98
+ stats["db_file_path"] = db_path
99
+ if os.path.exists(db_path):
100
+ stats["db_file_size_bytes"] = os.path.getsize(db_path)
101
+ else:
102
+ stats["db_file_size_bytes"] = "file_not_found"
103
+ else:
104
+ stats["db_file_path"] = "in_memory"
105
+ stats["db_file_size_bytes"] = "in_memory"
106
+
107
+ # Check database health by trying a simple query
108
+ try:
109
+ if hasattr(self.db_manager, "execute_query"):
110
+ self.db_manager.execute_query("SELECT 1")
111
+ stats["db_health"] = "healthy"
112
+ else:
113
+ stats["db_health"] = "unknown"
114
+ except Exception:
115
+ stats["db_health"] = "error"
116
+
117
+ # Memory usage estimation (approximate)
118
+ stats["in_memory_cache_size"] = "unavailable" # Would need specific implementation
119
+ else:
120
+ stats = {
121
+ "db_file_path": "unavailable",
122
+ "db_file_size_bytes": "unavailable",
123
+ "in_memory_cache_size": "unavailable",
124
+ "db_health": "unavailable",
125
+ }
126
+ except Exception as e:
127
+ stats["error"] = str(e)
128
+ return stats
129
+
130
+ def get_proxy_health(self) -> Dict[str, Any]:
131
+ """Return uptime, active threads, and recent errors."""
132
+ stats = {}
133
+ try:
134
+ stats["uptime_seconds"] = time.time() - self.start_time
135
+ stats["active_threads"] = threading.active_count()
136
+ stats["recent_errors"] = getattr(self.proxy, "get_recent_errors", lambda: [])()
137
+ except Exception as e:
138
+ stats["error"] = str(e)
139
+ return stats
140
+
141
+ def get_throttling_stats(self) -> Dict[str, Any]:
142
+ """Return current throttle state and per-domain request counts."""
143
+ stats = {}
144
+ try:
145
+ if self.throttle_manager:
146
+ # Get per-domain request counts from current window
147
+ requests_per_domain = {}
148
+ throttle_states = {}
149
+
150
+ # Get all tracked domains and their stats
151
+ if hasattr(self.throttle_manager, "states"):
152
+ for domain, state in self.throttle_manager.states.items():
153
+ requests_per_domain[domain] = {
154
+ "current_hour_requests": len(state.request_timestamps),
155
+ "total_requests": state.total_requests,
156
+ "violations": state.violations,
157
+ "current_delay_seconds": state.delay_seconds,
158
+ }
159
+ throttle_states[domain] = {
160
+ "is_throttled": state.delay_seconds > 1,
161
+ "violations": state.violations,
162
+ "delay_seconds": state.delay_seconds,
163
+ "last_violation": state.last_violation,
164
+ }
165
+
166
+ stats["requests_per_domain"] = requests_per_domain if requests_per_domain else {}
167
+ stats["throttle_state"] = throttle_states if throttle_states else {}
168
+
169
+ # Get configuration info
170
+ stats["default_requests_per_hour"] = self.throttle_manager.default_limit
171
+ stats["progressive_max_delay"] = self.throttle_manager.max_delay
172
+ stats["progressive_enabled"] = True # Progressive throttling is always enabled
173
+
174
+ # Get domain-specific limits
175
+ stats["domain_limits"] = self.throttle_manager.domain_limits
176
+
177
+ else:
178
+ stats = {
179
+ "requests_per_domain": {},
180
+ "throttle_state": {},
181
+ "default_requests_per_hour": None,
182
+ "progressive_enabled": None,
183
+ }
184
+ except Exception as e:
185
+ stats["error"] = str(e)
186
+ return stats
@@ -0,0 +1 @@
1
+ """Security module initializer."""