Coverage for downtify/update_check.py: 100%
54 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Checks GitHub Releases for a newer Downtify version than the one
2running, on an hourly background loop.
4The web UI only ever reads whatever the last check found (see
5``GET /api/check_update`` in ``downtify/api.py``) — the actual HTTP call
6to GitHub happens here, in the background, so loading the app never
7waits on it.
8"""
10from __future__ import annotations
12import asyncio
13import re
14from datetime import datetime, timezone
15from typing import Any, Optional
17import httpx
18from loguru import logger
20GITHUB_REPO = 'henriquesebastiao/downtify'
21RELEASES_API_URL = (
22 f'https://api.github.com/repos/{GITHUB_REPO}/releases/latest'
23)
24DEFAULT_RELEASES_PAGE_URL = f'https://github.com/{GITHUB_REPO}/releases/latest'
26#: Seconds between checks — "every hour", per the feature request.
27CHECK_INTERVAL_SECONDS = 3600
28REQUEST_TIMEOUT = 10
30_VERSION_RE = re.compile(r'\d+(?:\.\d+)*')
33def _parse_version(raw: str) -> tuple[int, ...]:
34 """Turn ``'2.11.0'``, ``'v2.11.0'`` or ``'Downtify 2.11.0'`` into
35 ``(2, 11, 0)``.
37 Falls back to an empty tuple for anything unparseable, which always
38 compares as "not newer" in :func:`is_newer` rather than raising.
39 """
40 match = _VERSION_RE.search(raw or '')
41 if not match:
42 return ()
43 return tuple(int(part) for part in match.group().split('.'))
46def is_newer(latest: str, current: str) -> bool:
47 """Whether ``latest`` is a strictly newer version than ``current``."""
48 latest_version = _parse_version(latest)
49 return bool(latest_version) and latest_version > _parse_version(current)
52class UpdateChecker:
53 """Caches the result of the last GitHub Releases check.
55 ``check_now()`` does the (blocking) network call and is meant to be
56 run via ``asyncio.to_thread`` from :func:`update_check_loop`;
57 :meth:`status` is cheap and safe to call from a request handler.
58 """
60 def __init__(self, repo: str = GITHUB_REPO) -> None:
61 self._repo = repo
62 self._latest_version: Optional[str] = None
63 self._release_url = DEFAULT_RELEASES_PAGE_URL
64 self._last_checked: Optional[str] = None
65 self._last_error: Optional[str] = None
67 def check_now(self) -> None:
68 """Fetch the latest release from GitHub. Never raises — a
69 network hiccup or GitHub's (unauthenticated) rate limit just
70 means the previous result carries over until the next hourly
71 check, rather than crashing the background loop.
72 """
73 url = f'https://api.github.com/repos/{self._repo}/releases/latest'
74 try:
75 response = httpx.get(
76 url,
77 headers={'Accept': 'application/vnd.github+json'},
78 timeout=REQUEST_TIMEOUT,
79 )
80 response.raise_for_status()
81 data = response.json()
82 tag = str(data.get('tag_name') or '').strip()
83 if not tag:
84 raise ValueError('release response has no tag_name')
85 self._latest_version = tag
86 self._release_url = data.get('html_url') or self._release_url
87 self._last_error = None
88 except Exception as exc:
89 logger.opt(exception=True).warning(
90 'Update check against GitHub Releases failed: {}', exc
91 )
92 self._last_error = str(exc)
93 finally:
94 self._last_checked = datetime.now(timezone.utc).isoformat()
96 def status(self, current_version: str) -> dict[str, Any]:
97 """Shape returned by ``GET /api/check_update``."""
98 update_available = bool(
99 self._latest_version
100 and is_newer(self._latest_version, current_version)
101 )
102 return {
103 'current_version': current_version,
104 'latest_version': self._latest_version,
105 'update_available': update_available,
106 'release_url': self._release_url,
107 'last_checked': self._last_checked,
108 }
111async def update_check_loop(
112 checker: UpdateChecker,
113 interval_seconds: int = CHECK_INTERVAL_SECONDS,
114) -> None:
115 """Background task: check GitHub Releases once immediately, then
116 every ``interval_seconds`` (an hour by default).
117 """
118 while True:
119 try:
120 await asyncio.to_thread(checker.check_now)
121 except Exception:
122 logger.exception('Unexpected error in update check loop')
123 await asyncio.sleep(interval_seconds)