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.
- reference_api_buddy/__init__.py +22 -0
- reference_api_buddy/cache/__init__.py +1 -0
- reference_api_buddy/cache/engine.py +353 -0
- reference_api_buddy/cli.py +167 -0
- reference_api_buddy/core/__init__.py +1 -0
- reference_api_buddy/core/admin_utils.py +77 -0
- reference_api_buddy/core/config.py +171 -0
- reference_api_buddy/core/handler.py +990 -0
- reference_api_buddy/core/proxy.py +416 -0
- reference_api_buddy/core/server.py +40 -0
- reference_api_buddy/core/ttl_manager.py +41 -0
- reference_api_buddy/database/__init__.py +1 -0
- reference_api_buddy/database/manager.py +410 -0
- reference_api_buddy/database/models.py +61 -0
- reference_api_buddy/monitoring/manager.py +186 -0
- reference_api_buddy/security/__init__.py +1 -0
- reference_api_buddy/security/manager.py +161 -0
- reference_api_buddy/throttling/__init__.py +1 -0
- reference_api_buddy/throttling/manager.py +120 -0
- reference_api_buddy/utils/__init__.py +1 -0
- reference_api_buddy/utils/logger.py +225 -0
- reference_api_buddy-0.4.2.dist-info/METADATA +1042 -0
- reference_api_buddy-0.4.2.dist-info/RECORD +27 -0
- reference_api_buddy-0.4.2.dist-info/WHEEL +5 -0
- reference_api_buddy-0.4.2.dist-info/entry_points.txt +2 -0
- reference_api_buddy-0.4.2.dist-info/licenses/LICENSE +21 -0
- reference_api_buddy-0.4.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,990 @@
|
|
|
1
|
+
"""Request processing pipeline for ProxyHTTPRequestHandler."""
|
|
2
|
+
|
|
3
|
+
import datetime
|
|
4
|
+
import gzip
|
|
5
|
+
import time
|
|
6
|
+
import traceback
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
import zlib
|
|
11
|
+
from http.server import BaseHTTPRequestHandler
|
|
12
|
+
from typing import Any, Dict
|
|
13
|
+
from urllib.parse import parse_qs, urlparse
|
|
14
|
+
|
|
15
|
+
from reference_api_buddy.utils.logger import get_logger
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RequestProcessingMixin:
|
|
19
|
+
"""Mixin to add request processing pipeline to ProxyHTTPRequestHandler."""
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def logger(self):
|
|
23
|
+
# Use the proxy's logger if available, else get a default handler logger
|
|
24
|
+
if hasattr(self, "proxy") and hasattr(self.proxy, "logger"):
|
|
25
|
+
return self.proxy.logger
|
|
26
|
+
return get_logger("core.handler")
|
|
27
|
+
|
|
28
|
+
def _forward_request(self, method: str, target_url: str, body: bytes = None, headers: dict = None):
|
|
29
|
+
"""Forward request to upstream server and return response data,
|
|
30
|
+
status, headers."""
|
|
31
|
+
|
|
32
|
+
start_time = time.time()
|
|
33
|
+
domain_key = None
|
|
34
|
+
real_url = None
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
# Map proxy requests to real ones
|
|
38
|
+
domain_mappings = self.proxy.config.get("domain_mappings", {})
|
|
39
|
+
|
|
40
|
+
# Parse the path to extract domain key
|
|
41
|
+
path_parts = target_url.lstrip("/").split("/")
|
|
42
|
+
if path_parts:
|
|
43
|
+
domain_key = path_parts[0]
|
|
44
|
+
if domain_key in domain_mappings:
|
|
45
|
+
upstream = domain_mappings[domain_key].get("upstream", "")
|
|
46
|
+
if upstream:
|
|
47
|
+
# Replace domain key with real upstream URL
|
|
48
|
+
real_path = "/" + "/".join(path_parts[1:]) if len(path_parts) > 1 else "/"
|
|
49
|
+
# Handle query parameters
|
|
50
|
+
if "?" in target_url:
|
|
51
|
+
path_part, query_part = target_url.split("?", 1)
|
|
52
|
+
real_path = "/" + "/".join(path_part.lstrip("/").split("/")[1:])
|
|
53
|
+
if not real_path or real_path == "/":
|
|
54
|
+
real_path = "/"
|
|
55
|
+
real_url = upstream.rstrip("/") + real_path + "?" + query_part
|
|
56
|
+
else:
|
|
57
|
+
real_url = upstream.rstrip("/") + real_path
|
|
58
|
+
else:
|
|
59
|
+
# No upstream configured, return 502 Bad Gateway
|
|
60
|
+
error_msg = f"No upstream configured for domain: {domain_key}"
|
|
61
|
+
self.logger.error(error_msg)
|
|
62
|
+
return error_msg.encode("utf-8"), 502, {"Content-Type": "text/plain"}
|
|
63
|
+
else:
|
|
64
|
+
# Domain not mapped, return 404 Not Found
|
|
65
|
+
error_msg = f"Domain not mapped: {domain_key}"
|
|
66
|
+
self.logger.warning(error_msg)
|
|
67
|
+
return error_msg.encode("utf-8"), 404, {"Content-Type": "text/plain"}
|
|
68
|
+
else:
|
|
69
|
+
# Invalid path, return 400 Bad Request
|
|
70
|
+
error_msg = "Invalid request path"
|
|
71
|
+
self.logger.warning(f"Invalid path: {target_url}")
|
|
72
|
+
return error_msg.encode("utf-8"), 400, {"Content-Type": "text/plain"}
|
|
73
|
+
|
|
74
|
+
self.logger.debug(f"Forwarding {method} request from {target_url} to {real_url}")
|
|
75
|
+
|
|
76
|
+
# Create request
|
|
77
|
+
req = urllib.request.Request(real_url, method=method)
|
|
78
|
+
|
|
79
|
+
# Add headers (filter out problematic ones)
|
|
80
|
+
if headers:
|
|
81
|
+
for key, value in headers.items():
|
|
82
|
+
if key.lower() not in ["host", "connection", "content-length"]:
|
|
83
|
+
req.add_header(key, value)
|
|
84
|
+
|
|
85
|
+
# Ensure we accept gzip encoding
|
|
86
|
+
req.add_header("Accept-Encoding", "gzip, deflate")
|
|
87
|
+
|
|
88
|
+
# Add body for POST requests
|
|
89
|
+
if body and method == "POST":
|
|
90
|
+
req.data = body
|
|
91
|
+
|
|
92
|
+
self.logger.debug(f"Making {method} request to {real_url} with timeout=30")
|
|
93
|
+
self.logger.debug(f"Request headers: {req.headers}")
|
|
94
|
+
|
|
95
|
+
# Make request with longer timeout for external services
|
|
96
|
+
with urllib.request.urlopen(req, timeout=30) as response:
|
|
97
|
+
response_data = response.read()
|
|
98
|
+
status_code = response.getcode()
|
|
99
|
+
response_headers = dict(response.headers)
|
|
100
|
+
|
|
101
|
+
# Calculate response time
|
|
102
|
+
response_time_ms = int((time.time() - start_time) * 1000)
|
|
103
|
+
|
|
104
|
+
self.logger.debug(f"Received response from {real_url}: {status_code}")
|
|
105
|
+
self.logger.debug(f"Response headers: {response_headers}")
|
|
106
|
+
|
|
107
|
+
# Handle compression
|
|
108
|
+
encoding = response_headers.get("Content-Encoding", "").lower()
|
|
109
|
+
decompressed = False
|
|
110
|
+
|
|
111
|
+
# Check if data is gzipped using magic number (more comprehensive check)
|
|
112
|
+
if len(response_data) >= 2 and response_data[:2] == b"\x1f\x8b":
|
|
113
|
+
self.logger.debug(
|
|
114
|
+
f"Detected gzipped data by magic number for {real_url} "
|
|
115
|
+
f"(first 10 bytes: {response_data[:10].hex()})"
|
|
116
|
+
)
|
|
117
|
+
try:
|
|
118
|
+
response_data = gzip.decompress(response_data)
|
|
119
|
+
decompressed = True
|
|
120
|
+
self.logger.debug(f"Successfully decompressed gzip data for " f"{real_url}")
|
|
121
|
+
except Exception as e:
|
|
122
|
+
self.logger.warning(f"Failed to decompress gzipped data for " f"{real_url}: {e}")
|
|
123
|
+
elif encoding in ["gzip", "deflate"]:
|
|
124
|
+
self.logger.debug(f"Detected {encoding} encoding via header for " f"{real_url}")
|
|
125
|
+
try:
|
|
126
|
+
if encoding == "gzip":
|
|
127
|
+
response_data = gzip.decompress(response_data)
|
|
128
|
+
elif encoding == "deflate":
|
|
129
|
+
response_data = zlib.decompress(response_data)
|
|
130
|
+
decompressed = True
|
|
131
|
+
self.logger.debug(f"Successfully decompressed {encoding} data for {real_url}")
|
|
132
|
+
except Exception as e:
|
|
133
|
+
self.logger.warning(f"Failed to decompress {encoding} data for {real_url}: {e}")
|
|
134
|
+
|
|
135
|
+
# Fix headers after decompression
|
|
136
|
+
if decompressed:
|
|
137
|
+
# Remove compression-related headers
|
|
138
|
+
response_headers.pop("Content-Encoding", None)
|
|
139
|
+
# Remove chunked encoding
|
|
140
|
+
response_headers.pop("Transfer-Encoding", None)
|
|
141
|
+
# Set correct content length for decompressed data
|
|
142
|
+
response_headers["Content-Length"] = str(len(response_data))
|
|
143
|
+
self.logger.debug(f"Updated headers after decompression: " f"Content-Length={len(response_data)}")
|
|
144
|
+
else:
|
|
145
|
+
# Even if not decompressed, ensure we have proper headers for the proxy response
|
|
146
|
+
# Remove chunked encoding as we'll send the full response at once
|
|
147
|
+
if "Transfer-Encoding" in response_headers and response_headers["Transfer-Encoding"] == "chunked":
|
|
148
|
+
response_headers.pop("Transfer-Encoding", None)
|
|
149
|
+
response_headers["Content-Length"] = str(len(response_data))
|
|
150
|
+
self.logger.debug(f"Removed chunked encoding, set Content-Length={len(response_data)}")
|
|
151
|
+
|
|
152
|
+
# Store upstream metrics for successful requests
|
|
153
|
+
if domain_key and hasattr(self.proxy, "db_manager"):
|
|
154
|
+
try:
|
|
155
|
+
self.proxy.db_manager.store_upstream_metrics(
|
|
156
|
+
domain=domain_key,
|
|
157
|
+
method=method,
|
|
158
|
+
response_time_ms=response_time_ms,
|
|
159
|
+
response_size_bytes=len(response_data),
|
|
160
|
+
cache_hit=False,
|
|
161
|
+
status_code=status_code,
|
|
162
|
+
)
|
|
163
|
+
except Exception as e:
|
|
164
|
+
self.logger.debug(f"Failed to store upstream metrics: {e}")
|
|
165
|
+
|
|
166
|
+
self.logger.debug(f"Final response: {response_data}")
|
|
167
|
+
return response_data, status_code, response_headers
|
|
168
|
+
|
|
169
|
+
except urllib.error.HTTPError as e:
|
|
170
|
+
# Calculate response time for failed requests too
|
|
171
|
+
response_time_ms = int((time.time() - start_time) * 1000)
|
|
172
|
+
|
|
173
|
+
# Store metrics for HTTP errors
|
|
174
|
+
if domain_key and hasattr(self.proxy, "db_manager"):
|
|
175
|
+
try:
|
|
176
|
+
self.proxy.db_manager.store_upstream_metrics(
|
|
177
|
+
domain=domain_key,
|
|
178
|
+
method=method,
|
|
179
|
+
response_time_ms=response_time_ms,
|
|
180
|
+
response_size_bytes=0,
|
|
181
|
+
cache_hit=False,
|
|
182
|
+
status_code=e.code,
|
|
183
|
+
)
|
|
184
|
+
except Exception as store_error:
|
|
185
|
+
self.logger.debug(f"Failed to store upstream error metrics: {store_error}")
|
|
186
|
+
|
|
187
|
+
# Handle HTTP errors (4xx, 5xx responses from upstream)
|
|
188
|
+
self.logger.error(f"HTTP error from upstream {real_url}: {e.code} {e.reason}")
|
|
189
|
+
error_msg = f"Upstream HTTP error: {e.code} {e.reason}"
|
|
190
|
+
return error_msg.encode("utf-8"), 502, {"Content-Type": "text/plain"}
|
|
191
|
+
except urllib.error.URLError as e:
|
|
192
|
+
# Calculate response time for network errors
|
|
193
|
+
response_time_ms = int((time.time() - start_time) * 1000)
|
|
194
|
+
|
|
195
|
+
# Store metrics for network errors
|
|
196
|
+
if domain_key and hasattr(self.proxy, "db_manager"):
|
|
197
|
+
try:
|
|
198
|
+
self.proxy.db_manager.store_upstream_metrics(
|
|
199
|
+
domain=domain_key,
|
|
200
|
+
method=method,
|
|
201
|
+
response_time_ms=response_time_ms,
|
|
202
|
+
response_size_bytes=0,
|
|
203
|
+
cache_hit=False,
|
|
204
|
+
status_code=502, # Gateway error
|
|
205
|
+
)
|
|
206
|
+
except Exception as store_error:
|
|
207
|
+
self.logger.debug(f"Failed to store upstream network error metrics: {store_error}")
|
|
208
|
+
|
|
209
|
+
# Handle URL/network errors
|
|
210
|
+
self.logger.error(f"Network error accessing upstream {real_url}: {e.reason}")
|
|
211
|
+
error_msg = f"Upstream network error: {e.reason}"
|
|
212
|
+
return error_msg.encode("utf-8"), 502, {"Content-Type": "text/plain"}
|
|
213
|
+
except Exception as e:
|
|
214
|
+
# Calculate response time for general errors
|
|
215
|
+
response_time_ms = int((time.time() - start_time) * 1000)
|
|
216
|
+
|
|
217
|
+
# Store metrics for general errors
|
|
218
|
+
if domain_key and hasattr(self.proxy, "db_manager"):
|
|
219
|
+
try:
|
|
220
|
+
self.proxy.db_manager.store_upstream_metrics(
|
|
221
|
+
domain=domain_key,
|
|
222
|
+
method=method,
|
|
223
|
+
response_time_ms=response_time_ms,
|
|
224
|
+
response_size_bytes=0,
|
|
225
|
+
cache_hit=False,
|
|
226
|
+
status_code=500, # Internal server error
|
|
227
|
+
)
|
|
228
|
+
except Exception as store_error:
|
|
229
|
+
self.logger.debug(f"Failed to store upstream general error metrics: {store_error}")
|
|
230
|
+
|
|
231
|
+
self.logger.error(f"Failed to forward request to {real_url}: {e}")
|
|
232
|
+
# Return 502 Bad Gateway on network/upstream errors
|
|
233
|
+
error_msg = f"Upstream server error: {str(e)}"
|
|
234
|
+
return error_msg.encode("utf-8"), 502, {"Content-Type": "text/plain"}
|
|
235
|
+
|
|
236
|
+
def _handle_request(self, method: str):
|
|
237
|
+
try:
|
|
238
|
+
import time
|
|
239
|
+
|
|
240
|
+
self.logger.debug(f"Handling {method} request for path: {self.path}")
|
|
241
|
+
# 1. Extract and validate secure key
|
|
242
|
+
sanitized_path = self.path
|
|
243
|
+
if hasattr(self.proxy, "security_manager") and self.proxy.security_manager is not None:
|
|
244
|
+
key, sanitized_path = self.proxy.security_manager.extract_secure_key(
|
|
245
|
+
self.path, self.headers, parse_qs(urlparse(self.path).query)
|
|
246
|
+
)
|
|
247
|
+
if self.proxy.config.get("security", {}).get("require_secure_key", False):
|
|
248
|
+
if not key or not self.proxy.security_manager.validate_request(key):
|
|
249
|
+
self.logger.warning("Unauthorized request: Invalid or missing secure key.")
|
|
250
|
+
self.send_response(401)
|
|
251
|
+
self.end_headers()
|
|
252
|
+
self.wfile.write(b"Unauthorized: Invalid or missing secure key\n")
|
|
253
|
+
return
|
|
254
|
+
|
|
255
|
+
# 2. Check for admin endpoints
|
|
256
|
+
if self._is_admin_path(sanitized_path):
|
|
257
|
+
if not self._is_admin_enabled():
|
|
258
|
+
self.send_response(404)
|
|
259
|
+
self.end_headers()
|
|
260
|
+
self.wfile.write(b"Not Found\n")
|
|
261
|
+
return
|
|
262
|
+
|
|
263
|
+
self._handle_admin_request(method, sanitized_path)
|
|
264
|
+
return
|
|
265
|
+
|
|
266
|
+
# 3. Check admin endpoints (stub: /admin/health) - kept for backward compatibility
|
|
267
|
+
if self.path.startswith("/admin/health"):
|
|
268
|
+
self.logger.debug("Health check endpoint hit.")
|
|
269
|
+
self.send_response(200)
|
|
270
|
+
self.end_headers()
|
|
271
|
+
self.wfile.write(b"OK\n")
|
|
272
|
+
return
|
|
273
|
+
# 4. Determine if this request matches a configured domain mapping
|
|
274
|
+
domain_mappings = self.proxy.config.get("domain_mappings", {})
|
|
275
|
+
matched = False
|
|
276
|
+
matched_domain_key = None
|
|
277
|
+
|
|
278
|
+
# Parse the request URL to handle both path-based and full URL requests
|
|
279
|
+
parsed_url = urlparse(self.path)
|
|
280
|
+
request_netloc = parsed_url.netloc
|
|
281
|
+
|
|
282
|
+
for domain_key, mapping in domain_mappings.items():
|
|
283
|
+
# Match by netloc (for full URLs like http://example.com/path)
|
|
284
|
+
if request_netloc and request_netloc == domain_key:
|
|
285
|
+
matched = True
|
|
286
|
+
matched_domain_key = domain_key
|
|
287
|
+
break
|
|
288
|
+
# Match by path prefix (for path-based requests like /example.com/path)
|
|
289
|
+
elif self.path.startswith(f"/{domain_key}/") or self.path == f"/{domain_key}":
|
|
290
|
+
matched = True
|
|
291
|
+
matched_domain_key = domain_key
|
|
292
|
+
break
|
|
293
|
+
# 5. If matched, apply cache-first architecture: check cache before any throttling
|
|
294
|
+
# This ensures cache hits bypass throttling entirely for maximum performance
|
|
295
|
+
if matched:
|
|
296
|
+
target_url = self.path # TODO: domain mapping logic
|
|
297
|
+
|
|
298
|
+
# Read request body for POST requests
|
|
299
|
+
body = self.rfile.read(int(self.headers.get("Content-Length", 0))) if method == "POST" else None
|
|
300
|
+
|
|
301
|
+
# Caching - check cache first before any throttling
|
|
302
|
+
cache_key = None
|
|
303
|
+
cached = None
|
|
304
|
+
if (
|
|
305
|
+
method in ("GET", "POST")
|
|
306
|
+
and hasattr(self.proxy, "cache_engine")
|
|
307
|
+
and self.proxy.cache_engine is not None
|
|
308
|
+
):
|
|
309
|
+
content_type = self.headers.get("Content-Type")
|
|
310
|
+
cache_key = self.proxy.cache_engine.generate_cache_key(method, target_url, body, content_type)
|
|
311
|
+
cached = self.proxy.cache_engine.get(cache_key)
|
|
312
|
+
if cached:
|
|
313
|
+
self.logger.info(f"Cache hit for key: {cache_key} {target_url}")
|
|
314
|
+
|
|
315
|
+
# Store cache hit metrics
|
|
316
|
+
if matched_domain_key and hasattr(self.proxy, "db_manager"):
|
|
317
|
+
try:
|
|
318
|
+
self.proxy.db_manager.store_upstream_metrics(
|
|
319
|
+
domain=matched_domain_key,
|
|
320
|
+
method=method,
|
|
321
|
+
response_time_ms=0, # Cache hits are essentially instantaneous
|
|
322
|
+
response_size_bytes=len(cached.data),
|
|
323
|
+
cache_hit=True,
|
|
324
|
+
status_code=cached.status_code,
|
|
325
|
+
)
|
|
326
|
+
except Exception as e:
|
|
327
|
+
self.logger.debug(f"Failed to store cache hit metrics: {e}")
|
|
328
|
+
|
|
329
|
+
self.send_response(cached.status_code)
|
|
330
|
+
# Send headers (data is already decompressed when cached)
|
|
331
|
+
for k, v in cached.headers.items():
|
|
332
|
+
self.send_header(k, v)
|
|
333
|
+
self.end_headers()
|
|
334
|
+
self.wfile.write(cached.data)
|
|
335
|
+
return
|
|
336
|
+
else:
|
|
337
|
+
self.logger.info(f"Cache miss for key: {cache_key}")
|
|
338
|
+
|
|
339
|
+
# Throttling - only apply when forwarding to upstream (cache miss)
|
|
340
|
+
if hasattr(self.proxy, "throttle_manager") and self.proxy.throttle_manager is not None:
|
|
341
|
+
# Use the matched domain key for throttling
|
|
342
|
+
domain = matched_domain_key
|
|
343
|
+
self.proxy.throttle_manager.record_request(domain)
|
|
344
|
+
if self.proxy.throttle_manager.should_throttle(domain):
|
|
345
|
+
delay = self.proxy.throttle_manager.get_throttle_delay(domain)
|
|
346
|
+
limit = getattr(self.proxy.throttle_manager, "domain_limits", {}).get(
|
|
347
|
+
domain, getattr(self.proxy.throttle_manager, "default_limit", 1000)
|
|
348
|
+
)
|
|
349
|
+
state = self.proxy.throttle_manager.get_state(domain)
|
|
350
|
+
remaining = max(0, limit - len(state.request_timestamps))
|
|
351
|
+
reset = 1
|
|
352
|
+
if state.request_timestamps:
|
|
353
|
+
reset = int(
|
|
354
|
+
self.proxy.throttle_manager.time_window - (time.time() - state.request_timestamps[0])
|
|
355
|
+
)
|
|
356
|
+
self.logger.info(
|
|
357
|
+
f"Throttling upstream request for domain {domain}: "
|
|
358
|
+
f"delay={delay}, limit={limit}, "
|
|
359
|
+
f"remaining={remaining}, reset={reset}"
|
|
360
|
+
)
|
|
361
|
+
self.send_response(429)
|
|
362
|
+
self.send_header("Retry-After", str(delay))
|
|
363
|
+
self.send_header("X-RateLimit-Limit", str(limit))
|
|
364
|
+
self.send_header("X-RateLimit-Remaining", str(remaining))
|
|
365
|
+
self.send_header("X-RateLimit-Reset", str(reset))
|
|
366
|
+
if hasattr(self.proxy, "metrics_collector") and self.proxy.metrics_collector:
|
|
367
|
+
self.proxy.metrics_collector.record_event(
|
|
368
|
+
"throttle",
|
|
369
|
+
{
|
|
370
|
+
"domain": domain,
|
|
371
|
+
"delay": delay,
|
|
372
|
+
"limit": limit,
|
|
373
|
+
"remaining": remaining,
|
|
374
|
+
"reset": reset,
|
|
375
|
+
"cache_miss": True, # Mark this as a cache miss throttle
|
|
376
|
+
},
|
|
377
|
+
)
|
|
378
|
+
self.end_headers()
|
|
379
|
+
self.wfile.write(b"Too Many Requests\n")
|
|
380
|
+
return
|
|
381
|
+
|
|
382
|
+
# Forward to upstream if cache miss
|
|
383
|
+
response_data, status_code, headers = self._forward_request(method, target_url, body, self.headers)
|
|
384
|
+
|
|
385
|
+
# Cache the response (data is already decompressed by _forward_request)
|
|
386
|
+
if (
|
|
387
|
+
method in ("GET", "POST")
|
|
388
|
+
and hasattr(self.proxy, "cache_engine")
|
|
389
|
+
and self.proxy.cache_engine is not None
|
|
390
|
+
):
|
|
391
|
+
from reference_api_buddy.database.models import CachedResponse
|
|
392
|
+
|
|
393
|
+
# Create proper CachedResponse object with no explicit TTL (will be set by TTL manager)
|
|
394
|
+
resp_obj = CachedResponse(
|
|
395
|
+
data=response_data,
|
|
396
|
+
headers=headers,
|
|
397
|
+
status_code=status_code,
|
|
398
|
+
created_at=None, # Will be set by cache engine
|
|
399
|
+
ttl_seconds=None, # Will be determined by TTL manager based on domain
|
|
400
|
+
access_count=0,
|
|
401
|
+
last_accessed=None,
|
|
402
|
+
)
|
|
403
|
+
# Cache with domain information for TTL resolution
|
|
404
|
+
self.proxy.cache_engine.set(cache_key, resp_obj, domain_key=matched_domain_key)
|
|
405
|
+
|
|
406
|
+
# Send response to client
|
|
407
|
+
self.send_response(status_code)
|
|
408
|
+
for k, v in headers.items():
|
|
409
|
+
self.send_header(k, v)
|
|
410
|
+
self.end_headers()
|
|
411
|
+
self.wfile.write(response_data)
|
|
412
|
+
return
|
|
413
|
+
# 5. If not matched, transparently proxy (no cache/throttle)
|
|
414
|
+
# In a real implementation, this would forward the request to the mapped
|
|
415
|
+
# upstream
|
|
416
|
+
self.logger.debug(f"Proxying request for path: {self.path}")
|
|
417
|
+
# Read request body for POST requests
|
|
418
|
+
body = self.rfile.read(int(self.headers.get("Content-Length", 0))) if method == "POST" else None
|
|
419
|
+
response_data, status_code, headers = self._forward_request(method, self.path, body, self.headers)
|
|
420
|
+
self.send_response(status_code)
|
|
421
|
+
for k, v in headers.items():
|
|
422
|
+
self.send_header(k, v)
|
|
423
|
+
self.end_headers()
|
|
424
|
+
self.wfile.write(response_data)
|
|
425
|
+
except Exception as e:
|
|
426
|
+
self.logger.error(f"Exception while handling request: {e}")
|
|
427
|
+
self.send_response(500)
|
|
428
|
+
self.end_headers()
|
|
429
|
+
tb = traceback.format_exc()
|
|
430
|
+
self.wfile.write(f"Internal Server Error\n{tb}".encode())
|
|
431
|
+
|
|
432
|
+
# Admin endpoint methods
|
|
433
|
+
def _is_admin_path(self, path: str) -> bool:
|
|
434
|
+
"""Check if path is an admin endpoint."""
|
|
435
|
+
return path.startswith("/admin/")
|
|
436
|
+
|
|
437
|
+
def _is_admin_enabled(self) -> bool:
|
|
438
|
+
"""Check if admin endpoints are enabled."""
|
|
439
|
+
return self.proxy.config.get("admin", {}).get("enabled", True)
|
|
440
|
+
|
|
441
|
+
def _check_admin_rate_limit(self) -> bool:
|
|
442
|
+
"""Check if request is within admin rate limits."""
|
|
443
|
+
from reference_api_buddy.core.admin_utils import AdminRateLimiter
|
|
444
|
+
|
|
445
|
+
# Use proxy-level rate limiter to share state across requests
|
|
446
|
+
if not hasattr(self.proxy, "_admin_rate_limiter"):
|
|
447
|
+
self.proxy._admin_rate_limiter = AdminRateLimiter()
|
|
448
|
+
|
|
449
|
+
client_ip = self.client_address[0]
|
|
450
|
+
limit = self.proxy.config.get("admin", {}).get("rate_limit_per_minute", 10)
|
|
451
|
+
|
|
452
|
+
return self.proxy._admin_rate_limiter.is_allowed(client_ip, limit)
|
|
453
|
+
|
|
454
|
+
def _handle_admin_request(self, method: str, path: str):
|
|
455
|
+
"""Handle admin endpoint requests with rate limiting and routing."""
|
|
456
|
+
try:
|
|
457
|
+
# Rate limiting check
|
|
458
|
+
if not self._check_admin_rate_limit():
|
|
459
|
+
self._send_admin_error(429, "RATE_LIMIT_EXCEEDED", "Too many requests")
|
|
460
|
+
return
|
|
461
|
+
|
|
462
|
+
# Log admin access
|
|
463
|
+
self._log_admin_access(method, path)
|
|
464
|
+
|
|
465
|
+
# Route to specific admin handler
|
|
466
|
+
if method == "GET":
|
|
467
|
+
self._route_admin_get(path)
|
|
468
|
+
elif method == "POST":
|
|
469
|
+
self._route_admin_post(path)
|
|
470
|
+
else:
|
|
471
|
+
self._send_admin_error(405, "METHOD_NOT_ALLOWED", f"Method {method} not allowed")
|
|
472
|
+
|
|
473
|
+
except Exception as e:
|
|
474
|
+
self.logger.error(f"Admin request error: {e}")
|
|
475
|
+
self._send_admin_error(500, "INTERNAL_ERROR", "Internal server error")
|
|
476
|
+
|
|
477
|
+
def _route_admin_get(self, path: str):
|
|
478
|
+
"""Route GET requests to appropriate admin handlers."""
|
|
479
|
+
if path == "/admin/config":
|
|
480
|
+
self._handle_admin_config()
|
|
481
|
+
elif path == "/admin/status":
|
|
482
|
+
self._handle_admin_status()
|
|
483
|
+
elif path == "/admin/domains":
|
|
484
|
+
self._handle_admin_domains()
|
|
485
|
+
elif path == "/admin/cache":
|
|
486
|
+
self._handle_admin_cache()
|
|
487
|
+
elif path.startswith("/admin/cache/"):
|
|
488
|
+
domain = path.split("/", 3)[3] # Extract domain from /admin/cache/{domain}
|
|
489
|
+
self._handle_admin_cache_domain(domain)
|
|
490
|
+
elif path == "/admin/health": # Keep existing health endpoint
|
|
491
|
+
self._handle_admin_health()
|
|
492
|
+
else:
|
|
493
|
+
self._send_admin_error(404, "ENDPOINT_NOT_FOUND", f"Admin endpoint not found: {path}")
|
|
494
|
+
|
|
495
|
+
def _route_admin_post(self, path: str):
|
|
496
|
+
"""Route POST requests to appropriate admin handlers."""
|
|
497
|
+
if path == "/admin/validate-config":
|
|
498
|
+
self._handle_admin_validate_config()
|
|
499
|
+
else:
|
|
500
|
+
self._send_admin_error(404, "ENDPOINT_NOT_FOUND", f"Admin endpoint not found: {path}")
|
|
501
|
+
|
|
502
|
+
def _send_admin_response(self, status_code: int, data: dict):
|
|
503
|
+
"""Send standardized JSON response for admin endpoints."""
|
|
504
|
+
import json
|
|
505
|
+
|
|
506
|
+
response_data = json.dumps(data, indent=2).encode("utf-8")
|
|
507
|
+
|
|
508
|
+
self.send_response(status_code)
|
|
509
|
+
self.send_header("Content-Type", "application/json")
|
|
510
|
+
self.send_header("Content-Length", str(len(response_data)))
|
|
511
|
+
self.end_headers()
|
|
512
|
+
self.wfile.write(response_data)
|
|
513
|
+
|
|
514
|
+
def _send_admin_error(self, status_code: int, error_code: str, message: str):
|
|
515
|
+
"""Send standardized error response for admin endpoints."""
|
|
516
|
+
from datetime import datetime, timezone
|
|
517
|
+
|
|
518
|
+
error_response = {
|
|
519
|
+
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
|
520
|
+
"success": False,
|
|
521
|
+
"error": message,
|
|
522
|
+
"error_code": error_code,
|
|
523
|
+
}
|
|
524
|
+
self._send_admin_response(status_code, error_response)
|
|
525
|
+
|
|
526
|
+
def _log_admin_access(self, method: str, path: str):
|
|
527
|
+
"""Log admin endpoint access for security auditing."""
|
|
528
|
+
if self.proxy.config.get("admin", {}).get("log_access", True):
|
|
529
|
+
client_ip = self.client_address[0]
|
|
530
|
+
self.logger.info(f"Admin access: {client_ip} {method} {path}")
|
|
531
|
+
|
|
532
|
+
def _handle_admin_health(self):
|
|
533
|
+
"""Handle GET /admin/health - simple health check."""
|
|
534
|
+
self.logger.debug("Health check endpoint hit.")
|
|
535
|
+
response = {"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z", "status": "healthy"}
|
|
536
|
+
self._send_admin_response(200, response)
|
|
537
|
+
|
|
538
|
+
def _handle_admin_config(self):
|
|
539
|
+
"""Handle GET /admin/config - return sanitized configuration."""
|
|
540
|
+
try:
|
|
541
|
+
config_data = self._get_sanitized_config()
|
|
542
|
+
response = {
|
|
543
|
+
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z",
|
|
544
|
+
"proxy_version": "1.0.0", # Could be dynamic from package metadata
|
|
545
|
+
"security_enabled": self.proxy.config.get("security", {}).get("require_secure_key", False),
|
|
546
|
+
"configuration": config_data["config"],
|
|
547
|
+
"sanitized_fields": config_data["sanitized_fields"],
|
|
548
|
+
}
|
|
549
|
+
self._send_admin_response(200, response)
|
|
550
|
+
except Exception as e:
|
|
551
|
+
self.logger.error(f"Config endpoint error: {e}")
|
|
552
|
+
self._send_admin_error(500, "CONFIG_ERROR", "Failed to retrieve configuration")
|
|
553
|
+
|
|
554
|
+
def _get_sanitized_config(self) -> dict:
|
|
555
|
+
"""Return configuration with sensitive data redacted."""
|
|
556
|
+
import copy
|
|
557
|
+
|
|
558
|
+
config = copy.deepcopy(self.proxy.config)
|
|
559
|
+
sanitized_fields = []
|
|
560
|
+
|
|
561
|
+
def sanitize_dict(d, path=""):
|
|
562
|
+
nonlocal sanitized_fields
|
|
563
|
+
for key, value in d.items():
|
|
564
|
+
current_path = f"{path}.{key}" if path else key
|
|
565
|
+
|
|
566
|
+
# Check if field name suggests sensitive data
|
|
567
|
+
if any(sensitive in key.lower() for sensitive in ["key", "secret", "password", "token"]):
|
|
568
|
+
d[key] = "[REDACTED]"
|
|
569
|
+
sanitized_fields.append(current_path)
|
|
570
|
+
elif isinstance(value, dict):
|
|
571
|
+
sanitize_dict(value, current_path)
|
|
572
|
+
|
|
573
|
+
sanitize_dict(config)
|
|
574
|
+
|
|
575
|
+
return {"config": config, "sanitized_fields": sanitized_fields}
|
|
576
|
+
|
|
577
|
+
def _handle_admin_status(self):
|
|
578
|
+
"""Handle GET /admin/status - return system health and metrics."""
|
|
579
|
+
try:
|
|
580
|
+
import time
|
|
581
|
+
|
|
582
|
+
uptime_seconds = int(time.time() - getattr(self.proxy, "start_time", time.time()))
|
|
583
|
+
|
|
584
|
+
components = self._get_component_status()
|
|
585
|
+
metrics = self._get_system_metrics()
|
|
586
|
+
|
|
587
|
+
overall_status = self._determine_overall_status(components)
|
|
588
|
+
|
|
589
|
+
response = {
|
|
590
|
+
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z",
|
|
591
|
+
"status": overall_status,
|
|
592
|
+
"uptime_seconds": uptime_seconds,
|
|
593
|
+
"components": components,
|
|
594
|
+
"metrics": metrics,
|
|
595
|
+
}
|
|
596
|
+
self._send_admin_response(200, response)
|
|
597
|
+
except Exception as e:
|
|
598
|
+
self.logger.error(f"Status endpoint error: {e}")
|
|
599
|
+
self._send_admin_error(500, "STATUS_ERROR", "Failed to retrieve status")
|
|
600
|
+
|
|
601
|
+
def _get_component_status(self) -> dict:
|
|
602
|
+
"""Get status of all proxy components."""
|
|
603
|
+
components = {}
|
|
604
|
+
|
|
605
|
+
# Cache Engine Status
|
|
606
|
+
try:
|
|
607
|
+
if hasattr(self.proxy, "cache_engine") and self.proxy.cache_engine:
|
|
608
|
+
cache_stats = (
|
|
609
|
+
self.proxy.cache_engine.get_stats() if hasattr(self.proxy.cache_engine, "get_stats") else {}
|
|
610
|
+
)
|
|
611
|
+
total_entries = cache_stats.get("cache_size", 0)
|
|
612
|
+
|
|
613
|
+
components["cache_engine"] = {
|
|
614
|
+
"status": "healthy",
|
|
615
|
+
"backend": (
|
|
616
|
+
"sqlite"
|
|
617
|
+
if self.proxy.config.get("cache", {}).get("database_path", ":memory:") != ":memory:"
|
|
618
|
+
else "memory"
|
|
619
|
+
),
|
|
620
|
+
"total_entries": total_entries,
|
|
621
|
+
"database_size_bytes": self._get_database_size(),
|
|
622
|
+
}
|
|
623
|
+
else:
|
|
624
|
+
components["cache_engine"] = {"status": "unavailable"}
|
|
625
|
+
except Exception as e:
|
|
626
|
+
components["cache_engine"] = {"status": "error", "error": str(e)}
|
|
627
|
+
|
|
628
|
+
# Database Manager Status
|
|
629
|
+
try:
|
|
630
|
+
if hasattr(self.proxy, "db_manager") and self.proxy.db_manager:
|
|
631
|
+
components["database_manager"] = {
|
|
632
|
+
"status": "healthy",
|
|
633
|
+
"connection_active": True,
|
|
634
|
+
"last_backup": None, # Could be enhanced with actual backup tracking
|
|
635
|
+
}
|
|
636
|
+
else:
|
|
637
|
+
components["database_manager"] = {"status": "unavailable"}
|
|
638
|
+
except Exception as e:
|
|
639
|
+
components["database_manager"] = {"status": "error", "error": str(e)}
|
|
640
|
+
|
|
641
|
+
# Throttle Manager Status
|
|
642
|
+
try:
|
|
643
|
+
if hasattr(self.proxy, "throttle_manager") and self.proxy.throttle_manager:
|
|
644
|
+
active_throttles = len([s for s in self.proxy.throttle_manager.states.values() if s.delay_seconds > 1])
|
|
645
|
+
components["throttle_manager"] = {"status": "healthy", "active_throttles": active_throttles}
|
|
646
|
+
else:
|
|
647
|
+
components["throttle_manager"] = {"status": "unavailable"}
|
|
648
|
+
except Exception as e:
|
|
649
|
+
components["throttle_manager"] = {"status": "error", "error": str(e)}
|
|
650
|
+
|
|
651
|
+
# Security Manager Status
|
|
652
|
+
try:
|
|
653
|
+
if hasattr(self.proxy, "security_manager") and self.proxy.security_manager:
|
|
654
|
+
components["security_manager"] = {
|
|
655
|
+
"status": "healthy",
|
|
656
|
+
"security_enabled": self.proxy.security_manager.security_enabled,
|
|
657
|
+
}
|
|
658
|
+
else:
|
|
659
|
+
components["security_manager"] = {"status": "unavailable"}
|
|
660
|
+
except Exception as e:
|
|
661
|
+
components["security_manager"] = {"status": "error", "error": str(e)}
|
|
662
|
+
|
|
663
|
+
return components
|
|
664
|
+
|
|
665
|
+
def _get_system_metrics(self) -> dict:
|
|
666
|
+
"""Collect system-wide metrics."""
|
|
667
|
+
metrics = {}
|
|
668
|
+
|
|
669
|
+
try:
|
|
670
|
+
# Use existing monitoring manager if available
|
|
671
|
+
if hasattr(self.proxy, "monitoring_manager") and self.proxy.monitoring_manager:
|
|
672
|
+
cache_stats = self.proxy.monitoring_manager.get_cache_stats()
|
|
673
|
+
upstream_stats = self.proxy.monitoring_manager.get_upstream_stats()
|
|
674
|
+
|
|
675
|
+
metrics["total_requests"] = upstream_stats.get("total_requests", 0)
|
|
676
|
+
metrics["cache_hit_rate"] = cache_stats.get("hit_rate", 0.0)
|
|
677
|
+
metrics["average_response_time_ms"] = upstream_stats.get("average_response_time", 0)
|
|
678
|
+
metrics["errors_last_hour"] = upstream_stats.get("error_count", 0)
|
|
679
|
+
else:
|
|
680
|
+
# Fallback metrics
|
|
681
|
+
metrics = {
|
|
682
|
+
"total_requests": "unavailable",
|
|
683
|
+
"cache_hit_rate": "unavailable",
|
|
684
|
+
"average_response_time_ms": "unavailable",
|
|
685
|
+
"errors_last_hour": "unavailable",
|
|
686
|
+
}
|
|
687
|
+
except Exception as e:
|
|
688
|
+
metrics["error"] = str(e)
|
|
689
|
+
|
|
690
|
+
return metrics
|
|
691
|
+
|
|
692
|
+
def _determine_overall_status(self, components: dict) -> str:
|
|
693
|
+
"""Determine overall system status from component statuses."""
|
|
694
|
+
statuses = [comp.get("status", "unavailable") for comp in components.values()]
|
|
695
|
+
|
|
696
|
+
if "error" in statuses:
|
|
697
|
+
return "error"
|
|
698
|
+
elif "degraded" in statuses:
|
|
699
|
+
return "degraded"
|
|
700
|
+
elif "unavailable" in statuses:
|
|
701
|
+
return "degraded"
|
|
702
|
+
else:
|
|
703
|
+
return "healthy"
|
|
704
|
+
|
|
705
|
+
def _get_database_size(self) -> int:
|
|
706
|
+
"""Get database file size in bytes."""
|
|
707
|
+
try:
|
|
708
|
+
import os
|
|
709
|
+
|
|
710
|
+
db_path = self.proxy.config.get("cache", {}).get("database_path", ":memory:")
|
|
711
|
+
if db_path and db_path != ":memory:" and os.path.exists(db_path):
|
|
712
|
+
return os.path.getsize(db_path)
|
|
713
|
+
return 0
|
|
714
|
+
except Exception:
|
|
715
|
+
return 0
|
|
716
|
+
|
|
717
|
+
def _handle_admin_cache(self):
|
|
718
|
+
"""Handle GET /admin/cache - return cache statistics."""
|
|
719
|
+
try:
|
|
720
|
+
cache_stats = self._get_cache_statistics()
|
|
721
|
+
response = {"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z", **cache_stats}
|
|
722
|
+
self._send_admin_response(200, response)
|
|
723
|
+
except Exception as e:
|
|
724
|
+
self.logger.error(f"Cache endpoint error: {e}")
|
|
725
|
+
self._send_admin_error(500, "CACHE_ERROR", "Failed to retrieve cache statistics")
|
|
726
|
+
|
|
727
|
+
def _handle_admin_cache_domain(self, domain: str):
|
|
728
|
+
"""Handle GET /admin/cache/{domain} - return domain-specific cache data."""
|
|
729
|
+
try:
|
|
730
|
+
domain_stats = self._get_domain_cache_statistics(domain)
|
|
731
|
+
if domain_stats is None:
|
|
732
|
+
self._send_admin_error(404, "DOMAIN_NOT_FOUND", f"Domain not found: {domain}")
|
|
733
|
+
return
|
|
734
|
+
|
|
735
|
+
response = {
|
|
736
|
+
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z",
|
|
737
|
+
"domain": domain,
|
|
738
|
+
**domain_stats,
|
|
739
|
+
}
|
|
740
|
+
self._send_admin_response(200, response)
|
|
741
|
+
except Exception as e:
|
|
742
|
+
self.logger.error(f"Domain cache endpoint error: {e}")
|
|
743
|
+
self._send_admin_error(500, "CACHE_ERROR", f"Failed to retrieve cache data for domain: {domain}")
|
|
744
|
+
|
|
745
|
+
def _get_cache_statistics(self) -> Dict[str, Any]:
|
|
746
|
+
"""Get comprehensive cache statistics."""
|
|
747
|
+
stats: Dict[str, Any] = {}
|
|
748
|
+
|
|
749
|
+
try:
|
|
750
|
+
cache_backend = (
|
|
751
|
+
"sqlite"
|
|
752
|
+
if self.proxy.config.get("cache", {}).get("database_path", ":memory:") != ":memory:"
|
|
753
|
+
else "memory"
|
|
754
|
+
)
|
|
755
|
+
db_path = self.proxy.config.get("cache", {}).get("database_path", ":memory:")
|
|
756
|
+
|
|
757
|
+
stats["cache_backend"] = cache_backend
|
|
758
|
+
stats["database_path"] = db_path if db_path != ":memory:" else "in-memory"
|
|
759
|
+
stats["database_size_bytes"] = self._get_database_size()
|
|
760
|
+
|
|
761
|
+
# Get cache statistics from cache engine
|
|
762
|
+
if hasattr(self.proxy, "cache_engine") and self.proxy.cache_engine:
|
|
763
|
+
cache_stats = (
|
|
764
|
+
self.proxy.cache_engine.get_stats() if hasattr(self.proxy.cache_engine, "get_stats") else {}
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
stats["total_entries"] = cache_stats.get("cache_size", 0)
|
|
768
|
+
stats["expired_entries"] = cache_stats.get("expired_entries", 0)
|
|
769
|
+
|
|
770
|
+
stats["statistics"] = {
|
|
771
|
+
"hit_rate": cache_stats.get("hit_rate", 0.0),
|
|
772
|
+
"total_hits": cache_stats.get("hits", 0),
|
|
773
|
+
"total_misses": cache_stats.get("misses", 0),
|
|
774
|
+
"total_sets": cache_stats.get("sets", 0),
|
|
775
|
+
"compressed_entries": cache_stats.get("compressed", 0),
|
|
776
|
+
"average_entry_size_bytes": cache_stats.get("average_size", 0),
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
# TTL distribution
|
|
780
|
+
default_ttl_count = cache_stats.get("default_ttl_entries", 0)
|
|
781
|
+
custom_ttl_count = cache_stats.get("custom_ttl_entries", 0)
|
|
782
|
+
stats["ttl_distribution"] = {"default_ttl": default_ttl_count, "custom_ttl": custom_ttl_count}
|
|
783
|
+
|
|
784
|
+
# Oldest and newest entries
|
|
785
|
+
stats["oldest_entry"] = cache_stats.get("oldest_entry")
|
|
786
|
+
stats["newest_entry"] = cache_stats.get("newest_entry")
|
|
787
|
+
else:
|
|
788
|
+
stats.update(
|
|
789
|
+
{
|
|
790
|
+
"total_entries": 0,
|
|
791
|
+
"expired_entries": 0,
|
|
792
|
+
"statistics": {
|
|
793
|
+
"hit_rate": 0.0,
|
|
794
|
+
"total_hits": 0,
|
|
795
|
+
"total_misses": 0,
|
|
796
|
+
"total_sets": 0,
|
|
797
|
+
"compressed_entries": 0,
|
|
798
|
+
"average_entry_size_bytes": 0,
|
|
799
|
+
},
|
|
800
|
+
"ttl_distribution": {"default_ttl": 0, "custom_ttl": 0},
|
|
801
|
+
"oldest_entry": None,
|
|
802
|
+
"newest_entry": None,
|
|
803
|
+
}
|
|
804
|
+
)
|
|
805
|
+
|
|
806
|
+
except Exception as e:
|
|
807
|
+
stats["error"] = str(e)
|
|
808
|
+
|
|
809
|
+
return stats
|
|
810
|
+
|
|
811
|
+
def _get_domain_cache_statistics(self, domain: str) -> dict:
|
|
812
|
+
"""Get cache statistics for a specific domain."""
|
|
813
|
+
try:
|
|
814
|
+
# Check if domain exists in domain mappings
|
|
815
|
+
domain_mappings = self.proxy.config.get("domain_mappings", {})
|
|
816
|
+
if domain not in domain_mappings:
|
|
817
|
+
return None
|
|
818
|
+
|
|
819
|
+
# Get domain-specific cache statistics
|
|
820
|
+
stats = {"cache_entries": 0, "total_size_bytes": 0, "hit_rate": 0.0, "entries": []}
|
|
821
|
+
|
|
822
|
+
# Try to get domain-specific stats from cache engine
|
|
823
|
+
if hasattr(self.proxy, "cache_engine") and self.proxy.cache_engine:
|
|
824
|
+
if hasattr(self.proxy.cache_engine, "get_domain_stats"):
|
|
825
|
+
domain_stats = self.proxy.cache_engine.get_domain_stats(domain)
|
|
826
|
+
if domain_stats:
|
|
827
|
+
stats.update(domain_stats)
|
|
828
|
+
|
|
829
|
+
# If the cache engine supports getting entries by domain
|
|
830
|
+
if hasattr(self.proxy.cache_engine, "get_domain_entries"):
|
|
831
|
+
entries = self.proxy.cache_engine.get_domain_entries(domain)
|
|
832
|
+
stats["entries"] = entries[:10] # Limit to 10 entries for response size
|
|
833
|
+
|
|
834
|
+
return stats
|
|
835
|
+
|
|
836
|
+
except Exception as e:
|
|
837
|
+
self.logger.error(f"Error getting domain cache statistics: {e}")
|
|
838
|
+
return None
|
|
839
|
+
|
|
840
|
+
def _handle_admin_domains(self):
|
|
841
|
+
"""Handle GET /admin/domains - return domain mapping status."""
|
|
842
|
+
try:
|
|
843
|
+
domain_stats = self._get_domain_mapping_statistics()
|
|
844
|
+
response = {
|
|
845
|
+
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z",
|
|
846
|
+
"domain_mappings": domain_stats,
|
|
847
|
+
}
|
|
848
|
+
self._send_admin_response(200, response)
|
|
849
|
+
except Exception as e:
|
|
850
|
+
self.logger.error(f"Domains endpoint error: {e}")
|
|
851
|
+
self._send_admin_error(500, "DOMAINS_ERROR", "Failed to retrieve domain statistics")
|
|
852
|
+
|
|
853
|
+
def _get_domain_mapping_statistics(self) -> dict:
|
|
854
|
+
"""Get statistics for all configured domain mappings."""
|
|
855
|
+
domain_stats = {}
|
|
856
|
+
domain_mappings = self.proxy.config.get("domain_mappings", {})
|
|
857
|
+
|
|
858
|
+
for domain_key, mapping in domain_mappings.items():
|
|
859
|
+
try:
|
|
860
|
+
stats = {
|
|
861
|
+
"upstream": mapping.get("upstream", ""),
|
|
862
|
+
"ttl_seconds": mapping.get(
|
|
863
|
+
"ttl_seconds", self.proxy.config.get("cache", {}).get("default_ttl_seconds", 86400)
|
|
864
|
+
),
|
|
865
|
+
"status": "healthy", # Default status
|
|
866
|
+
"last_successful_request": None,
|
|
867
|
+
"total_requests": 0,
|
|
868
|
+
"cache_entries": 0,
|
|
869
|
+
"error_rate": 0.0,
|
|
870
|
+
"last_error": None,
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
# Try to get upstream metrics from monitoring manager
|
|
874
|
+
if hasattr(self.proxy, "monitoring_manager") and self.proxy.monitoring_manager:
|
|
875
|
+
upstream_stats = self.proxy.monitoring_manager.get_upstream_stats()
|
|
876
|
+
|
|
877
|
+
# Look for domain-specific stats
|
|
878
|
+
domain_upstream_stats = upstream_stats.get("domains", {}).get(domain_key, {})
|
|
879
|
+
if domain_upstream_stats:
|
|
880
|
+
stats["total_requests"] = domain_upstream_stats.get("total_requests", 0)
|
|
881
|
+
stats["error_rate"] = domain_upstream_stats.get("error_rate", 0.0)
|
|
882
|
+
stats["last_successful_request"] = domain_upstream_stats.get("last_successful_request")
|
|
883
|
+
stats["last_error"] = domain_upstream_stats.get("last_error")
|
|
884
|
+
|
|
885
|
+
# Determine status based on error rate
|
|
886
|
+
if stats["error_rate"] > 0.5:
|
|
887
|
+
stats["status"] = "error"
|
|
888
|
+
elif stats["error_rate"] > 0.1:
|
|
889
|
+
stats["status"] = "degraded"
|
|
890
|
+
|
|
891
|
+
# Try to get cache entry count for this domain
|
|
892
|
+
if hasattr(self.proxy, "cache_engine") and self.proxy.cache_engine:
|
|
893
|
+
if hasattr(self.proxy.cache_engine, "get_domain_entry_count"):
|
|
894
|
+
stats["cache_entries"] = self.proxy.cache_engine.get_domain_entry_count(domain_key)
|
|
895
|
+
|
|
896
|
+
domain_stats[domain_key] = stats
|
|
897
|
+
|
|
898
|
+
except Exception as e:
|
|
899
|
+
domain_stats[domain_key] = {"upstream": mapping.get("upstream", ""), "status": "error", "error": str(e)}
|
|
900
|
+
|
|
901
|
+
return domain_stats
|
|
902
|
+
|
|
903
|
+
def _handle_admin_validate_config(self):
|
|
904
|
+
"""Handle POST /admin/validate-config - validate configuration without applying."""
|
|
905
|
+
try:
|
|
906
|
+
import json
|
|
907
|
+
from datetime import datetime, timezone
|
|
908
|
+
|
|
909
|
+
# Read and parse request body
|
|
910
|
+
content_length = int(self.headers.get("Content-Length", 0))
|
|
911
|
+
if content_length == 0:
|
|
912
|
+
self._send_admin_error(400, "EMPTY_BODY", "Request body is required")
|
|
913
|
+
return
|
|
914
|
+
|
|
915
|
+
body = self.rfile.read(content_length)
|
|
916
|
+
try:
|
|
917
|
+
request_data = json.loads(body.decode("utf-8"))
|
|
918
|
+
except json.JSONDecodeError:
|
|
919
|
+
self._send_admin_error(400, "INVALID_JSON", "Invalid JSON in request body")
|
|
920
|
+
return
|
|
921
|
+
|
|
922
|
+
config_to_validate = request_data.get("configuration", {})
|
|
923
|
+
|
|
924
|
+
# Validate configuration
|
|
925
|
+
from reference_api_buddy.core.config import ConfigurationValidator
|
|
926
|
+
|
|
927
|
+
merged_config = ConfigurationValidator.merge_with_defaults(config_to_validate)
|
|
928
|
+
is_valid, errors = ConfigurationValidator.validate_config(merged_config)
|
|
929
|
+
|
|
930
|
+
# Generate warnings for missing optional fields
|
|
931
|
+
warnings = self._generate_config_warnings(config_to_validate, merged_config)
|
|
932
|
+
|
|
933
|
+
response = {
|
|
934
|
+
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
|
935
|
+
"valid": is_valid,
|
|
936
|
+
"errors": errors,
|
|
937
|
+
"warnings": warnings,
|
|
938
|
+
"merged_config": merged_config,
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
status_code = 200 if is_valid else 400
|
|
942
|
+
self._send_admin_response(status_code, response)
|
|
943
|
+
|
|
944
|
+
except Exception as e:
|
|
945
|
+
self.logger.error(f"Config validation endpoint error: {e}")
|
|
946
|
+
self._send_admin_error(500, "VALIDATION_ERROR", "Failed to validate configuration")
|
|
947
|
+
|
|
948
|
+
def _generate_config_warnings(self, user_config: dict, merged_config: dict) -> list:
|
|
949
|
+
"""Generate warnings for configuration differences."""
|
|
950
|
+
warnings = []
|
|
951
|
+
|
|
952
|
+
def check_defaults(user_dict, merged_dict, path=""):
|
|
953
|
+
for key, value in merged_dict.items():
|
|
954
|
+
current_path = f"{path}.{key}" if path else key
|
|
955
|
+
|
|
956
|
+
if key not in user_dict:
|
|
957
|
+
if isinstance(value, (str, int, float, bool)):
|
|
958
|
+
warnings.append(f"{current_path} not specified, using default value: {value}")
|
|
959
|
+
elif isinstance(value, dict) and isinstance(user_dict.get(key), dict):
|
|
960
|
+
check_defaults(user_dict[key], value, current_path)
|
|
961
|
+
|
|
962
|
+
try:
|
|
963
|
+
check_defaults(user_config, merged_config)
|
|
964
|
+
except Exception as e:
|
|
965
|
+
warnings.append(f"Warning generation error: {str(e)}")
|
|
966
|
+
|
|
967
|
+
return warnings
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
class ProxyHTTPRequestHandler(RequestProcessingMixin, BaseHTTPRequestHandler):
|
|
971
|
+
"""HTTP request handler for the caching proxy."""
|
|
972
|
+
|
|
973
|
+
server_version = "ReferenceAPIBuddy/1.0"
|
|
974
|
+
|
|
975
|
+
def __init__(self, *args, proxy_instance=None, **kwargs):
|
|
976
|
+
self.proxy = proxy_instance
|
|
977
|
+
self.metrics_collector = getattr(proxy_instance, "metrics_collector", None)
|
|
978
|
+
super().__init__(*args, **kwargs)
|
|
979
|
+
|
|
980
|
+
def do_GET(self):
|
|
981
|
+
self._handle_request("GET")
|
|
982
|
+
|
|
983
|
+
def do_POST(self):
|
|
984
|
+
self._handle_request("POST")
|
|
985
|
+
|
|
986
|
+
def do_PUT(self):
|
|
987
|
+
self._handle_request("PUT")
|
|
988
|
+
|
|
989
|
+
def do_DELETE(self):
|
|
990
|
+
self._handle_request("DELETE")
|