diff --git a/modules/map/test/test_winds.py b/modules/map/test/test_winds.py index 4bd47c09..7902cad0 100644 --- a/modules/map/test/test_winds.py +++ b/modules/map/test/test_winds.py @@ -2,6 +2,7 @@ import json from http import HTTPStatus from unittest import mock +import aiohttp import pytest from modules.map import winds @@ -238,6 +239,41 @@ async def test_fetch_wind_field_slows_down(test_directory): await winds.fetch_wind_field([(10, 10)]) +@pytest.mark.asyncio +async def test_fetch_wind_field_reconnects(test_directory): + """A request which cannot connect is asked again a minute later, once, rather than losing the + batches already fetched.""" + unreachable = aiohttp.ClientConnectorError(mock.Mock(host='api.open-meteo.com', port=443, ssl='default'), + OSError('Connect call failed')) + answers = [unreachable] + slept = [] + + async def sleep(seconds): + slept.append(seconds) + + service = fake_service([]) + + async def unreachable_then_fine(url): + if answers: + raise answers.pop() + return await service(url) + + with mock.patch('modules.map.winds.request_forecast', unreachable_then_fine), \ + mock.patch('modules.map.winds.asyncio.sleep', sleep): + field = await winds.fetch_wind_field([(10, 10)]) + assert slept == [winds.BATCH_SECONDS] and field['points'] + + async def always_unreachable(url): + raise unreachable + + slept.clear() + with mock.patch('modules.map.winds.request_forecast', always_unreachable), \ + mock.patch('modules.map.winds.asyncio.sleep', sleep): + with pytest.raises(winds.WindsError, match='Could not reach the forecast service'): + await winds.fetch_wind_field([(10, 10)]) + assert slept == [winds.BATCH_SECONDS] + + @pytest.mark.asyncio async def test_latest_winds_api(async_client, test_directory): request, response = await async_client.get('/api/map/fallout/winds/latest') diff --git a/modules/map/winds.py b/modules/map/winds.py index b262fb81..ea822a2e 100644 --- a/modules/map/winds.py +++ b/modules/map/winds.py @@ -26,6 +26,7 @@ from pathlib import Path from typing import List, Optional, Sequence, Tuple from urllib.parse import urlencode +import aiohttp from sqlalchemy.orm import Session from modules.map.lib import get_map_directory @@ -195,7 +196,8 @@ async def request_forecast(url: str) -> list: async def request_batch(url: str) -> list: """The forecasts of a request; asked once more, a minute later, when the service says too many - have been asked of it.""" + have been asked of it, or could not be connected to (so the batches already fetched are not lost + to a moment's outage).""" for attempt in range(2): try: return await request_forecast(url) @@ -207,7 +209,11 @@ async def request_batch(url: str) -> list: except asyncio.TimeoutError as e: raise WindsError(f'The forecast service did not answer within {TIMEOUT} seconds') from e except Exception as e: - raise WindsError(f'Could not reach the forecast service: {str(e) or type(e).__name__}') from e + error = WindsError(f'Could not reach the forecast service: {str(e) or type(e).__name__}') + if attempt or not isinstance(e, aiohttp.ClientConnectionError): + raise error from e + logger.warning(f'{error}; trying again in a minute') + await asyncio.sleep(BATCH_SECONDS) async def fetch_wind_field(places: Sequence[Tuple[float, float]], progress=None, cancelled=None) -> dict: