Skip to content

Commit

Permalink
Fix async cancellation behaviour (#580)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomchristie committed Nov 7, 2022
1 parent 6c57627 commit ce8f872
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
12 changes: 6 additions & 6 deletions httpcore/_async/connection_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ async def handle_async_request(self, request: Request) -> Response:
)

status = RequestStatus(request)
self._requests.append(status)

async with self._pool_lock:
self._requests.append(status)
await self._close_expired_connections()
await self._attempt_to_acquire_connection(status)

Expand All @@ -229,9 +229,8 @@ async def handle_async_request(self, request: Request) -> Response:
# If we timeout here, or if the task is cancelled, then make
# sure to remove the request from the queue before bubbling
# up the exception.
async with self._pool_lock:
self._requests.remove(status)
raise exc
self._requests.remove(status)
raise exc

try:
response = await connection.handle_async_request(request)
Expand Down Expand Up @@ -274,10 +273,11 @@ async def response_closed(self, status: RequestStatus) -> None:
assert status.connection is not None
connection = status.connection

if status in self._requests:
self._requests.remove(status)

async with self._pool_lock:
# Update the state of the connection pool.
if status in self._requests:
self._requests.remove(status)

if connection.is_closed() and connection in self._pool:
self._pool.remove(connection)
Expand Down
12 changes: 6 additions & 6 deletions httpcore/_sync/connection_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ def handle_request(self, request: Request) -> Response:
)

status = RequestStatus(request)
self._requests.append(status)

with self._pool_lock:
self._requests.append(status)
self._close_expired_connections()
self._attempt_to_acquire_connection(status)

Expand All @@ -229,9 +229,8 @@ def handle_request(self, request: Request) -> Response:
# If we timeout here, or if the task is cancelled, then make
# sure to remove the request from the queue before bubbling
# up the exception.
with self._pool_lock:
self._requests.remove(status)
raise exc
self._requests.remove(status)
raise exc

try:
response = connection.handle_request(request)
Expand Down Expand Up @@ -274,10 +273,11 @@ def response_closed(self, status: RequestStatus) -> None:
assert status.connection is not None
connection = status.connection

if status in self._requests:
self._requests.remove(status)

with self._pool_lock:
# Update the state of the connection pool.
if status in self._requests:
self._requests.remove(status)

if connection.is_closed() and connection in self._pool:
self._pool.remove(connection)
Expand Down

0 comments on commit ce8f872

Please sign in to comment.