Skip to content

Commit

Permalink
Handle aiohttp task cancellation better (#6862)
Browse files Browse the repository at this point in the history
  • Loading branch information
balloob authored and pvizeli committed Mar 31, 2017
1 parent 5bb201c commit 8c97bcc
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
21 changes: 10 additions & 11 deletions homeassistant/components/camera/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""
import asyncio
import collections
from contextlib import suppress
from datetime import timedelta
import logging
import hashlib
Expand Down Expand Up @@ -167,7 +168,7 @@ def write(img_bytes):
if not img_bytes:
break

if img_bytes is not None and img_bytes != last_image:
if img_bytes and img_bytes != last_image:
write(img_bytes)

# Chrome seems to always ignore first picture,
Expand All @@ -180,8 +181,8 @@ def write(img_bytes):

yield from asyncio.sleep(.5)

except (asyncio.CancelledError, ConnectionResetError):
_LOGGER.debug("Close stream by frontend.")
except asyncio.CancelledError:
_LOGGER.debug("Stream closed by frontend.")
response = None

finally:
Expand Down Expand Up @@ -263,16 +264,14 @@ class CameraImageView(CameraView):
@asyncio.coroutine
def handle(self, request, camera):
"""Serve camera image."""
try:
image = yield from camera.async_camera_image()
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(10, loop=request.app['hass'].loop):
image = yield from camera.async_camera_image()

if image is None:
return web.Response(status=500)
if image:
return web.Response(body=image)

return web.Response(body=image)

except asyncio.CancelledError:
_LOGGER.debug("Close stream by frontend.")
return web.Response(status=500)


class CameraMjpegStream(CameraView):
Expand Down
13 changes: 11 additions & 2 deletions homeassistant/helpers/aiohttp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,16 @@ def async_aiohttp_proxy_web(hass, request, web_coro, buffer_size=102400,
with async_timeout.timeout(timeout, loop=hass.loop):
req = yield from web_coro

except asyncio.CancelledError:
# The user cancelled the request
return

except asyncio.TimeoutError as err:
# Timeout trying to start the web request
raise HTTPGatewayTimeout() from err

except aiohttp.ClientError as err:
# Something went wrong with the connection
raise HTTPBadGateway() from err

yield from async_aiohttp_proxy_stream(hass, request, req.content,
Expand All @@ -108,9 +114,12 @@ def async_aiohttp_proxy_stream(hass, request, stream, content_type,
response.write(data)

except (asyncio.TimeoutError, aiohttp.ClientError):
pass
# Something went wrong fetching data, close connection gracefully
yield from response.write_eof()

yield from response.write_eof()
except asyncio.CancelledError:
# The user closed the connection
pass


@callback
Expand Down

0 comments on commit 8c97bcc

Please sign in to comment.