reference-api-buddy 0.5.0__tar.gz → 0.5.1__tar.gz

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.
Files changed (35) hide show
  1. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/CHANGELOG.md +20 -0
  2. {reference_api_buddy-0.5.0/reference_api_buddy.egg-info → reference_api_buddy-0.5.1}/PKG-INFO +7 -1
  3. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/README.md +6 -0
  4. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/pyproject.toml +1 -1
  5. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/__init__.py +1 -1
  6. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/config.py +6 -0
  7. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/handler.py +174 -180
  8. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/proxy.py +2 -0
  9. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1/reference_api_buddy.egg-info}/PKG-INFO +7 -1
  10. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/LICENSE +0 -0
  11. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/MANIFEST.in +0 -0
  12. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/cache/__init__.py +0 -0
  13. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/cache/engine.py +0 -0
  14. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/cli.py +0 -0
  15. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/__init__.py +0 -0
  16. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/admin_utils.py +0 -0
  17. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/inflight_tracker.py +0 -0
  18. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/server.py +0 -0
  19. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/core/ttl_manager.py +0 -0
  20. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/database/__init__.py +0 -0
  21. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/database/manager.py +0 -0
  22. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/database/models.py +0 -0
  23. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/monitoring/manager.py +0 -0
  24. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/security/__init__.py +0 -0
  25. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/security/manager.py +0 -0
  26. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/throttling/__init__.py +0 -0
  27. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/throttling/manager.py +0 -0
  28. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/utils/__init__.py +0 -0
  29. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy/utils/logger.py +0 -0
  30. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/SOURCES.txt +0 -0
  31. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/dependency_links.txt +0 -0
  32. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/entry_points.txt +0 -0
  33. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/requires.txt +0 -0
  34. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/top_level.txt +0 -0
  35. {reference_api_buddy-0.5.0 → reference_api_buddy-0.5.1}/setup.cfg +0 -0
@@ -6,6 +6,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
 
9
+ ## [0.5.1] - 2026-11-24
10
+
11
+ ### Fixed
12
+ - **Upstream errors are no longer cached.** Only 2xx responses are stored, so an outage or a 4xx no longer
13
+ blanks a resource for the whole TTL. Throttled (429) responses are not cached either.
14
+ - **Upstream HTTP error statuses are passed through.** A 404 or 503 from upstream now reaches the caller with its
15
+ real status, body and headers instead of a generic 502. Network errors and unmapped upstreams still return 502.
16
+ - **A request answered with a 429 no longer stays in-flight forever.** The request that owns an in-flight entry now
17
+ releases it on every path, so later requests for the same resource get a prompt 429 instead of waiting 60s and
18
+ failing with a 500.
19
+ - **PUT and DELETE requests no longer share an in-flight slot.** They have no cache key and previously all
20
+ deduplicated onto the same entry, so concurrent requests could receive each other's responses.
21
+ - **`cache.max_cache_entries` is read from config.** The cache was capped at 1,000 entries whatever the config said.
22
+ The default stays 1,000; the value must be a positive integer.
23
+ - `reference_api_buddy.__version__` now matches the package version.
24
+
25
+ ### Tests
26
+ - Regression tests for all of the above against a local upstream server.
27
+ - Expiry tests no longer use a hard-coded "far future" timestamp that has since passed.
28
+
9
29
  ## [0.5.0] - 2025-10-20
10
30
 
11
31
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reference-api-buddy
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: HTTP caching proxy module for development environments with reference APIs
5
5
  Author-email: Reference API Buddy Team <tinkermonkey25@gmail.com>
6
6
  Maintainer-email: Reference API Buddy Team <tinkermonkey25@gmail.com>
@@ -79,6 +79,12 @@ A Python caching proxy module designed for reference APIs where the data is non-
79
79
 
80
80
  Currently this doesn't function as a vanilla MITM proxy since none of the upstream sources of interest are `HTTP` and this was built specifically to avoid having to disable `HTTPS` cert validation. If you're looking for a MITM proxy, there are many out there.
81
81
 
