diff --git a/paddleocr/_api_client/_async_http.py b/paddleocr/_api_client/_async_http.py index 7d02bed548c..42cc89b996e 100644 --- a/paddleocr/_api_client/_async_http.py +++ b/paddleocr/_api_client/_async_http.py @@ -12,8 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +import asyncio import json import os +from contextlib import asynccontextmanager from typing import Any, Dict, Optional import aiohttp @@ -77,6 +79,22 @@ def _api_headers(self) -> dict: headers["Client-Platform"] = self._client_platform return headers + @asynccontextmanager + async def _request(self, request_cm): + """Enter an aiohttp request context, mapping transport-level failures to + the SDK's error types. This keeps the async client's contract identical + to the sync client (see ``_http.py``), where every network failure is a + ``PaddleOCRAPIError`` subclass rather than a raw ``aiohttp``/``asyncio`` + exception. + """ + try: + async with request_cm as resp: + yield resp + except asyncio.TimeoutError as e: + raise RequestTimeoutError(f"Request timed out: {e}") from e + except aiohttp.ClientConnectionError as e: + raise NetworkError(f"Connection failed: {e}") from e + async def submit_url( self, model: str, @@ -96,10 +114,12 @@ async def submit_url( body["batchId"] = batch_id await self._ensure_session() - async with self._session.post( - self._jobs_url, - json=body, - headers={"Content-Type": "application/json"}, + async with self._request( + self._session.post( + self._jobs_url, + json=body, + headers={"Content-Type": "application/json"}, + ) ) as resp: await self._raise_for_response(resp) data = await self._response_data(resp) @@ -133,27 +153,31 @@ async def submit_file( ) await self._ensure_session() - async with self._session.post(self._jobs_url, data=form) as resp: + async with self._request(self._session.post(self._jobs_url, data=form)) as resp: await self._raise_for_response(resp) data = await self._response_data(resp) return extract_job_id(data) async def get_job_status(self, job_id: str) -> Dict[str, Any]: await self._ensure_session() - async with self._session.get(f"{self._jobs_url}/{job_id}") as resp: + async with self._request( + self._session.get(f"{self._jobs_url}/{job_id}") + ) as resp: await self._raise_for_response(resp) return await self._response_data(resp) async def get_batch_status(self, batch_id: str) -> Dict[str, Any]: await self._ensure_session() - async with self._session.get(f"{self._jobs_url}/batch/{batch_id}") as resp: + async with self._request( + self._session.get(f"{self._jobs_url}/batch/{batch_id}") + ) as resp: await self._raise_for_response(resp) return await self._response_data(resp) async def fetch_jsonl(self, url: str) -> list: timeout = aiohttp.ClientTimeout(total=self._timeout) async with aiohttp.ClientSession(timeout=timeout) as bare_session: - async with bare_session.get(url) as resp: + async with self._request(bare_session.get(url)) as resp: await self._raise_for_response(resp) text = await resp.text() try: diff --git a/tests/api_client/test_async_http.py b/tests/api_client/test_async_http.py new file mode 100644 index 00000000000..c83ad31e5f9 --- /dev/null +++ b/tests/api_client/test_async_http.py @@ -0,0 +1,106 @@ +# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Async HTTP client transport-error mapping. + +The async client must honor the same contract as the sync client: every network +failure surfaces as a ``PaddleOCRAPIError`` subclass, never a raw +``aiohttp``/``asyncio`` exception. These tests use ``asyncio.run`` so they need +no extra async-plugin dependency. +""" + +import asyncio +import socket +import time +from http.server import BaseHTTPRequestHandler, HTTPServer +from threading import Thread + +import pytest + +from paddleocr._api_client._async_http import AsyncHTTPClient +from paddleocr._api_client.errors import NetworkError, RequestTimeoutError + + +class _SlowHandler(BaseHTTPRequestHandler): + """Sleeps before responding, to force a client-side timeout.""" + + delay = 2.0 + + def do_GET(self): + time.sleep(self.__class__.delay) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"code": 0, "data": {}}') + + def log_message(self, format, *args): + pass + + +@pytest.fixture() +def slow_server(): + server = HTTPServer(("127.0.0.1", 0), _SlowHandler) + port = server.server_address[1] + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{port}" + server.shutdown() + + +def _unused_url(): + # Bind then immediately release a port so a connection there is refused. + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return f"http://127.0.0.1:{port}" + + +def test_connection_error_maps_to_network_error(): + client = AsyncHTTPClient(token="t", base_url=_unused_url(), timeout=5.0) + + async def run(): + try: + with pytest.raises(NetworkError): + await client.get_job_status("job-1") + finally: + await client.close() + + asyncio.run(run()) + + +def test_timeout_maps_to_request_timeout_error(slow_server): + client = AsyncHTTPClient(token="t", base_url=slow_server, timeout=0.5) + + async def run(): + try: + with pytest.raises(RequestTimeoutError): + await client.get_job_status("job-1") + finally: + await client.close() + + asyncio.run(run()) + + +def test_fetch_jsonl_connection_error_maps_to_network_error(): + client = AsyncHTTPClient(token="t", base_url="http://127.0.0.1", timeout=5.0) + + async def run(): + try: + with pytest.raises(NetworkError): + await client.fetch_jsonl(_unused_url()) + finally: + await client.close() + + asyncio.run(run())