Skip to content

Commit

Permalink
Close socket when read or write timeouts occur (#365)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomchristie committed Jun 15, 2021
1 parent 0137177 commit 8970484
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
2 changes: 2 additions & 0 deletions httpcore/_backends/anyio.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ async def read(self, n: int, timeout: TimeoutDict) -> bytes:
with anyio.fail_after(read_timeout):
return await self.stream.receive(n)
except TimeoutError:
await self.stream.aclose()
raise ReadTimeout from None
except BrokenResourceError as exc:
raise ReadError from exc
Expand All @@ -75,6 +76,7 @@ async def write(self, data: bytes, timeout: TimeoutDict) -> None:
with anyio.fail_after(write_timeout):
return await self.stream.send(data)
except TimeoutError:
await self.stream.aclose()
raise WriteTimeout from None
except BrokenResourceError as exc:
raise WriteError from exc
Expand Down
16 changes: 12 additions & 4 deletions httpcore/_backends/trio.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,12 @@ async def read(self, n: int, timeout: TimeoutDict) -> bytes:

async with self.read_lock:
with map_exceptions(exc_map):
with trio.fail_after(read_timeout):
return await self.stream.receive_some(max_bytes=n)
try:
with trio.fail_after(read_timeout):
return await self.stream.receive_some(max_bytes=n)
except trio.TooSlowError as exc:
await self.stream.aclose()
raise exc

async def write(self, data: bytes, timeout: TimeoutDict) -> None:
if not data:
Expand All @@ -73,8 +77,12 @@ async def write(self, data: bytes, timeout: TimeoutDict) -> None:

async with self.write_lock:
with map_exceptions(exc_map):
with trio.fail_after(write_timeout):
return await self.stream.send_all(data)
try:
with trio.fail_after(write_timeout):
return await self.stream.send_all(data)
except trio.TooSlowError as exc:
await self.stream.aclose()
raise exc

async def aclose(self) -> None:
async with self.write_lock:
Expand Down

0 comments on commit 8970484

Please sign in to comment.