Merge pull request #176 from Amateur-Digital-Network/feature/alias-download-gzip

perf(aliases): download alias lists gzip-compressed
pull/177/head
ce5rpy 2 weeks ago committed by GitHub
commit a6fb2cc2c0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -26,6 +26,7 @@
from __future__ import annotations
import csv
import gzip
import hashlib
import json
import logging
@ -35,10 +36,13 @@ import ssl
import sys
import threading
import time
import zlib
from collections.abc import Callable
from email.utils import formatdate
from pathlib import Path
from typing import Any
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from ...application.ports import AliasLoader
from ...domain.value_objects import SubscriberProfile
@ -71,38 +75,54 @@ def try_download(
`retry_timeout` so a fully unreachable host can't stall a caller for `max_attempts *
first_timeout` (this runs synchronously during startup, and off-thread on the
periodic reload — see alias_reload_loop in peer_server.py). Returns a result message.
Asks for gzip (the JSON lists shrink ~7x) and stores the decompressed file; the
published checksum is of the uncompressed content.
"""
if not url:
return f"ID ALIAS MAPPER: '{file_name}' URL empty, not downloaded"
full = path / file_name
now = time.time()
file_exists = full.is_file()
if_modified_since: str | None = None
if file_exists and expected_checksum and current_checksum:
if current_checksum == expected_checksum:
return f"ID ALIAS MAPPER: '{file_name}' is current, not downloaded"
else:
if file_exists:
file_old = (full.stat().st_mtime + stale_sec) < now
else:
file_old = True
if not file_old and file_exists:
return f"ID ALIAS MAPPER: '{file_name}' is current, not downloaded"
mtime = full.stat().st_mtime
if mtime + stale_sec >= now:
return f"ID ALIAS MAPPER: '{file_name}' is current, not downloaded"
if not expected_checksum:
if_modified_since = formatdate(mtime, usegmt=True)
data: bytes | None = None
last_error: Exception | None = None
not_modified = False
for attempt in range(1, max_attempts + 1):
timeout = first_timeout if attempt == 1 else retry_timeout
try:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with urlopen(url, context=ctx, timeout=timeout) as response:
request = Request(url, headers={"Accept-Encoding": "gzip"})
if if_modified_since:
request.add_header("If-Modified-Since", if_modified_since)
with urlopen(request, context=ctx, timeout=timeout) as response:
data = response.read()
encoding = response.headers.get("Content-Encoding") or ""
if encoding.lower() == "gzip":
data = gzip.decompress(data)
if expected_checksum and hashlib.blake2b(data).hexdigest() != expected_checksum:
raise ValueError("downloaded data does not match expected checksum")
last_error = None
break
except (OSError, ValueError) as e:
except (OSError, ValueError, zlib.error, EOFError) as e:
# urllib raises a 304 as HTTPError, an OSError.
if isinstance(e, HTTPError) and e.code == 304:
not_modified = True
last_error = None
break
last_error = e
data = None
if attempt < max_attempts:
@ -112,6 +132,12 @@ def try_download(
)
if retry_delay_sec:
time.sleep(retry_delay_sec)
if not_modified:
try:
os.utime(full)
except OSError as e:
return f"ID ALIAS mapper '{file_name}' file could not be written: {e}"
return f"ID ALIAS MAPPER: '{file_name}' is current, not downloaded"
if isinstance(last_error, ValueError):
return f"ID ALIAS MAPPER: '{file_name}' could not be downloaded, checksum mismatch after {max_attempts} attempts"
if last_error is not None:

@ -29,6 +29,7 @@ import json
import os
from pathlib import Path
from unittest.mock import patch
from urllib.request import Request
from adn_server.infrastructure.persistence.alias_loader import DefaultAliasLoader
@ -38,6 +39,7 @@ _URLOPEN = "adn_server.infrastructure.persistence.alias_loader.urlopen"
class _Resp:
def __init__(self, data: bytes) -> None:
self._data = data
self.headers: dict[str, str] = {}
def read(self) -> bytes:
return self._data
@ -74,8 +76,8 @@ class _Server:
).encode(),
}
def urlopen(self, url: str, context=None, timeout=None) -> _Resp:
name = url.rsplit("/", 1)[-1]
def urlopen(self, request: Request, context=None, timeout=None) -> _Resp:
name = request.full_url.rsplit("/", 1)[-1]
self.fetched.append(name)
return _Resp(self.files[name])

@ -0,0 +1,143 @@
# ADN DMR Peer Server - alias downloads over gzip and If-Modified-Since
#
###############################################################################
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
from __future__ import annotations
import gzip
import hashlib
import os
import threading
from collections.abc import Iterator
from email.message import Message
from email.utils import formatdate
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
from adn_server.infrastructure.persistence.alias_loader import try_download
_PLAIN = b'{"count": 1, "results": [{"id": 7300391, "callsign": "CE5RPY"}]}' * 200
class _Origin:
"""What the local HTTP server answers, and the headers of every request it got."""
def __init__(self) -> None:
self.body = _PLAIN
self.content_encoding: str | None = None
self.not_modified = False
self.requests: list[Message] = []
@pytest.fixture
def origin() -> Iterator[tuple[_Origin, str]]:
state = _Origin()
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
state.requests.append(self.headers)
if state.not_modified and self.headers.get("If-Modified-Since"):
self.send_response(304)
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
if state.content_encoding:
self.send_header("Content-Encoding", state.content_encoding)
self.send_header("Content-Length", str(len(state.body)))
self.end_headers()
self.wfile.write(state.body)
def log_message(self, *args: object) -> None:
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield state, f"http://127.0.0.1:{server.server_address[1]}/subscriber_ids.json"
finally:
server.shutdown()
server.server_close()
thread.join()
def _download(tmp_path: Path, url: str, **kwargs: object) -> str:
kwargs.setdefault("stale_sec", 0)
return try_download(
tmp_path, "subscriber_ids.json", url, max_attempts=3, retry_delay_sec=0, **kwargs
)
def test_request_asks_for_gzip(tmp_path: Path, origin: tuple[_Origin, str]) -> None:
state, url = origin
_download(tmp_path, url)
assert state.requests[0].get("Accept-Encoding") == "gzip"
def test_gzip_response_is_stored_decompressed_and_checked_on_plain_content(
tmp_path: Path, origin: tuple[_Origin, str]
) -> None:
state, url = origin
state.body, state.content_encoding = gzip.compress(_PLAIN), "gzip"
result = _download(tmp_path, url, expected_checksum=hashlib.blake2b(_PLAIN).hexdigest())
assert "successfully downloaded" in result
assert (tmp_path / "subscriber_ids.json").read_bytes() == _PLAIN
def test_uncompressed_response_is_stored_as_is(tmp_path: Path, origin: tuple[_Origin, str]) -> None:
_, url = origin
result = _download(tmp_path, url, expected_checksum=hashlib.blake2b(_PLAIN).hexdigest())
assert "successfully downloaded" in result
assert (tmp_path / "subscriber_ids.json").read_bytes() == _PLAIN
def test_corrupt_gzip_is_retried_then_fails_without_writing(
tmp_path: Path, origin: tuple[_Origin, str]
) -> None:
state, url = origin
state.body, state.content_encoding = gzip.compress(_PLAIN)[:-40], "gzip"
result = _download(tmp_path, url)
assert "could not be downloaded" in result
assert len(state.requests) == 3
assert list(tmp_path.iterdir()) == []
def test_not_modified_keeps_file_touches_it_and_reports_current(
tmp_path: Path, origin: tuple[_Origin, str]
) -> None:
state, url = origin
state.not_modified = True
full = tmp_path / "subscriber_ids.json"
full.write_bytes(b'{"old": true}')
old_mtime = 1_700_000_000
os.utime(full, (old_mtime, old_mtime))
result = _download(tmp_path, url, stale_sec=86400)
assert state.requests[0].get("If-Modified-Since") == formatdate(old_mtime, usegmt=True)
assert len(state.requests) == 1
assert "is current, not downloaded" in result
assert full.read_bytes() == b'{"old": true}'
assert full.stat().st_mtime > old_mtime

@ -126,6 +126,7 @@ def test_try_download_gives_up_after_max_attempts(tmp_path: Path) -> None:
class _FakeResponse:
def __init__(self, data: bytes) -> None:
self._data = data
self.headers: dict[str, str] = {}
def read(self) -> bytes:
return self._data

Loading…
Cancel
Save

Powered by TurnKey Linux.