unitbytes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1529 @@
1
+ """Provider-agnostic pluggable HTTP transports (`ApifyTransport`, `CloudGatewayTransport`, `RapidApiTransport`, `ZylaTransport`) with zero external dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from decimal import Decimal
7
+ import ipaddress
8
+ import json
9
+ import os
10
+ import re
11
+ import time
12
+ from typing import Any, Callable, Literal, Mapping
13
+ import urllib.error
14
+ import urllib.parse
15
+ import urllib.request
16
+ from urllib.parse import urlparse
17
+
18
+ from ._exceptions import (
19
+ SIGNUP_URL,
20
+ AuthenticationError,
21
+ ConfigurationError,
22
+ ProviderError,
23
+ RateLimitError,
24
+ UnitBytesError,
25
+ redact_secrets,
26
+ )
27
+ from ._serialization import format_decimal_param, normalize_max_charge_usd
28
+
29
+ ProviderLiteral = Literal["auto", "apify", "cloud", "rapidapi", "zyla"]
30
+ ResolvedProviderLiteral = Literal["apify", "cloud", "rapidapi", "zyla"]
31
+ HttpMethod = Literal["GET", "POST"]
32
+ HttpFunc = Callable[[str, str, dict[str, str], bytes | None, float], tuple[int, bytes]]
33
+
34
+ USER_AGENT = "unitbytes-python/1.0.0"
35
+ DEFAULT_APIFY_BASE_URL = "https://api.apify.com"
36
+ DEFAULT_GOOFISH_STANDBY_URL = "https://unitbytes--goofish-scraper.apify.actor"
37
+
38
+ TRUSTED_APIFY_API_HOSTS: frozenset[str] = frozenset({"api.apify.com"})
39
+ TRUSTED_APIFY_STANDBY_HOSTS: frozenset[str] = frozenset(
40
+ {
41
+ "unitbytes--goofish-scraper.apify.actor",
42
+ "unitbytes--goofish-xianyu-search-scraper.apify.actor",
43
+ }
44
+ )
45
+
46
+ DEFAULT_RAPIDAPI_HOSTS: dict[str, str] = {
47
+ "1688": "1688-wholesale-factory-data1.p.rapidapi.com",
48
+ "ali1688": "1688-wholesale-factory-data1.p.rapidapi.com",
49
+ "alibaba": "alibaba-b2b-wholesale-and-supplier-data.p.rapidapi.com",
50
+ "reddit": "reddit-community-post-comment-search-data-api.p.rapidapi.com",
51
+ "gmaps": "google-maps-b2b-leads-email-tech-stack-reviews-data-api.p.rapidapi.com",
52
+ "trends": "google-trending-searches-breakout-queries-and-news-ap.p.rapidapi.com",
53
+ "meta_ads": "meta-ads-library.p.rapidapi.com",
54
+ "meta-ads": "meta-ads-library.p.rapidapi.com",
55
+ "goofish": "goofish-xianyu-api-secondhand-deals-and-sellers.p.rapidapi.com",
56
+ "rednote": "rednote-xiaohongshu-api-notes-creators-comments-and-trends.p.rapidapi.com",
57
+ "craigslist": "craigslist-api-classifieds-cars-and-housing.p.rapidapi.com",
58
+ "offerup": "offerup-api-local-deals-cars-and-listings.p.rapidapi.com",
59
+ "fb_marketplace": "facebook-marketplace-deals-cars-and-rentals-api.p.rapidapi.com",
60
+ "fb-marketplace": "facebook-marketplace-deals-cars-and-rentals-api.p.rapidapi.com",
61
+ }
62
+
63
+ _SERVICE_PATH_ALIASES: dict[str, str] = {
64
+ "ali1688": "1688",
65
+ "meta_ads": "meta-ads",
66
+ "fb_marketplace": "fb-marketplace",
67
+ }
68
+
69
+ _LOOPBACK_HOSTS: frozenset[str] = frozenset({"127.0.0.1", "localhost", "::1"})
70
+ _ACTOR_SLUG_RE = re.compile(r"^[A-Za-z0-9_~.-]+$")
71
+ _RAPIDAPI_HOST_RE = re.compile(r"^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.p\.rapidapi\.com$")
72
+ _SAFE_SEGMENT_RE = re.compile(r"^[A-Za-z0-9_./-]+$")
73
+ _IDEMPOTENT_RETRY_STATUSES: frozenset[int] = frozenset({502, 503, 504})
74
+
75
+
76
+ class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
77
+ """Block all HTTP 3xx redirects so bearer tokens and API keys are never forwarded."""
78
+
79
+ def redirect_request(
80
+ self,
81
+ req: Any,
82
+ fp: Any,
83
+ code: int,
84
+ msg: str,
85
+ headers: Any,
86
+ newurl: str,
87
+ ) -> Any:
88
+ self._abort_redirect(fp, code, newurl)
89
+
90
+ def http_error_301(self, req: Any, fp: Any, code: int, msg: str, headers: Any) -> Any:
91
+ self._abort_redirect(fp, code, headers.get("Location", ""))
92
+
93
+ def http_error_302(self, req: Any, fp: Any, code: int, msg: str, headers: Any) -> Any:
94
+ self._abort_redirect(fp, code, headers.get("Location", ""))
95
+
96
+ def http_error_303(self, req: Any, fp: Any, code: int, msg: str, headers: Any) -> Any:
97
+ self._abort_redirect(fp, code, headers.get("Location", ""))
98
+
99
+ def http_error_307(self, req: Any, fp: Any, code: int, msg: str, headers: Any) -> Any:
100
+ self._abort_redirect(fp, code, headers.get("Location", ""))
101
+
102
+ def http_error_308(self, req: Any, fp: Any, code: int, msg: str, headers: Any) -> Any:
103
+ self._abort_redirect(fp, code, headers.get("Location", ""))
104
+
105
+ @staticmethod
106
+ def _abort_redirect(fp: Any, code: int, newurl: str) -> None:
107
+ if fp is not None:
108
+ try:
109
+ fp.close()
110
+ except Exception:
111
+ pass
112
+ target_host = (urlparse(str(newurl or "")).hostname or "").lower() or "redirect-target"
113
+ raise ProviderError(
114
+ f"Blocked HTTP {code} redirect to {target_host!r} to prevent credential forwarding.",
115
+ status_code=int(code),
116
+ code="REDIRECT_BLOCKED",
117
+ )
118
+
119
+
120
+ _SAFE_OPENER = urllib.request.build_opener(_NoRedirectHandler)
121
+
122
+
123
+ def default_http_request(
124
+ method: str,
125
+ url: str,
126
+ headers: dict[str, str],
127
+ body: bytes | None,
128
+ timeout_secs: float,
129
+ ) -> tuple[int, bytes]:
130
+ """Execute an HTTP request via stdlib `urllib.request` with 3xx redirects disabled."""
131
+ req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())
132
+ try:
133
+ with _SAFE_OPENER.open(req, timeout=timeout_secs) as resp:
134
+ status = int(resp.status)
135
+ if 300 <= status < 400:
136
+ raise ProviderError(
137
+ f"Blocked HTTP {status} redirect response.",
138
+ status_code=status,
139
+ code="REDIRECT_BLOCKED",
140
+ )
141
+ return status, resp.read()
142
+ except ProviderError:
143
+ raise
144
+ except urllib.error.HTTPError as exc:
145
+ code = int(exc.code)
146
+ if 300 <= code < 400:
147
+ if exc.fp is not None:
148
+ try:
149
+ exc.fp.close()
150
+ except Exception:
151
+ pass
152
+ raise ProviderError(
153
+ f"Blocked HTTP {code} redirect response.",
154
+ status_code=code,
155
+ code="REDIRECT_BLOCKED",
156
+ ) from exc
157
+ payload = exc.read() if exc.fp is not None else b""
158
+ return code, payload
159
+
160
+
161
+ def _parse_and_validate_base_url(
162
+ raw_url: str,
163
+ *,
164
+ label: str,
165
+ allow_custom_endpoints: bool,
166
+ allowed_hosts: frozenset[str] | None = None,
167
+ allowed_suffixes: tuple[str, ...] = (),
168
+ ) -> tuple[str, str]:
169
+ """Validate URL scheme, credentials, and host allowlist; returns `(clean_base_url, hostname)`."""
170
+ cleaned = str(raw_url or "").strip().rstrip("/")
171
+ if not cleaned:
172
+ raise ConfigurationError(f"{label} cannot be empty.")
173
+ if any(ch.isspace() or ord(ch) < 32 for ch in cleaned):
174
+ raise ConfigurationError(f"{label} must not contain whitespace or control characters.")
175
+
176
+ parsed = urlparse(cleaned)
177
+ if parsed.username or parsed.password or "@" in (parsed.netloc or ""):
178
+ raise ConfigurationError(f"{label} must not contain embedded URL credentials.")
179
+ if parsed.query or parsed.fragment:
180
+ raise ConfigurationError(f"{label} must not include query strings or fragments.")
181
+
182
+ scheme = (parsed.scheme or "").lower()
183
+ host = (parsed.hostname or "").lower().rstrip(".")
184
+ if not host:
185
+ raise ConfigurationError(f"Invalid {label}: {cleaned!r}")
186
+
187
+ is_loopback = host in _LOOPBACK_HOSTS
188
+ if scheme == "http":
189
+ if not (allow_custom_endpoints and is_loopback):
190
+ raise ConfigurationError(
191
+ f"{label} must use https:// (http:// is permitted only on 127.0.0.1/localhost when allow_custom_endpoints=True)."
192
+ )
193
+ elif scheme != "https":
194
+ raise ConfigurationError(f"{label} must use https:// scheme, got {scheme!r}.")
195
+
196
+ if not allow_custom_endpoints:
197
+ if is_loopback:
198
+ raise ConfigurationError(
199
+ f"Loopback host {host!r} in {label} requires allow_custom_endpoints=True."
200
+ )
201
+ try:
202
+ ip_obj = ipaddress.ip_address(host.split("%", 1)[0])
203
+ if (
204
+ not ip_obj.is_global
205
+ or ip_obj.is_private
206
+ or ip_obj.is_loopback
207
+ or ip_obj.is_link_local
208
+ or ip_obj.is_reserved
209
+ ):
210
+ raise ConfigurationError(
211
+ f"Non-public IP {host!r} in {label} is not allowed unless allow_custom_endpoints=True."
212
+ )
213
+ except ValueError:
214
+ if "." not in host:
215
+ raise ConfigurationError(f"Invalid hostname {host!r} in {label}.")
216
+
217
+ if allowed_hosts is not None or allowed_suffixes:
218
+ matched_exact = allowed_hosts is not None and host in allowed_hosts
219
+ matched_suffix = any(
220
+ host == sfx.lstrip(".") or (host.endswith(sfx) and len(host) > len(sfx))
221
+ for sfx in allowed_suffixes
222
+ )
223
+ if not (matched_exact or matched_suffix):
224
+ raise ConfigurationError(
225
+ f"Untrusted host {host!r} for {label}. Pass allow_custom_endpoints=True only for verified custom/test endpoints."
226
+ )
227
+
228
+ return cleaned, host
229
+
230
+
231
+ def canonicalize_service_path(service: str) -> str:
232
+ """Normalize a namespace/service name into its canonical `/v1/<service>` URL segment."""
233
+ raw = str(service or "").strip().strip("/")
234
+ if not raw:
235
+ raise ConfigurationError("service name cannot be empty.")
236
+ mapped = _SERVICE_PATH_ALIASES.get(raw.lower(), raw.lower())
237
+ if not _SAFE_SEGMENT_RE.fullmatch(mapped) or ".." in mapped:
238
+ raise ConfigurationError(f"Invalid service name {service!r}.")
239
+ return mapped
240
+
241
+
242
+ def normalize_operation_path(operation: str) -> str:
243
+ """Validate and normalize an operation path segment."""
244
+ cleaned = str(operation or "").strip().strip("/")
245
+ if not cleaned or not _SAFE_SEGMENT_RE.fullmatch(cleaned) or ".." in cleaned:
246
+ raise ConfigurationError(f"Invalid operation path {operation!r}.")
247
+ return cleaned
248
+
249
+
250
+ def normalize_actor_tilde_slug(actor_slug: str) -> str:
251
+ """Normalize `'google-jobs-scraper'` or `'unitbytes/google-jobs-scraper'` to `'unitbytes~google-jobs-scraper'`."""
252
+ cleaned = str(actor_slug or "").strip().strip("/")
253
+ if not cleaned:
254
+ raise ConfigurationError("actor_slug cannot be empty.")
255
+ if "/" in cleaned:
256
+ parts = [p for p in cleaned.split("/") if p]
257
+ if len(parts) != 2:
258
+ raise ConfigurationError(f"Invalid actor_slug {actor_slug!r}.")
259
+ tilde = f"{parts[0]}~{parts[1]}"
260
+ elif "~" in cleaned:
261
+ tilde = cleaned
262
+ else:
263
+ tilde = f"unitbytes~{cleaned}"
264
+ if not _ACTOR_SLUG_RE.fullmatch(tilde) or ".." in tilde:
265
+ raise ConfigurationError(f"Invalid actor_slug {actor_slug!r}.")
266
+ return tilde
267
+
268
+
269
+ def encode_query_params(params: Mapping[str, Any] | None) -> str:
270
+ """Encode non-empty query parameters deterministically (`bool` -> `'true'`/`'false'`, sequences -> comma-joined)."""
271
+ if not params:
272
+ return ""
273
+ clean: dict[str, str] = {}
274
+ for key, val in params.items():
275
+ if val is None or val == "":
276
+ continue
277
+ if isinstance(val, bool):
278
+ clean[str(key)] = "true" if val else "false"
279
+ elif isinstance(val, (list, tuple)):
280
+ joined = ",".join(str(x).strip() for x in val if x is not None and str(x).strip())
281
+ if joined:
282
+ clean[str(key)] = joined
283
+ else:
284
+ clean[str(key)] = str(val)
285
+ return urllib.parse.urlencode(clean) if clean else ""
286
+
287
+
288
+ def unwrap_items_payload(payload: Any) -> list[dict[str, Any]]:
289
+ """Extract a normalized `list[dict]` from Apify dataset arrays or `/v1/*` gateway JSON envelopes."""
290
+ if isinstance(payload, list):
291
+ return [dict(x) for x in payload if isinstance(x, Mapping)]
292
+ if isinstance(payload, Mapping):
293
+ data = payload.get("data")
294
+ if isinstance(data, list):
295
+ return [dict(x) for x in data if isinstance(x, Mapping)]
296
+ if isinstance(data, Mapping):
297
+ for key in ("items", "results", "listings", "reviews", "comments", "notes", "offers", "places"):
298
+ nested = data.get(key)
299
+ if isinstance(nested, list):
300
+ return [dict(x) for x in nested if isinstance(x, Mapping)]
301
+ return [dict(data)]
302
+ for key in ("items", "results", "listings", "reviews", "comments"):
303
+ top_list = payload.get(key)
304
+ if isinstance(top_list, list):
305
+ return [dict(x) for x in top_list if isinstance(x, Mapping)]
306
+ return [dict(payload)]
307
+ return []
308
+
309
+
310
+ def unwrap_object_payload(payload: Any) -> dict[str, Any]:
311
+ """Extract a normalized single `dict` from either a single-element list or `/v1/*` gateway JSON envelope."""
312
+ if isinstance(payload, list):
313
+ for item in payload:
314
+ if isinstance(item, Mapping):
315
+ return dict(item)
316
+ return {}
317
+ if isinstance(payload, Mapping):
318
+ if "data" in payload and isinstance(payload["data"], (Mapping, list)):
319
+ inner = payload["data"]
320
+ if isinstance(inner, Mapping):
321
+ prof = inner.get("profile")
322
+ if isinstance(prof, Mapping):
323
+ return {**dict(prof), **dict(inner)}
324
+ return dict(inner)
325
+ if isinstance(inner, list) and inner and isinstance(inner[0], Mapping):
326
+ return dict(inner[0])
327
+ return {}
328
+ return dict(payload)
329
+ return {}
330
+
331
+
332
+ def _extract_error_details(
333
+ status: int,
334
+ raw_bytes: bytes,
335
+ *,
336
+ fallback_target: str,
337
+ secrets: tuple[str | None, ...],
338
+ ) -> tuple[str | None, str]:
339
+ text = raw_bytes.decode("utf-8", errors="replace").strip()
340
+ parsed: dict[str, Any] = {}
341
+ if text:
342
+ try:
343
+ loaded = json.loads(text)
344
+ if isinstance(loaded, dict):
345
+ parsed = loaded
346
+ except json.JSONDecodeError:
347
+ parsed = {}
348
+
349
+ err_obj = parsed.get("error")
350
+ code: str | None = None
351
+ msg: str | None = None
352
+ if isinstance(err_obj, Mapping):
353
+ code = str(err_obj.get("code") or err_obj.get("type") or "").strip() or None
354
+ msg = str(err_obj.get("message") or "").strip() or None
355
+ elif isinstance(err_obj, str) and err_obj.strip():
356
+ code = err_obj.strip()
357
+
358
+ if not msg:
359
+ for key in ("message", "errorMessage", "detail"):
360
+ val = parsed.get(key)
361
+ if isinstance(val, str) and val.strip():
362
+ msg = val.strip()
363
+ break
364
+ if not msg:
365
+ msg = text[:240] if text else f"HTTP {status} from {fallback_target}"
366
+
367
+ return code, redact_secrets(msg, secrets)
368
+
369
+
370
+ def _raise_for_http_error(
371
+ status: int,
372
+ raw_bytes: bytes,
373
+ *,
374
+ target: str,
375
+ secrets: tuple[str | None, ...],
376
+ ) -> None:
377
+ code, safe_msg = _extract_error_details(status, raw_bytes, fallback_target=target, secrets=secrets)
378
+ if 300 <= status < 400:
379
+ raise ProviderError(
380
+ f"Blocked HTTP {status} redirect from {target}.",
381
+ status_code=status,
382
+ code="REDIRECT_BLOCKED",
383
+ secrets=secrets,
384
+ )
385
+ if status == 429:
386
+ raise RateLimitError(
387
+ f"Rate limit exceeded on {target} (HTTP 429): {safe_msg}",
388
+ status_code=429,
389
+ code=code or "RATE_LIMITED",
390
+ secrets=secrets,
391
+ )
392
+ if status in {401, 403} and code != "TIER_RESTRICTION":
393
+ raise AuthenticationError(
394
+ f"Authentication failed on {target} (HTTP {status}): {safe_msg}",
395
+ status_code=status,
396
+ code=code or "AUTH_ERROR",
397
+ secrets=secrets,
398
+ )
399
+ raise ProviderError(
400
+ f"Provider error on {target} (HTTP {status}): {safe_msg}",
401
+ status_code=status,
402
+ code=code or f"HTTP_{status}",
403
+ secrets=secrets,
404
+ )
405
+
406
+
407
+ class Transport(ABC):
408
+ """Abstract provider-agnostic transport interface for `UnitBytes`."""
409
+
410
+ provider_name: str = "custom"
411
+
412
+ @abstractmethod
413
+ def execute_operation(
414
+ self,
415
+ *,
416
+ service: str,
417
+ operation: str,
418
+ actor_slug: str | None = None,
419
+ actor_input: Mapping[str, Any] | None = None,
420
+ http_method: HttpMethod = "GET",
421
+ params: Mapping[str, Any] | None = None,
422
+ json_body: Mapping[str, Any] | None = None,
423
+ standby_path: str | None = None,
424
+ standby_params: Mapping[str, Any] | None = None,
425
+ prefer_standby: bool | None = None,
426
+ fallback_to_batch: bool = True,
427
+ rapidapi_host: str | None = None,
428
+ timeout_secs: int | None = None,
429
+ max_total_charge_usd: float | Decimal | None = None,
430
+ ) -> Any:
431
+ """Execute a domain operation against the active backend provider."""
432
+
433
+ @abstractmethod
434
+ def run_generic(
435
+ self,
436
+ target: str,
437
+ payload: Mapping[str, Any] | None = None,
438
+ *,
439
+ method: HttpMethod | None = None,
440
+ params: Mapping[str, Any] | None = None,
441
+ rapidapi_host: str | None = None,
442
+ timeout_secs: int | None = None,
443
+ max_total_charge_usd: float | Decimal | None = None,
444
+ ) -> Any:
445
+ """Execute a generic actor slug or `/v1/{service}/{operation}` endpoint call."""
446
+
447
+
448
+ class ApifyTransport(Transport):
449
+ """Pure-stdlib Apify REST v2 transport using non-retried start-once POST + idempotent GET polling."""
450
+
451
+ provider_name = "apify"
452
+
453
+ def __init__(
454
+ self,
455
+ api_key: str,
456
+ *,
457
+ base_url: str | None = None,
458
+ standby_url: str | None = None,
459
+ timeout_secs: int = 180,
460
+ max_total_charge_usd: float | Decimal | None = None,
461
+ prefer_standby: bool = False,
462
+ allow_custom_endpoints: bool = False,
463
+ poll_interval_secs: float = 0.0,
464
+ max_poll_retries: int = 2,
465
+ http_fn: HttpFunc | None = None,
466
+ sleep_fn: Callable[[float], None] = time.sleep,
467
+ monotonic_fn: Callable[[], float] = time.monotonic,
468
+ ) -> None:
469
+ cleaned_key = str(api_key or "").strip()
470
+ if not cleaned_key:
471
+ raise AuthenticationError(
472
+ f"Missing Apify API token. Export APIFY_TOKEN=... or sign up at {SIGNUP_URL}"
473
+ )
474
+ self._api_key = cleaned_key
475
+ self.allow_custom_endpoints = bool(allow_custom_endpoints)
476
+ self.base_url, _ = _parse_and_validate_base_url(
477
+ base_url or DEFAULT_APIFY_BASE_URL,
478
+ label="Apify base_url",
479
+ allow_custom_endpoints=self.allow_custom_endpoints,
480
+ allowed_hosts=TRUSTED_APIFY_API_HOSTS,
481
+ )
482
+ self.standby_url, _ = _parse_and_validate_base_url(
483
+ standby_url or DEFAULT_GOOFISH_STANDBY_URL,
484
+ label="Apify standby_url",
485
+ allow_custom_endpoints=self.allow_custom_endpoints,
486
+ allowed_hosts=TRUSTED_APIFY_STANDBY_HOSTS,
487
+ )
488
+ self.timeout_secs = max(5, int(timeout_secs))
489
+ self.max_total_charge_usd = normalize_max_charge_usd(max_total_charge_usd)
490
+ self.prefer_standby = bool(prefer_standby)
491
+ self.poll_interval_secs = max(0.0, float(poll_interval_secs))
492
+ self.max_poll_retries = max(0, int(max_poll_retries))
493
+ self._http: HttpFunc = http_fn or default_http_request
494
+ self._sleep = sleep_fn
495
+ self._monotonic = monotonic_fn
496
+
497
+ def __repr__(self) -> str:
498
+ return (
499
+ f"ApifyTransport(base_url={self.base_url!r}, api_key='[REDACTED]', "
500
+ f"timeout_secs={self.timeout_secs}, prefer_standby={self.prefer_standby})"
501
+ )
502
+
503
+ def _headers(self, *, json_content: bool = False) -> dict[str, str]:
504
+ hdrs = {
505
+ "Accept": "application/json",
506
+ "Authorization": f"Bearer {self._api_key}",
507
+ "User-Agent": USER_AGENT,
508
+ }
509
+ if json_content:
510
+ hdrs["Content-Type"] = "application/json"
511
+ return hdrs
512
+
513
+ def _call_idempotent_get(
514
+ self,
515
+ url: str,
516
+ *,
517
+ target_label: str,
518
+ timeout_secs: float,
519
+ ) -> bytes:
520
+ last_exc: Exception | None = None
521
+ for attempt in range(self.max_poll_retries + 1):
522
+ try:
523
+ status, raw_bytes = self._http("GET", url, self._headers(), None, timeout_secs)
524
+ except UnitBytesError as exc:
525
+ raise exc.__class__(
526
+ str(exc),
527
+ status_code=exc.status_code,
528
+ code=exc.code,
529
+ run_id=exc.run_id,
530
+ secrets=(self._api_key,),
531
+ ) from exc
532
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
533
+ last_exc = exc
534
+ if attempt < self.max_poll_retries:
535
+ self._sleep(0.3 * (2**attempt))
536
+ continue
537
+ raise ProviderError(
538
+ f"Network error calling {target_label}: {exc}",
539
+ code="NETWORK_ERROR",
540
+ secrets=(self._api_key,),
541
+ ) from exc
542
+
543
+ if status in _IDEMPOTENT_RETRY_STATUSES and attempt < self.max_poll_retries:
544
+ self._sleep(0.3 * (2**attempt))
545
+ continue
546
+
547
+ if status >= 300:
548
+ _raise_for_http_error(
549
+ status,
550
+ raw_bytes,
551
+ target=target_label,
552
+ secrets=(self._api_key,),
553
+ )
554
+ return raw_bytes
555
+
556
+ raise ProviderError(
557
+ f"Exhausted retries calling {target_label}: {last_exc}",
558
+ code="RETRY_EXHAUSTED",
559
+ secrets=(self._api_key,),
560
+ )
561
+
562
+ def _call_standby(
563
+ self,
564
+ path: str,
565
+ *,
566
+ params: Mapping[str, Any] | None = None,
567
+ timeout_secs: int | None = None,
568
+ ) -> Any:
569
+ norm_path = "/" + normalize_operation_path(path)
570
+ qs = encode_query_params(params)
571
+ url = f"{self.standby_url}{norm_path}" + (f"?{qs}" if qs else "")
572
+ eff_timeout = float(max(5, int(timeout_secs or self.timeout_secs)))
573
+ raw_bytes = self._call_idempotent_get(url, target_label=norm_path, timeout_secs=eff_timeout)
574
+ text = raw_bytes.decode("utf-8", errors="replace").strip()
575
+ if not text:
576
+ return {}
577
+ try:
578
+ parsed = json.loads(text)
579
+ except json.JSONDecodeError as exc:
580
+ raise ProviderError(
581
+ f"Invalid JSON from Standby {norm_path}.",
582
+ code="INVALID_JSON",
583
+ secrets=(self._api_key,),
584
+ ) from exc
585
+
586
+ if isinstance(parsed, Mapping) and (parsed.get("ok") is False or parsed.get("status") == "error"):
587
+ err_obj = parsed.get("error")
588
+ code = (
589
+ str(err_obj.get("code") or "STANDBY_ERROR")
590
+ if isinstance(err_obj, Mapping)
591
+ else str(err_obj or "STANDBY_ERROR")
592
+ )
593
+ msg = (
594
+ (err_obj.get("message") if isinstance(err_obj, Mapping) else None)
595
+ or parsed.get("message")
596
+ or f"Standby error on {norm_path}"
597
+ )
598
+ raise ProviderError(str(msg), code=code, secrets=(self._api_key,))
599
+ return parsed
600
+
601
+ def run_actor(
602
+ self,
603
+ actor_slug: str,
604
+ actor_input: Mapping[str, Any] | None = None,
605
+ *,
606
+ timeout_secs: int | None = None,
607
+ max_total_charge_usd: float | Decimal | None = None,
608
+ ) -> list[dict[str, Any]]:
609
+ """Start an Apify Actor run AT MOST ONCE (`POST` never retried), poll `GET /v2/actor-runs/{id}`, and fetch dataset items."""
610
+ actor_tilde = normalize_actor_tilde_slug(actor_slug)
611
+ eff_timeout = max(5, int(timeout_secs if timeout_secs is not None else self.timeout_secs))
612
+ eff_charge = (
613
+ normalize_max_charge_usd(max_total_charge_usd)
614
+ if max_total_charge_usd is not None
615
+ else self.max_total_charge_usd
616
+ )
617
+
618
+ clean_input = {k: v for k, v in (actor_input or {}).items() if v is not None}
619
+ wait_initial = min(60, eff_timeout)
620
+ start_query: dict[str, str] = {"waitForFinish": str(wait_initial)}
621
+ if eff_charge is not None:
622
+ start_query["maxTotalChargeUsd"] = format_decimal_param(eff_charge)
623
+
624
+ start_url = (
625
+ f"{self.base_url}/v2/acts/{urllib.parse.quote(actor_tilde, safe='~')}/runs"
626
+ f"?{urllib.parse.urlencode(start_query)}"
627
+ )
628
+ encoded_body = json.dumps(clean_input, ensure_ascii=False).encode("utf-8")
629
+ deadline = self._monotonic() + eff_timeout
630
+
631
+ # STRICT NON-RETRY GUARANTEE: POST /runs is executed ONCE and NEVER retried
632
+ # so duplicate paid Pay-Per-Event runs are impossible.
633
+ try:
634
+ post_status, post_bytes = self._http(
635
+ "POST",
636
+ start_url,
637
+ self._headers(json_content=True),
638
+ encoded_body,
639
+ float(wait_initial + 15),
640
+ )
641
+ except UnitBytesError as exc:
642
+ raise exc.__class__(
643
+ str(exc),
644
+ status_code=exc.status_code,
645
+ code=exc.code,
646
+ run_id=exc.run_id,
647
+ secrets=(self._api_key,),
648
+ ) from exc
649
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
650
+ raise ProviderError(
651
+ f"Network error starting actor {actor_slug} (POST not retried to prevent duplicate paid runs): {exc}",
652
+ code="NETWORK_ERROR",
653
+ secrets=(self._api_key,),
654
+ ) from exc
655
+
656
+ if post_status >= 300:
657
+ _raise_for_http_error(
658
+ post_status,
659
+ post_bytes,
660
+ target=f"acts/{actor_tilde}/runs",
661
+ secrets=(self._api_key,),
662
+ )
663
+
664
+ try:
665
+ start_payload = json.loads(post_bytes.decode("utf-8", errors="replace") or "{}")
666
+ except json.JSONDecodeError as exc:
667
+ raise ProviderError(
668
+ f"Invalid JSON metadata when starting actor {actor_slug}.",
669
+ code="INVALID_JSON",
670
+ secrets=(self._api_key,),
671
+ ) from exc
672
+
673
+ run_data = start_payload.get("data") if isinstance(start_payload, Mapping) else None
674
+ if not isinstance(run_data, Mapping):
675
+ run_data = start_payload if isinstance(start_payload, Mapping) else {}
676
+
677
+ run_id = str(run_data.get("id") or "").strip() or None
678
+ status = str(run_data.get("status") or "").strip().upper()
679
+
680
+ while status in {"READY", "RUNNING"}:
681
+ if not run_id:
682
+ raise ProviderError(
683
+ f"Actor {actor_slug} returned status={status!r} without a run ID.",
684
+ code="MISSING_RUN_ID",
685
+ secrets=(self._api_key,),
686
+ )
687
+ remaining = deadline - self._monotonic()
688
+ if remaining <= 0:
689
+ raise ProviderError(
690
+ f"Actor {actor_slug} timed out after {eff_timeout}s (run_id={run_id}, status={status!r}).",
691
+ code="RUN_TIMEOUT",
692
+ run_id=run_id,
693
+ secrets=(self._api_key,),
694
+ )
695
+ if self.poll_interval_secs > 0:
696
+ self._sleep(min(self.poll_interval_secs, max(0.0, remaining)))
697
+ remaining = deadline - self._monotonic()
698
+ if remaining <= 0:
699
+ raise ProviderError(
700
+ f"Actor {actor_slug} timed out after {eff_timeout}s (run_id={run_id}, status={status!r}).",
701
+ code="RUN_TIMEOUT",
702
+ run_id=run_id,
703
+ secrets=(self._api_key,),
704
+ )
705
+
706
+ wait_poll = 60 if remaining >= 60 else max(1, int(remaining))
707
+ poll_url = (
708
+ f"{self.base_url}/v2/actor-runs/{urllib.parse.quote(run_id)}"
709
+ f"?waitForFinish={wait_poll}"
710
+ )
711
+ poll_bytes = self._call_idempotent_get(
712
+ poll_url,
713
+ target_label=f"actor-runs/{run_id}",
714
+ timeout_secs=float(wait_poll + 15),
715
+ )
716
+ poll_json = json.loads(poll_bytes.decode("utf-8", errors="replace") or "{}")
717
+ next_data = poll_json.get("data") if isinstance(poll_json, Mapping) else None
718
+ if isinstance(next_data, Mapping):
719
+ run_data = next_data
720
+ elif isinstance(poll_json, Mapping):
721
+ run_data = poll_json
722
+ status = str(run_data.get("status") or "").strip().upper()
723
+
724
+ if status != "SUCCEEDED":
725
+ raise ProviderError(
726
+ f"Actor {actor_slug} finished with status={status!r} (run_id={run_id}).",
727
+ code=f"RUN_{status or 'FAILED'}",
728
+ run_id=run_id,
729
+ secrets=(self._api_key,),
730
+ )
731
+
732
+ dataset_id = str(
733
+ run_data.get("defaultDatasetId") or run_data.get("default_dataset_id") or ""
734
+ ).strip()
735
+ if not dataset_id:
736
+ return []
737
+
738
+ ds_url = (
739
+ f"{self.base_url}/v2/datasets/{urllib.parse.quote(dataset_id)}/items"
740
+ "?format=json&clean=true"
741
+ )
742
+ ds_bytes = self._call_idempotent_get(
743
+ ds_url,
744
+ target_label=f"datasets/{dataset_id}/items",
745
+ timeout_secs=float(eff_timeout),
746
+ )
747
+ if not ds_bytes:
748
+ return []
749
+
750
+ try:
751
+ raw_items = json.loads(ds_bytes.decode("utf-8", errors="replace"))
752
+ except json.JSONDecodeError as exc:
753
+ raise ProviderError(
754
+ f"Invalid JSON dataset items for actor {actor_slug} (dataset_id={dataset_id}).",
755
+ code="INVALID_DATASET_JSON",
756
+ run_id=run_id,
757
+ secrets=(self._api_key,),
758
+ ) from exc
759
+
760
+ rows = [dict(item) for item in raw_items if isinstance(item, Mapping)] if isinstance(raw_items, list) else []
761
+ if len(rows) == 1:
762
+ first = rows[0]
763
+ if (
764
+ first.get("error") is True
765
+ or first.get("status") == "error"
766
+ or first.get("recordType") == "error"
767
+ ):
768
+ err_code = str(
769
+ first.get("code") or first.get("errorType") or "ACTOR_ERROR"
770
+ ).strip()
771
+ err_msg = str(
772
+ first.get("error_message")
773
+ or first.get("message")
774
+ or first.get("error")
775
+ or f"Actor {actor_slug} reported an error."
776
+ )
777
+ raise ProviderError(
778
+ err_msg,
779
+ code=err_code,
780
+ run_id=run_id,
781
+ secrets=(self._api_key,),
782
+ )
783
+ return rows
784
+
785
+ def execute_operation(
786
+ self,
787
+ *,
788
+ service: str,
789
+ operation: str,
790
+ actor_slug: str | None = None,
791
+ actor_input: Mapping[str, Any] | None = None,
792
+ http_method: HttpMethod = "GET",
793
+ params: Mapping[str, Any] | None = None,
794
+ json_body: Mapping[str, Any] | None = None,
795
+ standby_path: str | None = None,
796
+ standby_params: Mapping[str, Any] | None = None,
797
+ prefer_standby: bool | None = None,
798
+ fallback_to_batch: bool = True,
799
+ rapidapi_host: str | None = None,
800
+ timeout_secs: int | None = None,
801
+ max_total_charge_usd: float | Decimal | None = None,
802
+ ) -> Any:
803
+ _ = (service, operation, http_method, params, json_body, rapidapi_host)
804
+ use_standby = self.prefer_standby if prefer_standby is None else bool(prefer_standby)
805
+ if standby_path and use_standby:
806
+ try:
807
+ return self._call_standby(
808
+ standby_path,
809
+ params=standby_params,
810
+ timeout_secs=timeout_secs,
811
+ )
812
+ except ProviderError as exc:
813
+ can_fallback = (
814
+ fallback_to_batch
815
+ and actor_slug is not None
816
+ and (
817
+ exc.status_code in _IDEMPOTENT_RETRY_STATUSES
818
+ or exc.code in {"NETWORK_ERROR", "RETRY_EXHAUSTED"}
819
+ )
820
+ )
821
+ if not can_fallback:
822
+ raise
823
+
824
+ if not actor_slug:
825
+ raise ConfigurationError(
826
+ f"Operation '{service}.{operation}' requires an actor_slug on ApifyTransport."
827
+ )
828
+ return self.run_actor(
829
+ actor_slug,
830
+ actor_input,
831
+ timeout_secs=timeout_secs,
832
+ max_total_charge_usd=max_total_charge_usd,
833
+ )
834
+
835
+ def run_generic(
836
+ self,
837
+ target: str,
838
+ payload: Mapping[str, Any] | None = None,
839
+ *,
840
+ method: HttpMethod | None = None,
841
+ params: Mapping[str, Any] | None = None,
842
+ rapidapi_host: str | None = None,
843
+ timeout_secs: int | None = None,
844
+ max_total_charge_usd: float | Decimal | None = None,
845
+ ) -> Any:
846
+ _ = (method, rapidapi_host)
847
+ merged_input: dict[str, Any] = {}
848
+ if params:
849
+ merged_input.update(params)
850
+ if payload:
851
+ merged_input.update(payload)
852
+ return self.run_actor(
853
+ target,
854
+ merged_input,
855
+ timeout_secs=timeout_secs,
856
+ max_total_charge_usd=max_total_charge_usd,
857
+ )
858
+
859
+
860
+ class _BaseRestGatewayTransport(Transport):
861
+ """Shared implementation for REST `/v1/{service}/{operation}` transports."""
862
+
863
+ def __init__(
864
+ self,
865
+ api_key: str,
866
+ *,
867
+ timeout_secs: int = 180,
868
+ allow_custom_endpoints: bool = False,
869
+ max_get_retries: int = 2,
870
+ http_fn: HttpFunc | None = None,
871
+ sleep_fn: Callable[[float], None] = time.sleep,
872
+ ) -> None:
873
+ self._api_key = api_key
874
+ self.timeout_secs = max(5, int(timeout_secs))
875
+ self.allow_custom_endpoints = bool(allow_custom_endpoints)
876
+ self.max_get_retries = max(0, int(max_get_retries))
877
+ self._http: HttpFunc = http_fn or default_http_request
878
+ self._sleep = sleep_fn
879
+
880
+ @abstractmethod
881
+ def _resolve_url_and_headers(
882
+ self,
883
+ *,
884
+ service: str,
885
+ operation: str,
886
+ rapidapi_host: str | None = None,
887
+ json_content: bool = False,
888
+ ) -> tuple[str, dict[str, str]]:
889
+ """Return `(endpoint_url_without_query, headers)`."""
890
+
891
+ def _send_rest_request(
892
+ self,
893
+ method: HttpMethod,
894
+ url: str,
895
+ headers: dict[str, str],
896
+ *,
897
+ params: Mapping[str, Any] | None = None,
898
+ json_body: Mapping[str, Any] | None = None,
899
+ timeout_secs: int | None = None,
900
+ target_label: str,
901
+ ) -> Any:
902
+ qs = encode_query_params(params)
903
+ full_url = f"{url}?{qs}" if qs else url
904
+ encoded_body: bytes | None = None
905
+ req_headers = dict(headers)
906
+ if json_body is not None:
907
+ req_headers["Content-Type"] = "application/json"
908
+ encoded_body = json.dumps(dict(json_body), ensure_ascii=False).encode("utf-8")
909
+
910
+ eff_timeout = float(max(5, int(timeout_secs if timeout_secs is not None else self.timeout_secs)))
911
+ max_attempts = (self.max_get_retries + 1) if method.upper() == "GET" else 1
912
+
913
+ last_exc: Exception | None = None
914
+ for attempt in range(max_attempts):
915
+ try:
916
+ status, raw_bytes = self._http(
917
+ method.upper(),
918
+ full_url,
919
+ req_headers,
920
+ encoded_body,
921
+ eff_timeout,
922
+ )
923
+ except UnitBytesError as exc:
924
+ raise exc.__class__(
925
+ str(exc),
926
+ status_code=exc.status_code,
927
+ code=exc.code,
928
+ run_id=exc.run_id,
929
+ secrets=(self._api_key,),
930
+ ) from exc
931
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
932
+ last_exc = exc
933
+ if attempt + 1 < max_attempts:
934
+ self._sleep(0.3 * (2**attempt))
935
+ continue
936
+ raise ProviderError(
937
+ f"Network error calling {target_label}: {exc}",
938
+ code="NETWORK_ERROR",
939
+ secrets=(self._api_key,),
940
+ ) from exc
941
+
942
+ if status in _IDEMPOTENT_RETRY_STATUSES and attempt + 1 < max_attempts:
943
+ self._sleep(0.3 * (2**attempt))
944
+ continue
945
+
946
+ if status >= 300:
947
+ _raise_for_http_error(
948
+ status,
949
+ raw_bytes,
950
+ target=target_label,
951
+ secrets=(self._api_key,),
952
+ )
953
+
954
+ text = raw_bytes.decode("utf-8", errors="replace").strip()
955
+ if not text:
956
+ return {}
957
+ try:
958
+ parsed = json.loads(text)
959
+ except json.JSONDecodeError as exc:
960
+ raise ProviderError(
961
+ f"Invalid JSON response from {target_label}.",
962
+ code="INVALID_JSON",
963
+ secrets=(self._api_key,),
964
+ ) from exc
965
+
966
+ if isinstance(parsed, Mapping) and parsed.get("success") is False:
967
+ err_obj = parsed.get("error") if isinstance(parsed.get("error"), Mapping) else {}
968
+ code = str(err_obj.get("code") or "GATEWAY_ERROR")
969
+ msg = str(err_obj.get("message") or parsed.get("message") or f"Error from {target_label}")
970
+ raise ProviderError(msg, status_code=status, code=code, secrets=(self._api_key,))
971
+
972
+ return parsed
973
+
974
+ raise ProviderError(
975
+ f"Exhausted retries calling {target_label}: {last_exc}",
976
+ code="RETRY_EXHAUSTED",
977
+ secrets=(self._api_key,),
978
+ )
979
+
980
+ def execute_operation(
981
+ self,
982
+ *,
983
+ service: str,
984
+ operation: str,
985
+ actor_slug: str | None = None,
986
+ actor_input: Mapping[str, Any] | None = None,
987
+ http_method: HttpMethod = "GET",
988
+ params: Mapping[str, Any] | None = None,
989
+ json_body: Mapping[str, Any] | None = None,
990
+ standby_path: str | None = None,
991
+ standby_params: Mapping[str, Any] | None = None,
992
+ prefer_standby: bool | None = None,
993
+ fallback_to_batch: bool = True,
994
+ rapidapi_host: str | None = None,
995
+ timeout_secs: int | None = None,
996
+ max_total_charge_usd: float | Decimal | None = None,
997
+ ) -> Any:
998
+ _ = (actor_slug, actor_input, standby_path, standby_params, prefer_standby, fallback_to_batch, max_total_charge_usd)
999
+ url, headers = self._resolve_url_and_headers(
1000
+ service=service,
1001
+ operation=operation,
1002
+ rapidapi_host=rapidapi_host,
1003
+ json_content=json_body is not None,
1004
+ )
1005
+ svc_clean = canonicalize_service_path(service)
1006
+ op_clean = normalize_operation_path(operation)
1007
+ return self._send_rest_request(
1008
+ http_method,
1009
+ url,
1010
+ headers,
1011
+ params=params,
1012
+ json_body=json_body,
1013
+ timeout_secs=timeout_secs,
1014
+ target_label=f"/v1/{svc_clean}/{op_clean}",
1015
+ )
1016
+
1017
+ def run_generic(
1018
+ self,
1019
+ target: str,
1020
+ payload: Mapping[str, Any] | None = None,
1021
+ *,
1022
+ method: HttpMethod | None = None,
1023
+ params: Mapping[str, Any] | None = None,
1024
+ rapidapi_host: str | None = None,
1025
+ timeout_secs: int | None = None,
1026
+ max_total_charge_usd: float | Decimal | None = None,
1027
+ ) -> Any:
1028
+ _ = max_total_charge_usd
1029
+ cleaned = str(target or "").strip().strip("/")
1030
+ if cleaned.startswith("v1/"):
1031
+ cleaned = cleaned[3:]
1032
+ if "/" in cleaned and not cleaned.startswith("unitbytes/"):
1033
+ svc, op = cleaned.split("/", 1)
1034
+ else:
1035
+ slug = cleaned.split("/", 1)[-1].split("~", 1)[-1]
1036
+ svc, op = slug, "run"
1037
+
1038
+ effective_method: HttpMethod = method or ("POST" if payload is not None else "GET")
1039
+ req_params = params if effective_method == "GET" else params
1040
+ req_body = payload if effective_method == "POST" else None
1041
+ if effective_method == "GET" and payload and not req_params:
1042
+ req_params = payload
1043
+
1044
+ return self.execute_operation(
1045
+ service=svc,
1046
+ operation=op,
1047
+ http_method=effective_method,
1048
+ params=req_params,
1049
+ json_body=req_body,
1050
+ rapidapi_host=rapidapi_host,
1051
+ timeout_secs=timeout_secs,
1052
+ )
1053
+
1054
+
1055
+ class CloudGatewayTransport(_BaseRestGatewayTransport):
1056
+ """REST transport for custom/enterprise UnitBytes Cloud Gateways (`GET/POST {base_url}/v1/{service}/{operation}`)."""
1057
+
1058
+ provider_name = "cloud"
1059
+
1060
+ def __init__(
1061
+ self,
1062
+ api_key: str,
1063
+ *,
1064
+ base_url: str | None = None,
1065
+ timeout_secs: int = 180,
1066
+ allow_custom_endpoints: bool = False,
1067
+ http_fn: HttpFunc | None = None,
1068
+ sleep_fn: Callable[[float], None] = time.sleep,
1069
+ ) -> None:
1070
+ cleaned_key = str(api_key or "").strip()
1071
+ if not cleaned_key:
1072
+ raise AuthenticationError(
1073
+ f"Missing UnitBytes Cloud API key. Export UNITBYTES_API_KEY=... or sign up at {SIGNUP_URL}"
1074
+ )
1075
+ if not base_url or not str(base_url).strip():
1076
+ raise ConfigurationError(
1077
+ "CloudGatewayTransport requires base_url='https://...' or the UNITBYTES_BASE_URL environment variable."
1078
+ )
1079
+ valid_base, _ = _parse_and_validate_base_url(
1080
+ base_url,
1081
+ label="UNITBYTES_BASE_URL / base_url",
1082
+ allow_custom_endpoints=allow_custom_endpoints,
1083
+ )
1084
+ super().__init__(
1085
+ cleaned_key,
1086
+ timeout_secs=timeout_secs,
1087
+ allow_custom_endpoints=allow_custom_endpoints,
1088
+ http_fn=http_fn,
1089
+ sleep_fn=sleep_fn,
1090
+ )
1091
+ self.base_url = valid_base
1092
+
1093
+ def __repr__(self) -> str:
1094
+ return (
1095
+ f"CloudGatewayTransport(base_url={self.base_url!r}, api_key='[REDACTED]', "
1096
+ f"timeout_secs={self.timeout_secs})"
1097
+ )
1098
+
1099
+ def _resolve_url_and_headers(
1100
+ self,
1101
+ *,
1102
+ service: str,
1103
+ operation: str,
1104
+ rapidapi_host: str | None = None,
1105
+ json_content: bool = False,
1106
+ ) -> tuple[str, dict[str, str]]:
1107
+ _ = (rapidapi_host, json_content)
1108
+ svc = canonicalize_service_path(service)
1109
+ op = normalize_operation_path(operation)
1110
+ url = f"{self.base_url}/v1/{svc}/{op}"
1111
+ headers = {
1112
+ "Accept": "application/json",
1113
+ "Authorization": f"Bearer {self._api_key}",
1114
+ "User-Agent": USER_AGENT,
1115
+ }
1116
+ return url, headers
1117
+
1118
+
1119
+ class RapidApiTransport(_BaseRestGatewayTransport):
1120
+ """REST transport for RapidAPI Hub (`https://{host}/v1/{service}/{operation}` with `X-RapidAPI-Key` & `X-RapidAPI-Host`)."""
1121
+
1122
+ provider_name = "rapidapi"
1123
+
1124
+ def __init__(
1125
+ self,
1126
+ api_key: str,
1127
+ *,
1128
+ rapidapi_host: str | None = None,
1129
+ base_url: str | None = None,
1130
+ timeout_secs: int = 180,
1131
+ allow_custom_endpoints: bool = False,
1132
+ http_fn: HttpFunc | None = None,
1133
+ sleep_fn: Callable[[float], None] = time.sleep,
1134
+ ) -> None:
1135
+ cleaned_key = str(api_key or "").strip()
1136
+ if not cleaned_key:
1137
+ raise AuthenticationError(
1138
+ "Missing RapidAPI key. Export RAPIDAPI_KEY=... or pass api_key='...'."
1139
+ )
1140
+ super().__init__(
1141
+ cleaned_key,
1142
+ timeout_secs=timeout_secs,
1143
+ allow_custom_endpoints=allow_custom_endpoints,
1144
+ http_fn=http_fn,
1145
+ sleep_fn=sleep_fn,
1146
+ )
1147
+ self.default_rapidapi_host: str | None = None
1148
+ self.base_url: str | None = None
1149
+
1150
+ if base_url and str(base_url).strip():
1151
+ valid_base, parsed_host = _parse_and_validate_base_url(
1152
+ base_url,
1153
+ label="RapidAPI base_url",
1154
+ allow_custom_endpoints=self.allow_custom_endpoints,
1155
+ allowed_suffixes=(".p.rapidapi.com",),
1156
+ )
1157
+ self.base_url = valid_base
1158
+ self.default_rapidapi_host = parsed_host
1159
+
1160
+ if rapidapi_host and str(rapidapi_host).strip():
1161
+ validated_host = self._validate_rapidapi_host(rapidapi_host)
1162
+ self.default_rapidapi_host = validated_host
1163
+
1164
+ def __repr__(self) -> str:
1165
+ return (
1166
+ f"RapidApiTransport(rapidapi_host={self.default_rapidapi_host!r}, "
1167
+ f"api_key='[REDACTED]', timeout_secs={self.timeout_secs})"
1168
+ )
1169
+
1170
+ def _validate_rapidapi_host(self, raw_host: str) -> str:
1171
+ host = str(raw_host or "").strip().lower().strip("/")
1172
+ if "://" in host or "/" in host or "@" in host or any(c.isspace() for c in host):
1173
+ raise ConfigurationError(f"Invalid rapidapi_host {raw_host!r}: expected bare hostname without scheme/path.")
1174
+ if not self.allow_custom_endpoints and not _RAPIDAPI_HOST_RE.fullmatch(host):
1175
+ raise ConfigurationError(
1176
+ f"Untrusted RapidAPI host {host!r}. Host must match '*.p.rapidapi.com' unless allow_custom_endpoints=True."
1177
+ )
1178
+ return host
1179
+
1180
+ def _resolve_url_and_headers(
1181
+ self,
1182
+ *,
1183
+ service: str,
1184
+ operation: str,
1185
+ rapidapi_host: str | None = None,
1186
+ json_content: bool = False,
1187
+ ) -> tuple[str, dict[str, str]]:
1188
+ _ = json_content
1189
+ svc_raw = str(service or "").strip().lower()
1190
+ svc_path = canonicalize_service_path(service)
1191
+ op_path = normalize_operation_path(operation)
1192
+
1193
+ if rapidapi_host and str(rapidapi_host).strip():
1194
+ host = self._validate_rapidapi_host(rapidapi_host)
1195
+ origin = self.base_url if (self.base_url and self.allow_custom_endpoints) else f"https://{host}"
1196
+ elif self.default_rapidapi_host:
1197
+ host = self.default_rapidapi_host
1198
+ origin = self.base_url or f"https://{host}"
1199
+ else:
1200
+ mapped_host = DEFAULT_RAPIDAPI_HOSTS.get(svc_raw) or DEFAULT_RAPIDAPI_HOSTS.get(svc_path)
1201
+ if not mapped_host:
1202
+ raise ConfigurationError(
1203
+ f"No built-in RapidAPI default host for service {service!r}. "
1204
+ "Pass rapidapi_host='<project>.p.rapidapi.com' explicitly."
1205
+ )
1206
+ host = mapped_host
1207
+ origin = f"https://{host}"
1208
+
1209
+ url = f"{origin}/v1/{svc_path}/{op_path}"
1210
+ headers = {
1211
+ "Accept": "application/json",
1212
+ "X-RapidAPI-Key": self._api_key,
1213
+ "X-RapidAPI-Host": host,
1214
+ "User-Agent": USER_AGENT,
1215
+ }
1216
+ return url, headers
1217
+
1218
+
1219
+ class ZylaTransport(_BaseRestGatewayTransport):
1220
+ """REST transport for Zyla API Hub (`https://zylalabs.com/...` with `Authorization: Bearer <key>`)."""
1221
+
1222
+ provider_name = "zyla"
1223
+
1224
+ def __init__(
1225
+ self,
1226
+ api_key: str,
1227
+ *,
1228
+ base_url: str | None = None,
1229
+ timeout_secs: int = 180,
1230
+ allow_custom_endpoints: bool = False,
1231
+ http_fn: HttpFunc | None = None,
1232
+ sleep_fn: Callable[[float], None] = time.sleep,
1233
+ ) -> None:
1234
+ cleaned_key = str(api_key or "").strip()
1235
+ if not cleaned_key:
1236
+ raise AuthenticationError(
1237
+ "Missing Zyla API key. Export ZYLA_API_KEY=... or pass api_key='...'."
1238
+ )
1239
+ if not base_url or not str(base_url).strip():
1240
+ raise ConfigurationError(
1241
+ "ZylaTransport requires base_url='https://zylalabs.com/...' (or ZYLA_BASE_URL)."
1242
+ )
1243
+ valid_base, _ = _parse_and_validate_base_url(
1244
+ base_url,
1245
+ label="Zyla base_url",
1246
+ allow_custom_endpoints=allow_custom_endpoints,
1247
+ allowed_hosts=frozenset({"zylalabs.com"}),
1248
+ allowed_suffixes=(".zylalabs.com",),
1249
+ )
1250
+ super().__init__(
1251
+ cleaned_key,
1252
+ timeout_secs=timeout_secs,
1253
+ allow_custom_endpoints=allow_custom_endpoints,
1254
+ http_fn=http_fn,
1255
+ sleep_fn=sleep_fn,
1256
+ )
1257
+ self.base_url = valid_base
1258
+
1259
+ def __repr__(self) -> str:
1260
+ return (
1261
+ f"ZylaTransport(base_url={self.base_url!r}, api_key='[REDACTED]', "
1262
+ f"timeout_secs={self.timeout_secs})"
1263
+ )
1264
+
1265
+ def _resolve_url_and_headers(
1266
+ self,
1267
+ *,
1268
+ service: str,
1269
+ operation: str,
1270
+ rapidapi_host: str | None = None,
1271
+ json_content: bool = False,
1272
+ ) -> tuple[str, dict[str, str]]:
1273
+ _ = (rapidapi_host, json_content)
1274
+ svc = canonicalize_service_path(service)
1275
+ op = normalize_operation_path(operation)
1276
+ url = f"{self.base_url}/v1/{svc}/{op}"
1277
+ headers = {
1278
+ "Accept": "application/json",
1279
+ "Authorization": f"Bearer {self._api_key}",
1280
+ "User-Agent": USER_AGENT,
1281
+ }
1282
+ return url, headers
1283
+
1284
+
1285
+ def resolve_transport(
1286
+ *,
1287
+ api_key: str | None = None,
1288
+ api_token: str | None = None,
1289
+ provider: ProviderLiteral = "auto",
1290
+ base_url: str | None = None,
1291
+ rapidapi_host: str | None = None,
1292
+ timeout_secs: int = 180,
1293
+ max_total_charge_usd: float | Decimal | None = None,
1294
+ allow_custom_endpoints: bool = False,
1295
+ prefer_standby: bool = False,
1296
+ transport: Transport | None = None,
1297
+ http_fn: HttpFunc | None = None,
1298
+ sleep_fn: Callable[[float], None] = time.sleep,
1299
+ ) -> Transport:
1300
+ """Resolve and instantiate the appropriate `Transport` with strict per-provider credential isolation."""
1301
+ if api_key is not None and api_token is not None and api_key.strip() != api_token.strip():
1302
+ raise ConfigurationError(
1303
+ "Conflicting api_key and api_token arguments provided; pass only one.",
1304
+ secrets=(api_key, api_token),
1305
+ )
1306
+
1307
+ if transport is not None:
1308
+ return transport
1309
+
1310
+ norm_charge = normalize_max_charge_usd(max_total_charge_usd)
1311
+ raw_provider = str(provider or "auto").strip().lower()
1312
+ if raw_provider == "auto":
1313
+ env_prov = (os.environ.get("UNITBYTES_PROVIDER") or "").strip().lower()
1314
+ if env_prov:
1315
+ raw_provider = env_prov
1316
+
1317
+ if raw_provider not in {"auto", "apify", "cloud", "rapidapi", "zyla"}:
1318
+ raise ConfigurationError(
1319
+ f"Unsupported provider {provider!r}. Expected 'auto', 'apify', 'cloud', 'rapidapi', or 'zyla'."
1320
+ )
1321
+
1322
+ explicit_key = (api_key if api_key is not None else api_token)
1323
+ cleaned_explicit = explicit_key.strip() if explicit_key is not None else ""
1324
+
1325
+ # 1. Explicit provider requested -> STRICT env var isolation (never cross-read another provider's env vars)
1326
+ if raw_provider == "cloud":
1327
+ key = cleaned_explicit or (os.environ.get("UNITBYTES_API_KEY") or "").strip()
1328
+ if not key:
1329
+ raise AuthenticationError(
1330
+ f"Missing UnitBytes Cloud API key for provider='cloud'. Export UNITBYTES_API_KEY=... or sign up at {SIGNUP_URL}"
1331
+ )
1332
+ cloud_url = (base_url or "").strip() or (os.environ.get("UNITBYTES_BASE_URL") or "").strip()
1333
+ if not cloud_url:
1334
+ raise ConfigurationError(
1335
+ "provider='cloud' requires base_url='https://...' or the UNITBYTES_BASE_URL environment variable."
1336
+ )
1337
+ return CloudGatewayTransport(
1338
+ key,
1339
+ base_url=cloud_url,
1340
+ timeout_secs=timeout_secs,
1341
+ allow_custom_endpoints=allow_custom_endpoints,
1342
+ http_fn=http_fn,
1343
+ sleep_fn=sleep_fn,
1344
+ )
1345
+
1346
+ if raw_provider == "apify":
1347
+ key = (
1348
+ cleaned_explicit
1349
+ or (os.environ.get("APIFY_TOKEN") or "").strip()
1350
+ or (os.environ.get("APIFY_API_TOKEN") or "").strip()
1351
+ )
1352
+ if not key:
1353
+ raise AuthenticationError(
1354
+ f"Missing Apify API token for provider='apify'. Export APIFY_TOKEN=... or sign up at {SIGNUP_URL}"
1355
+ )
1356
+ return ApifyTransport(
1357
+ key,
1358
+ base_url=base_url,
1359
+ timeout_secs=timeout_secs,
1360
+ max_total_charge_usd=norm_charge,
1361
+ prefer_standby=prefer_standby,
1362
+ allow_custom_endpoints=allow_custom_endpoints,
1363
+ http_fn=http_fn,
1364
+ sleep_fn=sleep_fn,
1365
+ )
1366
+
1367
+ if raw_provider == "rapidapi":
1368
+ key = (
1369
+ cleaned_explicit
1370
+ or (os.environ.get("RAPIDAPI_KEY") or "").strip()
1371
+ or (os.environ.get("X_RAPIDAPI_KEY") or "").strip()
1372
+ )
1373
+ if not key:
1374
+ raise AuthenticationError(
1375
+ "Missing RapidAPI key for provider='rapidapi'. Export RAPIDAPI_KEY=... or pass api_key='...'."
1376
+ )
1377
+ r_host = (rapidapi_host or "").strip() or (os.environ.get("RAPIDAPI_HOST") or "").strip() or None
1378
+ return RapidApiTransport(
1379
+ key,
1380
+ rapidapi_host=r_host,
1381
+ base_url=base_url,
1382
+ timeout_secs=timeout_secs,
1383
+ allow_custom_endpoints=allow_custom_endpoints,
1384
+ http_fn=http_fn,
1385
+ sleep_fn=sleep_fn,
1386
+ )
1387
+
1388
+ if raw_provider == "zyla":
1389
+ key = cleaned_explicit or (os.environ.get("ZYLA_API_KEY") or "").strip()
1390
+ if not key:
1391
+ raise AuthenticationError(
1392
+ "Missing Zyla API key for provider='zyla'. Export ZYLA_API_KEY=... or pass api_key='...'."
1393
+ )
1394
+ z_url = (base_url or "").strip() or (os.environ.get("ZYLA_BASE_URL") or "").strip() or None
1395
+ return ZylaTransport(
1396
+ key,
1397
+ base_url=z_url,
1398
+ timeout_secs=timeout_secs,
1399
+ allow_custom_endpoints=allow_custom_endpoints,
1400
+ http_fn=http_fn,
1401
+ sleep_fn=sleep_fn,
1402
+ )
1403
+
1404
+ # 2. provider="auto" -> inspect explicit key first, then env vars in strict priority order:
1405
+ # UNITBYTES_API_KEY -> APIFY_TOKEN/APIFY_API_TOKEN -> RAPIDAPI_KEY/X_RAPIDAPI_KEY -> ZYLA_API_KEY
1406
+ if cleaned_explicit:
1407
+ base_host = (urlparse(base_url.strip()).hostname or "").lower() if base_url and base_url.strip() else ""
1408
+ if cleaned_explicit.startswith("ub_"):
1409
+ cloud_url = (base_url or "").strip() or (os.environ.get("UNITBYTES_BASE_URL") or "").strip()
1410
+ if not cloud_url:
1411
+ raise ConfigurationError(
1412
+ "API key starting with 'ub_' requires base_url='https://...' or export UNITBYTES_BASE_URL=..."
1413
+ )
1414
+ return CloudGatewayTransport(
1415
+ cleaned_explicit,
1416
+ base_url=cloud_url,
1417
+ timeout_secs=timeout_secs,
1418
+ allow_custom_endpoints=allow_custom_endpoints,
1419
+ http_fn=http_fn,
1420
+ sleep_fn=sleep_fn,
1421
+ )
1422
+ if cleaned_explicit.startswith("apify_api_"):
1423
+ return ApifyTransport(
1424
+ cleaned_explicit,
1425
+ base_url=base_url,
1426
+ timeout_secs=timeout_secs,
1427
+ max_total_charge_usd=norm_charge,
1428
+ prefer_standby=prefer_standby,
1429
+ allow_custom_endpoints=allow_custom_endpoints,
1430
+ http_fn=http_fn,
1431
+ sleep_fn=sleep_fn,
1432
+ )
1433
+ if cleaned_explicit.startswith("zyla_") or base_host == "zylalabs.com" or base_host.endswith(".zylalabs.com"):
1434
+ z_url = (base_url or "").strip() or (os.environ.get("ZYLA_BASE_URL") or "").strip() or None
1435
+ return ZylaTransport(
1436
+ cleaned_explicit,
1437
+ base_url=z_url,
1438
+ timeout_secs=timeout_secs,
1439
+ allow_custom_endpoints=allow_custom_endpoints,
1440
+ http_fn=http_fn,
1441
+ sleep_fn=sleep_fn,
1442
+ )
1443
+ if (rapidapi_host and rapidapi_host.strip()) or base_host.endswith(".p.rapidapi.com"):
1444
+ return RapidApiTransport(
1445
+ cleaned_explicit,
1446
+ rapidapi_host=rapidapi_host,
1447
+ base_url=base_url,
1448
+ timeout_secs=timeout_secs,
1449
+ allow_custom_endpoints=allow_custom_endpoints,
1450
+ http_fn=http_fn,
1451
+ sleep_fn=sleep_fn,
1452
+ )
1453
+ return ApifyTransport(
1454
+ cleaned_explicit,
1455
+ base_url=base_url,
1456
+ timeout_secs=timeout_secs,
1457
+ max_total_charge_usd=norm_charge,
1458
+ prefer_standby=prefer_standby,
1459
+ allow_custom_endpoints=allow_custom_endpoints,
1460
+ http_fn=http_fn,
1461
+ sleep_fn=sleep_fn,
1462
+ )
1463
+
1464
+ env_ub = (os.environ.get("UNITBYTES_API_KEY") or "").strip()
1465
+ if env_ub:
1466
+ cloud_url = (base_url or "").strip() or (os.environ.get("UNITBYTES_BASE_URL") or "").strip()
1467
+ if not cloud_url:
1468
+ raise ConfigurationError(
1469
+ "UNITBYTES_API_KEY is set, but UNITBYTES_BASE_URL (or base_url) is missing. "
1470
+ "Export UNITBYTES_BASE_URL='https://...' to configure CloudGatewayTransport."
1471
+ )
1472
+ return CloudGatewayTransport(
1473
+ env_ub,
1474
+ base_url=cloud_url,
1475
+ timeout_secs=timeout_secs,
1476
+ allow_custom_endpoints=allow_custom_endpoints,
1477
+ http_fn=http_fn,
1478
+ sleep_fn=sleep_fn,
1479
+ )
1480
+
1481
+ env_apify = (
1482
+ (os.environ.get("APIFY_TOKEN") or "").strip()
1483
+ or (os.environ.get("APIFY_API_TOKEN") or "").strip()
1484
+ )
1485
+ if env_apify:
1486
+ return ApifyTransport(
1487
+ env_apify,
1488
+ base_url=base_url,
1489
+ timeout_secs=timeout_secs,
1490
+ max_total_charge_usd=norm_charge,
1491
+ prefer_standby=prefer_standby,
1492
+ allow_custom_endpoints=allow_custom_endpoints,
1493
+ http_fn=http_fn,
1494
+ sleep_fn=sleep_fn,
1495
+ )
1496
+
1497
+ env_rapid = (
1498
+ (os.environ.get("RAPIDAPI_KEY") or "").strip()
1499
+ or (os.environ.get("X_RAPIDAPI_KEY") or "").strip()
1500
+ )
1501
+ if env_rapid:
1502
+ r_host = (rapidapi_host or "").strip() or (os.environ.get("RAPIDAPI_HOST") or "").strip() or None
1503
+ return RapidApiTransport(
1504
+ env_rapid,
1505
+ rapidapi_host=r_host,
1506
+ base_url=base_url,
1507
+ timeout_secs=timeout_secs,
1508
+ allow_custom_endpoints=allow_custom_endpoints,
1509
+ http_fn=http_fn,
1510
+ sleep_fn=sleep_fn,
1511
+ )
1512
+
1513
+ env_zyla = (os.environ.get("ZYLA_API_KEY") or "").strip()
1514
+ if env_zyla:
1515
+ z_url = (base_url or "").strip() or (os.environ.get("ZYLA_BASE_URL") or "").strip() or None
1516
+ return ZylaTransport(
1517
+ env_zyla,
1518
+ base_url=z_url,
1519
+ timeout_secs=timeout_secs,
1520
+ allow_custom_endpoints=allow_custom_endpoints,
1521
+ http_fn=http_fn,
1522
+ sleep_fn=sleep_fn,
1523
+ )
1524
+
1525
+ raise AuthenticationError(
1526
+ "No API credentials found. Set `export UNITBYTES_API_KEY=...` (with `UNITBYTES_BASE_URL`), "
1527
+ "`export APIFY_TOKEN=...`, `export RAPIDAPI_KEY=...`, or `export ZYLA_API_KEY=...`, "
1528
+ f"or pass `api_key='...'`. Get started at {SIGNUP_URL}"
1529
+ )