Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close aiohttp client on error #2294

Merged
merged 2 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/huggingface_hub/inference/_generated/_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ async def post(
timeout = max(self.timeout - (time.time() - t0), 1) # type: ignore
continue
raise error
except Exception:
await client.close()
raise

async def audio_classification(
self,
Expand Down
17 changes: 17 additions & 0 deletions tests/test_inference_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import asyncio
import inspect
from unittest.mock import Mock, patch

import pytest
from aiohttp import ClientResponseError
Expand Down Expand Up @@ -350,3 +351,19 @@ async def test_unprocessable_entity_error() -> None:
with pytest.warns(FutureWarning, match=".*'InferenceClient.conversational'.*"):
await AsyncInferenceClient().conversational("Hi, who are you?", model="HuggingFaceH4/zephyr-7b-alpha")
assert "Make sure 'conversational' task is supported by the model." in error.value.message


class CustomException(Exception):
"""Mock any exception that could happen while making a POST request."""


@patch("aiohttp.ClientSession.post", side_effect=CustomException())
@patch("aiohttp.ClientSession.close")
@pytest.mark.asyncio
async def test_close_connection_on_post_error(mock_close: Mock, mock_post: Mock) -> None:
async_client = AsyncInferenceClient()

with pytest.raises(CustomException):
await async_client.post(model="http://127.0.0.1/api", json={})

mock_close.assert_called_once()
5 changes: 4 additions & 1 deletion utils/generate_async_inference_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,10 @@ def _rename_to_AsyncInferenceClient(code: str) -> str:
if timeout is not None:
timeout = max(self.timeout - (time.time() - t0), 1) # type: ignore
continue
raise error"""
raise error
except Exception:
await client.close()
raise"""


def _make_post_async(code: str) -> str:
Expand Down
Loading