raspbytes 1.1.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.
Files changed (39) hide show
  1. raspbytes/__init__.py +87 -0
  2. raspbytes/_core/__init__.py +1 -0
  3. raspbytes/_core/constants.py +38 -0
  4. raspbytes/_core/http.py +160 -0
  5. raspbytes/_core/transport.py +175 -0
  6. raspbytes/_core/types.py +11 -0
  7. raspbytes/_core/version.py +8 -0
  8. raspbytes/client.py +88 -0
  9. raspbytes/config.py +122 -0
  10. raspbytes/countries.py +278 -0
  11. raspbytes/exceptions.py +115 -0
  12. raspbytes/managed_scrapers.py +4 -0
  13. raspbytes/models.py +89 -0
  14. raspbytes/py.typed +1 -0
  15. raspbytes/resources/__init__.py +17 -0
  16. raspbytes/resources/_base.py +75 -0
  17. raspbytes/resources/_polling.py +73 -0
  18. raspbytes/resources/browser.py +185 -0
  19. raspbytes/resources/proxies.py +49 -0
  20. raspbytes/resources/scraper/__init__.py +45 -0
  21. raspbytes/resources/scraper/_generated/__init__.py +1 -0
  22. raspbytes/resources/scraper/_generated/managed.py +190 -0
  23. raspbytes/resources/scraper/_generated/wire.py +632 -0
  24. raspbytes/resources/scraper/_managed.py +14 -0
  25. raspbytes/resources/scraper/_request.py +128 -0
  26. raspbytes/resources/scraper/builder.py +199 -0
  27. raspbytes/resources/scraper/hub.py +168 -0
  28. raspbytes/resources/scraper/monitoring.py +132 -0
  29. raspbytes/resources/scraper/runs.py +202 -0
  30. raspbytes/resources/scraper/schedules.py +172 -0
  31. raspbytes/resources/scraper/storage.py +155 -0
  32. raspbytes/resources/scraper/tasks.py +134 -0
  33. raspbytes/resources/scraper/types.py +96 -0
  34. raspbytes/resources/unblocker.py +131 -0
  35. raspbytes/scraper_types.py +4 -0
  36. raspbytes-1.1.0.dist-info/METADATA +297 -0
  37. raspbytes-1.1.0.dist-info/RECORD +39 -0
  38. raspbytes-1.1.0.dist-info/WHEEL +4 -0
  39. raspbytes-1.1.0.dist-info/licenses/LICENSE +25 -0
