| 1 | """Metered proxy client for the optional proxy mode (LAST30DAYS_API_MODE=proxy). |
| 2 | |
| 3 | With LAST30DAYS_API_MODE=proxy, LAST30DAYS_API_KEY, and LAST30DAYS_API_BASE |
| 4 | set, the local engine runs as usual and only paid provider calls that have no |
| 5 | user key of their own go through the hosted service's metered proxy: |
| 6 | |
| 7 | {base}/proxy/{provider}{path} |
| 8 | |
| 9 | ``env.get_config`` fills each absent proxy-lane key (``PROVIDER_KEYS``) with |
| 10 | ``SENTINEL``, so the existing lane predicates light up. ``http.request`` is the |
| 11 | one seam that recognizes the sentinel in a request's auth headers, rewrites the |
| 12 | call to the proxy, strips provider auth, and adds the bearer key, a stable |
| 13 | per-call Idempotency-Key, the per-run X-L30D-Session, and X-L30D-Deadline. |
| 14 | Calls that carry a user's own key, and every free source, never touch it. |
| 15 | |
| 16 | Like ``hosted.py`` this module carries no pricing logic: the charge for each |
| 17 | call is whatever the service reports in ``x-l30d-charge-credits``. The API key |
| 18 | is never printed, logged, or persisted here. |
| 19 | """ |
| 20 | |
| 21 | from __future__ import annotations |
| 22 | |
| 23 | import json |
| 24 | import os |
| 25 | import re |
| 26 | import sys |
| 27 | import threading |
| 28 | import uuid |
| 29 | from dataclasses import dataclass |
| 30 | from decimal import Decimal, InvalidOperation |
| 31 | from typing import Any, Mapping, Optional |
| 32 | from urllib.parse import urlsplit |
| 33 | |
| 34 | from . import env |
| 35 | |
| 36 | # Placeholder that marks a provider key as "served by the proxy". It is never a |
| 37 | # credential: http.request strips it before any request leaves the machine. |
| 38 | SENTINEL = env.PROXY_SENTINEL |
| 39 | |
| 40 | # Lanes the proxy serves, keyed by the provider slug in the proxy path. |
| 41 | PROVIDER_KEYS = { |
| 42 | "scrapecreators": "SCRAPECREATORS_API_KEY", |
| 43 | "xai": "XAI_API_KEY", |
| 44 | "serper": "SERPER_API_KEY", |
| 45 | "parallel": "PARALLEL_API_KEY", |
| 46 | } |
| 47 | |
| 48 | _PROVIDER_HOSTS = { |
| 49 | "api.scrapecreators.com": "scrapecreators", |
| 50 | "api.x.ai": "xai", |
| 51 | "google.serper.dev": "serper", |
| 52 | "api.parallel.ai": "parallel", |
| 53 | } |
| 54 | |
| 55 | # Method and path of every call the proxy forwards. The server's allowlist is |
| 56 | # authoritative (it also checks query params and body fields); this copy only |
| 57 | # keeps a call the server would refuse from leaving the machine at all. |
| 58 | _SCRAPECREATORS_PATHS = frozenset({ |
| 59 | "/v1/tiktok/search/hashtag", |
| 60 | "/v1/tiktok/search/keyword", |
| 61 | "/v3/tiktok/profile/videos", |
| 62 | "/v1/tiktok/video/transcript", |
| 63 | "/v1/tiktok/video/comments", |
| 64 | "/v2/instagram/reels/search", |
| 65 | "/v1/instagram/user/reels", |
| 66 | "/v1/google/search", |
| 67 | "/v1/instagram/post", |
| 68 | "/v2/instagram/media/transcript", |
| 69 | "/v2/instagram/post/comments", |
| 70 | "/v1/threads/search", |
| 71 | "/v1/pinterest/search", |
| 72 | "/v1/youtube/search", |
| 73 | "/v1/youtube/video/transcript", |
| 74 | "/v1/youtube/video/comments", |
| 75 | "/v1/reddit/search", |
| 76 | "/v1/reddit/subreddit/search", |
| 77 | "/v1/reddit/post/comments", |
| 78 | "/v1/linkedin/search/posts", |
| 79 | "/v1/linkedin/profile", |
| 80 | "/v1/telegram/channel/posts", |
| 81 | "/v1/facebook/adLibrary/search/ads", |
| 82 | "/v1/facebook/adLibrary/search/companies", |
| 83 | "/v1/facebook/adLibrary/company/ads", |
| 84 | "/v1/facebook/adLibrary/ad/transcript", |
| 85 | }) |
| 86 | _ROUTES = { |
| 87 | "scrapecreators": ("GET", _SCRAPECREATORS_PATHS), |
| 88 | "xai": ("POST", frozenset({"/v1/responses"})), |
| 89 | "serper": ("POST", frozenset({"/search"})), |
| 90 | "parallel": ("POST", frozenset({"/v1/search"})), |
| 91 | } |
| 92 | |
| 93 | # Provider auth headers. Every one is dropped from a proxied call. |
| 94 | _PROVIDER_AUTH_HEADERS = frozenset({"authorization", "x-api-key"}) |
| 95 | |
| 96 | CHARGE_HEADER = "x-l30d-charge-credits" |
| 97 | SESSION_HEADER = "X-L30D-Session" |
| 98 | DEADLINE_HEADER = "X-L30D-Deadline" |
| 99 | IDEMPOTENCY_HEADER = "Idempotency-Key" |
| 100 | |
| 101 | # Proxy-originated error codes that end a lane for the rest of the run. |
| 102 | _EXHAUSTING_CODES = frozenset({"insufficient_credits", "spend_ceiling"}) |
| 103 | |
| 104 | |
| 105 | class ProxyUnavailable(Exception): |
| 106 | """A proxy-backed call that must not be sent (lane off for this run).""" |
| 107 | |
| 108 | def __init__(self, message: str, status_code: Optional[int] = None): |
| 109 | super().__init__(message) |
| 110 | self.status_code = status_code |
| 111 | |
| 112 | |
| 113 | @dataclass(frozen=True) |
| 114 | class Routed: |
| 115 | url: str |
| 116 | headers: dict[str, str] |
| 117 | provider: str |
| 118 | |
| 119 | |
| 120 | _lock = threading.Lock() |
| 121 | _session_id: Optional[str] = None |
| 122 | _charged = Decimal(0) |
| 123 | _calls = 0 |
| 124 | _exhausted: Optional[str] = None |
| 125 | _unavailable: set[str] = set() |
| 126 | # Idempotency keys whose charge is already in the session total, so a retry |
| 127 | # that comes back already_settled never counts the same call twice. |
| 128 | _counted_keys: set[str] = set() |
| 129 | |
| 130 | |
| 131 | def reset() -> None: |
| 132 | """Forget this process's session (tests, or a fresh run in one process).""" |
| 133 | global _session_id, _charged, _calls, _exhausted |
| 134 | with _lock: |
| 135 | _session_id = None |
| 136 | _charged = Decimal(0) |
| 137 | _calls = 0 |
| 138 | _exhausted = None |
| 139 | _unavailable.clear() |
| 140 | _counted_keys.clear() |
| 141 | |
| 142 | |
| 143 | def _api_base() -> str: |
| 144 | return (os.environ.get("LAST30DAYS_API_BASE") or "").strip().rstrip("/") |
| 145 | |
| 146 | |
| 147 | def _api_key() -> str: |
| 148 | return (env.read_secret_env("LAST30DAYS_API_KEY") or "").strip() |
| 149 | |
| 150 | |
| 151 | def configured() -> bool: |
| 152 | """True when proxy mode is selected and its key and base are usable.""" |
| 153 | if not env.proxy_mode_requested() or not _api_key(): |
| 154 | return False |
| 155 | from . import providers |
| 156 | |
| 157 | base = _api_base() |
| 158 | return bool(base) and providers.allowed_base_url_override(base) |
| 159 | |
| 160 | |
| 161 | def is_sentinel(value: Any) -> bool: |
| 162 | return value == SENTINEL |
| 163 | |
| 164 | |
| 165 | def real_key(value: Any) -> Any: |
| 166 | """The value unless it only marks a proxy lane (then None). |
| 167 | |
| 168 | For readers that hand a key to something other than ``http.request`` |
| 169 | (a subprocess, a raw-urllib client): the sentinel must never reach them. |
| 170 | """ |
| 171 | return None if is_sentinel(value) else value |
| 172 | |
| 173 | |
| 174 | def fill_config(config: dict[str, Any]) -> None: |
| 175 | """Mark each absent proxy-lane key as served by the proxy.""" |
| 176 | if not configured(): |
| 177 | return |
| 178 | for var in PROVIDER_KEYS.values(): |
| 179 | if not config.get(var): |
| 180 | config[var] = SENTINEL |
| 181 | |
| 182 | |
| 183 | def via_api_key(config: Mapping[str, Any]) -> list[str]: |
| 184 | """Config keys whose lane is served by the proxy, in a stable order.""" |
| 185 | return [var for var in PROVIDER_KEYS.values() if is_sentinel(config.get(var))] |
| 186 | |
| 187 | |
| 188 | def _carries_sentinel(headers: Mapping[str, str]) -> bool: |
| 189 | return any(isinstance(value, str) and SENTINEL in value for value in headers.values()) |
| 190 | |
| 191 | |
| 192 | def _session() -> str: |
| 193 | global _session_id |
| 194 | with _lock: |
| 195 | if _session_id is None: |
| 196 | _session_id = f"skill-{uuid.uuid4().hex}" |
| 197 | return _session_id |
| 198 | |
| 199 | |
| 200 | def new_idempotency_key() -> str: |
| 201 | return uuid.uuid4().hex |
| 202 | |
| 203 | |
| 204 | def ensure_open(provider: str) -> None: |
| 205 | """Raise ProxyUnavailable once this run has turned the lane off. |
| 206 | |
| 207 | Checked before every attempt, so a call waiting to retry stops as soon |
| 208 | as another call hits insufficient_credits, spend_ceiling, or |
| 209 | provider_unavailable. |
| 210 | """ |
| 211 | with _lock: |
| 212 | exhausted = _exhausted |
| 213 | unavailable = provider in _unavailable |
| 214 | if exhausted: |
| 215 | raise ProxyUnavailable(exhausted, status_code=402) |
| 216 | if unavailable: |
| 217 | raise ProxyUnavailable(f"{provider} is not available through the API key", status_code=503) |
| 218 | |
| 219 | |
| 220 | def route(method: str, url: str, headers: Mapping[str, str]) -> Optional[Routed]: |
| 221 | """Rewrite a sentinel-backed provider call to the proxy. |
| 222 | |
| 223 | Returns None for every call that does not carry the sentinel (free |
| 224 | sources, and paid lanes using the user's own key). Raises |
| 225 | ``ProxyUnavailable`` for a sentinel-backed call the proxy cannot serve, so |
| 226 | the sentinel never leaves the machine. |
| 227 | """ |
| 228 | if not _carries_sentinel(headers): |
| 229 | return None |
| 230 | if not configured(): |
| 231 | raise ProxyUnavailable("proxy mode is not configured for this call") |
| 232 | parts = urlsplit(url) |
| 233 | provider = _PROVIDER_HOSTS.get((parts.hostname or "").lower()) |
| 234 | if provider is None or parts.scheme != "https" or parts.port not in (None, 443): |
| 235 | raise ProxyUnavailable("this endpoint is not available through the API key") |
| 236 | ensure_open(provider) |
| 237 | allowed_method, paths = _ROUTES[provider] |
| 238 | if method.upper() != allowed_method or parts.path not in paths: |
| 239 | raise ProxyUnavailable("this endpoint is not available through the API key", status_code=404) |
| 240 | |
| 241 | target = f"{_api_base()}/proxy/{provider}{parts.path}" |
| 242 | if parts.query: |
| 243 | target = f"{target}?{parts.query}" |
| 244 | rewritten = { |
| 245 | name: value |
| 246 | for name, value in headers.items() |
| 247 | if name.lower() not in _PROVIDER_AUTH_HEADERS |
| 248 | and not (isinstance(value, str) and SENTINEL in value) |
| 249 | } |
| 250 | rewritten["Authorization"] = f"Bearer {_api_key()}" |
| 251 | rewritten[SESSION_HEADER] = _session() |
| 252 | return Routed(url=target, headers=rewritten, provider=provider) |
| 253 | |
| 254 | |
| 255 | def deadline_value(seconds: float) -> str: |
| 256 | """X-L30D-Deadline text for a per-attempt timeout in seconds.""" |
| 257 | seconds = max(float(seconds), 0.001) |
| 258 | if seconds == int(seconds): |
| 259 | return str(int(seconds)) |
| 260 | return f"{seconds:.3f}".rstrip("0").rstrip(".") |
| 261 | |
| 262 | |
| 263 | def _header(headers: Any, name: str) -> Optional[str]: |
| 264 | if headers is None: |
| 265 | return None |
| 266 | getter = getattr(headers, "get", None) |
| 267 | if getter is None: |
| 268 | return None |
| 269 | value = getter(name) |
| 270 | if value is None: |
| 271 | value = getter(name.title()) |
| 272 | if value is None and isinstance(headers, Mapping): |
| 273 | for key, candidate in headers.items(): |
| 274 | if isinstance(key, str) and key.lower() == name: |
| 275 | value = candidate |
| 276 | break |
| 277 | return value if isinstance(value, str) else None |
| 278 | |
| 279 | |
| 280 | def record_charge(headers: Any, *, settled: bool = True, call_key: Optional[str] = None) -> None: |
| 281 | """Add one call's reported charge to the session total. |
| 282 | |
| 283 | ``settled`` counts the call: a successful response, or the replay of a |
| 284 | call already charged. A passed-through upstream error reports a zero |
| 285 | charge and is not a charged call. ``call_key`` (the Idempotency-Key) |
| 286 | makes a settled charge count once per logical call, however many |
| 287 | attempts report it. |
| 288 | """ |
| 289 | global _charged, _calls |
| 290 | raw = _header(headers, CHARGE_HEADER) |
| 291 | if raw is None: |
| 292 | return |
| 293 | try: |
| 294 | amount = Decimal(raw.strip()) |
| 295 | except (InvalidOperation, ValueError): |
| 296 | return |
| 297 | if not amount.is_finite() or amount < 0: |
| 298 | return |
| 299 | with _lock: |
| 300 | if settled and call_key is not None: |
| 301 | if call_key in _counted_keys: |
| 302 | return |
| 303 | _counted_keys.add(call_key) |
| 304 | _charged += amount |
| 305 | if settled: |
| 306 | _calls += 1 |
| 307 | |
| 308 | |
| 309 | def _error_code(body: Optional[str]) -> Optional[str]: |
| 310 | if not body: |
| 311 | return None |
| 312 | try: |
| 313 | parsed = json.loads(body) |
| 314 | except (json.JSONDecodeError, TypeError, ValueError): |
| 315 | return None |
| 316 | if not isinstance(parsed, dict): |
| 317 | return None |
| 318 | code = parsed.get("code") |
| 319 | return code if isinstance(code, str) else None |
| 320 | |
| 321 | |
| 322 | def _billing_hint() -> str: |
| 323 | root = re.sub(r"/api/v\d+$", "", _api_base()) |
| 324 | return f"Add credits at {root}/dashboard/billing" if root else "Add credits to keep using paid sources." |
| 325 | |
| 326 | |
| 327 | def observe_error( |
| 328 | provider: str, status: int, body: Optional[str], headers: Any, call_key: Optional[str] = None, |
| 329 | ) -> bool: |
| 330 | """Note a proxied error response. True when the caller must not retry. |
| 331 | |
| 332 | Only proxy-originated errors carry a ``code``; an upstream provider's own |
| 333 | 401/402/429 passes through without one and is handled as before. |
| 334 | """ |
| 335 | global _exhausted |
| 336 | code = _error_code(body) |
| 337 | record_charge(headers, settled=code == "already_settled", call_key=call_key) |
| 338 | if code is None: |
| 339 | return False |
| 340 | if code in _EXHAUSTING_CODES: |
| 341 | if code == "insufficient_credits": |
| 342 | message = "API key is out of credits; paid sources are skipped for the rest of this run" |
| 343 | else: |
| 344 | message = "API key reached its hourly spend ceiling; paid sources are skipped for the rest of this run" |
| 345 | first = False |
| 346 | with _lock: |
| 347 | if _exhausted is None: |
| 348 | _exhausted = message |
| 349 | first = True |
| 350 | if first: |
| 351 | sys.stderr.write(f"[last30days] {message}. {_billing_hint()}\n") |
| 352 | sys.stderr.flush() |
| 353 | return True |
| 354 | if code == "provider_unavailable": |
| 355 | with _lock: |
| 356 | _unavailable.add(provider) |
| 357 | return True |
| 358 | return code in {"unsupported_endpoint", "in_flight", "idempotency_conflict", "already_settled"} |
| 359 | |
| 360 | |
| 361 | def provider_unavailable(provider: str) -> bool: |
| 362 | """True once the service has said it cannot serve this provider this run.""" |
| 363 | with _lock: |
| 364 | return provider in _unavailable |
| 365 | |
| 366 | |
| 367 | def exhausted() -> bool: |
| 368 | with _lock: |
| 369 | return _exhausted is not None |
| 370 | |
| 371 | |
| 372 | def session_summary() -> tuple[int, Decimal]: |
| 373 | """(charged calls, credits) reported by the proxy for this run.""" |
| 374 | with _lock: |
| 375 | return _calls, _charged |
| 376 | |
| 377 | |
| 378 | def session_id() -> Optional[str]: |
| 379 | """This run's X-L30D-Session id, once a call has used the proxy.""" |
| 380 | with _lock: |
| 381 | return _session_id |
| 382 | |
| 383 | |
| 384 | def format_credits(amount: Decimal) -> str: |
| 385 | text = f"{amount.quantize(Decimal('0.000001')):f}".rstrip("0").rstrip(".") |
| 386 | return text or "0" |
| 387 | |
| 388 | |
| 389 | def footer_line() -> Optional[str]: |
| 390 | """The footer line for a run that used the proxy, else None.""" |
| 391 | with _lock: |
| 392 | used = _session_id is not None |
| 393 | if not used: |
| 394 | return None |
| 395 | calls, credits = session_summary() |
| 396 | noun = "call" if calls == 1 else "calls" |
| 397 | return f"💳 API key: {format_credits(credits)} credits across {calls} paid {noun}" |
| 398 |