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,416 @@
1
+ import time
2
+ from typing import Any, Dict, List, Optional, Tuple
3
+
4
+ from reference_api_buddy.cache.engine import CacheEngine
5
+ from reference_api_buddy.database.manager import DatabaseManager
6
+ from reference_api_buddy.security.manager import SecurityManager
7
+ from reference_api_buddy.throttling.manager import ThrottleManager
8
+ from reference_api_buddy.utils.logger import configure_logging, get_logger
9
+
10
+
11
+ class SecurityError(Exception):
12
+ """Security-related errors raised during request validation.
13
+
14
+ This exception is raised when:
15
+ - Required secure key is missing
16
+ - Provided secure key is invalid
17
+ - Request fails security validation
18
+ """
19
+
20
+ pass
21
+
22
+
23
+ class CachingProxy:
24
+ @staticmethod
25
+ def get_logger(name: str):
26
+ """Expose the get_logger utility function for external use.
27
+
28
+ Args:
29
+ name: Name of the logger (usually __name__ of the module)
30
+
31
+ Returns:
32
+ Configured logger instance
33
+ """
34
+ from reference_api_buddy.utils.logger import get_logger as _get_logger
35
+
36
+ return _get_logger(name)
37
+
38
+ """Main entry point for the caching proxy module.
39
+
40
+ A thread-safe HTTP caching proxy that provides intelligent caching,
41
+ progressive throttling, and detailed metrics for development environments.
42
+
43
+ Example:
44
+ Basic usage with security enabled:
45
+
46
+ >>> config = {
47
+ ... "security": {"require_secure_key": True},
48
+ ... "domain_mappings": {
49
+ ... "example": {"upstream": "https://api.example.com"}
50
+ ... }
51
+ ... }
52
+ >>> proxy = CachingProxy(config)
53
+ >>> proxy.start(blocking=False)
54
+ >>> print(f"Secure key: {proxy.get_secure_key()}")
55
+ >>> proxy.stop()
56
+
57
+ Using as context manager:
58
+
59
+ >>> with CachingProxy(config) as proxy:
60
+ ... # proxy is automatically started and stopped
61
+ ... pass
62
+ """
63
+
64
+ def validate_request(
65
+ self, path: str, headers: Dict[str, str], query_params: Dict[str, str]
66
+ ) -> Tuple[Optional[str], str]:
67
+ """Extract and validate secure key from request.
68
+
69
+ Args:
70
+ path: The request path that may contain a secure key
71
+ headers: HTTP headers dictionary that may contain authentication
72
+ query_params: Query parameters dictionary that may contain the key
73
+
74
+ Returns:
75
+ A tuple of (extracted_key, sanitized_path) where extracted_key
76
+ is None if no key found or security is disabled
77
+
78
+ Raises:
79
+ SecurityError: If security is enabled but key is invalid or missing
80
+
81
+ Example:
82
+ >>> proxy = CachingProxy({"security": {"require_secure_key": True}})
83
+ >>> key, path = proxy.validate_request("/abc123/example.com/api", {}, {})
84
+ >>> print(f"Key: {key}, Path: {path}")
85
+ """
86
+ key, sanitized = self.security_manager.extract_secure_key(path, headers, query_params)
87
+ if not self.security_manager.validate_request(key):
88
+ self.logger.warning("Invalid or missing secure key for path: %s", path)
89
+ raise SecurityError("Invalid or missing secure key")
90
+ return key, sanitized
91
+
92
+ def _sanitize_path(self, path: str) -> str:
93
+ """Remove null bytes, non-ASCII chars, and collapse multiple slashes.
94
+
95
+ Args:
96
+ path: The input path that may contain problematic characters
97
+
98
+ Returns:
99
+ A cleaned path with only printable ASCII characters and
100
+ normalized slashes
101
+
102
+ Example:
103
+ >>> proxy = CachingProxy({})
104
+ >>> clean = proxy._sanitize_path("/api/\\x00test//path")
105
+ >>> print(clean) # "/api/test/path"
106
+ """
107
+ import re
108
+
109
+ cleaned = "".join([c for c in path if 32 <= ord(c) <= 126])
110
+ # Collapse multiple slashes
111
+ cleaned = re.sub(r"/+", "/", cleaned)
112
+ return cleaned
113
+
114
+ def _log_security_event(self, event_type: str, details: Dict[str, Any]) -> None:
115
+ """Log security event if enabled in configuration.
116
+
117
+ Args:
118
+ event_type: Type of security event (e.g., "invalid_key", "rate_limit")
119
+ details: Additional details about the event
120
+ """
121
+ if self.config.get("security", {}).get("log_security_events", True):
122
+ self.logger.info(f"[SECURITY] {event_type}: {details}")
123
+
124
+ def __init__(self, config: Dict[str, Any]) -> None:
125
+ """Initialize the proxy with configuration and all components.
126
+
127
+ Args:
128
+ config: Configuration dictionary containing server, security, cache,
129
+ throttling, and domain mapping settings
130
+
131
+ Raises:
132
+ ValueError: If configuration is invalid
133
+
134
+ Example:
135
+ >>> config = {
136
+ ... "server": {"host": "127.0.0.1", "port": 8080},
137
+ ... "security": {"require_secure_key": True},
138
+ ... "cache": {"database_path": "cache.db"},
139
+ ... "domain_mappings": {
140
+ ... "example": {"upstream": "https://api.example.com"}
141
+ ... }
142
+ ... }
143
+ >>> proxy = CachingProxy(config)
144
+ """
145
+ self.config = config or {}
146
+ self._validate_and_merge_config()
147
+ # Configure logging system
148
+ configure_logging(self.config.get("logging", {}))
149
+ self.logger = get_logger("core.proxy")
150
+ self.security_manager = SecurityManager(self.config.get("security", {}))
151
+ self.db_manager = DatabaseManager(self.config.get("cache", {}).get("database_path", ":memory:"))
152
+ self.cache_engine = CacheEngine(
153
+ self.db_manager,
154
+ config=self.config,
155
+ max_response_size=self.config.get("cache", {}).get("max_cache_response_size", 10485760),
156
+ )
157
+ self.throttle_manager = ThrottleManager(self.config.get("throttling", {}))
158
+ self.metrics_collector = MetricsCollector()
159
+ self.callbacks = self.config.get("callbacks", {})
160
+ self.server: Optional[Any] = None
161
+ self.running = False
162
+ self.start_time: Optional[float] = None
163
+ self._metrics: Dict[str, Any] = {}
164
+
165
+ def start(self, blocking: bool = False) -> None:
166
+ """Start the proxy server.
167
+
168
+ Args:
169
+ blocking: If True, blocks until server stops. If False,
170
+ starts server in background thread.
171
+
172
+ Raises:
173
+ RuntimeError: If server is already running
174
+ OSError: If unable to bind to specified host/port
175
+
176
+ Example:
177
+ >>> proxy = CachingProxy(config)
178
+ >>> proxy.start(blocking=False) # Start in background
179
+ >>> # Do other work...
180
+ >>> proxy.stop()
181
+ """
182
+ from reference_api_buddy.core.handler import ProxyHTTPRequestHandler
183
+ from reference_api_buddy.core.server import ThreadedHTTPServer
184
+
185
+ if self.running:
186
+ raise RuntimeError("Server is already running")
187
+
188
+ host = self.config.get("server", {}).get("host", "127.0.0.1")
189
+ port = self.config.get("server", {}).get("port", 8080)
190
+
191
+ if self.server is None:
192
+ self.server = ThreadedHTTPServer((host, port), ProxyHTTPRequestHandler, self)
193
+ self.running = True
194
+ self.start_time = time.time()
195
+ self.logger.info(f"Proxy server starting on {host}:{port} (blocking={blocking})")
196
+ self.server.start(blocking=blocking)
197
+
198
+ def stop(self) -> None:
199
+ """Stop the proxy server and cleanup resources.
200
+
201
+ This method is safe to call multiple times. If the server is not
202
+ running, this method does nothing.
203
+
204
+ Example:
205
+ >>> proxy.stop() # Gracefully stops the server
206
+ """
207
+ if self.server:
208
+ self.server.stop()
209
+ self.running = False
210
+
211
+ # Close database connections to release file locks (important for Windows)
212
+ if hasattr(self, "db_manager") and self.db_manager:
213
+ try:
214
+ self.db_manager.close()
215
+ except Exception as e:
216
+ self.logger.error(f"Error closing database manager: {e}")
217
+
218
+ self.logger.info("Proxy server stopped.")
219
+ # Graceful shutdown: flush metrics, call shutdown callbacks
220
+ if "on_shutdown" in self.callbacks:
221
+ try:
222
+ self.callbacks["on_shutdown"](self)
223
+ except Exception as e:
224
+ self.logger.error(f"Error in shutdown callback: {e}")
225
+
226
+ def get_secure_key(self) -> Optional[str]:
227
+ """Return the secure key if security is enabled.
228
+
229
+ Returns:
230
+ The secure key string if security is enabled, None otherwise
231
+
232
+ Example:
233
+ >>> proxy = CachingProxy({"security": {"require_secure_key": True}})
234
+ >>> key = proxy.get_secure_key()
235
+ >>> print(f"Use this key in requests: {key}")
236
+ """
237
+ self.logger.debug("Retrieving secure key from security manager.")
238
+ if hasattr(self.security_manager, "secure_key"):
239
+ return getattr(self.security_manager, "secure_key", None)
240
+ return None
241
+
242
+ def is_running(self) -> bool:
243
+ """Check if the proxy server is running.
244
+
245
+ Returns:
246
+ True if the server is currently running, False otherwise
247
+ """
248
+ return self.running
249
+
250
+ def get_metrics(self) -> Dict[str, Any]:
251
+ """Return current metrics and statistics.
252
+
253
+ Returns:
254
+ Dictionary containing cache hits, misses, throttling stats,
255
+ and performance metrics
256
+
257
+ Example:
258
+ >>> metrics = proxy.get_metrics()
259
+ >>> print(f"Cache hit rate: {metrics.get('hit_rate', 0):.2%}")
260
+ """
261
+ return self.metrics_collector.get_metrics()
262
+
263
+ def get_monitoring_manager(self):
264
+ """Get a MonitoringManager instance configured with all proxy components.
265
+
266
+ Returns:
267
+ MonitoringManager instance ready to use for comprehensive metrics
268
+
269
+ Example:
270
+ >>> monitor = proxy.get_monitoring_manager()
271
+ >>> cache_stats = monitor.get_cache_stats()
272
+ >>> upstream_stats = monitor.get_upstream_stats()
273
+ >>> throttle_stats = monitor.get_throttling_stats()
274
+ """
275
+ from reference_api_buddy.monitoring.manager import MonitoringManager
276
+
277
+ return MonitoringManager(self, self.cache_engine, self.db_manager, self.throttle_manager)
278
+
279
+ def clear_cache(self, domain: Optional[str] = None) -> int:
280
+ """Clear cache entries for a domain or all domains.
281
+
282
+ Args:
283
+ domain: Specific domain to clear cache for. If None, clears all
284
+ cache entries
285
+
286
+ Returns:
287
+ Number of cache entries that were cleared
288
+
289
+ Example:
290
+ >>> cleared = proxy.clear_cache("example.com")
291
+ >>> print(f"Cleared {cleared} cache entries for example.com")
292
+ >>> total_cleared = proxy.clear_cache() # Clear all
293
+ """
294
+ self.logger.info(f"Clearing cache for domain: {domain}")
295
+ return self.cache_engine.clear_cache(domain)
296
+
297
+ def update_config(self, key_path: str, value: Any) -> None:
298
+ """Update configuration at runtime using dot notation.
299
+
300
+ Args:
301
+ key_path: Dot-separated path to the configuration key (e.g., "server.port")
302
+ value: New value to set
303
+
304
+ Example:
305
+ >>> proxy.update_config("server.port", 9090)
306
+ >>> proxy.update_config("throttling.default_requests_per_hour", 500)
307
+ """
308
+ self.logger.info(f"Updating config '{key_path}' to {value}")
309
+ keys = key_path.split(".")
310
+ cfg = self.config
311
+ for k in keys[:-1]:
312
+ cfg = cfg.setdefault(k, {})
313
+ cfg[keys[-1]] = value
314
+
315
+ def reload_config(self, new_config: Dict[str, Any]) -> None:
316
+ """Reload configuration completely.
317
+
318
+ Args:
319
+ new_config: New configuration dictionary to replace current config
320
+
321
+ Note:
322
+ This will reinitialize all components with the new configuration.
323
+ The server must be restarted for server configuration changes
324
+ to take effect.
325
+ """
326
+ self.logger.info("Reloading configuration...")
327
+ self.config = new_config or {}
328
+ self._validate_and_merge_config()
329
+ # Re-configure logging system
330
+ configure_logging(self.config.get("logging", {}))
331
+ self.logger = get_logger("core.proxy")
332
+ # Re-initialize components
333
+ self.security_manager = SecurityManager(self.config.get("security", {}))
334
+ self.db_manager = DatabaseManager(self.config.get("cache", {}).get("database_path", ":memory:"))
335
+ self.cache_engine = CacheEngine(
336
+ self.db_manager,
337
+ config=self.config,
338
+ max_response_size=self.config.get("cache", {}).get("max_cache_response_size", 10485760),
339
+ )
340
+ self.throttle_manager = ThrottleManager(self.config.get("throttling", {}))
341
+ self.metrics_collector = MetricsCollector()
342
+ self.callbacks = self.config.get("callbacks", {})
343
+
344
+ def _validate_and_merge_config(self) -> None:
345
+ """Validate and merge configuration with defaults."""
346
+ # For now, just ensure required keys exist; could add schema validation
347
+ defaults = {
348
+ "server": {"host": "127.0.0.1", "port": 8080},
349
+ "security": {},
350
+ "cache": {"database_path": ":memory:", "max_cache_response_size": 10485760},
351
+ "throttling": {},
352
+ "callbacks": {},
353
+ }
354
+ for k, v in defaults.items():
355
+ self.config.setdefault(k, v)
356
+
357
+ def __enter__(self) -> "CachingProxy":
358
+ """Enter context manager and start the proxy server."""
359
+ self.start(blocking=False)
360
+ return self
361
+
362
+ def __exit__(self, exc_type: Optional[type], exc_val: Optional[Exception], exc_tb: Optional[Any]) -> None:
363
+ """Exit context manager and stop the proxy server."""
364
+ self.stop()
365
+
366
+
367
+ class MetricsCollector:
368
+ """Collects and reports proxy metrics, supports event callbacks.
369
+
370
+ Tracks request counts, cache performance, throttling events, and errors.
371
+ Thread-safe for concurrent request handling.
372
+ """
373
+
374
+ def __init__(self) -> None:
375
+ """Initialize metrics collector with default counters."""
376
+ self._metrics = {
377
+ "total_requests": 0,
378
+ "cache_hits": 0,
379
+ "cache_misses": 0,
380
+ "throttled": 0,
381
+ "errors": 0,
382
+ "start_time": time.time(),
383
+ }
384
+ self._events: List[Tuple[str, Dict[str, Any]]] = []
385
+
386
+ def record_event(self, event_type: str, details: Optional[Dict[str, Any]] = None) -> None:
387
+ """Record a proxy event for metrics tracking.
388
+
389
+ Args:
390
+ event_type: Type of event ("cache_hit", "cache_miss", "throttle", "error")
391
+ details: Additional event details dictionary
392
+ """
393
+ self._metrics["total_requests"] += 1
394
+ if event_type == "cache_hit":
395
+ self._metrics["cache_hits"] += 1
396
+ elif event_type == "cache_miss":
397
+ self._metrics["cache_misses"] += 1
398
+ elif event_type == "throttle":
399
+ self._metrics["throttled"] += 1
400
+ elif event_type == "error":
401
+ self._metrics["errors"] += 1
402
+ self._events.append((event_type, details or {}))
403
+
404
+ def get_metrics(self) -> Dict[str, Any]:
405
+ """Get current metrics summary.
406
+
407
+ Returns:
408
+ Dictionary with request counts, cache performance, uptime, and recent events
409
+ """
410
+ m = dict(self._metrics)
411
+ m["uptime_seconds"] = time.time() - self._metrics["start_time"]
412
+
413
+ # Include recent events for debugging (convert tuples to dicts)
414
+ m["events"] = [{"event_type": event_type, "details": details} for event_type, details in self._events]
415
+
416
+ return m
@@ -0,0 +1,40 @@
1
+ """Threaded HTTP server and handler for Reference API Buddy."""
2
+
3
+ import threading
4
+ from http.server import ThreadingHTTPServer
5
+ from logging import getLogger
6
+
7
+ logger = getLogger(__name__)
8
+
9
+
10
+ class ThreadedHTTPServer(ThreadingHTTPServer):
11
+ """Threaded HTTP server with connection pooling."""
12
+
13
+ allow_reuse_address = True
14
+
15
+ def __init__(self, server_address, RequestHandlerClass, proxy_instance):
16
+ self.proxy_instance = proxy_instance
17
+
18
+ def handler(*args, **kwargs):
19
+ return RequestHandlerClass(*args, proxy_instance=proxy_instance, **kwargs)
20
+
21
+ super().__init__(server_address, handler)
22
+ self._run_thread = None
23
+
24
+ def start(self, blocking=True):
25
+ if blocking:
26
+ logger.info("Starting server in blocking mode...")
27
+ self.serve_forever()
28
+ else:
29
+ logger.info("Starting server in non-blocking mode...")
30
+ self._run_thread = threading.Thread(target=self.serve_forever, daemon=True)
31
+ self._run_thread.start()
32
+ logger.info("Server started.")
33
+
34
+ def stop(self):
35
+ logger.info("Stopping server...")
36
+ self.shutdown()
37
+ self.server_close()
38
+ if self._run_thread:
39
+ self._run_thread.join()
40
+ logger.info("Server stopped.")
@@ -0,0 +1,41 @@
1
+ """TTL management utilities for cache configuration."""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class TTLManager:
7
+ """Manages TTL resolution for cache entries based on domain configuration."""
8
+
9
+ def __init__(self, config: dict):
10
+ """Initialize TTL manager with configuration.
11
+
12
+ Args:
13
+ config: Full proxy configuration dictionary
14
+ """
15
+ self.config = config
16
+ self.default_ttl = config.get("cache", {}).get("default_ttl_seconds", 86400)
17
+ self.domain_mappings = config.get("domain_mappings", {})
18
+
19
+ def get_ttl_for_domain(self, domain_key: str) -> int:
20
+ """Get TTL value for a specific domain.
21
+
22
+ Args:
23
+ domain_key: The domain key from domain_mappings
24
+
25
+ Returns:
26
+ TTL in seconds - domain-specific if configured, otherwise default
27
+ """
28
+ if domain_key in self.domain_mappings:
29
+ domain_config = self.domain_mappings[domain_key]
30
+ if isinstance(domain_config, dict):
31
+ return domain_config.get("ttl_seconds", self.default_ttl)
32
+
33
+ return self.default_ttl
34
+
35
+ def get_default_ttl(self) -> int:
36
+ """Get the system default TTL value.
37
+
38
+ Returns:
39
+ Default TTL in seconds
40
+ """
41
+ return self.default_ttl
@@ -0,0 +1 @@
1
+ """Database module initializer."""