raspbytes/__init__.py ADDED
@@ -0,0 +1,87 @@
1
+ from ._core.version import __version__
2
+ from .client import AsyncRaspbytes, Raspbytes
3
+ from .config import (
4
+ BaseConfig,
5
+ BrowserConfig,
6
+ ProxyConfig,
7
+ RaspbytesConfig,
8
+ ScraperConfig,
9
+ UnblockerConfig,
10
+ )
11
+ from .countries import COUNTRIES, Country
12
+ from .exceptions import (
13
+ APIConnectionError,
14
+ APIError,
15
+ APITimeoutError,
16
+ AuthenticationError,
17
+ BadRequestError,
18
+ ConfigurationError,
19
+ NotFoundError,
20
+ PaymentRequiredError,
21
+ PermissionDeniedError,
22
+ PollTimeoutError,
23
+ ProxyAuthenticationError,
24
+ RaspbytesError,
25
+ RateLimitError,
26
+ ScraperRunError,
27
+ ServerError,
28
+ TerminalStateError,
29
+ UpstreamRequestError,
30
+ )
31
+ from .models import (
32
+ BrowserProxy,
33
+ BrowserSessionParams,
34
+ ProxyConnectionParams,
35
+ UnblockRequest,
36
+ )
37
+ from .resources.scraper.types import (
38
+ ScraperHubItem,
39
+ ScraperHubPage,
40
+ ScraperHubRun,
41
+ ScraperHubRunConfiguration,
42
+ ScraperRequest,
43
+ ScraperRun,
44
+ ScraperRunPage,
45
+ )
46
+
47
+ __all__ = [
48
+ "APIConnectionError",
49
+ "APIError",
50
+ "APITimeoutError",
51
+ "AsyncRaspbytes",
52
+ "AuthenticationError",
53
+ "BadRequestError",
54
+ "BaseConfig",
55
+ "BrowserProxy",
56
+ "BrowserConfig",
57
+ "BrowserSessionParams",
58
+ "ConfigurationError",
59
+ "NotFoundError",
60
+ "PaymentRequiredError",
61
+ "PermissionDeniedError",
62
+ "PollTimeoutError",
63
+ "ProxyAuthenticationError",
64
+ "ProxyConfig",
65
+ "ProxyConnectionParams",
66
+ "Raspbytes",
67
+ "RaspbytesConfig",
68
+ "RaspbytesError",
69
+ "RateLimitError",
70
+ "COUNTRIES",
71
+ "Country",
72
+ "ScraperConfig",
73
+ "ScraperHubItem",
74
+ "ScraperHubPage",
75
+ "ScraperHubRun",
76
+ "ScraperHubRunConfiguration",
77
+ "ScraperRequest",
78
+ "ScraperRun",
79
+ "ScraperRunError",
80
+ "ScraperRunPage",
81
+ "ServerError",
82
+ "TerminalStateError",
83
+ "UnblockRequest",
84
+ "UnblockerConfig",
85
+ "UpstreamRequestError",
86
+ "__version__",
87
+ ]
@@ -0,0 +1 @@
1
+ """Shared HTTP and wire infrastructure."""
@@ -0,0 +1,38 @@
1
+ """Names used by the Raspbytes HTTP wire contract."""
2
+
3
+
4
+ class EnvironmentVariable:
5
+ API_KEY = "RASPBYTES_API_KEY"
6
+ BASE_URL = "RASPBYTES_BASE_URL"
7
+
8
+
9
+ class Header:
10
+ ACCEPT = "Accept"
11
+ API_KEY = "X-API-Key"
12
+ REQUEST_ID = "X-Request-ID"
13
+ REQUEST_ID_FALLBACK = "Request-ID"
14
+ RETRY_AFTER = "Retry-After"
15
+ USER_AGENT = "User-Agent"
16
+
17
+
18
+ class RequestField:
19
+ COUNTRY = "country"
20
+ PAGE = "page"
21
+ PAGE_SIZE = "page_size"
22
+ PROXY_TYPE = "proxy_type"
23
+ QUERY = "query"
24
+ SESSION = "session"
25
+ SESSION_ID = "session_id"
26
+ STATUS = "status"
27
+
28
+
29
+ class ResponseField:
30
+ CODE = "code"
31
+ CONNECTION = "connection"
32
+ DETAIL = "detail"
33
+ ERROR = "error"
34
+ MESSAGE = "message"
35
+ REQUEST_ID = "request_id"
36
+ RETRYABLE = "retryable"
37
+ STATUS = "status"
38
+ URL = "url"
@@ -0,0 +1,160 @@
1
+ """HTTP response, error, and retry helpers shared by both transports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import random
7
+ from collections.abc import Mapping
8
+ from datetime import UTC
9
+ from email.utils import parsedate_to_datetime
10
+ from http import HTTPStatus
11
+ from math import isfinite
12
+ from time import time
13
+ from typing import cast
14
+
15
+ import httpx
16
+
17
+ from ..exceptions import (
18
+ APIError,
19
+ AuthenticationError,
20
+ BadRequestError,
21
+ NotFoundError,
22
+ PaymentRequiredError,
23
+ PermissionDeniedError,
24
+ ProxyAuthenticationError,
25
+ RateLimitError,
26
+ ServerError,
27
+ UpstreamRequestError,
28
+ )
29
+ from .constants import Header, ResponseField
30
+ from .types import ResponseData
31
+ from .version import __version__
32
+
33
+ _ERROR_TYPES: dict[int, type[APIError]] = {
34
+ HTTPStatus.BAD_REQUEST: BadRequestError,
35
+ HTTPStatus.UNAUTHORIZED: AuthenticationError,
36
+ HTTPStatus.PAYMENT_REQUIRED: PaymentRequiredError,
37
+ HTTPStatus.FORBIDDEN: PermissionDeniedError,
38
+ HTTPStatus.NOT_FOUND: NotFoundError,
39
+ HTTPStatus.PROXY_AUTHENTICATION_REQUIRED: ProxyAuthenticationError,
40
+ HTTPStatus.FAILED_DEPENDENCY: UpstreamRequestError,
41
+ HTTPStatus.TOO_MANY_REQUESTS: RateLimitError,
42
+ }
43
+ _RETRYABLE_STATUS_CODES = frozenset(
44
+ {
45
+ HTTPStatus.REQUEST_TIMEOUT,
46
+ HTTPStatus.CONFLICT,
47
+ HTTPStatus.TOO_MANY_REQUESTS,
48
+ HTTPStatus.INTERNAL_SERVER_ERROR,
49
+ HTTPStatus.BAD_GATEWAY,
50
+ HTTPStatus.SERVICE_UNAVAILABLE,
51
+ HTTPStatus.GATEWAY_TIMEOUT,
52
+ }
53
+ )
54
+
55
+
56
+ def build_headers(api_key: str | None, extra: Mapping[str, str] | None = None) -> dict[str, str]:
57
+ headers = {
58
+ Header.ACCEPT: "application/json",
59
+ Header.USER_AGENT: f"raspbytes-python/{__version__}",
60
+ }
61
+ if api_key:
62
+ headers[Header.API_KEY] = api_key
63
+ if extra:
64
+ headers.update(extra)
65
+ return headers
66
+
67
+
68
+ def decode_response(response: httpx.Response) -> ResponseData:
69
+ if response.status_code == HTTPStatus.NO_CONTENT or not response.content:
70
+ return None
71
+ try:
72
+ return cast(ResponseData, response.json())
73
+ except (json.JSONDecodeError, UnicodeDecodeError):
74
+ return response.text
75
+
76
+
77
+ def api_error_from_response(response: httpx.Response) -> APIError:
78
+ body = decode_response(response)
79
+ request_id = response.headers.get(Header.REQUEST_ID) or response.headers.get(
80
+ Header.REQUEST_ID_FALLBACK
81
+ )
82
+ code: str | None = None
83
+ message = response.reason_phrase or "Raspbytes API request failed"
84
+
85
+ if isinstance(body, dict):
86
+ error = body.get(ResponseField.ERROR)
87
+ if isinstance(error, dict):
88
+ code_value = error.get(ResponseField.CODE)
89
+ code = str(code_value) if code_value is not None else None
90
+ message = str(
91
+ error.get(ResponseField.MESSAGE) or error.get(ResponseField.DETAIL) or message
92
+ )
93
+ request_value = error.get(ResponseField.REQUEST_ID)
94
+ if request_value is not None:
95
+ request_id = str(request_value)
96
+ elif isinstance(error, str):
97
+ message = error
98
+ else:
99
+ code_value = body.get(ResponseField.CODE)
100
+ code = str(code_value) if code_value is not None else None
101
+ message = str(
102
+ body.get(ResponseField.MESSAGE) or body.get(ResponseField.DETAIL) or message
103
+ )
104
+ if body.get(ResponseField.REQUEST_ID) is not None:
105
+ request_id = str(body[ResponseField.REQUEST_ID])
106
+ elif isinstance(body, str) and body:
107
+ message = body
108
+
109
+ error_type = _ERROR_TYPES.get(response.status_code)
110
+ if error_type is None:
111
+ error_type = (
112
+ ServerError if response.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR else APIError
113
+ )
114
+ return error_type(
115
+ message,
116
+ status_code=response.status_code,
117
+ code=code,
118
+ request_id=request_id,
119
+ body=body,
120
+ headers=response.headers,
121
+ )
122
+
123
+
124
+ def is_retryable_response(response: httpx.Response) -> bool:
125
+ if response.status_code not in _RETRYABLE_STATUS_CODES:
126
+ return False
127
+ try:
128
+ body = response.json()
129
+ except (json.JSONDecodeError, UnicodeDecodeError):
130
+ return False
131
+ if not isinstance(body, dict):
132
+ return False
133
+ if body.get(ResponseField.RETRYABLE) is True:
134
+ return True
135
+ error = body.get(ResponseField.ERROR)
136
+ return isinstance(error, dict) and error.get(ResponseField.RETRYABLE) is True
137
+
138
+
139
+ def _retry_after_seconds(value: str) -> float | None:
140
+ try:
141
+ delay = float(value)
142
+ except ValueError:
143
+ try:
144
+ retry_at = parsedate_to_datetime(value)
145
+ except ValueError:
146
+ return None
147
+ if retry_at.tzinfo is None:
148
+ retry_at = retry_at.replace(tzinfo=UTC)
149
+ delay = retry_at.timestamp() - time()
150
+ return delay if isfinite(delay) else None
151
+
152
+
153
+ def retry_delay(response: httpx.Response | None, attempt: int) -> float:
154
+ if response is not None:
155
+ retry_after = response.headers.get(Header.RETRY_AFTER)
156
+ if retry_after:
157
+ delay = _retry_after_seconds(retry_after)
158
+ if delay is not None:
159
+ return min(max(delay, 0.0), 60.0)
160
+ return cast(float, min(0.5 * (2**attempt) + random.uniform(0, 0.25), 8.0))
@@ -0,0 +1,175 @@
1
+ """Synchronous and asynchronous HTTP transports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import time
8
+ from collections.abc import Mapping
9
+ from typing import Any, Self
10
+
11
+ import httpx
12
+
13
+ from ..config import DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, _ResolvedConfig
14
+ from ..exceptions import APIConnectionError, APITimeoutError, ConfigurationError
15
+ from . import http
16
+ from .constants import EnvironmentVariable
17
+ from .types import Query, ResponseData
18
+
19
+
20
+ class SyncTransport:
21
+ def __init__(
22
+ self,
23
+ *,
24
+ api_key: str | None = None,
25
+ base_url: str = DEFAULT_BASE_URL,
26
+ timeout: float = DEFAULT_TIMEOUT,
27
+ max_retries: int = DEFAULT_MAX_RETRIES,
28
+ http_client: httpx.Client | None = None,
29
+ ) -> None:
30
+ if max_retries < 0:
31
+ raise ConfigurationError("max_retries cannot be negative")
32
+ self.api_key = api_key if api_key is not None else os.getenv(EnvironmentVariable.API_KEY)
33
+ self.base_url = base_url.rstrip("/") + "/"
34
+ self.max_retries = max_retries
35
+ self.timeout = timeout
36
+ self._resolved_config = _ResolvedConfig(
37
+ api_key=self.api_key,
38
+ base_url=self.base_url,
39
+ timeout=self.timeout,
40
+ max_retries=self.max_retries,
41
+ )
42
+ self._owns_client = http_client is None
43
+ self._http = http_client or httpx.Client(timeout=timeout)
44
+
45
+ def request(
46
+ self,
47
+ method: str,
48
+ path: str,
49
+ *,
50
+ params: Query | None = None,
51
+ json: Mapping[str, Any] | None = None,
52
+ headers: Mapping[str, str] | None = None,
53
+ config: _ResolvedConfig | None = None,
54
+ retry_response: bool = True,
55
+ ) -> ResponseData:
56
+ request_config = config or self._resolved_config
57
+ url = request_config.base_url + path.lstrip("/")
58
+ clean_params = {key: value for key, value in (params or {}).items() if value is not None}
59
+ for attempt in range(request_config.max_retries + 1):
60
+ try:
61
+ response = self._http.request(
62
+ method,
63
+ url,
64
+ params=clean_params or None,
65
+ json=json,
66
+ headers=http.build_headers(request_config.api_key, headers),
67
+ timeout=request_config.timeout,
68
+ )
69
+ except httpx.TimeoutException as exc:
70
+ raise APITimeoutError(f"Request to {url} timed out") from exc
71
+ except httpx.HTTPError as exc:
72
+ if attempt < request_config.max_retries and isinstance(exc, httpx.ConnectError):
73
+ time.sleep(http.retry_delay(None, attempt))
74
+ continue
75
+ raise APIConnectionError(f"Could not connect to {url}") from exc
76
+ if response.is_success:
77
+ return http.decode_response(response)
78
+ if (
79
+ retry_response
80
+ and attempt < request_config.max_retries
81
+ and http.is_retryable_response(response)
82
+ ):
83
+ time.sleep(http.retry_delay(response, attempt))
84
+ continue
85
+ raise http.api_error_from_response(response)
86
+ raise AssertionError("unreachable")
87
+
88
+ def close(self) -> None:
89
+ if self._owns_client:
90
+ self._http.close()
91
+
92
+ def __enter__(self) -> Self:
93
+ return self
94
+
95
+ def __exit__(self, *_: object) -> None:
96
+ self.close()
97
+
98
+
99
+ class AsyncTransport:
100
+ def __init__(
101
+ self,
102
+ *,
103
+ api_key: str | None = None,
104
+ base_url: str = DEFAULT_BASE_URL,
105
+ timeout: float = DEFAULT_TIMEOUT,
106
+ max_retries: int = DEFAULT_MAX_RETRIES,
107
+ http_client: httpx.AsyncClient | None = None,
108
+ ) -> None:
109
+ if max_retries < 0:
110
+ raise ConfigurationError("max_retries cannot be negative")
111
+ self.api_key = api_key if api_key is not None else os.getenv(EnvironmentVariable.API_KEY)
112
+ self.base_url = base_url.rstrip("/") + "/"
113
+ self.max_retries = max_retries
114
+ self.timeout = timeout
115
+ self._resolved_config = _ResolvedConfig(
116
+ api_key=self.api_key,
117
+ base_url=self.base_url,
118
+ timeout=self.timeout,
119
+ max_retries=self.max_retries,
120
+ )
121
+ self._owns_client = http_client is None
122
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
123
+
124
+ async def request(
125
+ self,
126
+ method: str,
127
+ path: str,
128
+ *,
129
+ params: Query | None = None,
130
+ json: Mapping[str, Any] | None = None,
131
+ headers: Mapping[str, str] | None = None,
132
+ config: _ResolvedConfig | None = None,
133
+ retry_response: bool = True,
134
+ ) -> ResponseData:
135
+ request_config = config or self._resolved_config
136
+ url = request_config.base_url + path.lstrip("/")
137
+ clean_params = {key: value for key, value in (params or {}).items() if value is not None}
138
+ for attempt in range(request_config.max_retries + 1):
139
+ try:
140
+ response = await self._http.request(
141
+ method,
142
+ url,
143
+ params=clean_params or None,
144
+ json=json,
145
+ headers=http.build_headers(request_config.api_key, headers),
146
+ timeout=request_config.timeout,
147
+ )
148
+ except httpx.TimeoutException as exc:
149
+ raise APITimeoutError(f"Request to {url} timed out") from exc
150
+ except httpx.HTTPError as exc:
151
+ if attempt < request_config.max_retries and isinstance(exc, httpx.ConnectError):
152
+ await asyncio.sleep(http.retry_delay(None, attempt))
153
+ continue
154
+ raise APIConnectionError(f"Could not connect to {url}") from exc
155
+ if response.is_success:
156
+ return http.decode_response(response)
157
+ if (
158
+ retry_response
159
+ and attempt < request_config.max_retries
160
+ and http.is_retryable_response(response)
161
+ ):
162
+ await asyncio.sleep(http.retry_delay(response, attempt))
163
+ continue
164
+ raise http.api_error_from_response(response)
165
+ raise AssertionError("unreachable")
166
+
167
+ async def close(self) -> None:
168
+ if self._owns_client:
169
+ await self._http.aclose()
170
+
171
+ async def __aenter__(self) -> Self:
172
+ return self
173
+
174
+ async def __aexit__(self, *_: object) -> None:
175
+ await self.close()
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any, TypeAlias
5
+
6
+ JSONPrimitive: TypeAlias = str | int | float | bool | None
7
+ JSONValue: TypeAlias = JSONPrimitive | list["JSONValue"] | dict[str, "JSONValue"]
8
+ JSONObject = dict[str, JSONValue]
9
+ JSONMapping = Mapping[str, JSONValue]
10
+ ResponseData = JSONObject | list[JSONValue] | JSONPrimitive
11
+ Query = Mapping[str, Any]
@@ -0,0 +1,8 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("raspbytes")
7
+ except PackageNotFoundError: # pragma: no cover - only possible from an unpackaged source tree
8
+ __version__ = "0.0.0"
raspbytes/client.py ADDED
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ import httpx
4
+
5
+ from ._core.transport import AsyncTransport, SyncTransport
6
+ from .config import BaseConfig, RaspbytesConfig, _resolve_config
7
+ from .resources import (
8
+ AsyncBrowserResource,
9
+ AsyncProxiesResource,
10
+ AsyncScraperResource,
11
+ AsyncUnblockerResource,
12
+ BrowserResource,
13
+ ProxiesResource,
14
+ ScraperResource,
15
+ UnblockerResource,
16
+ )
17
+
18
+
19
+ class Raspbytes(SyncTransport):
20
+ """Synchronous client for every documented Raspbytes product API."""
21
+
22
+ def __init__(
23
+ self,
24
+ *,
25
+ config: RaspbytesConfig | None = None,
26
+ api_key: str | None = None,
27
+ base_url: str | None = None,
28
+ timeout: float | None = None,
29
+ max_retries: int | None = None,
30
+ http_client: httpx.Client | None = None,
31
+ ) -> None:
32
+ root_config = config or RaspbytesConfig()
33
+ resolved = _resolve_config(
34
+ BaseConfig(
35
+ api_key=api_key,
36
+ base_url=base_url,
37
+ timeout=timeout,
38
+ max_retries=max_retries,
39
+ ),
40
+ fallback=_resolve_config(root_config),
41
+ )
42
+ super().__init__(
43
+ api_key=resolved.api_key,
44
+ base_url=resolved.base_url,
45
+ timeout=resolved.timeout,
46
+ max_retries=resolved.max_retries,
47
+ http_client=http_client,
48
+ )
49
+ self.proxies = ProxiesResource(self, root_config.proxies)
50
+ self.browser = BrowserResource(self, root_config.browser)
51
+ self.unblocker = UnblockerResource(self, root_config.unblocker)
52
+ self.scraper = ScraperResource(self, root_config.scraper)
53
+
54
+
55
+ class AsyncRaspbytes(AsyncTransport):
56
+ """Asynchronous client for every documented Raspbytes product API."""
57
+
58
+ def __init__(
59
+ self,
60
+ *,
61
+ config: RaspbytesConfig | None = None,
62
+ api_key: str | None = None,
63
+ base_url: str | None = None,
64
+ timeout: float | None = None,
65
+ max_retries: int | None = None,
66
+ http_client: httpx.AsyncClient | None = None,
67
+ ) -> None:
68
+ root_config = config or RaspbytesConfig()
69
+ resolved = _resolve_config(
70
+ BaseConfig(
71
+ api_key=api_key,
72
+ base_url=base_url,
73
+ timeout=timeout,
74
+ max_retries=max_retries,
75
+ ),
76
+ fallback=_resolve_config(root_config),
77
+ )
78
+ super().__init__(
79
+ api_key=resolved.api_key,
80
+ base_url=resolved.base_url,
81
+ timeout=resolved.timeout,
82
+ max_retries=resolved.max_retries,
83
+ http_client=http_client,
84
+ )
85
+ self.proxies = AsyncProxiesResource(self, root_config.proxies)
86
+ self.browser = AsyncBrowserResource(self, root_config.browser)
87
+ self.unblocker = AsyncUnblockerResource(self, root_config.unblocker)
88
+ self.scraper = AsyncScraperResource(self, root_config.scraper)
raspbytes/config.py ADDED
@@ -0,0 +1,122 @@
1
+ """Typed configuration for the client and individual Raspbytes products."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from math import isfinite
8
+
9
+ from ._core.constants import EnvironmentVariable
10
+ from .exceptions import ConfigurationError
11
+
12
+ DEFAULT_BASE_URL = "https://api.raspbytes.com/api/v1/"
13
+ DEFAULT_TIMEOUT = 90.0
14
+ DEFAULT_MAX_RETRIES = 2
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class BaseConfig:
19
+ """Transport settings that can be inherited or overridden by a product."""
20
+
21
+ api_key: str | None = field(default=None, repr=False)
22
+ base_url: str | None = None
23
+ timeout: float | None = None
24
+ max_retries: int | None = None
25
+
26
+ def __post_init__(self) -> None:
27
+ if self.base_url is not None and not self.base_url.strip():
28
+ raise ConfigurationError("base_url cannot be empty")
29
+ if self.timeout is not None and self.timeout <= 0:
30
+ raise ConfigurationError("timeout must be positive")
31
+ if self.max_retries is not None and self.max_retries < 0:
32
+ raise ConfigurationError("max_retries cannot be negative")
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ProxyConfig(BaseConfig):
37
+ """Proxy API configuration."""
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class BrowserConfig(BaseConfig):
42
+ """Browser API transport and session polling configuration."""
43
+
44
+ poll_timeout: float = 60.0
45
+ poll_interval: float = 1.0
46
+
47
+ def __post_init__(self) -> None:
48
+ super().__post_init__()
49
+ _validate_polling(self.poll_timeout, self.poll_interval)
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class UnblockerConfig(BaseConfig):
54
+ """Web Unblocker transport and request polling configuration."""
55
+
56
+ poll_timeout: float = 90.0
57
+ poll_interval: float = 1.0
58
+
59
+ def __post_init__(self) -> None:
60
+ super().__post_init__()
61
+ _validate_polling(self.poll_timeout, self.poll_interval)
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class ScraperConfig(BaseConfig):
66
+ """Scraper API transport and run polling configuration."""
67
+
68
+ poll_timeout: float = 120.0
69
+ poll_interval: float = 1.0
70
+
71
+ def __post_init__(self) -> None:
72
+ super().__post_init__()
73
+ _validate_polling(self.poll_timeout, self.poll_interval)
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class RaspbytesConfig(BaseConfig):
78
+ """Root configuration with optional per-product overrides."""
79
+
80
+ proxies: ProxyConfig = field(default_factory=ProxyConfig)
81
+ browser: BrowserConfig = field(default_factory=BrowserConfig)
82
+ unblocker: UnblockerConfig = field(default_factory=UnblockerConfig)
83
+ scraper: ScraperConfig = field(default_factory=ScraperConfig)
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class _ResolvedConfig:
88
+ """Complete internal transport configuration after inheritance."""
89
+
90
+ api_key: str | None = field(repr=False)
91
+ base_url: str
92
+ timeout: float
93
+ max_retries: int
94
+
95
+
96
+ def _resolve_config(
97
+ config: BaseConfig,
98
+ *,
99
+ fallback: _ResolvedConfig | None = None,
100
+ ) -> _ResolvedConfig:
101
+ inherited = fallback or _ResolvedConfig(
102
+ api_key=None,
103
+ base_url=os.getenv(EnvironmentVariable.BASE_URL) or DEFAULT_BASE_URL,
104
+ timeout=DEFAULT_TIMEOUT,
105
+ max_retries=DEFAULT_MAX_RETRIES,
106
+ )
107
+ base_url = config.base_url if config.base_url is not None else inherited.base_url
108
+ return _ResolvedConfig(
109
+ api_key=config.api_key if config.api_key is not None else inherited.api_key,
110
+ base_url=base_url.rstrip("/") + "/",
111
+ timeout=config.timeout if config.timeout is not None else inherited.timeout,
112
+ max_retries=(
113
+ config.max_retries if config.max_retries is not None else inherited.max_retries
114
+ ),
115
+ )
116
+
117
+
118
+ def _validate_polling(timeout: float, interval: float) -> None:
119
+ if not isfinite(timeout) or timeout < 0:
120
+ raise ConfigurationError("poll_timeout must be finite and non-negative")
121
+ if not isfinite(interval) or interval < 0:
122
+ raise ConfigurationError("poll_interval must be finite and non-negative")