diff --git a/README.md b/README.md index d9933d5..7e3b3dd 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ Full API reference (all endpoints, error codes, captcha-type details): **https:/ - [Tencent](#tencent) - [Advanced Usage](#advanced-usage) - [Check balance](#check-balance) + - [Debug mode](#debug-mode) - [Custom timeout and polling](#custom-timeout-and-polling) - [Worker language pool](#worker-language-pool) - [Async client](#async-client) @@ -189,6 +190,7 @@ Constructor. | `timeout` | `int` | `120` | Polling window after task creation, in seconds. Overridable per call; each HTTP request has a separate 30-second timeout. | | `polling_interval` | `int` | `10` | Seconds before the first `getTaskResult` poll and between subsequent polls. | | `language_pool` | `Optional[str]` | `None` | Default worker pool (`"en"` or `"ru"`) applied to every call that doesn't pass its own `language_pool`. | +| `debug` | `bool` | `False` | Emit sanitized request/response, timing, polling, error, and solve summary logs. | Both clients hold a reusable connection pool (`requests.Session` / `httpx.AsyncClient`) for their lifetime instead of opening one per request. Close it when you're done -- @@ -622,7 +624,7 @@ Use this method to identify points that a worker should click in a generic image | `body` | yes | The captcha image, base64-encoded. | | `comment` | no (recommended) | Hint for the worker, e.g. `"click on the green apple"`. | | `imgInstructions` | no | Optional instruction image, base64-encoded. | -| `minClicks` | no | Minimum number of clicks expected (default `1`). | +| `minClicks` | no | Minimum number of clicks expected. When unset, the SDK omits this field and lets the API apply its default. | | `maxClicks` | no | Maximum number of clicks allowed. | **Response:** `coordinates` -- a list of `{"x": int, "y": int}` pixel positions to click, in order. @@ -684,6 +686,38 @@ balance = client.get_balance() print(f"Balance: {balance}") ``` +### Debug mode + +Pass `debug=True` to either client to diagnose an integration. The SDK logs its version and +configuration, each HTTP operation and duration, compact one-line `processing` polls, detailed +sanitized request/response blocks for completed operations and failures, and a `SOLVE SUMMARY` +after every `solve()` call (including failed calls). Debug mode is never enabled from an +environment variable and logging failures do not change request results or SDK exceptions. + +```python +client = CaptchaClient("your_api_key", debug=True) +solution = client.solve(task) +``` + +API credentials, cookies, and proxy credentials are replaced with `[MASKED]`. Proxy type and +port remain visible. Base64 image fields are +replaced with their character count, and other strings longer than 200 characters retain only +their first and last 40 characters plus the original length. The SDK does not log HTTP headers. +URLs and custom task fields can still contain application data, so review logs before sharing +them publicly. + +Dedicated synchronous and asynchronous examples demonstrate debug mode: + +```bash +python examples/sync/debug_mode.py +python examples/async/debug_mode.py +``` + +Examples read `CAPTCHA_API_KEY` from the environment or `.env`. They create real paid CAPTCHA +tasks unless their description says otherwise. See +[`examples/sync/debug_mode.py`](examples/sync/debug_mode.py) and +[`examples/async/debug_mode.py`](examples/async/debug_mode.py). + ### Custom timeout and polling ```python @@ -711,8 +745,8 @@ check the same task later; calling `solve()` again creates a new task. While polling, `solve()` retries short network failures and HTTP timeouts of `getTaskResult` on the next poll, so a brief outage does not lose an already -created task. After `poll_retries` (default 3) consecutive failures the error is -raised. API errors are not retried, and `createTask` is never retried because +created task. The SDK tolerates up to `poll_retries` (default 3) consecutive +failures and raises the next one. API errors are not retried, and `createTask` is never retried because that could create and pay for a second task. To change the limit: ```python diff --git a/captcha_solver_api/_constants.py b/captcha_solver_api/_constants.py new file mode 100644 index 0000000..23fa4e8 --- /dev/null +++ b/captcha_solver_api/_constants.py @@ -0,0 +1,3 @@ +"""Internal constants shared by the synchronous and asynchronous clients.""" + +HTTP_TIMEOUT_SECONDS = 30 diff --git a/captcha_solver_api/_debug.py b/captcha_solver_api/_debug.py new file mode 100644 index 0000000..d5f12aa --- /dev/null +++ b/captcha_solver_api/_debug.py @@ -0,0 +1,239 @@ +"""Internal, best-effort debug logging helpers.""" + +from __future__ import annotations + +import json +import logging +from datetime import datetime +from typing import Any, Dict, List, Optional + +_MASKED_KEYS = { + "authorization", + "clientkey", + "cookie", + "cookies", + "password", + "proxyaddress", + "proxylogin", + "proxypassword", +} +_BASE64_KEYS = {"body", "image", "imginstructions"} +_handler: Optional[logging.Handler] = None + + +def _sanitize(value: Any, key: str = "") -> Any: + """Return a sanitized copy suitable for diagnostic output.""" + normalized_key = key.lower() + if normalized_key in _MASKED_KEYS: + return "[MASKED]" + if normalized_key in _BASE64_KEYS and isinstance(value, str): + return f"[base64, {len(value)} chars]" + if isinstance(value, dict): + return {item_key: _sanitize(item, str(item_key)) for item_key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_sanitize(item) for item in value] + if isinstance(value, str) and len(value) > 200: + return f"{value[:40]}...[{len(value)} chars]...{value[-40:]}" + return value + + +def _json(value: Any) -> str: + return json.dumps(_sanitize(value), indent=2, ensure_ascii=False, default=repr) + + +def _timestamp() -> str: + now = datetime.now().astimezone() + offset = now.strftime("%z") + offset = f"{offset[:3]}:{offset[3:]}" + return now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + f" {offset}" + + +def _error_details(error: BaseException) -> str: + details: List[str] = [] + current: Optional[BaseException] = error + seen = set() + while current is not None and len(details) < 4 and id(current) not in seen: + seen.add(id(current)) + text = str(current).replace("\n", " ").strip() + description = f"{type(current).__name__}: {text}" if text else type(current).__name__ + if not (details and text and str(error) == text): + details.append(description) + current = current.__cause__ or current.__context__ + return " <- ".join(details) + + +class DebugLogger: + """Emit complete logical events while never affecting SDK behavior.""" + + def __init__(self, enabled: bool, name: str) -> None: + self.enabled = enabled + self.name = name + self.logger = logging.getLogger(f"captcha_solver_api.{name}") + if enabled: + self._ensure_default_handler() + + def _ensure_default_handler(self) -> None: + global _handler + if logging.getLogger().hasHandlers(): + return + if _handler is None: + _handler = logging.StreamHandler() + _handler.setFormatter(logging.Formatter("%(message)s")) + if _handler not in self.logger.handlers: + self.logger.addHandler(_handler) + + def emit(self, message: str) -> None: + if not self.enabled and not self.logger.isEnabledFor(logging.DEBUG): + return + try: + formatted = f"[{_timestamp()}] [{self.name}] {message}" + if self.enabled: + record = self.logger.makeRecord( + self.logger.name, + logging.DEBUG, + "", + 0, + formatted, + (), + None, + ) + self.logger.handle(record) + else: + self.logger.debug(formatted) + except Exception: + return + + def initialized( + self, + version: str, + base_url: str, + http_timeout: Any, + timeout: Any, + polling: Any, + ) -> None: + self.emit( + f"client initialized sdk=python-sdk/{version} baseUrl={base_url} " + f"httpTimeout={http_timeout}s timeout={timeout}s pollingInterval={polling}s" + ) + + def request_success( + self, + endpoint: str, + url: str, + payload: Dict[str, Any], + data: Dict[str, Any], + status: int, + reason: str, + elapsed_ms: int, + ) -> None: + try: + summary = _summary(endpoint, payload, data) + if endpoint == "getTaskResult" and data.get("status") == "processing": + self.emit(f"{summary} ({elapsed_ms}ms)") + return + self.emit( + f"{summary} ({elapsed_ms}ms)\n" + f"REQUEST (POST {url}):\n{_json(payload)}\n" + f"RESPONSE (HTTP {status} {reason}, {elapsed_ms}ms):\n{_json(data)}" + ) + except Exception: + return + + def request_failure( + self, + endpoint: str, + url: str, + payload: Dict[str, Any], + error: BaseException, + elapsed_ms: int, + status: Optional[int] = None, + reason: str = "", + data: Optional[Any] = None, + invalid_json: bool = False, + body_missing: bool = False, + ) -> None: + try: + context = _request_context(endpoint, payload) + label = f"{endpoint} {context}".rstrip() + detail = _error_details(error) + if status is None: + response = ( + "RESPONSE: none - no response from the server " + f"({type(error).__name__}, {elapsed_ms}ms)" + ) + elif body_missing: + response = ( + f"RESPONSE (HTTP {status} {reason}, {elapsed_ms}ms): " + f"body was not received ({type(error).__name__})" + ) + elif invalid_json: + response = ( + f"RESPONSE (HTTP {status} {reason}, {elapsed_ms}ms): body is not valid JSON" + ) + else: + response = f"RESPONSE (HTTP {status} {reason}, {elapsed_ms}ms):\n{_json(data)}" + self.emit( + f"{label} -> failed: {detail} ({elapsed_ms}ms)\n" + f"REQUEST (POST {url}):\n{_json(payload)}\n{response}" + ) + except Exception: + return + + def solve_summary( + self, + solved: bool, + task_id: Optional[int], + task_type: Optional[str], + elapsed: float, + polls: int, + result: Optional[Dict[str, Any]] = None, + error: Optional[BaseException] = None, + ) -> None: + try: + server_time: Optional[str] = None + if result is not None: + created = result.get("createTime") + ended = result.get("endTime") + if isinstance(created, (int, float)) and isinstance(ended, (int, float)): + server_time = f"{ended - created:g}s" + lines = [ + "SOLVE SUMMARY:", + f" status: {'solved' if solved else 'not solved'}", + f" taskId: {task_id if task_id is not None else '- (task was not created)'}", + ] + if task_type: + lines.append(f" taskType: {task_type}") + lines.append(f" elapsed: {elapsed:.3f}s") + if server_time is not None: + lines.append(f" serverSolveTime: {server_time}") + lines.append(f" polls: {polls}") + if error is not None: + lines.append(f" error: {_error_details(error)}") + self.emit("\n".join(lines)) + except Exception: + return + + +def _request_context(endpoint: str, payload: Dict[str, Any]) -> str: + if endpoint == "createTask": + task = payload.get("task") + return str(task.get("type", "unknown")) if isinstance(task, dict) else "unknown" + if endpoint == "getTaskResult": + return f"taskId={payload.get('taskId', 'unknown')}" + return "" + + +def _summary(endpoint: str, payload: Dict[str, Any], data: Dict[str, Any]) -> str: + context = _request_context(endpoint, payload) + prefix = f"{endpoint} {context}".rstrip() + if data.get("errorId", 0) != 0: + code = data.get("errorCode", "UNKNOWN_ERROR") + message = data.get("errorDescription", "Unknown API error.") + return f"{prefix} -> failed: ApiError {code}: {message}" + if endpoint == "createTask": + return f"{prefix} -> taskId={data.get('taskId')}" + if endpoint == "getTaskResult": + return f"{prefix} -> {data.get('status', 'unknown')}" + if endpoint == "getBalance": + return f"{prefix} -> balance={data.get('balance')}" + return f"{prefix} -> success" diff --git a/captcha_solver_api/async_client.py b/captcha_solver_api/async_client.py index 921d1ea..92f5c4e 100644 --- a/captcha_solver_api/async_client.py +++ b/captcha_solver_api/async_client.py @@ -12,6 +12,8 @@ import httpx +from ._constants import HTTP_TIMEOUT_SECONDS +from ._debug import DebugLogger from ._version import __version__ from .exceptions import ( ApiError, @@ -42,6 +44,12 @@ class AsyncCaptchaClient: Defaults to 10. Waiting does not block the event loop. language_pool: Default worker pool, e.g. `"en"` or `"ru"`. `None` uses the account default. Can be overridden in `solve()` or `create_task()`. + debug: Enable opt-in diagnostic logging. Logs SDK configuration, + sanitized requests and responses, request timing, polling updates, + errors, and a summary after every `solve()` call. API keys, cookies, + proxy credentials, and Base64 image data are masked. Defaults to + `False`; it is never enabled from an environment variable, and a + logging failure does not change SDK results or exceptions. Raises: ValidationError: `client_key` is missing, empty, or whitespace. @@ -70,6 +78,7 @@ def __init__( timeout: int = 120, polling_interval: int = 10, language_pool: Optional[str] = None, + debug: bool = False, ) -> None: """Create an async client with a reusable HTTP connection pool. @@ -88,6 +97,12 @@ def __init__( applied to every `create_task()`/`solve()` call that doesn't pass its own `language_pool`. Leave unset to use the account's default pool. + debug: Enable opt-in diagnostic logging. Logs SDK configuration, + sanitized requests and responses, request timing, polling updates, + errors, and a summary after every `solve()` call. API keys, + cookies, proxy credentials, and Base64 image data are masked. + Defaults to `False`; it is never enabled from an environment + variable, and a logging failure does not affect SDK behavior. Raises: ValidationError: `client_key` is missing, empty, or whitespace. @@ -100,6 +115,8 @@ def __init__( self.timeout = timeout self.polling_interval = polling_interval self.language_pool = language_pool + self.debug = debug + self._debug_log = DebugLogger(debug, "AsyncCaptchaClient") self._client = httpx.AsyncClient( follow_redirects=True, @@ -109,6 +126,13 @@ def __init__( "X-SDK": f"python-sdk/{__version__}", }, ) + self._debug_log.initialized( + __version__, + self.base_url, + HTTP_TIMEOUT_SECONDS, + self.timeout, + self.polling_interval, + ) async def aclose(self) -> None: """Closes the underlying connection pool. Call this when you're done with @@ -128,22 +152,90 @@ async def _request( payload: Dict[str, Any], ) -> Dict[str, Any]: url = f"{self.base_url}/{endpoint.lstrip('/')}" + started = time.monotonic() try: - response = await self._client.post(url, json=payload, timeout=30) + response = await self._client.post(url, json=payload, timeout=HTTP_TIMEOUT_SECONDS) response.raise_for_status() except httpx.TimeoutException as exc: - raise CaptchaTimeoutError("Request timed out.") from exc + error_response = getattr(exc, "response", None) + timeout_failure = CaptchaTimeoutError("Request timed out.") + self._debug_log.request_failure( + endpoint, + url, + payload, + timeout_failure, + round((time.monotonic() - started) * 1000), + status=getattr(error_response, "status_code", None), + reason=getattr(error_response, "reason_phrase", "") or "", + body_missing=error_response is not None, + ) + raise timeout_failure from exc except httpx.HTTPError as exc: - raise NetworkError(str(exc)) from exc + error_response = getattr(exc, "response", None) + network_failure = NetworkError(str(exc)) + # The debug event is emitted before ``raise ... from exc`` attaches the cause. + network_failure.__cause__ = exc + data = None + invalid_json = False + if error_response is not None: + try: + data = error_response.json() + except ValueError: + invalid_json = True + self._debug_log.request_failure( + endpoint, + url, + payload, + network_failure, + round((time.monotonic() - started) * 1000), + status=getattr(error_response, "status_code", None), + reason=getattr(error_response, "reason_phrase", "") or "", + data=data, + invalid_json=invalid_json, + ) + raise network_failure from exc try: data = response.json() except ValueError as exc: - raise NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") from exc + parse_failure = NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") + # The debug event is emitted before ``raise ... from exc`` attaches the cause. + parse_failure.__cause__ = exc + self._debug_log.request_failure( + endpoint, + url, + payload, + parse_failure, + round((time.monotonic() - started) * 1000), + status=response.status_code, + reason=response.reason_phrase or "", + invalid_json=True, + ) + raise parse_failure from exc if not isinstance(data, dict): - raise NetworkError(f"Unexpected API response shape: {type(data).__name__}") + error = NetworkError(f"Unexpected API response shape: {type(data).__name__}") + self._debug_log.request_failure( + endpoint, + url, + payload, + error, + round((time.monotonic() - started) * 1000), + status=response.status_code, + reason=response.reason_phrase or "", + data=data, + ) + raise error + self._debug_log.request_success( + endpoint, + url, + payload, + data, + response.status_code, + response.reason_phrase or "", + round((time.monotonic() - started) * 1000), + ) return data def _ensure_success(self, data: Dict[str, Any]) -> None: @@ -309,38 +401,59 @@ async def solve( token = solution["gRecaptchaResponse"] """ - task_id = await self.create_task(task, language_pool=language_pool) - - deadline = time.monotonic() + (timeout if timeout is not None else self.timeout) - poll_failures = 0 - - while time.monotonic() < deadline: - remaining = deadline - time.monotonic() - await asyncio.sleep(min(self.polling_interval, max(0, remaining))) - if time.monotonic() >= deadline: - break - try: - result = await self.get_task_result(task_id) - except (NetworkError, CaptchaTimeoutError): - # getTaskResult is safe to repeat: retry a short transport - # failure on the next poll instead of losing a paid task. - poll_failures += 1 - if poll_failures > self.poll_retries: - raise - continue + started = time.monotonic() + task_id: Optional[int] = None + task_type = getattr(task, "type", None) + polls = 0 + final_result: Optional[Dict[str, Any]] = None + solved = False + error: Optional[BaseException] = None + try: + task_id = await self.create_task(task, language_pool=language_pool) + deadline = time.monotonic() + (timeout if timeout is not None else self.timeout) poll_failures = 0 - if result.get("status") == "ready": - solution = result["solution"] - if not isinstance(solution, (dict, str)) or solution == "": - raise NetworkError( - "API returned a ready task without a valid solution", - task_id=task_id, - ) - return solution - - raise CaptchaTimeoutError( - f"Task {task_id} was not solved within the polling timeout. It may still " - f"be solved later: check it with get_task_result({task_id}).", - task_id=task_id, - ) + while time.monotonic() < deadline: + remaining = deadline - time.monotonic() + await asyncio.sleep(min(self.polling_interval, max(0, remaining))) + if time.monotonic() >= deadline: + break + try: + polls += 1 + result = await self.get_task_result(task_id) + except (NetworkError, CaptchaTimeoutError): + poll_failures += 1 + if poll_failures > self.poll_retries: + raise + continue + poll_failures = 0 + + if result.get("status") == "ready": + final_result = result + solution = result["solution"] + if not isinstance(solution, (dict, str)) or solution == "": + raise NetworkError( + "API returned a ready task without a valid solution", + task_id=task_id, + ) + solved = True + return solution + + raise CaptchaTimeoutError( + f"Task {task_id} was not solved within the polling timeout. It may still " + f"be solved later: check it with get_task_result({task_id}).", + task_id=task_id, + ) + except BaseException as exc: + error = exc + raise + finally: + self._debug_log.solve_summary( + solved, + task_id, + task_type, + time.monotonic() - started, + polls, + final_result, + error, + ) diff --git a/captcha_solver_api/client.py b/captcha_solver_api/client.py index 3b48ed2..d03e970 100644 --- a/captcha_solver_api/client.py +++ b/captcha_solver_api/client.py @@ -9,6 +9,8 @@ import requests +from ._constants import HTTP_TIMEOUT_SECONDS +from ._debug import DebugLogger from ._version import __version__ from .exceptions import ( ApiError, @@ -32,6 +34,12 @@ class CaptchaClient: Defaults to 10. language_pool: Default worker pool, e.g. `"en"` or `"ru"`. `None` uses the account default. Can be overridden in `solve()` or `create_task()`. + debug: Enable opt-in diagnostic logging. Logs SDK configuration, + sanitized requests and responses, request timing, polling updates, + errors, and a summary after every `solve()` call. API keys, cookies, + proxy credentials, and Base64 image data are masked. Defaults to + `False`; it is never enabled from an environment variable, and a + logging failure does not change SDK results or exceptions. Raises: ValidationError: `client_key` is missing, empty, or whitespace. @@ -60,6 +68,7 @@ def __init__( timeout: int = 120, polling_interval: int = 10, language_pool: Optional[str] = None, + debug: bool = False, ) -> None: """Create a client with a reusable HTTP connection pool. @@ -78,6 +87,12 @@ def __init__( applied to every `create_task()`/`solve()` call that doesn't pass its own `language_pool`. Leave unset to use the account's default pool. + debug: Enable opt-in diagnostic logging. Logs SDK configuration, + sanitized requests and responses, request timing, polling updates, + errors, and a summary after every `solve()` call. API keys, + cookies, proxy credentials, and Base64 image data are masked. + Defaults to `False`; it is never enabled from an environment + variable, and a logging failure does not affect SDK behavior. Raises: ValidationError: `client_key` is missing, empty, or whitespace. @@ -90,6 +105,8 @@ def __init__( self.timeout = timeout self.polling_interval = polling_interval self.language_pool = language_pool + self.debug = debug + self._debug_log = DebugLogger(debug, "CaptchaClient") self.session = requests.Session() self.session.headers.update( @@ -99,6 +116,13 @@ def __init__( "X-SDK": f"python-sdk/{__version__}", } ) + self._debug_log.initialized( + __version__, + self.base_url, + HTTP_TIMEOUT_SECONDS, + self.timeout, + self.polling_interval, + ) def close(self) -> None: """Closes the underlying connection pool. Call this when you're done with @@ -118,22 +142,90 @@ def _request( payload: Dict[str, Any], ) -> Dict[str, Any]: url = f"{self.base_url}/{endpoint.lstrip('/')}" + started = time.monotonic() try: - response = self.session.post(url, json=payload, timeout=30) + response = self.session.post(url, json=payload, timeout=HTTP_TIMEOUT_SECONDS) response.raise_for_status() except requests.exceptions.Timeout as exc: - raise CaptchaTimeoutError("Request timed out.") from exc + error_response = getattr(exc, "response", None) + timeout_failure = CaptchaTimeoutError("Request timed out.") + self._debug_log.request_failure( + endpoint, + url, + payload, + timeout_failure, + round((time.monotonic() - started) * 1000), + status=getattr(error_response, "status_code", None), + reason=getattr(error_response, "reason", "") or "", + body_missing=error_response is not None, + ) + raise timeout_failure from exc except requests.exceptions.RequestException as exc: - raise NetworkError(str(exc)) from exc + error_response = getattr(exc, "response", None) + network_failure = NetworkError(str(exc)) + # The debug event is emitted before ``raise ... from exc`` attaches the cause. + network_failure.__cause__ = exc + data = None + invalid_json = False + if error_response is not None: + try: + data = error_response.json() + except ValueError: + invalid_json = True + self._debug_log.request_failure( + endpoint, + url, + payload, + network_failure, + round((time.monotonic() - started) * 1000), + status=getattr(error_response, "status_code", None), + reason=getattr(error_response, "reason", "") or "", + data=data, + invalid_json=invalid_json, + ) + raise network_failure from exc try: data = response.json() except ValueError as exc: - raise NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") from exc + parse_failure = NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") + # The debug event is emitted before ``raise ... from exc`` attaches the cause. + parse_failure.__cause__ = exc + self._debug_log.request_failure( + endpoint, + url, + payload, + parse_failure, + round((time.monotonic() - started) * 1000), + status=response.status_code, + reason=response.reason or "", + invalid_json=True, + ) + raise parse_failure from exc if not isinstance(data, dict): - raise NetworkError(f"Unexpected API response shape: {type(data).__name__}") + error = NetworkError(f"Unexpected API response shape: {type(data).__name__}") + self._debug_log.request_failure( + endpoint, + url, + payload, + error, + round((time.monotonic() - started) * 1000), + status=response.status_code, + reason=response.reason or "", + data=data, + ) + raise error + self._debug_log.request_success( + endpoint, + url, + payload, + data, + response.status_code, + response.reason or "", + round((time.monotonic() - started) * 1000), + ) return data def _ensure_success(self, data: Dict[str, Any]) -> None: @@ -287,38 +379,59 @@ def solve( token = solution["gRecaptchaResponse"] """ - task_id = self.create_task(task, language_pool=language_pool) - - deadline = time.monotonic() + (timeout if timeout is not None else self.timeout) - poll_failures = 0 - - while time.monotonic() < deadline: - remaining = deadline - time.monotonic() - time.sleep(min(self.polling_interval, max(0, remaining))) - if time.monotonic() >= deadline: - break - try: - result = self.get_task_result(task_id) - except (NetworkError, CaptchaTimeoutError): - # getTaskResult is safe to repeat: retry a short transport - # failure on the next poll instead of losing a paid task. - poll_failures += 1 - if poll_failures > self.poll_retries: - raise - continue + started = time.monotonic() + task_id: Optional[int] = None + task_type = getattr(task, "type", None) + polls = 0 + final_result: Optional[Dict[str, Any]] = None + solved = False + error: Optional[BaseException] = None + try: + task_id = self.create_task(task, language_pool=language_pool) + deadline = time.monotonic() + (timeout if timeout is not None else self.timeout) poll_failures = 0 - if result.get("status") == "ready": - solution = result["solution"] - if not isinstance(solution, (dict, str)) or solution == "": - raise NetworkError( - "API returned a ready task without a valid solution", - task_id=task_id, - ) - return solution - - raise CaptchaTimeoutError( - f"Task {task_id} was not solved within the polling timeout. It may still " - f"be solved later: check it with get_task_result({task_id}).", - task_id=task_id, - ) + while time.monotonic() < deadline: + remaining = deadline - time.monotonic() + time.sleep(min(self.polling_interval, max(0, remaining))) + if time.monotonic() >= deadline: + break + try: + polls += 1 + result = self.get_task_result(task_id) + except (NetworkError, CaptchaTimeoutError): + poll_failures += 1 + if poll_failures > self.poll_retries: + raise + continue + poll_failures = 0 + + if result.get("status") == "ready": + final_result = result + solution = result["solution"] + if not isinstance(solution, (dict, str)) or solution == "": + raise NetworkError( + "API returned a ready task without a valid solution", + task_id=task_id, + ) + solved = True + return solution + + raise CaptchaTimeoutError( + f"Task {task_id} was not solved within the polling timeout. It may still " + f"be solved later: check it with get_task_result({task_id}).", + task_id=task_id, + ) + except BaseException as exc: + error = exc + raise + finally: + self._debug_log.solve_summary( + solved, + task_id, + task_type, + time.monotonic() - started, + polls, + final_result, + error, + ) diff --git a/examples/README.md b/examples/README.md index aea0c90..7d14fb7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -82,6 +82,16 @@ python examples/sync/yandex_smartcaptcha_kaleidoscope.py python examples/async/recaptcha_v2_proxyless.py ``` +Use the dedicated sync or async example to see sanitized SDK request, response, +timing, polling, error, and solve-summary logs: + +```bash +python examples/sync/debug_mode.py +python examples/async/debug_mode.py +``` + +Both examples enable debug mode directly with `debug=True`. + Async scripts create an `AsyncCaptchaClient` and await the same operations as the synchronous client. For several captchas, see the parallel solving pattern in the main [README](../README.md#solving-multiple-captchas-in-parallel). ## Important notes diff --git a/examples/async/balance.py b/examples/async/balance.py index 3c81311..d1d9d78 100644 --- a/examples/async/balance.py +++ b/examples/async/balance.py @@ -25,10 +25,10 @@ from captcha_solver_api import AsyncCaptchaClient # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/async/debug_mode.py b/examples/async/debug_mode.py new file mode 100644 index 0000000..cbdd201 --- /dev/null +++ b/examples/async/debug_mode.py @@ -0,0 +1,55 @@ +"""Example: Run one Image to Text task with sanitized async debug logging enabled. + +What it does: + This example reads a bundled CAPTCHA image, enables debug mode explicitly, + solves it with ImageToTextTask and AsyncCaptchaClient.solve(), and prints the + recognized text after the diagnostic events and SOLVE SUMMARY. + +How it works: + STEP-01 - Configure AsyncCaptchaClient with debug=True and read the bundled image. + STEP-02 - Encode the image and create ImageToTextTask. + STEP-03 - Await solve(), which creates and polls the task while logging safely. + STEP-04 - Inspect the sanitized logs and print the recognized text. + +Prerequisites: + Set the CAPTCHA_API_KEY environment variable or add it to the repository .env. + This example creates a real, paid CAPTCHA task. +""" + +import asyncio +import os +import sys +from base64 import b64encode + +try: + from dotenv import load_dotenv +except ModuleNotFoundError as exc: + if exc.name != "dotenv": + raise + load_dotenv = None + +repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +sys.path.append(repo_root) +if load_dotenv is not None: + load_dotenv(os.path.join(repo_root, ".env")) + +from captcha_solver_api import AsyncCaptchaClient +from captcha_solver_api.tasks import ImageToTextTask + + +async def main() -> None: + api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") + image_path = os.path.join(repo_root, "examples", "assets", "captcha-digits.png") + + with open(image_path, "rb") as image_file: + image_body = b64encode(image_file.read()).decode("utf-8") + + async with AsyncCaptchaClient(api_key, debug=True) as client: + solution = await client.solve( + ImageToTextTask(body=image_body, numeric=1, minLength=4, maxLength=6) + ) + + print(f"Recognized text: {solution['text']}") + + +asyncio.run(main()) diff --git a/examples/sync/balance.py b/examples/sync/balance.py index f3a6ae7..5cfa72b 100644 --- a/examples/sync/balance.py +++ b/examples/sync/balance.py @@ -24,10 +24,10 @@ from captcha_solver_api import CaptchaClient # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/coordinates.py b/examples/sync/coordinates.py index 59c3421..32a2fd5 100644 --- a/examples/sync/coordinates.py +++ b/examples/sync/coordinates.py @@ -29,10 +29,10 @@ from captcha_solver_api.tasks import CoordinatesTask # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/debug_mode.py b/examples/sync/debug_mode.py new file mode 100644 index 0000000..583e67c --- /dev/null +++ b/examples/sync/debug_mode.py @@ -0,0 +1,47 @@ +"""Example: Run one Image to Text task with sanitized debug logging enabled. + +What it does: + This example reads a bundled CAPTCHA image, enables debug mode explicitly, + solves it with ImageToTextTask and CaptchaClient.solve(), and prints the + recognized text after the diagnostic events and SOLVE SUMMARY. + +How it works: + STEP-01 - Configure CaptchaClient with debug=True and read the bundled image. + STEP-02 - Encode the image and create ImageToTextTask. + STEP-03 - Call solve(), which creates and polls the task while logging safely. + STEP-04 - Inspect the sanitized logs and print the recognized text. + +Prerequisites: + Set the CAPTCHA_API_KEY environment variable or add it to the repository .env. + This example creates a real, paid CAPTCHA task. +""" + +import os +import sys +from base64 import b64encode + +try: + from dotenv import load_dotenv +except ModuleNotFoundError as exc: + if exc.name != "dotenv": + raise + load_dotenv = None + +repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +sys.path.append(repo_root) +if load_dotenv is not None: + load_dotenv(os.path.join(repo_root, ".env")) + +from captcha_solver_api import CaptchaClient +from captcha_solver_api.tasks import ImageToTextTask + +api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") +image_path = os.path.join(repo_root, "examples", "assets", "captcha-digits.png") + +with open(image_path, "rb") as image_file: + image_body = b64encode(image_file.read()).decode("utf-8") + +with CaptchaClient(api_key, debug=True) as client: + solution = client.solve(ImageToTextTask(body=image_body, numeric=1, minLength=4, maxLength=6)) + +print(f"Recognized text: {solution['text']}") diff --git a/examples/sync/geetest_v3_proxy.py b/examples/sync/geetest_v3_proxy.py index e91b441..f8a7835 100644 --- a/examples/sync/geetest_v3_proxy.py +++ b/examples/sync/geetest_v3_proxy.py @@ -33,10 +33,10 @@ from captcha_solver_api.tasks import GeeTestTask # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/geetest_v3_proxyless.py b/examples/sync/geetest_v3_proxyless.py index 10503e6..9e61e7a 100644 --- a/examples/sync/geetest_v3_proxyless.py +++ b/examples/sync/geetest_v3_proxyless.py @@ -33,10 +33,10 @@ from captcha_solver_api.tasks import GeeTestTaskProxyless # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/geetest_v4_proxy.py b/examples/sync/geetest_v4_proxy.py index 9d05bdf..f959cec 100644 --- a/examples/sync/geetest_v4_proxy.py +++ b/examples/sync/geetest_v4_proxy.py @@ -28,10 +28,10 @@ from captcha_solver_api.tasks import GeeTestTask # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/geetest_v4_proxyless.py b/examples/sync/geetest_v4_proxyless.py index 55cb061..f25b5f0 100644 --- a/examples/sync/geetest_v4_proxyless.py +++ b/examples/sync/geetest_v4_proxyless.py @@ -28,10 +28,10 @@ from captcha_solver_api.tasks import GeeTestTaskProxyless # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/image_to_text.py b/examples/sync/image_to_text.py index 892d693..4a449d7 100644 --- a/examples/sync/image_to_text.py +++ b/examples/sync/image_to_text.py @@ -28,10 +28,10 @@ from captcha_solver_api.tasks import ImageToTextTask # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/recaptcha_v2_enterprise_proxy.py b/examples/sync/recaptcha_v2_enterprise_proxy.py index b2e5ba3..b788161 100644 --- a/examples/sync/recaptcha_v2_enterprise_proxy.py +++ b/examples/sync/recaptcha_v2_enterprise_proxy.py @@ -26,10 +26,10 @@ from captcha_solver_api.tasks import RecaptchaV2EnterpriseTask # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/recaptcha_v2_enterprise_proxyless.py b/examples/sync/recaptcha_v2_enterprise_proxyless.py index bd7ebc5..1bb0e1f 100644 --- a/examples/sync/recaptcha_v2_enterprise_proxyless.py +++ b/examples/sync/recaptcha_v2_enterprise_proxyless.py @@ -26,10 +26,10 @@ from captcha_solver_api.tasks import RecaptchaV2EnterpriseTaskProxyless # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/recaptcha_v2_proxy.py b/examples/sync/recaptcha_v2_proxy.py index 40f6674..0998e03 100644 --- a/examples/sync/recaptcha_v2_proxy.py +++ b/examples/sync/recaptcha_v2_proxy.py @@ -25,10 +25,10 @@ from captcha_solver_api.tasks import RecaptchaV2Task # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/recaptcha_v2_proxyless.py b/examples/sync/recaptcha_v2_proxyless.py index 2670021..776c62e 100644 --- a/examples/sync/recaptcha_v2_proxyless.py +++ b/examples/sync/recaptcha_v2_proxyless.py @@ -25,10 +25,10 @@ from captcha_solver_api.tasks import RecaptchaV2TaskProxyless # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/recaptcha_v3.py b/examples/sync/recaptcha_v3.py index cd2164b..0ce6775 100644 --- a/examples/sync/recaptcha_v3.py +++ b/examples/sync/recaptcha_v3.py @@ -27,10 +27,10 @@ from captcha_solver_api.tasks import RecaptchaV3TaskProxyless # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/turnstile_proxy.py b/examples/sync/turnstile_proxy.py index 29d61ac..748f2e2 100644 --- a/examples/sync/turnstile_proxy.py +++ b/examples/sync/turnstile_proxy.py @@ -26,10 +26,10 @@ from captcha_solver_api.tasks import TurnstileTask # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/examples/sync/turnstile_proxyless.py b/examples/sync/turnstile_proxyless.py index 258402d..2a32588 100644 --- a/examples/sync/turnstile_proxyless.py +++ b/examples/sync/turnstile_proxyless.py @@ -26,10 +26,10 @@ from captcha_solver_api.tasks import TurnstileTaskProxyless # in this example we store the API key inside environment variables that can be set like: -# export CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS -# set CAPTCHA_API_KEY=1abc234de56fab7c89012d34e56fa7b8 on Windows +# export CAPTCHA_API_KEY=your_api_key on Linux or macOS +# set CAPTCHA_API_KEY=your_api_key on Windows # you can just set the API key directly to its value like: -# api_key="1abc234de56fab7c89012d34e56fa7b8" +# api_key="your_api_key" api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") diff --git a/tests/async/test_async_debug.py b/tests/async/test_async_debug.py new file mode 100644 index 0000000..5a91792 --- /dev/null +++ b/tests/async/test_async_debug.py @@ -0,0 +1,111 @@ +from unittest.mock import AsyncMock, Mock, patch + +import httpx +import pytest + +from captcha_solver_api import AsyncCaptchaClient, CaptchaTimeoutError, NetworkError +from captcha_solver_api.tasks import ImageToTextTask + + +def messages(client): + return [call.args[0].getMessage() for call in client._debug_log.logger.handle.call_args_list] + + +async def test_async_debug_success_processing_summary_and_masking(): + client = AsyncCaptchaClient("async-secret", polling_interval=0, debug=True) + client._debug_log.logger.handle = Mock() + task = ImageToTextTask(body="A" * 300) + responses = [ + httpx.Response( + 200, json={"errorId": 0, "taskId": 9}, request=httpx.Request("POST", "https://x") + ), + httpx.Response( + 200, + json={"errorId": 0, "status": "processing"}, + request=httpx.Request("POST", "https://x"), + ), + httpx.Response( + 200, + json={ + "errorId": 0, + "status": "ready", + "createTime": 2, + "endTime": 5, + "solution": {"text": "1234"}, + }, + request=httpx.Request("POST", "https://x"), + ), + ] + client._client.post = AsyncMock(side_effect=responses) + + assert await client.solve(task) == {"text": "1234"} + + output = "\n".join(messages(client)) + assert "async-secret" not in output + assert "[base64, 300 chars]" in output + assert "getTaskResult taskId=9 -> processing" in output + assert "SOLVE SUMMARY" in output + assert "polls: 2" in output + assert "serverSolveTime: 3s" in output + await client.aclose() + + +async def test_async_debug_transport_timeout_and_isolation(): + client = AsyncCaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + client._client.post = AsyncMock(side_effect=httpx.ConnectError("dns failed")) + with pytest.raises(NetworkError): + await client.get_balance() + assert "failed: NetworkError" in messages(client)[0] + assert "failed: NetworkError: dns failed" in messages(client)[0] + assert "RESPONSE: none - no response from the server (NetworkError" in messages(client)[0] + + client._debug_log.logger.handle = Mock() + client._client.post = AsyncMock(side_effect=httpx.ReadTimeout("slow")) + with pytest.raises(CaptchaTimeoutError): + await client.get_balance() + assert "failed: CaptchaTimeoutError: Request timed out." in messages(client)[0] + assert ( + "RESPONSE: none - no response from the server (CaptchaTimeoutError" in messages(client)[0] + ) + + client._debug_log.logger.handle = Mock(side_effect=RuntimeError("logger failed")) + client._client.post = AsyncMock( + return_value=httpx.Response( + 200, json={"errorId": 0, "balance": 1.25}, request=httpx.Request("POST", "https://x") + ) + ) + assert await client.get_balance() == 1.25 + await client.aclose() + + +async def test_async_timeout_after_headers_reports_body_was_not_received(): + client = AsyncCaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + error = httpx.ReadTimeout("body read timed out") + error.response = httpx.Response( + 200, request=httpx.Request("POST", "https://api.captcha-solver.com/getBalance") + ) + client._client.post = AsyncMock(side_effect=error) + + with pytest.raises(CaptchaTimeoutError): + await client.get_balance() + + message = messages(client)[0] + assert "failed: CaptchaTimeoutError: Request timed out." in message + assert "RESPONSE (HTTP 200 OK" in message + assert "body was not received (CaptchaTimeoutError)" in message + await client.aclose() + + +async def test_async_failed_solve_has_summary_when_task_not_created(): + client = AsyncCaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + task = ImageToTextTask(body="image") + with patch.object(client, "create_task", side_effect=NetworkError("offline")): + with pytest.raises(NetworkError): + await client.solve(task) + summary = messages(client)[0] + assert "status: not solved" in summary + assert "taskId: - (task was not created)" in summary + await client.aclose() diff --git a/tests/sync/test_debug.py b/tests/sync/test_debug.py new file mode 100644 index 0000000..fa6b863 --- /dev/null +++ b/tests/sync/test_debug.py @@ -0,0 +1,236 @@ +import logging +import re +from io import StringIO +from unittest.mock import Mock, patch + +import pytest +import requests + +from captcha_solver_api import ApiError, CaptchaClient, CaptchaTimeoutError, NetworkError +from captcha_solver_api.tasks import ImageToTextTask + + +def response(status=200, reason="OK", data=None): + result = Mock(status_code=status, reason=reason, text="response text") + result.json.return_value = data + if status >= 400: + error = requests.HTTPError(f"{status} {reason}", response=result) + result.raise_for_status.side_effect = error + return result + + +def debug_messages(client): + return [call.args[0].getMessage() for call in client._debug_log.logger.handle.call_args_list] + + +def test_debug_is_disabled_by_default(): + client = CaptchaClient("secret") + assert client.debug is False + assert client._debug_log.enabled is False + + +def test_debug_initialization_is_one_timestamped_event(): + with patch("logging.Logger.handle") as logger: + CaptchaClient("secret", debug=True) + + logger.assert_called_once() + message = logger.call_args.args[0].getMessage() + assert re.match( + r"^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} [+-]\d{2}:\d{2}\] " + r"\[CaptchaClient\] client initialized ", + message, + ) + assert "sdk=python-sdk/" in message + assert "baseUrl=" in message + assert "pollingInterval=" in message + assert "\n" not in message + + +def test_debug_logs_reach_configured_root_handler(): + stream = StringIO() + handler = logging.StreamHandler(stream) + root_logger = logging.getLogger() + root_logger.addHandler(handler) + try: + CaptchaClient("secret", debug=True) + finally: + root_logger.removeHandler(handler) + + assert "[CaptchaClient] client initialized" in stream.getvalue() + + +def test_standard_logging_can_enable_debug_events_without_flag(): + stream = StringIO() + handler = logging.StreamHandler(stream) + root_logger = logging.getLogger() + sdk_logger = logging.getLogger("captcha_solver_api") + previous_level = sdk_logger.level + root_logger.addHandler(handler) + sdk_logger.setLevel(logging.DEBUG) + try: + CaptchaClient("secret") + finally: + sdk_logger.setLevel(previous_level) + root_logger.removeHandler(handler) + + assert "[CaptchaClient] client initialized" in stream.getvalue() + + +def test_success_masks_and_truncates_without_mutating_payload(): + client = CaptchaClient("api-secret", debug=True) + client._debug_log.logger.handle = Mock() + long_token = "x" * 250 + body = "Y" * 300 + payload = { + "clientKey": "api-secret", + "cookie": "session=secret", + "proxyAddress": "127.0.0.1", + "task": {"type": "ImageToTextTask", "body": body}, + } + client.session.post = Mock( + return_value=response(data={"errorId": 0, "taskId": 123, "solution": {"token": long_token}}) + ) + + result = client._request("createTask", payload) + + assert result["taskId"] == 123 + message = debug_messages(client)[0] + assert "REQUEST (POST" in message and "RESPONSE (HTTP 200 OK" in message + assert "api-secret" not in message + assert "session=secret" not in message + assert "127.0.0.1" not in message + assert "[MASKED]" in message + assert "[base64, 300 chars]" in message + assert f"{'x' * 40}...[250 chars]...{'x' * 40}" in message + assert payload["clientKey"] == "api-secret" + assert payload["task"]["body"] == body + + +def test_processing_is_compact_single_line(): + client = CaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + client.session.post = Mock(return_value=response(data={"errorId": 0, "status": "processing"})) + + client.get_task_result(42) + + message = debug_messages(client)[0] + assert "getTaskResult taskId=42 -> processing" in message + assert "REQUEST" not in message + assert "\n" not in message + + +def test_api_and_http_errors_include_paired_request_response(): + client = CaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + client.session.post = Mock( + side_effect=[ + response( + data={ + "errorId": 1, + "errorCode": "ERROR_KEY_DOES_NOT_EXIST", + "errorDescription": "Account not found", + } + ), + response(502, "Bad Gateway", {"message": "upstream failed"}), + ] + ) + + with pytest.raises(ApiError): + client.get_balance() + with pytest.raises(NetworkError): + client.get_balance() + + api_message, http_message = debug_messages(client) + assert "failed: ApiError ERROR_KEY_DOES_NOT_EXIST: Account not found" in api_message + assert "REQUEST" in api_message and "RESPONSE (HTTP 200 OK" in api_message + assert "failed: NetworkError" in http_message + assert "RESPONSE (HTTP 502 Bad Gateway" in http_message + assert "upstream failed" in http_message + + +def test_invalid_json_network_and_timeout_explain_missing_response(): + client = CaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + invalid = response() + invalid.json.side_effect = ValueError("bad json") + client.session.post = Mock( + side_effect=[invalid, requests.ConnectionError("dns failed"), requests.Timeout("slow")] + ) + + with pytest.raises(NetworkError): + client.get_balance() + with pytest.raises(NetworkError): + client.get_balance() + with pytest.raises(CaptchaTimeoutError): + client.get_balance() + + invalid_message, network_message, timeout_message = debug_messages(client) + assert "body is not valid JSON" in invalid_message + assert "RESPONSE: none - no response from the server (NetworkError" in network_message + assert "failed: NetworkError: dns failed" in network_message + assert "RESPONSE: none - no response from the server (CaptchaTimeoutError" in timeout_message + + +def test_timeout_after_headers_reports_body_was_not_received(): + client = CaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock() + partial_response = response(status=200, reason="OK") + client.session.post = Mock( + side_effect=requests.Timeout("body read timed out", response=partial_response) + ) + + with pytest.raises(CaptchaTimeoutError): + client.get_balance() + + message = debug_messages(client)[0] + assert "failed: CaptchaTimeoutError: Request timed out." in message + assert "RESPONSE (HTTP 200 OK" in message + assert "body was not received (CaptchaTimeoutError)" in message + + +def test_solve_summary_reports_success_failure_and_poll_count(): + task = ImageToTextTask(body="image") + client = CaptchaClient("secret", polling_interval=0, debug=True) + client._debug_log.logger.handle = Mock() + with patch.object(client, "_request") as request: + request.side_effect = [ + {"errorId": 0, "taskId": 7}, + {"errorId": 0, "status": "processing"}, + { + "errorId": 0, + "status": "ready", + "createTime": 10, + "endTime": 18, + "solution": {"text": "1234"}, + }, + ] + assert client.solve(task) == {"text": "1234"} + + summary = debug_messages(client)[0] + assert "SOLVE SUMMARY" in summary + assert "status: solved" in summary + assert "taskId: 7" in summary + assert "taskType: ImageToTextTask" in summary + assert "serverSolveTime: 8s" in summary + assert "polls: 2" in summary + + client._debug_log.logger.handle.reset_mock() + with patch.object(client, "create_task", side_effect=ApiError("BAD", "failed")): + with pytest.raises(ApiError): + client.solve(task) + summary = debug_messages(client)[0] + assert "status: not solved" in summary + assert "taskId: - (task was not created)" in summary + assert "error:" in summary + assert "serverSolveTime:" not in summary + + +def test_debug_failure_does_not_change_result_or_exception(): + client = CaptchaClient("secret", debug=True) + client._debug_log.logger.handle = Mock(side_effect=RuntimeError("logger failed")) + client.session.post = Mock(return_value=response(data={"errorId": 0, "balance": 4.5})) + assert client.get_balance() == 4.5 + + client.session.post = Mock(side_effect=requests.ConnectionError("original failure")) + with pytest.raises(NetworkError, match="original failure"): + client.get_balance()