Open gordonwatts opened 3 years ago
I think I'm having the same issue. I was trying to use async for ...
with a function wrapped using backoff. The use case is handling websocket disconnects.
@awm33 - Would the algorithm above have handled it? The problem with re-starting something when the sequence is halfway done is... well... difficult.
@gordonwatts I used a wrapper within the wrapper. Here's a condensed version of what I was trying to do:
async def events():
url = getws_url()
req_kwargs = {}
add_auth_header(req_kwargs)
@backoff.on_exception(backoff.expo,
(aiohttp.ClientResponseError,
aiohttp.ClientConnectorError,
aiohttp.WebSocketError,
aiohttp.WSCloseCode,
DisconnectError))
async def connect_wrapper():
async with session.ws_connect(url, **req_kwargs) as ws:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
yield msg.json()
elif msg.type == aiohttp.WSMsgType.ERROR:
break
if not ws_disconnecting: ## tracks if the disconnect was intended
raise DisconnectError()
async for event in connect_wrapper(): # there is no "async yield for ..."
yield event
Then
async for event in self.events():
print(event)
Ok - so this looks like it is the same pattern I had - you need to catch and recover from errors that occurred in the ws_connect
call. But once messages started returning from the session, then you didn't need to catch errors there.
I needed to restart an async iterator if it hadn't returned any items yet. The algorithm I needed was:
The logic here is basically once the async iterator has returned an item there is no way to "get it back" - so the exception should follow the same logic.
I used
backoff
in my project already, so I thought I'd just re-use the coreasync
code you have already written to implement this. I came up with the code below. As you can tell, it is about 99% copied from this library. The only important difference comes in theretry_exception_itr
function, in the retry function, in the while loop (so about 20 lines down from the top).Which leads me to: is this a feature you'd be interested in having in this library? If so, does the below approach make sense?
As always, thanks for a really excellent library!