82
+ ## Intstall
83
+
84
+ `pip install reference-api-buddy`
85
+
86
+ [https://pypi.org/project/reference-api-buddy/](https://pypi.org/project/reference-api-buddy/)
87
+
82
88
  ## Features
83
89
 
84
90
  - **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
@@ -4,6 +4,12 @@ A Python caching proxy module designed for reference APIs where the data is non-
4
4
 
5
5
  Currently this doesn't function as a vanilla MITM proxy since none of the upstream sources of interest are `HTTP` and this was built specifically to avoid having to disable `HTTPS` cert validation. If you're looking for a MITM proxy, there are many out there.
6
6
 
7
+ ## Intstall
8
+
9
+ `pip install reference-api-buddy`
10
+
11
+ [https://pypi.org/project/reference-api-buddy/](https://pypi.org/project/reference-api-buddy/)
12
+
7
13
  ## Features
8
14
 
9
15
  - **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "reference-api-buddy"
7
- version = "0.5.0"
7
+ version = "0.5.1"
8
8
  description = "HTTP caching proxy module for development environments with reference APIs"
9
9
  readme = "README.md"
10
10
  license = {file = "LICENSE"}
@@ -9,7 +9,7 @@ from reference_api_buddy.core.proxy import CachingProxy, SecurityError
9
9
  from reference_api_buddy.security.manager import SecurityManager
10
10
  from reference_api_buddy.throttling.manager import ThrottleManager
11
11
 
12
- __version__ = "0.2.0"
12
+ __version__ = "0.5.1"
13
13
  __author__ = "Reference API Buddy Team"
14
14
  __email__ = "contact@example.com"
15
15
 
@@ -10,6 +10,7 @@ DEFAULT_CONFIG = {
10
10
  "cache": {
11
11
  "database_path": ":memory:",
12
12
  "max_cache_response_size": 10485760, # 10MB
13
+ "max_cache_entries": 1000, # LRU eviction beyond this many entries
13
14
  "default_ttl_seconds": 86400, # 1 day = 24 * 3600 seconds
14
15
  },
15
16
  "throttling": {"default_requests_per_hour": 1000, "progressive_max_delay": 300},
@@ -74,6 +75,11 @@ class ConfigurationValidator:
74
75
  errors.append("cache.database_path must be a string.")
75
76
  if not isinstance(cache.get("max_cache_response_size", None), int):
76
77
  errors.append("cache.max_cache_response_size must be an integer.")
78
+ max_entries = cache.get("max_cache_entries")
79
+ if max_entries is not None and (
80
+ isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries <= 0
81
+ ):
82
+ errors.append("cache.max_cache_entries must be a positive integer.")
77
83
 
78
84
  # Validate cache TTL
79
85
  default_ttl = cache.get("default_ttl_seconds")
@@ -12,6 +12,7 @@ from http.server import BaseHTTPRequestHandler
12
12
  from typing import Any, Dict
13
13
  from urllib.parse import parse_qs, urlparse
14
14
 
15
+ from reference_api_buddy.database.models import CachedResponse
15
16
  from reference_api_buddy.utils.logger import get_logger
16
17
 
17
18
 
@@ -25,6 +26,138 @@ class RequestProcessingMixin:
25
26
  return self.proxy.logger
26
27
  return get_logger("core.handler")
27
28
 
29
+ def _normalize_upstream_response(self, response_data: bytes, response_headers: dict, real_url: str):
30
+ """Decompress an upstream body and fix its framing headers for the proxy response.
31
+
32
+ Returns:
33
+ Tuple of (response_data, response_headers)
34
+ """
35
+ # Handle compression - be more robust about gzip detection and decompression
36
+ encoding = response_headers.get("Content-Encoding", "").lower()
37
+ decompressed = False
38
+
39
+ # Check if data is gzipped using magic number (more comprehensive check)
40
+ if len(response_data) >= 2 and response_data[:2] == b"\x1f\x8b":
41
+ self.logger.debug(
42
+ f"Detected gzipped data by magic number for {real_url} " f"(first 10 bytes: {response_data[:10].hex()})"
43
+ )
44
+ try:
45
+ decompressed_data = gzip.decompress(response_data)
46
+ response_data = decompressed_data
47
+ decompressed = True
48
+ self.logger.debug(f"Successfully decompressed gzip data for " f"{real_url}")
49
+ except (gzip.BadGzipFile, zlib.error, OSError) as e:
50
+ self.logger.warning(f"Failed to decompress gzipped data for " f"{real_url}: {e}")
51
+ # Keep original data if decompression fails
52
+ elif encoding in ["gzip", "deflate"]:
53
+ self.logger.debug(f"Detected {encoding} encoding via header for " f"{real_url}")
54
+ try:
55
+ if encoding == "gzip":
56
+ decompressed_data = gzip.decompress(response_data)
57
+ elif encoding == "deflate":
58
+ decompressed_data = zlib.decompress(response_data)
59
+ response_data = decompressed_data
60
+ decompressed = True
61
+ self.logger.debug(f"Successfully decompressed {encoding} data for {real_url}")
62
+ except (gzip.BadGzipFile, zlib.error, OSError) as e:
63
+ self.logger.warning(f"Failed to decompress {encoding} data for {real_url}: {e}")
64
+ # Keep original data if decompression fails
65
+
66
+ # Fix headers after decompression
67
+ if decompressed:
68
+ # Remove compression-related headers (case-insensitive)
69
+ response_headers = {
70
+ k: v
71
+ for k, v in response_headers.items()
72
+ if k.lower() not in ["content-encoding", "transfer-encoding", "content-length"]
73
+ }
74
+ # Set correct content length for decompressed data
75
+ response_headers["Content-Length"] = str(len(response_data))
76
+ self.logger.debug(f"Updated headers after decompression: " f"Content-Length={len(response_data)}")
77
+ else:
78
+ # Even if not decompressed, ensure we have proper headers for the proxy response
79
+ # Remove chunked encoding as we'll send the full response at once
80
+ # Remove 'transfer-encoding: chunked' headers efficiently
81
+ response_headers = {
82
+ k: v
83
+ for k, v in response_headers.items()
84
+ if not (k.lower() == "transfer-encoding" and v.lower() == "chunked")
85
+ }
86
+ # Only set Content-Length if not already present (case-insensitive check)
87
+ has_content_length = any(key.lower() == "content-length" for key in response_headers.keys())
88
+ if not has_content_length:
89
+ response_headers["Content-Length"] = str(len(response_data))
90
+ self.logger.debug(f"Removed chunked encoding, set Content-Length={len(response_data)}")
91
+
92
+ return response_data, response_headers
93
+
94
+ @staticmethod
95
+ def _is_cacheable_status(status_code: int) -> bool:
96
+ """Return True if a response with this status may be cached.
97
+
98
+ Only 2xx responses are cached: an upstream error, a throttled request or a
99
+ 304 replayed from the cache would otherwise be served for the full TTL.
100
+ """
101
+ return 200 <= status_code < 300
102
+
103
+ def _throttle_upstream_request(self, domain: str):
104
+ """Apply rate limiting before an upstream request.
105
+
106
+ Sleeps when a short delay keeps the domain within its limits, then records
107
+ the request. When the required delay exceeds max_delay, nothing is recorded.
108
+
109
+ Returns:
110
+ None if the request may proceed, or a (body, 429, headers) response tuple
111
+ if it must be rejected.
112
+ """
113
+ throttle_manager = getattr(self.proxy, "throttle_manager", None)
114
+ if throttle_manager is None:
115
+ return None
116
+
117
+ delay = throttle_manager.get_required_delay(domain)
118
+ if delay == -1.0:
119
+ limit = getattr(throttle_manager, "domain_limits", {}).get(
120
+ domain, getattr(throttle_manager, "default_limit", 1000)
121
+ )
122
+ state = throttle_manager.get_state(domain)
123
+ remaining = max(0, limit - len(state.request_timestamps))
124
+ reset = 1
125
+ if state.request_timestamps:
126
+ reset = int(throttle_manager.time_window - (time.time() - state.request_timestamps[0]))
127
+ max_delay = throttle_manager.max_delay
128
+ self.logger.info(
129
+ f"Throttling upstream request for domain {domain}: "
130
+ f"required delay exceeds max_delay ({max_delay}s), returning 429"
131
+ )
132
+ metrics_collector = getattr(self.proxy, "metrics_collector", None)
133
+ if metrics_collector:
134
+ metrics_collector.record_event(
135
+ "throttle",
136
+ {
137
+ "domain": domain,
138
+ "delay": max_delay,
139
+ "limit": limit,
140
+ "remaining": remaining,
141
+ "reset": reset,
142
+ "cache_miss": True,
143
+ },
144
+ )
145
+ headers = {
146
+ "Retry-After": str(max_delay),
147
+ "X-RateLimit-Limit": str(limit),
148
+ "X-RateLimit-Remaining": str(remaining),
149
+ "X-RateLimit-Reset": str(reset),
150
+ }
151
+ return b"Too Many Requests\n", 429, headers
152
+
153
+ if delay > 0:
154
+ self.logger.info(f"Rate limiting: delaying request to domain {domain} by {delay:.3f}s")
155
+ time.sleep(delay)
156
+
157
+ # Record the request after delay (only for actual upstream requests)
158
+ throttle_manager.record_request(domain)
159
+ return None
160
+
28
161
  def _forward_request(self, method: str, target_url: str, body: bytes = None, headers: dict = None):
29
162
  """Forward request to upstream server and return response data,
30
163
  status, headers."""
@@ -108,63 +241,9 @@ class RequestProcessingMixin:
108
241
  self.logger.debug(f"Received response from {real_url}: {status_code}")
109
242
  self.logger.debug(f"Response headers: {response_headers}")
110
243
 
111
- # Handle compression - be more robust about gzip detection and decompression
112
- encoding = response_headers.get("Content-Encoding", "").lower()
113
- decompressed = False
114
-
115
- # Check if data is gzipped using magic number (more comprehensive check)
116
- if len(response_data) >= 2 and response_data[:2] == b"\x1f\x8b":
117
- self.logger.debug(
118
- f"Detected gzipped data by magic number for {real_url} "
119
- f"(first 10 bytes: {response_data[:10].hex()})"
120
- )
121
- try:
122
- decompressed_data = gzip.decompress(response_data)
123
- response_data = decompressed_data
124
- decompressed = True
125
- self.logger.debug(f"Successfully decompressed gzip data for " f"{real_url}")
126
- except (gzip.BadGzipFile, zlib.error, OSError) as e:
127
- self.logger.warning(f"Failed to decompress gzipped data for " f"{real_url}: {e}")
128
- # Keep original data if decompression fails
129
- elif encoding in ["gzip", "deflate"]:
130
- self.logger.debug(f"Detected {encoding} encoding via header for " f"{real_url}")
131
- try:
132
- if encoding == "gzip":
133
- decompressed_data = gzip.decompress(response_data)
134
- elif encoding == "deflate":
135
- decompressed_data = zlib.decompress(response_data)
136
- response_data = decompressed_data
137
- decompressed = True
138
- self.logger.debug(f"Successfully decompressed {encoding} data for {real_url}")
139
- except (gzip.BadGzipFile, zlib.error, OSError) as e:
140
- self.logger.warning(f"Failed to decompress {encoding} data for {real_url}: {e}")
141
- # Keep original data if decompression fails
142
-
143
- # Fix headers after decompression
144
- if decompressed:
145
- # Remove compression-related headers (case-insensitive)
146
- response_headers = {
147
- k: v
148
- for k, v in response_headers.items()
149
- if k.lower() not in ["content-encoding", "transfer-encoding", "content-length"]
150
- }
151
- # Set correct content length for decompressed data
152
- response_headers["Content-Length"] = str(len(response_data))
153
- self.logger.debug(f"Updated headers after decompression: " f"Content-Length={len(response_data)}")
154
- else:
155
- # Even if not decompressed, ensure we have proper headers for the proxy response
156
- # Remove chunked encoding as we'll send the full response at once
157
- # Remove 'transfer-encoding: chunked' headers efficiently
158
- response_headers = {
159
- k: v
160
- for k, v in response_headers.items()
161
- if not (k.lower() == "transfer-encoding" and v.lower() == "chunked")
162
- }
163
- # Only set Content-Length if not already present (case-insensitive check)
164
- has_content_length = any(key.lower() == "content-length" for key in response_headers.keys())
165
- if not has_content_length:
166
- response_headers["Content-Length"] = str(len(response_data))
167
- self.logger.debug(f"Removed chunked encoding, set Content-Length={len(response_data)}")
244
+ response_data, response_headers = self._normalize_upstream_response(
245
+ response_data, response_headers, real_url
246
+ )
168
247
 
169
248
  # Store upstream metrics for successful requests
170
249
  if domain_key and hasattr(self.proxy, "db_manager"):
@@ -201,10 +280,18 @@ class RequestProcessingMixin:
201
280
  except Exception as store_error:
202
281
  self.logger.debug(f"Failed to store upstream error metrics: {store_error}")
203
282
 
204
- # Handle HTTP errors (4xx, 5xx responses from upstream)
283
+ # Pass the upstream status, body and headers through so callers can tell
284
+ # a 404 from an outage. These responses are never cached (see _is_cacheable_status).
205
285
  self.logger.error(f"HTTP error from upstream {real_url}: {e.code} {e.reason}")
206
- error_msg = f"Upstream HTTP error: {e.code} {e.reason}"
207
- return error_msg.encode("utf-8"), 502, {"Content-Type": "text/plain"}
286
+ try:
287
+ error_body = e.read()
288
+ error_headers = dict(e.headers) if e.headers is not None else {}
289
+ except Exception as read_error:
290
+ self.logger.debug(f"Failed to read upstream error body: {read_error}")
291
+ error_body = f"Upstream HTTP error: {e.code} {e.reason}".encode("utf-8")
292
+ error_headers = {"Content-Type": "text/plain"}
293
+ error_body, error_headers = self._normalize_upstream_response(error_body, error_headers, real_url)
294
+ return error_body, e.code, error_headers
208
295
  except urllib.error.URLError as e:
209
296
  # Calculate response time for network errors
210
297
  response_time_ms = int((time.time() - start_time) * 1000)
@@ -353,16 +440,18 @@ class RequestProcessingMixin:
353
440
  else:
354
441
  self.logger.info(f"Cache miss for key: {cache_key}")
355
442
 
356
- # Check if another thread is already fetching this resource (deduplication)
357
- # Do this BEFORE rate limiting to avoid counting duplicate requests
358
- if hasattr(self.proxy, "inflight_tracker") and self.proxy.inflight_tracker is not None:
359
- inflight_request = self.proxy.inflight_tracker.should_wait(cache_key)
443
+ # Deduplicate concurrent requests for the same resource. Only cacheable
444
+ # methods have a cache key; PUT/DELETE must never share an in-flight slot.
445
+ # Do this BEFORE rate limiting to avoid counting duplicate requests.
446
+ inflight_tracker = getattr(self.proxy, "inflight_tracker", None)
447
+ if cache_key is not None and inflight_tracker is not None:
448
+ inflight_request = inflight_tracker.should_wait(cache_key)
360
449
 
361
450
  if inflight_request is not None:
362
451
  # Another thread is fetching this, wait for its result
363
452
  # Deduplicated requests do NOT count against rate limits
364
453
  self.logger.info(f"Request already in-flight for key: {cache_key}, waiting for result")
365
- result, error = self.proxy.inflight_tracker.wait_for_result(cache_key, inflight_request)
454
+ result, error = inflight_tracker.wait_for_result(cache_key, inflight_request)
366
455
 
367
456
  if error:
368
457
  # The in-flight request failed
@@ -386,129 +475,34 @@ class RequestProcessingMixin:
386
475
  response_data, status_code, headers = result
387
476
  self.logger.info(f"Using deduplicated result for key: {cache_key}")
388
477
  else:
389
- # We're the first thread for this resource
390
- # Apply rate limiting ONLY to the actual upstream request
391
- if hasattr(self.proxy, "throttle_manager") and self.proxy.throttle_manager is not None:
392
- # Use the matched domain key for throttling
393
- domain = matched_domain_key
394
-
395
- # Calculate required delay to stay within rate limits
396
- delay = self.proxy.throttle_manager.get_required_delay(domain)
397
-
398
- if delay == -1.0:
399
- # Delay exceeds max_delay, return 429
400
- limit = getattr(self.proxy.throttle_manager, "domain_limits", {}).get(
401
- domain, getattr(self.proxy.throttle_manager, "default_limit", 1000)
402
- )
403
- state = self.proxy.throttle_manager.get_state(domain)
404
- remaining = max(0, limit - len(state.request_timestamps))
405
- reset = 1
406
- if state.request_timestamps:
407
- reset = int(
408
- self.proxy.throttle_manager.time_window
409
- - (time.time() - state.request_timestamps[0])
410
- )
411
- max_delay = self.proxy.throttle_manager.max_delay
412
- self.logger.info(
413
- f"Throttling upstream request for domain {domain}: "
414
- f"required delay exceeds max_delay ({max_delay}s), returning 429"
415
- )
416
- self.send_response(429)
417
- self.send_header("Retry-After", str(max_delay))
418
- self.send_header("X-RateLimit-Limit", str(limit))
419
- self.send_header("X-RateLimit-Remaining", str(remaining))
420
- self.send_header("X-RateLimit-Reset", str(reset))
421
- if hasattr(self.proxy, "metrics_collector") and self.proxy.metrics_collector:
422
- self.proxy.metrics_collector.record_event(
423
- "throttle",
424
- {
425
- "domain": domain,
426
- "delay": max_delay,
427
- "limit": limit,
428
- "remaining": remaining,
429
- "reset": reset,
430
- "cache_miss": True,
431
- },
432
- )
433
- self.end_headers()
434
- self.wfile.write(b"Too Many Requests\n")
435
- return
436
- elif delay > 0:
437
- # Sleep to stay within rate limits
438
- self.logger.info(f"Rate limiting: delaying request to domain {domain} by {delay:.3f}s")
439
- time.sleep(delay)
440
-
441
- # Record the request after delay (only for actual upstream requests)
442
- self.proxy.throttle_manager.record_request(domain)
443
-
444
- # Make the actual upstream request
478
+ # We're the first thread for this resource, so we own the in-flight
479
+ # entry and must release it on every path, including a 429.
480
+ outcome = None
481
+ failure = None
445
482
  try:
446
- response_data, status_code, headers = self._forward_request(
447
- method, target_url, body, self.headers
448
- )
449
- # Notify waiters of success
450
- self.proxy.inflight_tracker.complete_request(
451
- cache_key, result=(response_data, status_code, headers)
452
- )
483
+ outcome = self._throttle_upstream_request(matched_domain_key)
484
+ if outcome is None:
485
+ outcome = self._forward_request(method, target_url, body, self.headers)
453
486
  except Exception as e:
454
- # Notify waiters of failure
455
- self.proxy.inflight_tracker.complete_request(cache_key, error=e)
487
+ failure = e
456
488
  raise
489
+ finally:
490
+ inflight_tracker.complete_request(cache_key, result=outcome, error=failure)
491
+ response_data, status_code, headers = outcome
457
492
  else:
458
493
  # No deduplication, apply rate limiting and make the request
459
- if hasattr(self.proxy, "throttle_manager") and self.proxy.throttle_manager is not None:
460
- domain = matched_domain_key
461
- delay = self.proxy.throttle_manager.get_required_delay(domain)
462
-
463
- if delay == -1.0:
464
- # Return 429 if delay exceeds tolerance
465
- limit = getattr(self.proxy.throttle_manager, "domain_limits", {}).get(
466
- domain, getattr(self.proxy.throttle_manager, "default_limit", 1000)
467
- )
468
- state = self.proxy.throttle_manager.get_state(domain)
469
- remaining = max(0, limit - len(state.request_timestamps))
470
- reset = 1
471
- if state.request_timestamps:
472
- reset = int(
473
- self.proxy.throttle_manager.time_window
474
- - (time.time() - state.request_timestamps[0])
475
- )
476
- max_delay = self.proxy.throttle_manager.max_delay
477
- self.send_response(429)
478
- self.send_header("Retry-After", str(max_delay))
479
- self.send_header("X-RateLimit-Limit", str(limit))
480
- self.send_header("X-RateLimit-Remaining", str(remaining))
481
- self.send_header("X-RateLimit-Reset", str(reset))
482
- if hasattr(self.proxy, "metrics_collector") and self.proxy.metrics_collector:
483
- self.proxy.metrics_collector.record_event(
484
- "throttle",
485
- {
486
- "domain": domain,
487
- "delay": max_delay,
488
- "limit": limit,
489
- "remaining": remaining,
490
- "reset": reset,
491
- "cache_miss": True,
492
- },
493
- )
494
- self.end_headers()
495
- self.wfile.write(b"Too Many Requests\n")
496
- return
497
- elif delay > 0:
498
- time.sleep(delay)
499
-
500
- self.proxy.throttle_manager.record_request(domain)
494
+ outcome = self._throttle_upstream_request(matched_domain_key)
495
+ if outcome is None:
496
+ outcome = self._forward_request(method, target_url, body, self.headers)
497
+ response_data, status_code, headers = outcome
501
498
 
502
- response_data, status_code, headers = self._forward_request(method, target_url, body, self.headers)
503
-
504
- # Cache the response (data is already decompressed by _forward_request)
499
+ # Cache successful responses only (data is already decompressed by _forward_request).
500
+ # Errors and throttled responses must not blank a resource for the whole TTL.
505
501
  if (
506
- method in ("GET", "POST")
507
- and hasattr(self.proxy, "cache_engine")
508
- and self.proxy.cache_engine is not None
502
+ cache_key is not None
503
+ and self._is_cacheable_status(status_code)
504
+ and getattr(self.proxy, "cache_engine", None) is not None
509
505
  ):
510
- from reference_api_buddy.database.models import CachedResponse
511
-
512
506
  # Create proper CachedResponse object with no explicit TTL (will be set by TTL manager)
513
507
  resp_obj = CachedResponse(
514
508
  data=response_data,
@@ -154,6 +154,7 @@ class CachingProxy:
154
154
  self.db_manager,
155
155
  config=self.config,
156
156
  max_response_size=self.config.get("cache", {}).get("max_cache_response_size", 10485760),
157
+ max_cache_entries=self.config.get("cache", {}).get("max_cache_entries", 1000),
157
158
  )
158
159
  self.throttle_manager = ThrottleManager(
159
160
  self.config.get("throttling", {}), domain_mappings=self.config.get("domain_mappings", {})
@@ -340,6 +341,7 @@ class CachingProxy:
340
341
  self.db_manager,
341
342
  config=self.config,
342
343
  max_response_size=self.config.get("cache", {}).get("max_cache_response_size", 10485760),
344
+ max_cache_entries=self.config.get("cache", {}).get("max_cache_entries", 1000),
343
345
  )
344
346
  self.throttle_manager = ThrottleManager(
345
347
  self.config.get("throttling", {}), domain_mappings=self.config.get("domain_mappings", {})
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reference-api-buddy
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: HTTP caching proxy module for development environments with reference APIs
5
5
  Author-email: Reference API Buddy Team <tinkermonkey25@gmail.com>
6
6
  Maintainer-email: Reference API Buddy Team <tinkermonkey25@gmail.com>
@@ -79,6 +79,12 @@ A Python caching proxy module designed for reference APIs where the data is non-
79
79
 
80
80
  Currently this doesn't function as a vanilla MITM proxy since none of the upstream sources of interest are `HTTP` and this was built specifically to avoid having to disable `HTTPS` cert validation. If you're looking for a MITM proxy, there are many out there.
81
81
 
82
+ ## Intstall
83
+
84
+ `pip install reference-api-buddy`
85
+
86
+ [https://pypi.org/project/reference-api-buddy/](https://pypi.org/project/reference-api-buddy/)
87
+
82
88
  ## Features
83
89
 
84
90
  - **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression