Refactor of caching & data storage part 9 #118

This commit is contained in:
Ian Renton
2026-08-02 09:06:10 +01:00
parent 0b0c8aa4f3
commit 2157bf114e
72 changed files with 159 additions and 131 deletions
+36
View File
@@ -0,0 +1,36 @@
import json
import logging
import geopandas
from shapely import prepare
from core.data_store import DATA_STORE
from providers.staticdata.local_file_static_data_provider import LocalFileStaticDataProvider
class CQZoneData(LocalFileStaticDataProvider):
"""Static data provider for CQ zone geodata."""
PATH = "datafiles/cqzones.geojson"
def __init__(self, provider_config):
super().__init__("CQ Zone Data", provider_config, self.PATH)
def _load_data(self, path):
try:
with open(path) as f:
cq_zone_data = geopandas.GeoDataFrame.from_features(json.load(f)["features"])
for idx in cq_zone_data.index:
prepare(cq_zone_data.at[idx, 'geometry'])
# Bail out if a stop has been requested, i.e. the program is shutting down - no need to prepare the rest
# of the data in this case
if self.stop:
break
DATA_STORE.cq_zone_data = cq_zone_data
return True
except Exception as e:
logging.error("Exception when loading CQ zone data.", e, exc_info=True)
return False
@@ -0,0 +1,77 @@
import logging
from datetime import datetime
from threading import Thread, Event
import pytz
from requests import ReadTimeout
from requests.exceptions import ConnectionError, ConnectTimeout
from core.constants import HTTP_HEADERS
from core.url_data_cache import URLDataCache
from providers.staticdata.static_data_provider import StaticDataProvider
class FileDownloadStaticDataProvider(StaticDataProvider):
"""Generic static reference data provider class for providers that fetch their data from the web by downloading a
file."""
def __init__(self, name, provider_config, url, poll_interval):
""" Set up the provider, note poll_interval is in *days*."""
super().__init__(name, provider_config)
self._url = url
self._poll_interval = poll_interval
self._thread = None
self._stop_event = Event()
self._url_data_cache = URLDataCache("staticdata_" + name)
def start(self):
# Fire off the polling thread. It will poll immediately on startup, then sleep for poll_interval between
# subsequent polls, so start() returns immediately and the application can continue starting.
logging.info(
"Set up query of " + self.name + " static reference data every " + str(self._poll_interval) + " days.")
self._thread = Thread(target=self._run, daemon=True)
self._thread.start()
def stop(self):
self._stop_event.set()
def _run(self):
while True:
self._poll()
if self._stop_event.wait(timeout=self._poll_interval * 60 * 60 * 24):
break
def _poll(self):
try:
# Request data from API. Use the data cache (with a TTL of 1 day) here, not as the main mechanism for
# caching, but just so continual restarts of the software during testing don't hammer the servers.
logging.debug("Downloading " + self.name + " static reference data...")
http_response = self._url_data_cache.get(self._url, headers=HTTP_HEADERS)
# Check response code was good
if http_response.ok:
# Pass off to the subclass for processing
ok = self._handle_http_response(http_response)
if ok:
self.status = "OK"
self.last_update_time = datetime.now(pytz.UTC)
logging.info("Updated static reference data for " + self.name)
else:
self.status = "Error"
logging.warning(f"HTTP {http_response.status_code} when downloading static reference data for {self.name}.")
except ConnectionError:
self.status = "Error"
logging.warning(f"Connection error when downloading static reference data for {self.name}.")
except (ConnectTimeout, ReadTimeout):
self.status = "Error"
logging.warning(f"Timeout when downloading static reference data for {self.name}.")
except Exception:
self.status = "Error"
logging.exception("Exception in HTTP static reference data provider (" + self.name + ")")
self._stop_event.wait(timeout=1)
def _handle_http_response(self, http_response):
"""Handle an HTTP response returned by the server and load the data from it. Return true if successful,
false otherwise."""
raise NotImplementedError("Subclasses must implement this method")
+36
View File
@@ -0,0 +1,36 @@
import json
import logging
import geopandas
from shapely import prepare
from core.data_store import DATA_STORE
from providers.staticdata.local_file_static_data_provider import LocalFileStaticDataProvider
class ITUZoneData(LocalFileStaticDataProvider):
"""Static data provider for ITU zone geodata."""
PATH = "datafiles/ituzones.geojson"
def __init__(self, provider_config):
super().__init__("ITU Zone Data", provider_config, self.PATH)
def _load_data(self, path):
try:
with open(path) as f:
itu_zone_data = geopandas.GeoDataFrame.from_features(json.load(f)["features"])
for idx in itu_zone_data.index:
prepare(itu_zone_data.at[idx, 'geometry'])
# Bail out if a stop has been requested, i.e. the program is shutting down - no need to prepare the rest
# of the data in this case
if self.stop:
break
DATA_STORE.itu_zone_data = itu_zone_data
return True
except Exception as e:
logging.error("Exception when loading ITU zone data.", e, exc_info=True)
return False
+46
View File
@@ -0,0 +1,46 @@
import logging
from core.data_store import DATA_STORE
from providers.staticdata.file_download_static_data_provider import FileDownloadStaticDataProvider
class K0SWE(FileDownloadStaticDataProvider):
"""Static data provider for K0SWE's dxcc.json, which provides callsign regex to DXCC entity mapping, plus DXCC to
continent, flag emoji etc."""
POLL_INTERVAL_DAYS = 7
DATA_URL = "https://raw.githubusercontent.com/k0swe/dxcc-json/refs/heads/main/dxcc.json"
def __init__(self, provider_config):
super().__init__("K0SWE DXCC JSON", provider_config, self.DATA_URL, self.POLL_INTERVAL_DAYS)
def _handle_http_response(self, http_response):
try:
dxcc_list = http_response.json()["dxcc"]
# Reformat as a map for to place in the data store
dxcc_map = {}
for dxcc in dxcc_list:
dxcc_map[dxcc["entityCode"]] = dxcc
# Bail out if a stop has been requested, i.e. the program is shutting down - no need to parse the rest
# of the data in this case
if self._stop_event.is_set():
break
# Add to data store
for k, v in dxcc_map.items():
DATA_STORE.dxcc_data[k] = v
if self._stop_event.is_set():
break
# Regenerate in-memory regex-to-DXCC-entity-code map.
DATA_STORE.regenerate_call_regex_to_dxcc_entity_map()
return True
except Exception as e:
logging.error("Exception when loading K0SWE dxcc.json.", e, exc_info=True)
return False
@@ -0,0 +1,38 @@
import logging
from datetime import datetime
import pytz
from providers.staticdata.static_data_provider import StaticDataProvider
class LocalFileStaticDataProvider(StaticDataProvider):
"""Generic static reference data provider class for providers that fetch their data from a local file on startup."""
def __init__(self, name, provider_config, path):
super().__init__(name, provider_config)
self._path = path
self._stop = False
def start(self):
logging.debug("Loading " + self.name + " static reference data from file.")
try:
ok = self._load_data(self._path)
if ok:
self.status = "OK"
self.last_update_time = datetime.now(pytz.UTC)
logging.info("Updated static reference data for " + self.name)
else:
self.status = "Error"
logging.error("Failed to load data for " + self.name)
except Exception as e:
self.status = "Error"
logging.error("Exception in local file Static Data Provider (" + self.name + ")", e, exc_info=True)
def stop(self):
self._stop = True
def _load_data(self, path):
"""Load data from the given file path. Return true if successful, false otherwise."""
raise NotImplementedError("Subclasses must implement this method")
@@ -0,0 +1,28 @@
from datetime import datetime
import pytz
class StaticDataProvider:
"""Generic static reference data provider class. Subclasses of this query the individual URLs or files for data."""
def __init__(self, name, provider_config):
"""Constructor"""
self.name = name
self.enabled = provider_config["enabled"]
self.last_update_time = datetime.min.replace(tzinfo=pytz.UTC)
self.status = "Not Started" if self.enabled else "Disabled"
self.reference_count = 0
def start(self):
"""Start the provider. This should return immediately after spawning threads to access the remote resources"""
raise NotImplementedError("Subclasses must implement this method")
def stop(self):
"""Stop any threads and prepare for application shutdown"""
raise NotImplementedError("Subclasses must implement this method")