Async Retry with Timeout
Hard · Async
Network calls can hang forever. await asyncio.wait_for(coro, timeout) runs a coroutine, but if it takes longer than timeout seconds it cancels it and raises TimeoutError.
Write async def fetch_with_retry(fetch, attempts, timeout):
- call fetch() up to attempts times, each call limited to timeout seconds with asyncio.wait_for
- return the first successful result
- retry after a TimeoutError or a ConnectionError
- any other exception (like ValueError) means retrying will not help: let it propagate right away
- if every attempt fails, raise RuntimeError("gave up after <attempts> attempts")
The driver check_fetch(plan, attempts) is already written and uses a timeout of 0.1 seconds. Its fake fetch follows a plan, one outcome per attempt: "fast" answers after 0.01 s, "slow" would take 1 s (so the timeout cancels it), "down" raises ConnectionError and "bad" raises ValueError. It returns your result (or the error) and the log the fake wrote.