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,1042 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: reference-api-buddy
|
|
3
|
+
Version: 0.4.2
|
|
4
|
+
Summary: HTTP caching proxy module for development environments with reference APIs
|
|
5
|
+
Author-email: Reference API Buddy Team <contact@example.com>
|
|
6
|
+
Maintainer-email: Reference API Buddy Team <contact@example.com>
|
|
7
|
+
License: MIT License
|
|
8
|
+
|
|
9
|
+
Copyright (c) 2025 Tinker Monkey
|
|
10
|
+
|
|
11
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
+
in the Software without restriction, including without limitation the rights
|
|
14
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
+
furnished to do so, subject to the following conditions:
|
|
17
|
+
|
|
18
|
+
The above copyright notice and this permission notice shall be included in all
|
|
19
|
+
copies or substantial portions of the Software.
|
|
20
|
+
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
27
|
+
SOFTWARE.
|
|
28
|
+
|
|
29
|
+
Project-URL: Homepage, https://github.com/tinkermonkey/reference-api-buddy
|
|
30
|
+
Project-URL: Documentation, https://reference-api-buddy.readthedocs.io/
|
|
31
|
+
Project-URL: Repository, https://github.com/tinkermonkey/reference-api-buddy
|
|
32
|
+
Project-URL: Issues, https://github.com/tinkermonkey/reference-api-buddy/issues
|
|
33
|
+
Project-URL: Changelog, https://github.com/tinkermonkey/reference-api-buddy/blob/main/CHANGELOG.md
|
|
34
|
+
Keywords: proxy,caching,api,http,development,rate-limiting
|
|
35
|
+
Classifier: Development Status :: 3 - Alpha
|
|
36
|
+
Classifier: Intended Audience :: Developers
|
|
37
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
38
|
+
Classifier: Programming Language :: Python :: 3
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
43
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
45
|
+
Classifier: Topic :: Internet :: Proxy Servers
|
|
46
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
47
|
+
Classifier: Topic :: System :: Networking
|
|
48
|
+
Requires-Python: >=3.8
|
|
49
|
+
Description-Content-Type: text/markdown
|
|
50
|
+
License-File: LICENSE
|
|
51
|
+
Requires-Dist: requests>=2.32.0
|
|
52
|
+
Requires-Dist: urllib3>=2.5.0
|
|
53
|
+
Requires-Dist: certifi>=2025.8.0
|
|
54
|
+
Requires-Dist: charset-normalizer>=3.4.0
|
|
55
|
+
Requires-Dist: idna>=3.10
|
|
56
|
+
Provides-Extra: dev
|
|
57
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
58
|
+
Requires-Dist: pytest-cov>=4.0; extra == "dev"
|
|
59
|
+
Requires-Dist: pytest-timeout>=2.1; extra == "dev"
|
|
60
|
+
Requires-Dist: black>=23.0; extra == "dev"
|
|
61
|
+
Requires-Dist: isort>=5.12; extra == "dev"
|
|
62
|
+
Requires-Dist: flake8>=6.0; extra == "dev"
|
|
63
|
+
Requires-Dist: mypy>=1.0; extra == "dev"
|
|
64
|
+
Requires-Dist: pre-commit>=3.0; extra == "dev"
|
|
65
|
+
Requires-Dist: autopep8>=2.3.0; extra == "dev"
|
|
66
|
+
Requires-Dist: build>=1.3.0; extra == "dev"
|
|
67
|
+
Requires-Dist: coverage>=7.10.0; extra == "dev"
|
|
68
|
+
Requires-Dist: twine>=6.1.0; extra == "dev"
|
|
69
|
+
Requires-Dist: typing-extensions>=4.14.0; extra == "dev"
|
|
70
|
+
Requires-Dist: pip-audit>=2.9.0; extra == "dev"
|
|
71
|
+
Provides-Extra: docs
|
|
72
|
+
Requires-Dist: sphinx>=6.0; extra == "docs"
|
|
73
|
+
Requires-Dist: sphinx-rtd-theme>=1.3; extra == "docs"
|
|
74
|
+
Requires-Dist: myst-parser>=2.0; extra == "docs"
|
|
75
|
+
Dynamic: license-file
|
|
76
|
+
|
|
77
|
+
# Reference API Buddy
|
|
78
|
+
|
|
79
|
+
A Python caching proxy module designed for reference APIs where the data is non-secure and not changing frequently (ConceptNet, DBpedia, Wikidata, etc). The proxy provides configurable caching, progressive throttling, and detailed metrics to reduce API costs and prevent rate limiting. It is designed to be run on the "client" device, either embedded in a python app or standalone, and to service only specific domains through url manipulation and typically `HTTP` to `HTTPS` (`http://127.0.0.1/conceptnet/query...` -> `https://api.conceptnet.io/query...`). The URL manipulation scheme allows you to not need an `HTTP` proxy at the application level, so most traffic from your app will not pass through API Buddy. The `HTTP` -> `HTTPS` leg obviously meaningfuly shifts the security footprint for these requests, but if you need caching, this can be a lesser evil as you don't need to a) write your own custom API clients if this is only used during the dev cycle and b) ignore certs for `HTTPS` traffic in your app. So while the `HTTPS` security for the traffic to the reference sources is compromised, it leaves the rest of the traffic in your app secure. If your upstream API is highly sensitive and you think someone might be monitoring traffic on your local device, this is not for you.
|
|
80
|
+
|
|
81
|
+
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.
|
|
82
|
+
|
|
83
|
+
## Features
|
|
84
|
+
|
|
85
|
+
- **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
|
|
86
|
+
- **Progressive Throttling**: Domain-specific rate limiting with exponential backoff (applied only to upstream requests)
|
|
87
|
+
- **Proxy Security**: Optional secure key authentication to control proxy access
|
|
88
|
+
- **Upstream Pass-through**: Transparent forwarding of API keys and authentication to upstream APIs
|
|
89
|
+
- **Metrics Collection**: Detailed statistics on cache performance, request patterns, and throttling
|
|
90
|
+
- **Thread-Safe**: Built on Python's `ThreadingHTTPServer` for concurrent request handling
|
|
91
|
+
- **Configurable**: Flexible configuration of domains, limits, and security settings
|
|
92
|
+
|
|
93
|
+
## What It's For
|
|
94
|
+
|
|
95
|
+
While building and tuning LLM pipelines/graphs/bots and NLP pipelines there are frequently external resources available via API that are consumed as part of the pipeline that don't absolutely need to be retrieved fresh from the source of truth each time the pipeline runs. Resources like ConceptNet, DBpedia, Wikidata are amazing resources made publicly available where the data is not changing on a minute-by-minute basis, and for which it would be wonderful to reduce some of the repetititous requests made while testing software. Additionally, there are paid resources like search engines where caching results for a day or so can reduce costs without impacting the efficacy. It could also be possible to cache requests to LLMs themselves, but they mostly offer caching at the token level which is more effective and less disruptive. If you have the resources to run the reference source locally, that is still optimal, but this attempts to strike a balance where that's not feasible.
|
|
96
|
+
|
|
97
|
+
## How It Works
|
|
98
|
+
|
|
99
|
+
The basic premise is that where an API client allows the server URL to be configured, you configure `Reference API Buddy` to handle that traffic by setting the API client URL to `http://127.0.0.1/api_name/` which `Reference API Buddy` will intercept, transform the requests into an upstream URL and `POST` payload caching signature, check the cache, and forward the request if needed, storing the result for subsequent requests before returning it.
|
|
100
|
+
|
|
101
|
+
Optionally you can configure `Reference API Buddy` to use a cryptographic hash as an authorization key and include it in the URL so that only requests made with that key will be handled. The URL pattern for that is `http://127.0.0.1/api_name/secure_key`, or the key can be included in the header (see details below). If enabled, a key will be generated automatically if you don't provide one and made available through `get_secure_key()` (see detail below). If you're using this standalone and need a key, you'll want to pass one in because you'll also need to pass it into the proxy client. This obviously doesn't encrypt the traffic to the proxy, but it does authorize the traffic to ensure other software running on your system cannot untilize the proxy without your involvement. Again, if you're in a highly secure environment, this is likely not for you.
|
|
102
|
+
|
|
103
|
+
### Request Flow
|
|
104
|
+
|
|
105
|
+
```mermaid
|
|
106
|
+
sequenceDiagram
|
|
107
|
+
participant Client
|
|
108
|
+
participant Proxy as CachingProxy
|
|
109
|
+
participant Cache as CacheEngine
|
|
110
|
+
participant Throttle as ThrottleManager
|
|
111
|
+
participant Security as SecurityManager
|
|
112
|
+
participant Upstream as Upstream API
|
|
113
|
+
|
|
114
|
+
Client->>Proxy: HTTP Request (with proxy secure key + upstream auth)
|
|
115
|
+
Proxy->>Security: Validate proxy secure key
|
|
116
|
+
alt Invalid proxy key
|
|
117
|
+
Security-->>Proxy: Invalid
|
|
118
|
+
Proxy-->>Client: 401 Unauthorized
|
|
119
|
+
else Valid proxy key
|
|
120
|
+
Security-->>Proxy: Valid
|
|
121
|
+
Proxy->>Cache: Check cache first
|
|
122
|
+
alt Cache hit
|
|
123
|
+
Cache-->>Proxy: Cached response
|
|
124
|
+
Proxy-->>Client: Cached response (no throttling)
|
|
125
|
+
else Cache miss
|
|
126
|
+
Cache-->>Proxy: Not found
|
|
127
|
+
Proxy->>Throttle: Check rate limits for upstream
|
|
128
|
+
alt Rate limited
|
|
129
|
+
Throttle-->>Proxy: Throttled
|
|
130
|
+
Proxy-->>Client: 429 Too Many Requests
|
|
131
|
+
else Within limits
|
|
132
|
+
Throttle-->>Proxy: OK
|
|
133
|
+
Proxy->>Upstream: Forward request (with upstream auth)
|
|
134
|
+
Upstream-->>Proxy: Response
|
|
135
|
+
Proxy->>Cache: Store response
|
|
136
|
+
Proxy-->>Client: Response
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Class Hierarchy
|
|
143
|
+
|
|
144
|
+
```mermaid
|
|
145
|
+
classDiagram
|
|
146
|
+
class CachingProxy {
|
|
147
|
+
-SecurityManager security_manager
|
|
148
|
+
-CacheEngine cache_engine
|
|
149
|
+
-ThrottleManager throttle_manager
|
|
150
|
+
-DatabaseManager db_manager
|
|
151
|
+
-MetricsCollector metrics_collector
|
|
152
|
+
-ThreadedHTTPServer server
|
|
153
|
+
+start(blocking: bool)
|
|
154
|
+
+stop()
|
|
155
|
+
+get_secure_key() str
|
|
156
|
+
+get_metrics() dict
|
|
157
|
+
+clear_cache(domain: str) int
|
|
158
|
+
+update_config(key_path: str, value: Any)
|
|
159
|
+
+validate_request(path, headers, query_params) tuple
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
class ThreadedHTTPServer {
|
|
163
|
+
-proxy_instance: CachingProxy
|
|
164
|
+
+start(blocking: bool)
|
|
165
|
+
+stop()
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
class ProxyHTTPRequestHandler {
|
|
169
|
+
-proxy: CachingProxy
|
|
170
|
+
-metrics_collector: MetricsCollector
|
|
171
|
+
+do_GET()
|
|
172
|
+
+do_POST()
|
|
173
|
+
+do_PUT()
|
|
174
|
+
+do_DELETE()
|
|
175
|
+
+_handle_request(method: str)
|
|
176
|
+
+_forward_request(method: str, target_url: str, body: bytes, headers: dict)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
class RequestProcessingMixin {
|
|
180
|
+
+_handle_request(method: str)
|
|
181
|
+
+_forward_request(method: str, target_url: str, body: bytes, headers: dict)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
class CacheEngine {
|
|
185
|
+
-DatabaseManager db_manager
|
|
186
|
+
-_lock: threading.Lock
|
|
187
|
+
-_stats: dict
|
|
188
|
+
+get(cache_key: str) CachedResponse
|
|
189
|
+
+set(cache_key: str, response: CachedResponse) bool
|
|
190
|
+
+generate_cache_key(method: str, url: str, body: bytes, content_type: str) str
|
|
191
|
+
+get_cache_performance() dict
|
|
192
|
+
+clear() int
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
class SecurityManager {
|
|
196
|
+
-secure_key: str
|
|
197
|
+
-security_enabled: bool
|
|
198
|
+
+generate_secure_key() str
|
|
199
|
+
+validate_request(provided_key: str) bool
|
|
200
|
+
+extract_secure_key(request_path: str, headers: dict, query_params: dict) tuple
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
class ThrottleManager {
|
|
204
|
+
-states: dict
|
|
205
|
+
-lock: threading.Lock
|
|
206
|
+
+should_throttle(domain: str) bool
|
|
207
|
+
+record_request(domain: str)
|
|
208
|
+
+get_throttle_delay(domain: str) int
|
|
209
|
+
+reset_throttle(domain: str)
|
|
210
|
+
+get_state(domain: str) ThrottleState
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
class DatabaseManager {
|
|
214
|
+
-_pool: List[sqlite3.Connection]
|
|
215
|
+
-_lock: threading.Lock
|
|
216
|
+
+execute_query(query: str, params: tuple) List
|
|
217
|
+
+execute_update(query: str, params: tuple) int
|
|
218
|
+
+get_connection() sqlite3.Connection
|
|
219
|
+
+return_connection(conn: sqlite3.Connection)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
class MetricsCollector {
|
|
223
|
+
-_metrics: dict
|
|
224
|
+
-_events: list
|
|
225
|
+
+record_event(event_type: str, details: dict)
|
|
226
|
+
+get_metrics() dict
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
class ThrottleState {
|
|
230
|
+
+violations: int
|
|
231
|
+
+delay_seconds: int
|
|
232
|
+
+last_violation: float
|
|
233
|
+
+total_requests: int
|
|
234
|
+
+request_timestamps: deque
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
class CachedResponse {
|
|
238
|
+
+data: bytes
|
|
239
|
+
+headers: dict
|
|
240
|
+
+status_code: int
|
|
241
|
+
+created_at: datetime
|
|
242
|
+
+ttl_seconds: int
|
|
243
|
+
+access_count: int
|
|
244
|
+
+last_accessed: datetime
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
CachingProxy --> SecurityManager
|
|
248
|
+
CachingProxy --> CacheEngine
|
|
249
|
+
CachingProxy --> ThrottleManager
|
|
250
|
+
CachingProxy --> DatabaseManager
|
|
251
|
+
CachingProxy --> MetricsCollector
|
|
252
|
+
CachingProxy --> ThreadedHTTPServer
|
|
253
|
+
ThreadedHTTPServer --> ProxyHTTPRequestHandler
|
|
254
|
+
ProxyHTTPRequestHandler --|> RequestProcessingMixin
|
|
255
|
+
CacheEngine --> DatabaseManager
|
|
256
|
+
CacheEngine --> CachedResponse
|
|
257
|
+
ThrottleManager --> ThrottleState
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## Installation
|
|
261
|
+
|
|
262
|
+
### For Development
|
|
263
|
+
|
|
264
|
+
```bash
|
|
265
|
+
git clone https://github.com/tinkermonkey/reference-api-buddy.git
|
|
266
|
+
cd reference-api-buddy
|
|
267
|
+
python -m venv .venv
|
|
268
|
+
source .venv/bin/activate
|
|
269
|
+
pip install -e ".[dev]" # Installs with all development dependencies
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### For Production Use
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
git clone https://github.com/tinkermonkey/reference-api-buddy.git
|
|
276
|
+
cd reference-api-buddy
|
|
277
|
+
python -m venv .venv
|
|
278
|
+
source .venv/bin/activate
|
|
279
|
+
pip install -e . # Installs with production dependencies only
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### As a Package
|
|
283
|
+
|
|
284
|
+
Publishing to PyPi is forthcoming, for now build this locally.
|
|
285
|
+
|
|
286
|
+
### For Local Testing and Building
|
|
287
|
+
|
|
288
|
+
```bash
|
|
289
|
+
git clone https://github.com/tinkermonkey/reference-api-buddy.git
|
|
290
|
+
cd reference-api-buddy
|
|
291
|
+
python -m venv .venv
|
|
292
|
+
source .venv/bin/activate
|
|
293
|
+
pip install -e ".[dev]" # Includes build tools
|
|
294
|
+
python -m build --wheel
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
## Usage
|
|
298
|
+
|
|
299
|
+
### Basic Usage
|
|
300
|
+
|
|
301
|
+
```python
|
|
302
|
+
from reference_api_buddy import CachingProxy
|
|
303
|
+
|
|
304
|
+
# Configure domain mappings
|
|
305
|
+
config = {
|
|
306
|
+
"domain_mappings": {
|
|
307
|
+
"conceptnet": {
|
|
308
|
+
"upstream": "https://api.conceptnet.io",
|
|
309
|
+
"ttl_seconds": 7200 # Optional: 2 hours for ConceptNet
|
|
310
|
+
},
|
|
311
|
+
"dbpedia": {
|
|
312
|
+
"upstream": "https://lookup.dbpedia.org",
|
|
313
|
+
"ttl_seconds": 86400 # Optional: 1 day for DBpedia
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
"cache": {
|
|
317
|
+
"default_ttl_seconds": 43200 # 12 hours default
|
|
318
|
+
},
|
|
319
|
+
"server": {
|
|
320
|
+
"host": "127.0.0.1",
|
|
321
|
+
"port": 8080
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
# Start the proxy
|
|
326
|
+
proxy = CachingProxy(config)
|
|
327
|
+
proxy.start(blocking=False)
|
|
328
|
+
|
|
329
|
+
# Make requests through the proxy
|
|
330
|
+
# http://localhost:8080/conceptnet/c/en/example
|
|
331
|
+
# http://localhost:8080/dbpedia/api/search?query=python
|
|
332
|
+
|
|
333
|
+
# Get secure key if security is enabled
|
|
334
|
+
secure_key = proxy.get_secure_key()
|
|
335
|
+
print(f"Secure key: {secure_key}")
|
|
336
|
+
|
|
337
|
+
# Stop the proxy
|
|
338
|
+
proxy.stop()
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### Advanced Configuration
|
|
342
|
+
|
|
343
|
+
```python
|
|
344
|
+
config = {
|
|
345
|
+
"domain_mappings": {
|
|
346
|
+
"conceptnet": {
|
|
347
|
+
"upstream": "https://api.conceptnet.io",
|
|
348
|
+
"ttl_seconds": 3600 # 1 hour for frequently changing data
|
|
349
|
+
},
|
|
350
|
+
"wikidata": {
|
|
351
|
+
"upstream": "https://www.wikidata.org",
|
|
352
|
+
"ttl_seconds": 86400 # 1 day for more stable data
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
"server": {
|
|
356
|
+
"host": "127.0.0.1",
|
|
357
|
+
"port": 8080
|
|
358
|
+
},
|
|
359
|
+
"security": {
|
|
360
|
+
"require_secure_key": True,
|
|
361
|
+
"secure_key": "your-secure-key-here", # Optionally pass in your own key if desired
|
|
362
|
+
"log_security_events": True
|
|
363
|
+
},
|
|
364
|
+
"cache": {
|
|
365
|
+
"database_path": "./cache.db",
|
|
366
|
+
"max_cache_response_size": 10485760, # 10MB
|
|
367
|
+
"max_cache_entries": 10000,
|
|
368
|
+
"default_ttl_seconds": 86400 # 1 day default for all domains
|
|
369
|
+
},
|
|
370
|
+
"throttling": {
|
|
371
|
+
"default_requests_per_hour": 1000,
|
|
372
|
+
"progressive_max_delay": 300,
|
|
373
|
+
"domain_limits": {
|
|
374
|
+
"conceptnet": 500,
|
|
375
|
+
"wikidata": 200
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
"logging": {
|
|
379
|
+
"level": "INFO",
|
|
380
|
+
"parent_logger": None, # Pass in your logger if desired
|
|
381
|
+
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
382
|
+
"date_format": "%Y-%m-%d %H:%M:%S",
|
|
383
|
+
"enable_console": True,
|
|
384
|
+
"enable_file": False,
|
|
385
|
+
"file_path": None,
|
|
386
|
+
"max_file_size": 10485760,
|
|
387
|
+
"backup_count": 5,
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
proxy = CachingProxy(config)
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
### Cache-First Throttling Behavior
|
|
395
|
+
|
|
396
|
+
The proxy implements a **cache-first architecture** where caching takes priority over throttling:
|
|
397
|
+
|
|
398
|
+
```python
|
|
399
|
+
# Example demonstrating cache-first throttling
|
|
400
|
+
config = {
|
|
401
|
+
"domain_mappings": {
|
|
402
|
+
"api": {"upstream": "https://api.example.com"}
|
|
403
|
+
},
|
|
404
|
+
"throttling": {
|
|
405
|
+
"domain_limits": {"api": 2} # Very restrictive: 2 requests per hour
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
proxy = CachingProxy(config)
|
|
410
|
+
proxy.start(blocking=False)
|
|
411
|
+
|
|
412
|
+
# First request: goes to upstream, gets cached
|
|
413
|
+
response1 = requests.get("http://localhost:8080/api/data") # ✓ 200 OK (upstream)
|
|
414
|
+
|
|
415
|
+
# Second request: cache hit, bypasses throttling entirely
|
|
416
|
+
response2 = requests.get("http://localhost:8080/api/data") # ✓ 200 OK (cache hit)
|
|
417
|
+
|
|
418
|
+
# Third request: same endpoint, still cache hit
|
|
419
|
+
response3 = requests.get("http://localhost:8080/api/data") # ✓ 200 OK (cache hit)
|
|
420
|
+
|
|
421
|
+
# Fourth request: different endpoint, cache miss, hits throttle limit
|
|
422
|
+
response4 = requests.get("http://localhost:8080/api/other") # ✗ 429 Throttled (cache miss)
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
**Key Benefits:**
|
|
426
|
+
- **Cache hits are instant** - No throttling delays for cached responses
|
|
427
|
+
- **Upstream APIs are protected** - Throttling only applies to actual upstream requests
|
|
428
|
+
- **Better user experience** - Frequently requested data remains fast
|
|
429
|
+
- **Cost optimization** - Reduces upstream API usage and associated costs
|
|
430
|
+
|
|
431
|
+
### TTL (Time To Live) Configuration
|
|
432
|
+
|
|
433
|
+
The proxy supports flexible TTL configuration at both system-wide and per-domain levels:
|
|
434
|
+
|
|
435
|
+
#### System Default TTL
|
|
436
|
+
Configure a default TTL for all cached responses:
|
|
437
|
+
|
|
438
|
+
```python
|
|
439
|
+
config = {
|
|
440
|
+
"cache": {
|
|
441
|
+
"default_ttl_seconds": 86400 # 1 day default (24 * 3600 seconds)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
#### Domain-Specific TTL
|
|
447
|
+
Override the default TTL for specific domains based on data volatility:
|
|
448
|
+
|
|
449
|
+
```python
|
|
450
|
+
config = {
|
|
451
|
+
"cache": {
|
|
452
|
+
"default_ttl_seconds": 86400 # 1 day default
|
|
453
|
+
},
|
|
454
|
+
"domain_mappings": {
|
|
455
|
+
"weather": {
|
|
456
|
+
"upstream": "https://api.weather.com",
|
|
457
|
+
"ttl_seconds": 3600 # 1 hour for weather data
|
|
458
|
+
},
|
|
459
|
+
"reference": {
|
|
460
|
+
"upstream": "https://api.reference.com",
|
|
461
|
+
"ttl_seconds": 604800 # 1 week for reference data
|
|
462
|
+
},
|
|
463
|
+
"news": {
|
|
464
|
+
"upstream": "https://api.news.com",
|
|
465
|
+
"ttl_seconds": 1800 # 30 minutes for news
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
#### TTL Behavior
|
|
472
|
+
- **Fallback**: Domains without specific TTL use the system default
|
|
473
|
+
- **Priority**: Domain-specific TTL always overrides the system default
|
|
474
|
+
- **Units**: All TTL values are in seconds for precise control
|
|
475
|
+
- **Validation**: TTL values must be positive integers
|
|
476
|
+
|
|
477
|
+
#### Example TTL Use Cases
|
|
478
|
+
|
|
479
|
+
```python
|
|
480
|
+
# Fast-changing data (stock prices, live feeds)
|
|
481
|
+
"stocks": {"upstream": "https://api.stocks.com", "ttl_seconds": 300} # 5 minutes
|
|
482
|
+
|
|
483
|
+
# Moderate-changing data (weather, news)
|
|
484
|
+
"weather": {"upstream": "https://api.weather.com", "ttl_seconds": 3600} # 1 hour
|
|
485
|
+
|
|
486
|
+
# Stable reference data (dictionaries, ontologies)
|
|
487
|
+
"wordnet": {"upstream": "https://api.wordnet.com", "ttl_seconds": 604800} # 1 week
|
|
488
|
+
|
|
489
|
+
# Very stable data (historical facts, archived content)
|
|
490
|
+
"archive": {"upstream": "https://api.archive.com", "ttl_seconds": 2592000} # 30 days
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
For comprehensive TTL configuration examples, see `example_ttl_config.json`. For migration from older configurations, see `documentation/02_ttl_config/02.4_ttl_migration_guide.md`.
|
|
494
|
+
|
|
495
|
+
To see TTL configuration examples in action, run:
|
|
496
|
+
```bash
|
|
497
|
+
python demo_ttl_config.py
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
### Security Examples
|
|
501
|
+
|
|
502
|
+
```python
|
|
503
|
+
# Example 1: No security (open proxy for development)
|
|
504
|
+
config_open = {
|
|
505
|
+
"domain_mappings": {
|
|
506
|
+
"conceptnet": {"upstream": "https://api.conceptnet.io"}
|
|
507
|
+
},
|
|
508
|
+
"security": {
|
|
509
|
+
"require_secure_key": False # No proxy security required
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
# Example 2: Proxy security enabled (clients must provide proxy key)
|
|
514
|
+
config_secure = {
|
|
515
|
+
"domain_mappings": {
|
|
516
|
+
"openai": {"upstream": "https://api.openai.com"}
|
|
517
|
+
},
|
|
518
|
+
"security": {
|
|
519
|
+
"require_secure_key": True,
|
|
520
|
+
"secure_key": "my-proxy-secret-key" # (optional) This can be passed in or a key will be generated
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
# Client requests would need the proxy key:
|
|
525
|
+
# curl -H "X-API-Buddy-Key: my-proxy-secret-key" \
|
|
526
|
+
# -H "Authorization: Bearer sk-openai-api-key" \
|
|
527
|
+
# http://localhost:8080/openai/v1/completions
|
|
528
|
+
|
|
529
|
+
# Example 3: The proxy handles both security layers independently
|
|
530
|
+
proxy = CachingProxy(config_secure)
|
|
531
|
+
proxy.start(blocking=False)
|
|
532
|
+
|
|
533
|
+
# The proxy will:
|
|
534
|
+
# 1. Validate the proxy secure key (if required)
|
|
535
|
+
# 2. Forward the upstream Authorization header to the upstream API
|
|
536
|
+
# 3. Cache the response for future requests with the same parameters
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
## API Endpoints
|
|
540
|
+
|
|
541
|
+
### Proxy Endpoints
|
|
542
|
+
- `GET/POST /{domain}/{path}` - Proxy requests to configured upstream APIs
|
|
543
|
+
- `GET /admin/health` - Health check endpoint
|
|
544
|
+
|
|
545
|
+
### Security
|
|
546
|
+
|
|
547
|
+
The proxy provides two levels of security:
|
|
548
|
+
|
|
549
|
+
#### 1. Proxy Access Control (Optional)
|
|
550
|
+
When `require_secure_key` is enabled, the proxy requires its own secure key for **all requests**. The proxy will accept the secure key via:
|
|
551
|
+
- **Header**: `X-API-Buddy-Key: your-proxy-key`
|
|
552
|
+
- **Bearer Token**: `Authorization: Bearer your-proxy-key`
|
|
553
|
+
- **Query Parameter**: `?key=your-proxy-key`
|
|
554
|
+
- **Path Prefix**: `/{your-proxy-key}/domain/path`
|
|
555
|
+
|
|
556
|
+
**Note**: The proxy validates the secure key before any caching, throttling, or forwarding occurs. If security is disabled (`require_secure_key: false`), all requests are allowed through regardless of whether a key is provided.
|
|
557
|
+
|
|
558
|
+
#### 2. Upstream API Authentication (Pass-through)
|
|
559
|
+
The proxy transparently forwards authentication headers and tokens to upstream APIs. Common patterns include:
|
|
560
|
+
- **API Keys**: `X-API-Key: your-upstream-api-key`
|
|
561
|
+
- **Bearer Tokens**: `Authorization: Bearer your-upstream-token`
|
|
562
|
+
- **Custom Headers**: Any authentication headers required by the upstream API
|
|
563
|
+
|
|
564
|
+
**Example with both security layers:**
|
|
565
|
+
```bash
|
|
566
|
+
# Request with proxy security + upstream API key
|
|
567
|
+
curl -H "X-API-Buddy-Key: proxy-secure-key-123" \
|
|
568
|
+
-H "X-API-Key: upstream-api-key-456" \
|
|
569
|
+
http://localhost:8080/conceptnet/c/en/example
|
|
570
|
+
|
|
571
|
+
# Or using path-based proxy key + upstream auth header
|
|
572
|
+
curl -H "Authorization: Bearer upstream-token-789" \
|
|
573
|
+
http://localhost:8080/proxy-secure-key-123/wikidata/w/api.php?action=query
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
## Monitoring and Metrics
|
|
577
|
+
|
|
578
|
+
The proxy provides comprehensive operational metrics through the `MonitoringManager`. You can access detailed statistics about cache performance, upstream API usage, database health, proxy status, and throttling behavior.
|
|
579
|
+
|
|
580
|
+
### Accessing Metrics
|
|
581
|
+
|
|
582
|
+
```python
|
|
583
|
+
from reference_api_buddy import CachingProxy
|
|
584
|
+
|
|
585
|
+
# Configure and start proxy
|
|
586
|
+
proxy = CachingProxy(config)
|
|
587
|
+
proxy.start(blocking=False)
|
|
588
|
+
|
|
589
|
+
# Get monitoring manager with convenient method
|
|
590
|
+
monitoring = proxy.get_monitoring_manager()
|
|
591
|
+
|
|
592
|
+
# Get all metrics at once
|
|
593
|
+
all_stats = {
|
|
594
|
+
'cache': monitoring.get_cache_stats(),
|
|
595
|
+
'upstream': monitoring.get_upstream_stats(),
|
|
596
|
+
'database': monitoring.get_database_stats(),
|
|
597
|
+
'proxy_health': monitoring.get_proxy_health(),
|
|
598
|
+
'throttling': monitoring.get_throttling_stats()
|
|
599
|
+
}
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
### Cache Metrics
|
|
603
|
+
|
|
604
|
+
Monitor cache performance, hit rates, and storage efficiency:
|
|
605
|
+
|
|
606
|
+
```python
|
|
607
|
+
cache_stats = monitoring.get_cache_stats()
|
|
608
|
+
print(cache_stats)
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
**Example Output:**
|
|
612
|
+
```python
|
|
613
|
+
{
|
|
614
|
+
'total_entries': 1247,
|
|
615
|
+
'entries_per_domain': {
|
|
616
|
+
'conceptnet': 892,
|
|
617
|
+
'dbpedia': 355
|
|
618
|
+
},
|
|
619
|
+
'cache_size_bytes': 2485760,
|
|
620
|
+
'cache_size_per_domain': {
|
|
621
|
+
'conceptnet': 1847320,
|
|
622
|
+
'dbpedia': 638440
|
|
623
|
+
},
|
|
624
|
+
'hit_count': 3420,
|
|
625
|
+
'miss_count': 1247,
|
|
626
|
+
'hit_rate': 0.733,
|
|
627
|
+
'miss_rate': 0.267,
|
|
628
|
+
'sets': 1247,
|
|
629
|
+
'compressed': 892,
|
|
630
|
+
'decompressed': 3420,
|
|
631
|
+
'ttl_distribution': {
|
|
632
|
+
'expired': 23,
|
|
633
|
+
'valid': 1224,
|
|
634
|
+
'average_ttl_remaining': 18360
|
|
635
|
+
},
|
|
636
|
+
'expired_entries': 23,
|
|
637
|
+
'evicted_entries': 0
|
|
638
|
+
}
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
### Upstream API Metrics
|
|
642
|
+
|
|
643
|
+
Track API response times, error rates, and domain-specific performance:
|
|
644
|
+
|
|
645
|
+
```python
|
|
646
|
+
upstream_stats = monitoring.get_upstream_stats()
|
|
647
|
+
print(upstream_stats)
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
**Example Output:**
|
|
651
|
+
```python
|
|
652
|
+
{
|
|
653
|
+
'overall': {
|
|
654
|
+
'total_requests': 1247,
|
|
655
|
+
'avg_response_time_ms': 245.3,
|
|
656
|
+
'success_rate': 0.967,
|
|
657
|
+
'error_rate': 0.033,
|
|
658
|
+
'requests_per_hour': 89.1,
|
|
659
|
+
'errors_by_status': {
|
|
660
|
+
'200': 1206,
|
|
661
|
+
'404': 28,
|
|
662
|
+
'500': 8,
|
|
663
|
+
'503': 5,
|
|
664
|
+
'timeout': 0
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
'by_domain': {
|
|
668
|
+
'conceptnet': {
|
|
669
|
+
'total_requests': 892,
|
|
670
|
+
'avg_response_time_ms': 198.7,
|
|
671
|
+
'success_rate': 0.982,
|
|
672
|
+
'error_rate': 0.018,
|
|
673
|
+
'requests_per_hour': 63.7,
|
|
674
|
+
'errors_by_status': {
|
|
675
|
+
'200': 876,
|
|
676
|
+
'404': 12,
|
|
677
|
+
'500': 3,
|
|
678
|
+
'503': 1,
|
|
679
|
+
'timeout': 0
|
|
680
|
+
}
|
|
681
|
+
},
|
|
682
|
+
'dbpedia': {
|
|
683
|
+
'total_requests': 355,
|
|
684
|
+
'avg_response_time_ms': 367.2,
|
|
685
|
+
'success_rate': 0.930,
|
|
686
|
+
'error_rate': 0.070,
|
|
687
|
+
'requests_per_hour': 25.4,
|
|
688
|
+
'errors_by_status': {
|
|
689
|
+
'200': 330,
|
|
690
|
+
'404': 16,
|
|
691
|
+
'500': 5,
|
|
692
|
+
'503': 4,
|
|
693
|
+
'timeout': 0
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
```
|
|
699
|
+
|
|
700
|
+
### Database Health
|
|
701
|
+
|
|
702
|
+
Monitor database file size, connection health, and storage usage:
|
|
703
|
+
|
|
704
|
+
```python
|
|
705
|
+
db_stats = monitoring.get_database_stats()
|
|
706
|
+
print(db_stats)
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
**Example Output:**
|
|
710
|
+
```python
|
|
711
|
+
{
|
|
712
|
+
'db_file_path': '/path/to/api_buddy_cache.db',
|
|
713
|
+
'db_file_size_bytes': 2847392,
|
|
714
|
+
'db_health': 'healthy',
|
|
715
|
+
'in_memory_cache_size': 'unavailable'
|
|
716
|
+
}
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
### Proxy Health
|
|
720
|
+
|
|
721
|
+
Track proxy uptime, active connections, and system health:
|
|
722
|
+
|
|
723
|
+
```python
|
|
724
|
+
health_stats = monitoring.get_proxy_health()
|
|
725
|
+
print(health_stats)
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
**Example Output:**
|
|
729
|
+
```python
|
|
730
|
+
{
|
|
731
|
+
'uptime_seconds': 3647.2,
|
|
732
|
+
'active_threads': 8,
|
|
733
|
+
'recent_errors': []
|
|
734
|
+
}
|
|
735
|
+
```
|
|
736
|
+
|
|
737
|
+
### Throttling Metrics
|
|
738
|
+
|
|
739
|
+
Monitor rate limiting behavior, domain-specific limits, and throttling effectiveness:
|
|
740
|
+
|
|
741
|
+
```python
|
|
742
|
+
throttle_stats = monitoring.get_throttling_stats()
|
|
743
|
+
print(throttle_stats)
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
**Example Output:**
|
|
747
|
+
```python
|
|
748
|
+
{
|
|
749
|
+
'requests_per_domain': {
|
|
750
|
+
'conceptnet': {
|
|
751
|
+
'current_hour_requests': 63,
|
|
752
|
+
'total_requests': 892,
|
|
753
|
+
'violations': 2,
|
|
754
|
+
'current_delay_seconds': 4
|
|
755
|
+
},
|
|
756
|
+
'dbpedia': {
|
|
757
|
+
'current_hour_requests': 25,
|
|
758
|
+
'total_requests': 355,
|
|
759
|
+
'violations': 0,
|
|
760
|
+
'current_delay_seconds': 1
|
|
761
|
+
}
|
|
762
|
+
},
|
|
763
|
+
'throttle_state': {
|
|
764
|
+
'conceptnet': {
|
|
765
|
+
'is_throttled': True,
|
|
766
|
+
'violations': 2,
|
|
767
|
+
'delay_seconds': 4,
|
|
768
|
+
'last_violation': 1650123456.78
|
|
769
|
+
},
|
|
770
|
+
'dbpedia': {
|
|
771
|
+
'is_throttled': False,
|
|
772
|
+
'violations': 0,
|
|
773
|
+
'delay_seconds': 1,
|
|
774
|
+
'last_violation': 0.0
|
|
775
|
+
}
|
|
776
|
+
},
|
|
777
|
+
'default_requests_per_hour': 1000,
|
|
778
|
+
'progressive_max_delay': 300,
|
|
779
|
+
'progressive_enabled': True,
|
|
780
|
+
'domain_limits': {
|
|
781
|
+
'conceptnet': 500,
|
|
782
|
+
'dbpedia': 200
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
### Monitoring in Production
|
|
788
|
+
|
|
789
|
+
For production monitoring, consider periodic metric collection:
|
|
790
|
+
|
|
791
|
+
```python
|
|
792
|
+
import time
|
|
793
|
+
import json
|
|
794
|
+
|
|
795
|
+
def monitor_proxy_health(proxy, interval_seconds=60):
|
|
796
|
+
"""Collect and log proxy metrics periodically."""
|
|
797
|
+
monitoring = proxy.get_monitoring_manager()
|
|
798
|
+
|
|
799
|
+
while True:
|
|
800
|
+
try:
|
|
801
|
+
# Collect all metrics
|
|
802
|
+
metrics = {
|
|
803
|
+
'timestamp': time.time(),
|
|
804
|
+
'cache': monitoring.get_cache_stats(),
|
|
805
|
+
'upstream': monitoring.get_upstream_stats(),
|
|
806
|
+
'database': monitoring.get_database_stats(),
|
|
807
|
+
'proxy_health': monitoring.get_proxy_health(),
|
|
808
|
+
'throttling': monitoring.get_throttling_stats()
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
# Log or send to monitoring system
|
|
812
|
+
print(json.dumps(metrics, indent=2))
|
|
813
|
+
|
|
814
|
+
# Check for alerts
|
|
815
|
+
cache_hit_rate = metrics['cache'].get('hit_rate', 0)
|
|
816
|
+
if cache_hit_rate < 0.5:
|
|
817
|
+
print(f"ALERT: Low cache hit rate: {cache_hit_rate:.3f}")
|
|
818
|
+
|
|
819
|
+
upstream_error_rate = metrics['upstream']['overall'].get('error_rate', 0)
|
|
820
|
+
if upstream_error_rate > 0.1:
|
|
821
|
+
print(f"ALERT: High upstream error rate: {upstream_error_rate:.3f}")
|
|
822
|
+
|
|
823
|
+
except Exception as e:
|
|
824
|
+
print(f"Monitoring error: {e}")
|
|
825
|
+
|
|
826
|
+
time.sleep(interval_seconds)
|
|
827
|
+
|
|
828
|
+
# Start monitoring in a separate thread
|
|
829
|
+
import threading
|
|
830
|
+
monitor_thread = threading.Thread(
|
|
831
|
+
target=monitor_proxy_health,
|
|
832
|
+
args=(proxy, 60),
|
|
833
|
+
daemon=True
|
|
834
|
+
)
|
|
835
|
+
monitor_thread.start()
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
## Development Workflow
|
|
839
|
+
|
|
840
|
+
### Pre-commit Hooks
|
|
841
|
+
|
|
842
|
+
This project uses pre-commit hooks to automatically enforce code quality standards. The hooks run automatically on every commit to ensure consistent formatting and catch issues early.
|
|
843
|
+
|
|
844
|
+
#### Setup
|
|
845
|
+
|
|
846
|
+
Install the development dependencies and pre-commit hooks:
|
|
847
|
+
|
|
848
|
+
```bash
|
|
849
|
+
# Clone and setup the repository
|
|
850
|
+
git clone https://github.com/tinkermonkey/reference-api-buddy.git
|
|
851
|
+
cd reference-api-buddy
|
|
852
|
+
python -m venv .venv
|
|
853
|
+
source .venv/bin/activate
|
|
854
|
+
|
|
855
|
+
# Install with development dependencies (includes pre-commit)
|
|
856
|
+
pip install -e ".[dev]"
|
|
857
|
+
|
|
858
|
+
# Install pre-commit hooks
|
|
859
|
+
pre-commit install
|
|
860
|
+
```
|
|
861
|
+
|
|
862
|
+
Alternatively, use the Makefile shortcut:
|
|
863
|
+
|
|
864
|
+
```bash
|
|
865
|
+
make setup-dev # Installs dependencies and sets up pre-commit hooks
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
#### What the Hooks Do
|
|
869
|
+
|
|
870
|
+
The pre-commit hooks automatically:
|
|
871
|
+
- **Format code** with Black (120-character line length)
|
|
872
|
+
- **Sort imports** with isort (compatible with Black)
|
|
873
|
+
- **Lint code** with flake8 for style and quality issues
|
|
874
|
+
- **Type check** with mypy (excluding test files)
|
|
875
|
+
- **Fix common issues** like trailing whitespace and file endings
|
|
876
|
+
- **Validate files** like YAML, JSON, and TOML syntax
|
|
877
|
+
|
|
878
|
+
#### Usage
|
|
879
|
+
|
|
880
|
+
Hooks run automatically on commit:
|
|
881
|
+
|
|
882
|
+
```bash
|
|
883
|
+
git add .
|
|
884
|
+
git commit -m "your changes" # Hooks run automatically
|
|
885
|
+
```
|
|
886
|
+
|
|
887
|
+
You can also run hooks manually:
|
|
888
|
+
|
|
889
|
+
```bash
|
|
890
|
+
# Run all hooks on all files
|
|
891
|
+
pre-commit run --all-files
|
|
892
|
+
|
|
893
|
+
# Run specific hooks
|
|
894
|
+
pre-commit run black # Format code
|
|
895
|
+
pre-commit run flake8 # Lint code
|
|
896
|
+
pre-commit run mypy # Type check
|
|
897
|
+
|
|
898
|
+
# Format code manually (also available via hooks)
|
|
899
|
+
make format # Run black and isort
|
|
900
|
+
make lint # Run all linting tools
|
|
901
|
+
```
|
|
902
|
+
|
|
903
|
+
If hooks fail, they often auto-fix the issues. Simply re-stage the files and commit again:
|
|
904
|
+
|
|
905
|
+
```bash
|
|
906
|
+
git add . # Re-stage the auto-fixed files
|
|
907
|
+
git commit -m "message" # Commit again
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
## Testing
|
|
911
|
+
|
|
912
|
+
```bash
|
|
913
|
+
# Run all tests (requires dev dependencies)
|
|
914
|
+
pytest
|
|
915
|
+
|
|
916
|
+
# Run specific test categories
|
|
917
|
+
pytest tests/unit_tests/
|
|
918
|
+
pytest tests/integration_tests/
|
|
919
|
+
pytest tests/performance_tests/
|
|
920
|
+
|
|
921
|
+
# Run with coverage
|
|
922
|
+
pytest --cov=reference_api_buddy
|
|
923
|
+
|
|
924
|
+
# Install dev dependencies if not already installed
|
|
925
|
+
pip install -e ".[dev]"
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
## Building Distribution
|
|
929
|
+
|
|
930
|
+
```bash
|
|
931
|
+
# Install build dependencies (included in dev dependencies)
|
|
932
|
+
pip install -e ".[dev]"
|
|
933
|
+
|
|
934
|
+
# Build wheel
|
|
935
|
+
python -m build --wheel
|
|
936
|
+
|
|
937
|
+
# Install from wheel
|
|
938
|
+
pip install dist/reference_api_buddy-*.whl
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
## Dependency Management
|
|
942
|
+
|
|
943
|
+
This project uses `pyproject.toml` for modern Python packaging with separated dependency groups:
|
|
944
|
+
|
|
945
|
+
### Dependency Categories
|
|
946
|
+
- **Production dependencies** (`dependencies`): Core runtime requirements for the proxy server
|
|
947
|
+
- **Development dependencies** (`[dev]`): Testing, linting, formatting, and build tools
|
|
948
|
+
- **Documentation dependencies** (`[docs]`): Sphinx and related documentation tools
|
|
949
|
+
|
|
950
|
+
### Installation Options
|
|
951
|
+
```bash
|
|
952
|
+
# Production only (minimal install)
|
|
953
|
+
pip install -e .
|
|
954
|
+
|
|
955
|
+
# Development environment (includes testing, linting, building tools)
|
|
956
|
+
pip install -e ".[dev]"
|
|
957
|
+
|
|
958
|
+
# Documentation building
|
|
959
|
+
pip install -e ".[docs]"
|
|
960
|
+
|
|
961
|
+
# Multiple groups
|
|
962
|
+
pip install -e ".[dev,docs]"
|
|
963
|
+
```
|
|
964
|
+
|
|
965
|
+
## Performance Considerations
|
|
966
|
+
|
|
967
|
+
- **Cache Compression**: Responses larger than 1KB are automatically compressed
|
|
968
|
+
- **Connection Pooling**: Database connections are pooled for efficiency
|
|
969
|
+
- **Thread Safety**: All components are designed for concurrent access
|
|
970
|
+
- **Memory Usage**: Configurable cache size limits and automatic cleanup
|
|
971
|
+
- **Cache-First Throttling**:
|
|
972
|
+
- **Cache hits bypass throttling entirely** for maximum performance
|
|
973
|
+
- Throttling only applies to upstream requests (cache misses)
|
|
974
|
+
- This ensures cached data is served instantly regardless of rate limits
|
|
975
|
+
- Reduces upstream API load and prevents unnecessary throttling delays
|
|
976
|
+
- **Progressive Throttling**: Exponential backoff prevents overwhelming upstream APIs
|
|
977
|
+
|
|
978
|
+
## Development Methodology
|
|
979
|
+
|
|
980
|
+
This is very much a side quest and not a day job. No deep networking or python network/http/threading stack expertise went into building this. If you possess that expertise and find imperfections, your constructive feedback is very welcome. This was built out of an end-user need that seemed to be general enough that a tool might be useful to others, and basic searching turned up MITM proxies that weren't preferable. The research was not exhaustive.
|
|
981
|
+
|
|
982
|
+
By no means does this methodology need to be followed for contributions, this is offered as an explanation or perhaps excuse for what you find before you.
|
|
983
|
+
|
|
984
|
+
As a side quest, this was also built using a little help from our robot friends, chiefly `Claude 4 Sonnet` via `Copilot`. The art of teaching the robots to take over from us is rapidly evolving, so this is offered as a snapshot and a data point.
|
|
985
|
+
|
|
986
|
+
Aside from helping guide the robots, this methodology was found to be very valueable for the Human In The Loop by forcing the process to more of a "think, analyze, act" process that might resemble a Product Development Lifecycle rather than a perhaps more reductive "build, build, build, think, start over" cycle that might be more representive of a bare SDLC.
|
|
987
|
+
|
|
988
|
+
`GPT 4.1` contributed some dreck, and some occasional value, and `Claude` and the Human In The Loop cleaned up what we could. If you find duplicate code in the same file, `GPT 4.1` can be thanked. Some of the methods attempted to prevent a large twine-ball of code from being built were:
|
|
989
|
+
|
|
990
|
+
- [.github/copilot-instructions.md](.github/copilot-instructions.md)
|
|
991
|
+
|
|
992
|
+
- Basic guidelines to keep efforts roughly on-track, within the tech stack, and well organized
|
|
993
|
+
|
|
994
|
+
- [documentation/](documentation/)
|
|
995
|
+
|
|
996
|
+
- The basic organization is a `[XX]_[feature name]` folder containing a finite set of requirements. `Github` issues and the `GitHub` MCP integration could of course be used instead, but your faithful Human is lagging and has not picked up that methodology yet.
|
|
997
|
+
|
|
998
|
+
- `[XX].01_[feature]_requirements.md` contains the product requirements for this feature or feature set. This is used to ensure there is a ground truth to guide the robots.
|
|
999
|
+
|
|
1000
|
+
- `[XX].02_[feature]_design.md` contains the generated and edited design for the implementation of the feature set. This is used as both an active listening exercise to ensure the requirements are as-intended and as the technical foundation for the implementation.
|
|
1001
|
+
|
|
1002
|
+
- `[XX].03_[feature]_plan.md` contains a generated implementation plan based on the design. This is used to facilitate iterative development of the design to prevent disorderly code or trying to boil the ocean with LLM usage (that has two interpretations!).
|
|
1003
|
+
|
|
1004
|
+
- Workflow for [[XX].01_[feature]_requirements.md](documentation/01_poc/01.1_poc_requirements.md)
|
|
1005
|
+
|
|
1006
|
+
- Here we attempt to follow some basic software development best practices and structured problem solving without becoming encumbered in process. The way this has been used is to work with non-copilot `Claude`, for this round `Claude 4.1`, to build out an idea, incorporate basic research, explore current solutions, and eventually create a (mostly) concise set of requirements. These are edited by your dear Human In The Loop while nodding on camera and pretending to listen (they can tell I'm reading by my eye movements, right?), and brought into `copilot`.
|
|
1007
|
+
|
|
1008
|
+
- Workflow for [[XX].02_[feature]_design.md](documentation/01_poc/01.2_poc_design.md)
|
|
1009
|
+
|
|
1010
|
+
- Once the requirements are in `copilot`, the first task is generate the design based on the tech stack outlined in [copilot-instructions.md](.github/copilot-instructions.md)
|
|
1011
|
+
|
|
1012
|
+
- As mentioned above, this is used first as a feedback loop for the requirements and often times the requirements change / grow / get refined based on this design and the design is re-generated or updated.
|
|
1013
|
+
|
|
1014
|
+
- The design doc is human-edited and adjusted until satisfactory, often times removing dreck and slop or over-ambitious aspirations.
|
|
1015
|
+
|
|
1016
|
+
- Workflow for [[XX].03_[feature]_plan.md](documentation/01_poc/01.3_poc_plan.md)
|
|
1017
|
+
|
|
1018
|
+
- The plan is used primarily to drive implementation one phase at a time, and as such, it's the most-lightly-edited aspect of this workflow. Often times `copilot` ignores the details of this plan anyway, sometimes for the better and sometimes for the worse, so the time and attention are comensurate to that.
|
|
1019
|
+
|
|
1020
|
+
- `copilot` is driven through the implementation phase-by-phase using a prompt like "Implement phase 1 of the plan detailed in #01.3_poc_plan.md according to the details in the design #01.2_poc_design.md including test coverage"
|
|
1021
|
+
|
|
1022
|
+
- For this round `Claude 4 Sonnet` in `Agent` mode was used for the bulk of the development with a few diversions into using `GPT 4.1` in `Agent` mode for either targetted tasks or attempts to conserve the `Premium Request` budget. Many of the `GPT 4.1` adventures ended in disaster with basic edits failing, code placed in the wrong part of the file, stupid random edits attempted. One aspiration of the detailed plan was to use `Claude 4 Sonnet` for the hard work and `GPT 4.1` for the smaller tasks, but that failed as often as it succeeded and frequently `GPT 4.1` change sets were rolled back after a frustrating 30 minutes and the task was started fresh with `Claude`.
|
|
1023
|
+
|
|
1024
|
+
- [documentation/copilot](documentation/copilot)
|
|
1025
|
+
|
|
1026
|
+
- Claude 4 Sonnet in particular is wonderful but can be pretty verbose and seems to be incentivised to create long markdown files full of emoji. Maybe that's `copilot` innards attempting to burn down the premium budget on easy tasks. Guidance in `copilot-instructions.md` attempts to corral these files to this folder which is ignored by git. You'll have to generate your own.
|
|
1027
|
+
|
|
1028
|
+
## Contributing
|
|
1029
|
+
|
|
1030
|
+
- Be respectful, patient, and considerate
|
|
1031
|
+
|
|
1032
|
+
- Maintain the test coverage changes are made
|
|
1033
|
+
|
|
1034
|
+
- Use your robots wisely
|
|
1035
|
+
|
|
1036
|
+
## License
|
|
1037
|
+
|
|
1038
|
+
MIT License - see [LICENSE](LICENSE) file for details.
|
|
1039
|
+
|
|
1040
|
+
```
|
|
1041
|
+
|
|
1042
|
+
```
|