Handle network outages

Quote queries will hang indefinitely when the network goes down.
Instead poll for network reestablishment such that roaming on
wifi is supported and real-time feeds will resume once the network is
back.
kivy_mainline_and_py3.8
Tyler Goodlet 2018-03-31 12:02:22 -04:00
parent 2b51e84a3c
commit 01cfbbdd64
1 changed files with 23 additions and 1 deletions

View File

@ -3,6 +3,8 @@ Core broker-daemon tasks and API.
""" """
import time import time
import inspect import inspect
from functools import partial
import socket
from types import ModuleType from types import ModuleType
from typing import AsyncContextManager from typing import AsyncContextManager
@ -44,6 +46,17 @@ async def quote(brokermod: ModuleType, tickers: [str]) -> dict:
return results return results
async def wait_for_network(get_quotes, sleep=1):
"""Wait until the network comes back up.
"""
while True:
try:
return await get_quotes()
except socket.gaierror:
log.warn(f"Network is down waiting for reestablishment...")
await trio.sleep(sleep)
async def poll_tickers( async def poll_tickers(
client: 'Client', client: 'Client',
quoter: AsyncContextManager, quoter: AsyncContextManager,
@ -64,7 +77,16 @@ async def poll_tickers(
async with quoter(client, tickers) as get_quotes: async with quoter(client, tickers) as get_quotes:
while True: # use an event here to trigger exit? while True: # use an event here to trigger exit?
prequote_start = time.time() prequote_start = time.time()
quotes = await get_quotes(tickers)
with trio.move_on_after(3) as cancel_scope:
quotes = await get_quotes(tickers)
cancelled = cancel_scope.cancelled_caught
if cancelled:
log.warn("Quote query timed out after 3 seconds, retrying...")
# handle network outages by idling until response is received
quotes = await wait_for_network(partial(get_quotes, tickers))
postquote_start = time.time() postquote_start = time.time()
payload = {} payload = {}
for symbol, quote in quotes.items(): for symbol, quote in quotes.items():