nonecap 0.11.2__tar.gz → 0.12.2__tar.gz

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.
@@ -11,7 +11,7 @@ permissions:
11
11
 
12
12
  jobs:
13
13
  test:
14
- runs-on: ubuntu-latest
14
+ runs-on: ubuntu-24.04
15
15
  strategy:
16
16
  matrix:
17
17
  python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: nonecap
3
- Version: 0.11.2
3
+ Version: 0.12.2
4
4
  Summary: Official Python client for NoneCap, the hCaptcha solver API.
5
5
  Project-URL: Homepage, https://nonecap.com/
6
6
  Project-URL: Documentation, https://nonecap.com/api-reference
@@ -172,7 +172,7 @@ except RateLimitError as err:
172
172
  time.sleep(err.retry_after or 1)
173
173
  ```
174
174
 
175
- The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `RecognitionFailedError` (422, `recognize()` found no answer; nothing was charged), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
175
+ The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `RecognitionFailedError` (422, `recognize()` found no answer; nothing was charged), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause and its subclass `SitekeyUnavailableError` when solving for one sitekey is currently in maintenance, `retry_after` set), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
176
176
 
177
177
  `SolveFailedError` carries the full `solve`. `solve.error.code` is a `SolveErrorCode`, `solve.error.reason` a typed sub-reason or `None` (`proxy_rejected`, `sitekey_rate_limited`, …), and `solve.error.retryable` says whether resubmitting the same request unchanged can succeed; `err.retryable`, `err.reason` and `err.solve_code` are shortcuts to those fields. Failed solves are never charged.
178
178
 
@@ -191,7 +191,7 @@ solve = nc.solve(
191
191
 
192
192
  ## Proxies
193
193
 
194
- Pass a proxy as a dict or a URL string. The solve runs through it, and the bytes are metered back on the solve.
194
+ Pass a proxy as a dict or a URL string. The solve runs through it, and the bytes are metered back on the solve. For HTTP/3 through your own proxy, see [HTTP/3 on your own proxy](https://nonecap.com/api-reference#http3-own-proxy).
195
195
 
196
196
  ```python
