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,22 @@
1
+ """Reference API Buddy - HTTP Caching Proxy for Development.
2
+
3
+ A Python HTTP-to-HTTPS caching proxy module designed for reference APIs where
4
+ the data is non-secure and not changing frequently (ConceptNet, DBpedia, Wikidata, etc).
5
+ """
6
+
7
+ from reference_api_buddy.cache.engine import CacheEngine
8
+ from reference_api_buddy.core.proxy import CachingProxy, SecurityError
9
+ from reference_api_buddy.security.manager import SecurityManager
10
+ from reference_api_buddy.throttling.manager import ThrottleManager
11
+
12
+ __version__ = "0.2.0"
13
+ __author__ = "Reference API Buddy Team"
14
+ __email__ = "contact@example.com"
15
+
16
+ __all__ = [
17
+ "CachingProxy",
18
+ "SecurityError",
19
+ "SecurityManager",
20
+ "CacheEngine",
21
+ "ThrottleManager",
22
+ ]
@@ -0,0 +1 @@
1
+ """Cache module initializer."""
@@ -0,0 +1,353 @@
1
+ """Cache engine implementation for Reference API Buddy."""
2
+
3
+ import hashlib
4
+ import json
5
+ import threading
6
+ import time
7
+ import zlib
8
+ from typing import Any, Dict, Optional
9
+
10
+ from reference_api_buddy.database.manager import DatabaseManager
11
+ from reference_api_buddy.database.models import CachedResponse
12
+
13
+
14
+ class CacheEngine:
15
+ """Core caching logic with key generation, method-specific caching, TTL,
16
+ and statistics.
17
+
18
+ Provides thread-safe caching operations with automatic compression, TTL management,
19
+ and cache size limits. Supports both GET and POST request caching with
20
+ content-aware key generation.
21
+
22
+ Example:
23
+ >>> db_manager = DatabaseManager(":memory:")
24
+ >>> cache = CacheEngine(db_manager, max_response_size=1024*1024)
25
+ >>> cache.set("test_key", response_object)
26
+ >>> cached = cache.get("test_key")
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ db_manager: DatabaseManager,
32
+ config: dict = None,
33
+ max_response_size: int = 10485760,
34
+ compression_threshold: int = 1024,
35
+ max_cache_entries: int = 1000,
36
+ ) -> None:
37
+ """Initialize cache engine with database manager and configuration.
38
+
39
+ Args:
40
+ db_manager: Database manager for persistent storage
41
+ config: Full configuration dictionary for TTL management
42
+ max_response_size: Maximum response size to cache (bytes)
43
+ compression_threshold: Minimum size for compression (bytes)
44
+ max_cache_entries: Maximum number of cache entries
45
+ """
46
+ self.db_manager = db_manager
47
+ self.max_response_size = max_response_size
48
+ self.compression_threshold = compression_threshold
49
+ self.max_cache_entries = max_cache_entries
50
+ self._lock = threading.Lock()
51
+ self._stats = {
52
+ "hits": 0,
53
+ "misses": 0,
54
+ "evictions": 0,
55
+ "sets": 0,
56
+ "expired": 0,
57
+ "compressed": 0,
58
+ "decompressed": 0,
59
+ }
60
+
61
+ # Initialize TTL manager if config is provided
62
+ if config:
63
+ from reference_api_buddy.core.ttl_manager import TTLManager
64
+
65
+ self._ttl_manager = TTLManager(config)
66
+ else:
67
+ self._ttl_manager = None
68
+
69
+ self._cleanup_expired_entries()
70
+
71
+ def _normalize_url(self, url: str) -> str:
72
+ """Normalize URL for consistent cache keys.
73
+
74
+ Args:
75
+ url: The URL to normalize
76
+
77
+ Returns:
78
+ Normalized URL with sorted query parameters and consistent path handling
79
+ """
80
+ from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
81
+
82
+ parsed = urlparse(url)
83
+ query = urlencode(sorted(parse_qsl(parsed.query)))
84
+ # Treat all trailing slashes as insignificant except for root
85
+ path = parsed.path
86
+ if path != "/":
87
+ path = path.rstrip("/")
88
+ if not path:
89
+ path = "/"
90
+ normalized = parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), path=path, query=query)
91
+ # If the normalized path is empty, set to '/'
92
+ if not normalized.path:
93
+ normalized = normalized._replace(path="/")
94
+ return urlunparse(normalized)
95
+
96
+ def _normalize_request_body(self, body: bytes, content_type: Optional[str]) -> str:
97
+ """Normalize request body for consistent cache key generation.
98
+
99
+ Args:
100
+ body: Request body bytes
101
+ content_type: Content-Type header value
102
+
103
+ Returns:
104
+ Normalized string representation of the body
105
+ """
106
+ if not body:
107
+ return ""
108
+ if content_type and "application/json" in content_type:
109
+ try:
110
+ obj = json.loads(body.decode("utf-8"))
111
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"))
112
+ except Exception:
113
+ pass
114
+ # Fallback: hash the body
115
+ return hashlib.sha256(body).hexdigest()
116
+
117
+ def generate_cache_key(
118
+ self, method: str, url: str, body: Optional[bytes] = None, content_type: Optional[str] = None
119
+ ) -> str:
120
+ """Generate a cache key based on method, URL, and body.
121
+
122
+ Args:
123
+ method: HTTP method (GET, POST, etc.)
124
+ url: Request URL
125
+ body: Request body (for POST requests)
126
+ content_type: Content-Type header value
127
+
128
+ Returns:
129
+ SHA256 hash as hexadecimal string for use as cache key
130
+
131
+ Example:
132
+ >>> cache = CacheEngine(db_manager)
133
+ >>> key = cache.generate_cache_key("GET", "https://api.example.com/data")
134
+ >>> print(f"Cache key: {key}")
135
+ """
136
+ normalized_url = self._normalize_url(url)
137
+ key_components = [method.upper(), normalized_url]
138
+ if method.upper() == "POST" and body:
139
+ normalized_body = self._normalize_request_body(body, content_type)
140
+ key_components.append(normalized_body)
141
+ key_string = ":".join(key_components)
142
+ return hashlib.sha256(key_string.encode("utf-8")).hexdigest()
143
+
144
+ def get(self, cache_key: str) -> Optional[CachedResponse]:
145
+ """Retrieve a cached response if not expired and decompress if needed.
146
+
147
+ Args:
148
+ cache_key: The cache key to retrieve
149
+
150
+ Returns:
151
+ CachedResponse object if found and not expired, None otherwise
152
+
153
+ Example:
154
+ >>> cached = cache.get("some_cache_key")
155
+ >>> if cached:
156
+ ... print(f"Cache hit! Status: {cached.status_code}")
157
+ """
158
+ with self._lock: # Protect database operations from concurrent access
159
+ rows = self.db_manager.execute_query(
160
+ "SELECT response_data, headers, status_code, created_at, "
161
+ "ttl_seconds, access_count, last_accessed "
162
+ "FROM cache_entries WHERE cache_key = ?",
163
+ (cache_key,),
164
+ )
165
+ if not rows:
166
+ self._stats["misses"] += 1
167
+ return None
168
+ (
169
+ data,
170
+ headers,
171
+ status_code,
172
+ created_at,
173
+ ttl_seconds,
174
+ access_count,
175
+ last_accessed,
176
+ ) = rows[0]
177
+ now = int(time.time())
178
+ # created_at may be a string or a datetime.datetime
179
+ if hasattr(created_at, "timestamp"):
180
+ created_ts = int(created_at.timestamp())
181
+ elif isinstance(created_at, str):
182
+ try:
183
+ created_ts = int(time.mktime(time.strptime(created_at, "%Y-%m-%d %H:%M:%S")))
184
+ except Exception:
185
+ from datetime import datetime
186
+
187
+ created_ts = int(datetime.fromisoformat(created_at).timestamp())
188
+ else:
189
+ created_ts = int(created_at)
190
+ if now > created_ts + ttl_seconds:
191
+ self.delete(cache_key)
192
+ self._stats["expired"] += 1
193
+ return None
194
+ # Decompress if needed
195
+ if data and data[:2] == b"\x78\x9c": # zlib magic header
196
+ try:
197
+ data = zlib.decompress(data)
198
+ self._stats["decompressed"] += 1
199
+ except Exception:
200
+ pass
201
+ # Update access count and last_accessed
202
+ self.db_manager.execute_update(
203
+ "UPDATE cache_entries SET access_count = access_count + 1, "
204
+ "last_accessed = CURRENT_TIMESTAMP WHERE cache_key = ?",
205
+ (cache_key,),
206
+ )
207
+ self._stats["hits"] += 1
208
+ return CachedResponse(
209
+ data=data,
210
+ headers=json.loads(headers),
211
+ status_code=status_code,
212
+ created_at=created_at,
213
+ ttl_seconds=ttl_seconds,
214
+ access_count=access_count + 1,
215
+ last_accessed=last_accessed,
216
+ )
217
+
218
+ def set(self, cache_key: str, response: CachedResponse, domain_key: Optional[str] = None) -> bool:
219
+ """Store a response in the cache with appropriate TTL.
220
+
221
+ Args:
222
+ cache_key: The cache key
223
+ response: Response object to cache
224
+ domain_key: Optional domain key for domain-specific TTL
225
+
226
+ Returns:
227
+ True if cached successfully, False otherwise
228
+ """
229
+ data = response.data
230
+ # Always check original size before compression
231
+ if len(data) > self.max_response_size:
232
+ return False
233
+
234
+ # If no TTL is set in response, determine it based on domain/default
235
+ if hasattr(self, "_ttl_manager") and self._ttl_manager and response.ttl_seconds is None:
236
+ if domain_key:
237
+ response.ttl_seconds = self._ttl_manager.get_ttl_for_domain(domain_key)
238
+ else:
239
+ response.ttl_seconds = self._ttl_manager.get_default_ttl()
240
+
241
+ compressed = False
242
+ if len(data) > self.compression_threshold:
243
+ try:
244
+ data = zlib.compress(data)
245
+ compressed = True
246
+ except Exception:
247
+ pass
248
+
249
+ # Protect database operations from concurrent access
250
+ with self._lock:
251
+ self.db_manager.execute_update(
252
+ "REPLACE INTO cache_entries (cache_key, response_data, "
253
+ "headers, status_code, created_at, ttl_seconds, "
254
+ "access_count, last_accessed) "
255
+ "VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, ?, 0, CURRENT_TIMESTAMP)",
256
+ (
257
+ cache_key,
258
+ data,
259
+ json.dumps(response.headers, separators=(",", ":")),
260
+ response.status_code,
261
+ response.ttl_seconds,
262
+ ),
263
+ )
264
+ self._evict_if_needed()
265
+ self._stats["sets"] += 1
266
+ if compressed:
267
+ self._stats["compressed"] += 1
268
+ return True
269
+
270
+ def _evict_if_needed(self):
271
+ """Evict least recently used entries if over max_cache_entries."""
272
+ while True:
273
+ count = self.db_manager.execute_query("SELECT COUNT(*) FROM cache_entries")[0][0]
274
+ if count <= self.max_cache_entries:
275
+ break
276
+ to_evict = count - self.max_cache_entries
277
+ rows = self.db_manager.execute_query(
278
+ "SELECT cache_key FROM cache_entries ORDER BY " "last_accessed ASC LIMIT ?", (to_evict,)
279
+ )
280
+ for (cache_key,) in rows:
281
+ self.delete(cache_key)
282
+ self._stats["evictions"] += 1
283
+
284
+ def _cleanup_expired_entries(self):
285
+ """Remove expired cache entries."""
286
+ now = int(time.time())
287
+ rows = self.db_manager.execute_query("SELECT cache_key, created_at, ttl_seconds FROM cache_entries")
288
+ expired_count = 0
289
+ for cache_key, created_at, ttl_seconds in rows:
290
+ # created_at may be a string or datetime
291
+ if hasattr(created_at, "timestamp"):
292
+ created_ts = int(created_at.timestamp())
293
+ elif isinstance(created_at, str):
294
+ try:
295
+ created_ts = int(time.mktime(time.strptime(created_at, "%Y-%m-%d %H:%M:%S")))
296
+ except Exception:
297
+ from datetime import datetime
298
+
299
+ created_ts = int(datetime.fromisoformat(created_at).timestamp())
300
+ else:
301
+ created_ts = int(created_at)
302
+ if now > created_ts + ttl_seconds:
303
+ self.delete(cache_key)
304
+ expired_count += 1
305
+
306
+ # Update stats in a thread-safe way
307
+ if expired_count > 0:
308
+ with self._lock:
309
+ self._stats["expired"] += expired_count
310
+
311
+ def get_cache_performance(self) -> Dict[str, Any]:
312
+ """Return cache performance metrics."""
313
+ total_entries = self.db_manager.execute_query("SELECT COUNT(*) FROM cache_entries")[0][0]
314
+ total_size = self.db_manager.execute_query("SELECT SUM(LENGTH(response_data)) FROM cache_entries")[0][0] or 0
315
+ stats = self.get_stats()
316
+ return {
317
+ "total_entries": total_entries,
318
+ "total_size_bytes": total_size,
319
+ "expired_entries": stats["expired"],
320
+ "hit_rate": (
321
+ stats["hits"] / (stats["hits"] + stats["misses"]) if (stats["hits"] + stats["misses"]) > 0 else 0.0
322
+ ),
323
+ "evictions": stats["evictions"],
324
+ "compressed": stats["compressed"],
325
+ "decompressed": stats["decompressed"],
326
+ }
327
+
328
+ def delete(self, cache_key: str) -> int:
329
+ """Delete a cache entry."""
330
+ return self.db_manager.execute_update("DELETE FROM cache_entries WHERE cache_key = ?", (cache_key,))
331
+
332
+ def clear(self) -> int:
333
+ """Clear all cache entries."""
334
+ return self.db_manager.execute_update("DELETE FROM cache_entries")
335
+
336
+ def clear_cache(self, domain: Optional[str] = None) -> int:
337
+ """Clear cache entries for a specific domain or all entries.
338
+
339
+ Args:
340
+ domain: Domain to clear cache for. If None, clears all entries.
341
+
342
+ Returns:
343
+ Number of entries cleared.
344
+ """
345
+ if domain is None:
346
+ return self.clear()
347
+ # Clear entries for specific domain by matching cache keys
348
+ # that contain the domain
349
+ return self.db_manager.execute_update("DELETE FROM cache_entries WHERE cache_key LIKE ?", (f"%{domain}%",))
350
+
351
+ def get_stats(self) -> Dict[str, int]:
352
+ with self._lock:
353
+ return dict(self._stats)
@@ -0,0 +1,167 @@
1
+ """Command-line interface for Reference API Buddy."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any, Dict
8
+
9
+ from reference_api_buddy.core.proxy import CachingProxy
10
+ from reference_api_buddy.utils.logger import configure_logging
11
+
12
+
13
+ def load_config(config_path: Path) -> Dict[str, Any]:
14
+ """Load configuration from JSON file."""
15
+ try:
16
+ with open(config_path, "r") as f:
17
+ return json.load(f)
18
+ except FileNotFoundError:
19
+ print(f"Error: Configuration file not found: {config_path}")
20
+ sys.exit(1)
21
+ except json.JSONDecodeError as e:
22
+ print(f"Error: Invalid JSON in configuration file: {e}")
23
+ sys.exit(1)
24
+
25
+
26
+ def create_default_config() -> Dict[str, Any]:
27
+ """Create a default configuration."""
28
+ import os
29
+
30
+ # Use environment variable for database path if set (for CI)
31
+ db_path = os.environ.get("API_BUDDY_DB_PATH", "api_buddy_cache.db")
32
+ log_level = os.environ.get("API_BUDDY_LOG_LEVEL", "INFO")
33
+
34
+ return {
35
+ "server": {"host": "127.0.0.1", "port": 8080},
36
+ "security": {"require_secure_key": True},
37
+ "cache": {"database_path": db_path, "default_ttl_seconds": 86400}, # 1 day in seconds
38
+ "throttling": {"default_requests_per_hour": 1000},
39
+ "domain_mappings": {"example": {"upstream": "https://api.example.com"}},
40
+ "logging": {"level": log_level},
41
+ }
42
+
43
+
44
+ def main():
45
+ """Main CLI entry point."""
46
+ parser = argparse.ArgumentParser(
47
+ description="Reference API Buddy - HTTP Caching Proxy",
48
+ formatter_class=argparse.RawDescriptionHelpFormatter,
49
+ epilog="""
50
+ Examples:
51
+ api-buddy --config config.json # Start with config file
52
+ api-buddy --port 9090 --host 0.0.0.0 # Custom host/port
53
+ api-buddy --generate-config # Generate default config
54
+ api-buddy --security-key-only # Just print security key
55
+
56
+ Configuration:
57
+ The proxy supports configurable TTL (Time To Live) for cache entries:
58
+ - System default: cache.default_ttl_seconds (default: 86400 = 1 day)
59
+ - Per-domain: domain_mappings.{domain}.ttl_seconds (optional override)
60
+
61
+ See example_ttl_config.json for comprehensive TTL configuration examples.
62
+ """,
63
+ )
64
+
65
+ parser.add_argument("--config", "-c", type=Path, help="Path to configuration JSON file")
66
+
67
+ parser.add_argument("--host", default="127.0.0.1", help="Host to bind to (default: 127.0.0.1)")
68
+
69
+ parser.add_argument("--port", "-p", type=int, default=8080, help="Port to bind to (default: 8080)")
70
+
71
+ parser.add_argument("--generate-config", action="store_true", help="Generate a default configuration file and exit")
72
+
73
+ parser.add_argument(
74
+ "--security-key-only", action="store_true", help="Generate and print security key only, then exit"
75
+ )
76
+
77
+ parser.add_argument(
78
+ "--log-level",
79
+ choices=["DEBUG", "INFO", "WARNING", "ERROR"],
80
+ default="INFO",
81
+ help="Set logging level (default: INFO)",
82
+ )
83
+
84
+ parser.add_argument("--version", action="version", version="%(prog)s 0.1.0")
85
+
86
+ args = parser.parse_args()
87
+
88
+ # Handle special modes
89
+ if args.generate_config:
90
+ config = create_default_config()
91
+ config_file = Path("api_buddy_config.json")
92
+ with open(config_file, "w") as f:
93
+ json.dump(config, f, indent=2)
94
+ print(f"Generated default configuration: {config_file}")
95
+ return
96
+
97
+ if args.security_key_only:
98
+ from reference_api_buddy.security.manager import SecurityManager
99
+
100
+ manager = SecurityManager({})
101
+ key = manager.generate_secure_key()
102
+ print(f"Generated security key: {key}")
103
+ return
104
+
105
+ # Load configuration
106
+ if args.config:
107
+ config = load_config(args.config)
108
+ else:
109
+ config = create_default_config()
110
+ print("Using default configuration. Use --generate-config to " "create a config file.")
111
+
112
+ # Override with CLI arguments
113
+ if args.host != "127.0.0.1":
114
+ config.setdefault("server", {})["host"] = args.host
115
+ if args.port != 8080:
116
+ config.setdefault("server", {})["port"] = args.port
117
+
118
+ # Configure logging
119
+ config.setdefault("logging", {})["level"] = args.log_level
120
+ configure_logging(config["logging"])
121
+
122
+ # Start proxy
123
+ try:
124
+ proxy = CachingProxy(config)
125
+
126
+ # Print startup information
127
+ host = config.get("server", {}).get("host", "127.0.0.1")
128
+ port = config.get("server", {}).get("port", 8080)
129
+
130
+ print(f"Starting Reference API Buddy on {host}:{port}")
131
+ sys.stdout.flush() # Ensure output is flushed for CI
132
+
133
+ if config.get("security", {}).get("require_secure_key", False):
134
+ key = proxy.get_secure_key() # type: ignore
135
+ if key:
136
+ print(f"Security key: {key}")
137
+ print("Include this key in your requests:")
138
+ print(f" Path prefix: /{key}/domain/path")
139
+ print(f" Query param: ?key={key}")
140
+ print(f" Header: X-API-Buddy-Key: {key}")
141
+
142
+ print("\nPress Ctrl+C to stop")
143
+ sys.stdout.flush() # Ensure output is flushed for CI
144
+ proxy.start(blocking=True)
145
+
146
+ except KeyboardInterrupt:
147
+ print("\nShutting down...")
148
+ if "proxy" in locals():
149
+ proxy.stop()
150
+ except OSError as e:
151
+ print(f"Error binding to {host}:{port}: {e}")
152
+ # Try to provide helpful error message for common issues
153
+ if "Address already in use" in str(e):
154
+ print(f"Port {port} is already in use. Try a different port with --port option.")
155
+ elif "Permission denied" in str(e):
156
+ print(f"Permission denied to bind to {host}:{port}. Try using a port above 1024.")
157
+ sys.exit(1)
158
+ except Exception as e:
159
+ print(f"Error starting proxy: {e}")
160
+ import traceback
161
+
162
+ print(f"Traceback: {traceback.format_exc()}")
163
+ sys.exit(1)
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()
@@ -0,0 +1 @@
1
+ """Core module initializer."""
@@ -0,0 +1,77 @@
1
+ """Admin utilities for the caching proxy module."""
2
+
3
+ import threading
4
+ import time
5
+ from typing import Dict, List
6
+
7
+
8
+ class AdminRateLimiter:
9
+ """Simple rate limiter for admin endpoints."""
10
+
11
+ def __init__(self):
12
+ """Initialize the rate limiter with empty request tracking."""
13
+ self.requests: Dict[str, List[float]] = {} # IP -> list of timestamps
14
+ self.lock = threading.Lock()
15
+
16
+ def is_allowed(self, client_ip: str, limit_per_minute: int = 10) -> bool:
17
+ """Check if client is within rate limit.
18
+
19
+ Args:
20
+ client_ip: IP address of the client
21
+ limit_per_minute: Maximum requests allowed per minute
22
+
23
+ Returns:
24
+ True if request is allowed, False if rate limit exceeded
25
+ """
26
+ now = time.time()
27
+ minute_ago = now - 60
28
+
29
+ with self.lock:
30
+ if client_ip not in self.requests:
31
+ self.requests[client_ip] = []
32
+
33
+ # Remove old requests
34
+ self.requests[client_ip] = [t for t in self.requests[client_ip] if t > minute_ago]
35
+
36
+ # Check limit
37
+ if len(self.requests[client_ip]) >= limit_per_minute:
38
+ return False
39
+
40
+ # Add current request
41
+ self.requests[client_ip].append(now)
42
+ return True
43
+
44
+ def get_request_count(self, client_ip: str) -> int:
45
+ """Get current request count for a client IP.
46
+
47
+ Args:
48
+ client_ip: IP address of the client
49
+
50
+ Returns:
51
+ Number of requests in the current minute window
52
+ """
53
+ now = time.time()
54
+ minute_ago = now - 60
55
+
56
+ with self.lock:
57
+ if client_ip not in self.requests:
58
+ return 0
59
+
60
+ # Count recent requests
61
+ recent_requests = [t for t in self.requests[client_ip] if t > minute_ago]
62
+ return len(recent_requests)
63
+
64
+ def clear_client(self, client_ip: str) -> None:
65
+ """Clear rate limit data for a specific client.
66
+
67
+ Args:
68
+ client_ip: IP address of the client to clear
69
+ """
70
+ with self.lock:
71
+ if client_ip in self.requests:
72
+ del self.requests[client_ip]
73
+
74
+ def clear_all(self) -> None:
75
+ """Clear all rate limit data."""
76
+ with self.lock:
77
+ self.requests.clear()