197
197
  nc.solve(
@@ -141,7 +141,7 @@ except RateLimitError as err:
141
141
  time.sleep(err.retry_after or 1)
142
142
  ```
143
143
 
144
- The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `RecognitionFailedError` (422, `recognize()` found no answer; nothing was charged), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
144
+ The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `RecognitionFailedError` (422, `recognize()` found no answer; nothing was charged), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause and its subclass `SitekeyUnavailableError` when solving for one sitekey is currently in maintenance, `retry_after` set), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
145
145
 
146
146
  `SolveFailedError` carries the full `solve`. `solve.error.code` is a `SolveErrorCode`, `solve.error.reason` a typed sub-reason or `None` (`proxy_rejected`, `sitekey_rate_limited`, …), and `solve.error.retryable` says whether resubmitting the same request unchanged can succeed; `err.retryable`, `err.reason` and `err.solve_code` are shortcuts to those fields. Failed solves are never charged.
147
147
 
@@ -160,7 +160,7 @@ solve = nc.solve(
160
160
 
161
161
  ## Proxies
162
162
 
163
- Pass a proxy as a dict or a URL string. The solve runs through it, and the bytes are metered back on the solve.
163
+ Pass a proxy as a dict or a URL string. The solve runs through it, and the bytes are metered back on the solve. For HTTP/3 through your own proxy, see [HTTP/3 on your own proxy](https://nonecap.com/api-reference#http3-own-proxy).
164
164
 
165
165
  ```python
166
166
  nc.solve(
@@ -33,6 +33,7 @@ from ._errors import (
33
33
  RecognitionFailedError,
34
34
  ServiceUnavailableError,
35
35
  SitekeyRateLimitedError,
36
+ SitekeyUnavailableError,
36
37
  SolveFailedError,
37
38
  SolveTimeoutError,
38
39
  UnsupportedMediaTypeError,
@@ -137,6 +138,7 @@ __all__ = [
137
138
  "RecognitionFailedError",
138
139
  "APIError",
139
140
  "ServiceUnavailableError",
141
+ "SitekeyUnavailableError",
140
142
  "APIConnectionError",
141
143
  "APITimeoutError",
142
144
  "SolveFailedError",
@@ -72,6 +72,8 @@ DEFAULT_SOLVE_TIMEOUT = 180.0
72
72
  """Default overall budget (seconds) for the ``solve()`` helper."""
73
73
  _MAX_WAIT_SECONDS = 90
74
74
  """The API caps server-side long-poll at 90 seconds."""
75
+ _POLL_RETRY_DELAY = 1.0
76
+ """Seconds between re-polls after a long-poll GET was lost (reset, timeout, 5xx)."""
75
77
  FEEDBACK_BATCH_MAX = 500
76
78
  """The API caps one ``POST /v1/feedback`` call at 500 items."""
77
79
 
@@ -87,6 +89,14 @@ def _wait_seconds(deadline: float) -> int:
87
89
  return max(1, min(_MAX_WAIT_SECONDS, remaining))
88
90
 
89
91
 
92
+ def _poll_error_is_retryable(exc: Exception) -> bool:
93
+ """A lost long-poll GET leaves the solve running server-side: re-poll the
94
+ same id instead of surfacing an error that callers turn into a re-solve."""
95
+ if isinstance(exc, APIConnectionError):
96
+ return True
97
+ return isinstance(exc, APIError) and (exc.status or 0) >= 500
98
+
99
+
90
100
  def _request_timeout_for_wait(wait: Optional[int], default: float) -> float:
91
101
  """Give the socket a margin beyond the server's long-poll window."""
92
102
  if wait is None:
@@ -466,7 +476,13 @@ class SolveHandle:
466
476
  solve_id=solve.id,
467
477
  solve=solve,
468
478
  )
469
- solve = self._solves.retrieve(solve.id, wait=_wait_seconds(deadline))
479
+ try:
480
+ solve = self._solves.retrieve(solve.id, wait=_wait_seconds(deadline))
481
+ except (APIConnectionError, APIError) as exc:
482
+ if not _poll_error_is_retryable(exc):
483
+ raise
484
+ time.sleep(max(0.0, min(_POLL_RETRY_DELAY, deadline - time.monotonic())))
485
+ continue
470
486
  self._solve = solve
471
487
  self._settled = solve
472
488
  return self._result_from(solve)
@@ -968,7 +984,14 @@ class AsyncSolveHandle:
968
984
  solve_id=solve.id,
969
985
  solve=solve,
970
986
  )
971
- solve = await self._solves.retrieve(solve.id, wait=_wait_seconds(deadline))
987
+ try:
988
+ solve = await self._solves.retrieve(solve.id, wait=_wait_seconds(deadline))
989
+ except (APIConnectionError, APIError) as exc:
990
+ if not _poll_error_is_retryable(exc):
991
+ raise
992
+ remaining = deadline - time.monotonic()
993
+ await asyncio.sleep(max(0.0, min(_POLL_RETRY_DELAY, remaining)))
994
+ continue
972
995
  self._solve = solve
973
996
  return solve
974
997
 
@@ -110,6 +110,11 @@ class ServiceUnavailableError(APIError):
110
110
  """503 — new solves are paused for maintenance. Retry shortly."""
111
111
 
112
112
 
113
+ class SitekeyUnavailableError(ServiceUnavailableError):
114
+ """503 — solving for this sitekey is currently in maintenance. Retry after
115
+ ``retry_after`` seconds."""
116
+
117
+
113
118
  class APIConnectionError(NoneCapError):
114
119
  """The request never reached the API (DNS, TCP, TLS, offline)."""
115
120
 
@@ -211,6 +216,8 @@ def error_from_response(
211
216
  cls = RecognitionFailedError
212
217
  elif code == "maintenance":
213
218
  cls = ServiceUnavailableError
219
+ elif code == "sitekey_unavailable":
220
+ cls = SitekeyUnavailableError
214
221
  else:
215
222
  cls = APIError
216
223
  return cls(
@@ -0,0 +1 @@
1
+ __version__ = "0.12.2"
@@ -6,7 +6,7 @@ from typing import Any
6
6
  import httpx
7
7
  import pytest
8
8
 
9
- from nonecap import AsyncNoneCap, SolveFailedError, SolveTimeoutError
9
+ from nonecap import AsyncNoneCap, NotFoundError, SolveFailedError, SolveTimeoutError
10
10
 
11
11
  from .conftest import Script, error_payload, solve_payload
12
12
 
@@ -238,3 +238,44 @@ async def test_async_context_manager_closes_owned_client() -> None:
238
238
  async with AsyncNoneCap(api_key="k") as nc:
239
239
  http = nc._http
240
240
  assert http.is_closed
241
+
242
+
243
+ def _reset(request: httpx.Request) -> httpx.Response:
244
+ raise httpx.ReadError("Connection reset by peer", request=request)
245
+
246
+
247
+ @pytest.fixture
248
+ def no_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None:
249
+ monkeypatch.setattr("nonecap._client._POLL_RETRY_DELAY", 0.0, raising=False)
250
+
251
+
252
+ @pytest.mark.usefixtures("no_retry_delay")
253
+ async def test_async_solve_repolls_after_a_lost_long_poll() -> None:
254
+ script = Script(
255
+ (202, solve_payload(status="pending")),
256
+ _reset,
257
+ (503, error_payload("maintenance")),
258
+ (200, solve_payload(status="solved", token="TOK")),
259
+ )
260
+ nc = client_for(script)
261
+ solve = await nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com")
262
+ assert solve.token == "TOK"
263
+ assert [r.method for r in script.requests] == ["POST", "GET", "GET", "GET"]
264
+
265
+
266
+ @pytest.mark.usefixtures("no_retry_delay")
267
+ async def test_async_lost_long_polls_end_in_solve_timeout() -> None:
268
+ script = Script((202, solve_payload(status="pending")), _reset)
269
+ nc = client_for(script)
270
+ with pytest.raises(SolveTimeoutError) as exc_info:
271
+ await nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com", timeout=0.05)
272
+ assert exc_info.value.solve_id == "solve_1"
273
+
274
+
275
+ @pytest.mark.usefixtures("no_retry_delay")
276
+ async def test_async_long_poll_4xx_is_not_retried() -> None:
277
+ script = Script((202, solve_payload(status="pending")), (404, error_payload("not_found")))
278
+ nc = client_for(script)
279
+ with pytest.raises(NotFoundError):
280
+ await nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com")
281
+ assert len(script.requests) == 2
@@ -22,6 +22,7 @@ from nonecap import (
22
22
  RateLimitError,
23
23
  ServiceUnavailableError,
24
24
  SitekeyRateLimitedError,
25
+ SitekeyUnavailableError,
25
26
  SolveErrorReason,
26
27
  SolveFailedError,
27
28
  SolveTimeoutError,
@@ -275,6 +276,7 @@ class TestErrorMapping:
275
276
  (404, "not_found", NotFoundError),
276
277
  (404, "not_eligible", NotFoundError),
277
278
  (503, "maintenance", ServiceUnavailableError),
279
+ (503, "sitekey_unavailable", SitekeyUnavailableError),
278
280
  (503, "maintenance", APIError),
279
281
  (500, "internal_error", APIError),
280
282
  (500, "some_future_code", APIError),
@@ -626,3 +628,58 @@ class TestLifecycle:
626
628
  pass
627
629
  assert not external.is_closed
628
630
  external.close()
631
+
632
+
633
+ def _reset(request: httpx.Request) -> httpx.Response:
634
+ raise httpx.ReadError("Connection reset by peer", request=request)
635
+
636
+
637
+ @pytest.fixture
638
+ def no_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None:
639
+ monkeypatch.setattr("nonecap._client._POLL_RETRY_DELAY", 0.0, raising=False)
640
+
641
+
642
+ @pytest.mark.usefixtures("no_retry_delay")
643
+ def test_solve_repolls_after_a_lost_long_poll() -> None:
644
+ script = Script(
645
+ (202, solve_payload(status="pending")),
646
+ _reset,
647
+ (200, solve_payload(status="solved", token="TOK")),
648
+ )
649
+ nc = client_for(script)
650
+ solve = nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com")
651
+ assert solve.token == "TOK"
652
+ assert [r.method for r in script.requests] == ["POST", "GET", "GET"]
653
+ assert script.requests[2].url.path == "/v1/solves/solve_1"
654
+
655
+
656
+ @pytest.mark.usefixtures("no_retry_delay")
657
+ def test_solve_repolls_after_a_5xx_on_the_long_poll() -> None:
658
+ script = Script(
659
+ (202, solve_payload(status="pending")),
660
+ (502, {"error": {"code": "bad_gateway", "message": "upstream", "param": None}}),
661
+ (200, solve_payload(status="solved", token="TOK")),
662
+ )
663
+ nc = client_for(script)
664
+ assert nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com").token == "TOK"
665
+ assert len(script.requests) == 3
666
+
667
+
668
+ @pytest.mark.usefixtures("no_retry_delay")
669
+ def test_long_poll_4xx_is_not_retried() -> None:
670
+ script = Script((202, solve_payload(status="pending")), (404, error_payload("not_found")))
671
+ nc = client_for(script)
672
+ with pytest.raises(NotFoundError):
673
+ nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com")
674
+ assert len(script.requests) == 2
675
+
676
+
677
+ @pytest.mark.usefixtures("no_retry_delay")
678
+ def test_lost_long_polls_end_in_solve_timeout_with_the_id() -> None:
679
+ script = Script((202, solve_payload(status="pending")), _reset)
680
+ nc = client_for(script)
681
+ with pytest.raises(SolveTimeoutError) as exc_info:
682
+ nc.solve(type="hcaptcha", sitekey="sk", url="https://e.com", timeout=0.05)
683
+ assert exc_info.value.solve_id == "solve_1"
684
+ assert script.requests[0].method == "POST"
685
+ assert all(r.method == "GET" for r in script.requests[1:])
@@ -1 +0,0 @@
1
- __version__ = "0.11.2"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes