From 5050dbda979184ad84135b0deae0746a1972944e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Fri, 27 Nov 2026 08:39:54 +0100 Subject: [PATCH 1/2] feat: report rate-limit and permission failures as repair issues A refresh that fails because the GitHub rate limit is used up or the token is refused now raises a Repairs notice for the affected data group and clears it on the next successful refresh. Repository snapshots are requested in batches of 10 instead of 50 so the first refresh of a long list stays short. --- CHANGELOG.md | 10 ++ README.md | 3 + custom_components/github_pulse/__init__.py | 11 +- custom_components/github_pulse/coordinator.py | 68 ++++++++- .../github_pulse/repository_fetch.py | 2 +- .../github_pulse/translations/de.json | 10 ++ .../github_pulse/translations/en.json | 10 ++ tests/test_coordinator.py | 138 ++++++++++++++++++ tests/test_hardening.py | 17 ++- tests/test_repository_fetch.py | 4 + 10 files changed, 266 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 864aff7..2360d3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Added + +- A **Repairs** notice when a refresh fails because GitHub's rate limit is used up or the token is refused. It names the affected data group and, for a rate limit, when it resets, and disappears after the next successful refresh. + +### Changed + +- Repositories are now requested in batches of 10 instead of 50, so the first refresh of a long repository list no longer risks running into Home Assistant's startup limits. + ## [1.5.0] - 2026-11-27 ### Added diff --git a/README.md b/README.md index 6514ede..8bbafa6 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,9 @@ statistics. > [!NOTE] > Why do totals differ from github.com, and why are some counts "restricted"? See [visible and restricted contributions](docs/contributions.md). +> [!NOTE] +> If GitHub's rate limit is used up or the token is refused, a notice appears under **Settings → Repairs** and clears after the next successful refresh. The sensors keep their last known values meanwhile. + > [!NOTE] > Language statistics are **estimated**: GitHub provides language data per repository, not per commit. The estimate weights your commits by each repository's language mix. diff --git a/custom_components/github_pulse/__init__.py b/custom_components/github_pulse/__init__.py index ee7c950..beb43c2 100644 --- a/custom_components/github_pulse/__init__.py +++ b/custom_components/github_pulse/__init__.py @@ -12,6 +12,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers import device_registry as dr from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.typing import ConfigType @@ -144,8 +145,14 @@ async def _listener(hass: HomeAssistant, updated: ConfigEntry[Any]) -> None: async def async_unload_entry( hass: HomeAssistant, entry: GitHubPulseConfigEntry ) -> bool: - """Unload a config entry.""" - return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + """Unload a config entry and drop its repair issues.""" + unloaded = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + if unloaded: + registry = ir.async_get(hass) + for domain, issue_id in list(registry.issues): + if domain == DOMAIN and issue_id.startswith(f"{entry.entry_id}_"): + ir.async_delete_issue(hass, domain, issue_id) + return unloaded def _snapshot(entry: ConfigEntry[Any]) -> dict[str, Any]: diff --git a/custom_components/github_pulse/coordinator.py b/custom_components/github_pulse/coordinator.py index 602363f..07e4bd7 100644 --- a/custom_components/github_pulse/coordinator.py +++ b/custom_components/github_pulse/coordinator.py @@ -9,14 +9,26 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed - -from .api import GitHubAuthError, GitHubClient, GitHubError -from .const import LOGGER +from homeassistant.util import dt as dt_util + +from .api import ( + GitHubAuthError, + GitHubClient, + GitHubError, + GitHubForbiddenError, + GitHubRateLimitError, +) +from .const import DOMAIN, LOGGER from .models import GitHubPulseConfigEntry SLOWDOWN_FACTOR = 4 +ISSUE_RATE_LIMITED = "rate_limited" +ISSUE_FORBIDDEN = "forbidden" +_ISSUE_KINDS = (ISSUE_RATE_LIMITED, ISSUE_FORBIDDEN) + type GroupFetcher = Callable[[], Awaitable[Any]] @@ -27,6 +39,8 @@ class GitHubPulseCoordinator(DataUpdateCoordinator[dict[str, Any]]): * A group that fails keeps its last good value; the error is kept in :attr:`errors`. The update only fails when every active group failed. * An authentication error starts reauthentication. + * A rate-limit or permission error raises a repair issue that clears once + the group refreshes again. * While the rate budget of ``rate_resource`` is low, polling slows down. """ @@ -77,6 +91,7 @@ async def _async_update_data(self) -> dict[str, Any]: if isinstance(error, GitHubAuthError): raise ConfigEntryAuthFailed(str(error)) from error self.errors = {group: str(error) for group, error in failures.items()} + self._sync_repair_issues(successes, failures) self._adapt_interval() if failures and not successes: @@ -92,9 +107,56 @@ async def _fetch(self, group: str) -> tuple[str, Any, GitHubError | None]: LOGGER.debug("Group %s failed: %s", group, err) return group, None, err + def _issue_id(self, group: str, kind: str) -> str: + return f"{self.config_entry.entry_id}_{self.name}_{group}_{kind}" + + def _sync_repair_issues( + self, successes: Mapping[str, Any], failures: Mapping[str, GitHubError] + ) -> None: + """Raise a repair issue per rate-limited or forbidden group, clear the rest.""" + for group in successes: + for kind in _ISSUE_KINDS: + ir.async_delete_issue(self.hass, DOMAIN, self._issue_id(group, kind)) + for group, error in failures.items(): + if isinstance(error, GitHubRateLimitError): + kind = ISSUE_RATE_LIMITED + elif isinstance(error, GitHubForbiddenError): + kind = ISSUE_FORBIDDEN + else: + continue + for other in _ISSUE_KINDS: + if other != kind: + ir.async_delete_issue( + self.hass, DOMAIN, self._issue_id(group, other) + ) + ir.async_create_issue( + self.hass, + DOMAIN, + self._issue_id(group, kind), + is_fixable=False, + severity=ir.IssueSeverity.WARNING, + translation_key=kind, + translation_placeholders={ + "name": self.name or "", + "group": group, + "reset": _format_reset(error), + "detail": str(error), + }, + ) + def _adapt_interval(self) -> None: """Slow polling down while the rate budget is nearly spent.""" low = self.client.budget.is_low(self._rate_resource) self.update_interval = ( self._base_interval * SLOWDOWN_FACTOR if low else self._base_interval ) + + +def _format_reset(error: GitHubError) -> str: + """Return the local time the rate limit resets, or a dash when unknown.""" + reset_at = getattr(error, "reset_at", None) + if reset_at is None: + return "-" + return dt_util.as_local(dt_util.utc_from_timestamp(reset_at)).strftime( + "%Y-%m-%d %H:%M" + ) diff --git a/custom_components/github_pulse/repository_fetch.py b/custom_components/github_pulse/repository_fetch.py index bbf9546..fdcb527 100644 --- a/custom_components/github_pulse/repository_fetch.py +++ b/custom_components/github_pulse/repository_fetch.py @@ -17,7 +17,7 @@ ) from .api import GitHubClient -BATCH_SIZE = 50 +BATCH_SIZE = 10 COMMIT_PAGE = 100 _TIME = "%Y-%m-%dT%H:%M:%SZ" diff --git a/custom_components/github_pulse/translations/de.json b/custom_components/github_pulse/translations/de.json index 4806fa8..9548089 100644 --- a/custom_components/github_pulse/translations/de.json +++ b/custom_components/github_pulse/translations/de.json @@ -397,6 +397,16 @@ "message": "Das GraphQL-Ratenbudget ist fast aufgebraucht. Versuche es nach dem Zurücksetzen erneut." } }, + "issues": { + "rate_limited": { + "title": "GitHub-Rate-Limit erreicht", + "description": "GitHub Pulse konnte {name} ({group}) nicht aktualisieren, weil das GitHub-Rate-Limit aufgebraucht ist. Die Werte bleiben auf dem letzten bekannten Stand. Das Limit wird um {reset} zurückgesetzt. GitHub meldete: {detail}" + }, + "forbidden": { + "title": "GitHub hat eine Anfrage abgelehnt", + "description": "GitHub Pulse konnte {name} ({group}) nicht aktualisieren, weil GitHub die Anfrage abgelehnt hat. Dem Zugriffstoken fehlt womöglich eine Berechtigung oder ein Scope. GitHub meldete: {detail}" + } + }, "config_subentries": { "repository": { "initiate_flow": { diff --git a/custom_components/github_pulse/translations/en.json b/custom_components/github_pulse/translations/en.json index 7e38e6c..1488031 100644 --- a/custom_components/github_pulse/translations/en.json +++ b/custom_components/github_pulse/translations/en.json @@ -397,6 +397,16 @@ "message": "The GraphQL rate budget is nearly used up. Try again after it resets." } }, + "issues": { + "rate_limited": { + "title": "GitHub rate limit reached", + "description": "GitHub Pulse could not refresh {name} ({group}) because the GitHub rate limit is used up. Values stay at their last known state. The limit resets at {reset}. GitHub said: {detail}" + }, + "forbidden": { + "title": "GitHub refused a request", + "description": "GitHub Pulse could not refresh {name} ({group}) because GitHub refused the request. The access token may lack a permission or scope. GitHub said: {detail}" + } + }, "config_subentries": { "repository": { "initiate_flow": { diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py index 80d5718..96925a7 100644 --- a/tests/test_coordinator.py +++ b/tests/test_coordinator.py @@ -10,6 +10,8 @@ from custom_components.github_pulse.api import ( GitHubAuthError, GitHubClient, + GitHubForbiddenError, + GitHubRateLimitError, GitHubTransportError, ) from custom_components.github_pulse.const import ( @@ -26,6 +28,7 @@ from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.update_coordinator import UpdateFailed from pytest_homeassistant_custom_component.common import MockConfigEntry @@ -179,5 +182,140 @@ async def test_polling_slows_down_while_the_budget_is_low( assert coordinator.update_interval == INTERVAL +def _issue_ids(hass: HomeAssistant) -> set[str]: + return { + issue_id for domain, issue_id in ir.async_get(hass).issues if domain == DOMAIN + } + + +async def test_rate_limit_failure_raises_a_repair_issue( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + coordinator = _coordinator( + hass, + entry, + { + "a": _value(1), + "b": _failing(GitHubRateLimitError("limit", reset_at=1893456000.0)), + }, + {"a", "b"}, + ) + + await coordinator._async_update_data() + + issue = ir.async_get(hass).async_get_issue( + DOMAIN, f"{entry.entry_id}_test_b_rate_limited" + ) + assert issue is not None + assert issue.translation_key == "rate_limited" + assert issue.is_fixable is False + assert issue.translation_placeholders is not None + assert issue.translation_placeholders["group"] == "b" + assert issue.translation_placeholders["reset"][:4] in {"2029", "2030"} + + +async def test_rate_limit_without_reset_time_still_raises_an_issue( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + coordinator = _coordinator( + hass, entry, {"a": _failing(GitHubRateLimitError("limit"))}, {"a"} + ) + + with pytest.raises(UpdateFailed): + await coordinator._async_update_data() + + assert f"{entry.entry_id}_test_a_rate_limited" in _issue_ids(hass) + + +async def test_forbidden_failure_raises_a_repair_issue( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + coordinator = _coordinator( + hass, + entry, + {"a": _value(1), "b": _failing(GitHubForbiddenError("no scope"))}, + {"a", "b"}, + ) + + await coordinator._async_update_data() + + assert f"{entry.entry_id}_test_b_forbidden" in _issue_ids(hass) + + +async def test_other_failures_raise_no_repair_issue( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + coordinator = _coordinator( + hass, + entry, + {"a": _value(1), "b": _failing(GitHubTransportError("down"))}, + {"a", "b"}, + ) + + await coordinator._async_update_data() + + assert _issue_ids(hass) == set() + + +async def test_repair_issue_clears_after_a_successful_refresh( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + limited = True + + async def flaky() -> int: + if limited: + raise GitHubRateLimitError("limit") + return 2 + + coordinator = _coordinator(hass, entry, {"a": _value(1), "b": flaky}, {"a", "b"}) + await coordinator._async_update_data() + assert f"{entry.entry_id}_test_b_rate_limited" in _issue_ids(hass) + + limited = False + await coordinator._async_update_data() + + assert _issue_ids(hass) == set() + + +async def test_switching_error_kind_replaces_the_issue( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + error: GitHubRateLimitError | GitHubForbiddenError = GitHubRateLimitError("limit") + + async def flaky() -> int: + raise error + + coordinator = _coordinator(hass, entry, {"a": _value(1), "b": flaky}, {"a", "b"}) + await coordinator._async_update_data() + error = GitHubForbiddenError("no scope") + await coordinator._async_update_data() + + assert _issue_ids(hass) == {f"{entry.entry_id}_test_b_forbidden"} + + +async def test_unloading_the_entry_removes_its_repair_issues( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + coordinator = _coordinator( + hass, + entry, + {"a": _value(1), "b": _failing(GitHubRateLimitError("limit"))}, + {"a", "b"}, + ) + await coordinator._async_update_data() + assert _issue_ids(hass) + + assert await hass.config_entries.async_unload(entry.entry_id) + + assert _issue_ids(hass) == set() + + def test_entry_state_import_is_used() -> None: assert ConfigEntryState.LOADED diff --git a/tests/test_hardening.py b/tests/test_hardening.py index 5487118..f249a10 100644 --- a/tests/test_hardening.py +++ b/tests/test_hardening.py @@ -92,13 +92,28 @@ async def test_a_large_account_is_fetched_in_batches( await hass.async_block_till_done() assert entry.state is ConfigEntryState.LOADED - assert session.snapshots == 3 # 120 repositories in batches of 50 + assert session.snapshots == 12 # 120 repositories in batches of 10 registry = er.async_get(hass) stars = [e for e in registry.entities.values() if e.unique_id.endswith("_stars")] assert len(stars) == 120 assert len(entry.runtime_data.repositories.data[GROUP_OVERVIEW]) == 120 +async def test_starting_offline_with_repositories_retries_instead_of_failing( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + session = _AccountSession() + session.mode = "offline" + patch_session(session) + entry = _entry(["repositories"], subentries_data=[_subentry("org/repo")]) + entry.add_to_hass(hass) + + with patch("custom_components.github_pulse.api.client._backoff", return_value=0): + await hass.config_entries.async_setup(entry.entry_id) + + assert entry.state is ConfigEntryState.SETUP_RETRY + + async def test_starting_offline_retries_instead_of_failing( hass: HomeAssistant, patch_session: Callable[[FakeSession], None] ) -> None: diff --git a/tests/test_repository_fetch.py b/tests/test_repository_fetch.py index ee28a04..a46441c 100644 --- a/tests/test_repository_fetch.py +++ b/tests/test_repository_fetch.py @@ -131,6 +131,10 @@ async def test_adding_a_repository_does_not_add_a_request() -> None: assert one.graphql.await_count == ten.graphql.await_count == 1 +def test_batches_stay_small_enough_for_a_fast_first_refresh() -> None: + assert BATCH_SIZE <= 10 + + async def test_very_long_lists_are_split_into_batches() -> None: client = _client() From 39038a4d4f6481c15cebbb33e3c1fcf1187a1fe7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Fri, 27 Nov 2026 08:50:45 +0100 Subject: [PATCH 2/2] fix: keep repository data when a single batch fails A failing batch of repositories (for example a GitHub 502) used to fail the whole overview group, leaving every repository sensor unavailable after a restart. The other batches are now kept, the failed ones fall back to their previous snapshot, and a repeated outage raises a Repairs notice. --- CHANGELOG.md | 3 +- README.md | 2 +- custom_components/github_pulse/coordinator.py | 52 +++++++++----- .../github_pulse/repository_coordinator.py | 1 + .../github_pulse/repository_fetch.py | 31 +++++++- .../github_pulse/translations/de.json | 4 ++ .../github_pulse/translations/en.json | 4 ++ tests/test_coordinator.py | 67 +++++++++++++++++- tests/test_repository_fetch.py | 70 ++++++++++++++++++- 9 files changed, 211 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2360d3f..1160ecf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,12 @@ All notable changes to this project are documented here. The format follows [Kee ### Added -- A **Repairs** notice when a refresh fails because GitHub's rate limit is used up or the token is refused. It names the affected data group and, for a rate limit, when it resets, and disappears after the next successful refresh. +- A **Repairs** notice when a refresh fails because GitHub's rate limit is used up, the token is refused, or GitHub does not answer properly for two refreshes in a row. It names the affected data group and, for a rate limit, when it resets, and disappears after the next successful refresh. ### Changed - Repositories are now requested in batches of 10 instead of 50, so the first refresh of a long repository list no longer risks running into Home Assistant's startup limits. +- When GitHub fails for one batch of repositories (for example with a 502), the other batches are still updated and the affected repositories keep their last values, instead of every repository sensor turning unavailable. ## [1.5.0] - 2026-11-27 diff --git a/README.md b/README.md index 8bbafa6..2fe0e04 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ statistics. > Why do totals differ from github.com, and why are some counts "restricted"? See [visible and restricted contributions](docs/contributions.md). > [!NOTE] -> If GitHub's rate limit is used up or the token is refused, a notice appears under **Settings → Repairs** and clears after the next successful refresh. The sensors keep their last known values meanwhile. +> If GitHub's rate limit is used up, the token is refused, or GitHub keeps failing to answer, a notice appears under **Settings → Repairs** and clears after the next successful refresh. The sensors keep their last known values meanwhile. > [!NOTE] > Language statistics are **estimated**: GitHub provides language data per repository, not per commit. The estimate weights your commits by each repository's language mix. diff --git a/custom_components/github_pulse/coordinator.py b/custom_components/github_pulse/coordinator.py index 07e4bd7..eeb9ad7 100644 --- a/custom_components/github_pulse/coordinator.py +++ b/custom_components/github_pulse/coordinator.py @@ -19,6 +19,7 @@ GitHubError, GitHubForbiddenError, GitHubRateLimitError, + GitHubTransportError, ) from .const import DOMAIN, LOGGER from .models import GitHubPulseConfigEntry @@ -27,7 +28,10 @@ ISSUE_RATE_LIMITED = "rate_limited" ISSUE_FORBIDDEN = "forbidden" -_ISSUE_KINDS = (ISSUE_RATE_LIMITED, ISSUE_FORBIDDEN) +ISSUE_UNAVAILABLE = "unavailable" +_ISSUE_KINDS = (ISSUE_RATE_LIMITED, ISSUE_FORBIDDEN, ISSUE_UNAVAILABLE) +OUTAGE_STREAK = 2 +HTTP_SERVER_ERROR = 500 type GroupFetcher = Callable[[], Awaitable[Any]] @@ -39,8 +43,9 @@ class GitHubPulseCoordinator(DataUpdateCoordinator[dict[str, Any]]): * A group that fails keeps its last good value; the error is kept in :attr:`errors`. The update only fails when every active group failed. * An authentication error starts reauthentication. - * A rate-limit or permission error raises a repair issue that clears once - the group refreshes again. + * A rate-limit or permission error raises a repair issue at once, an outage + (network error or GitHub 5xx) after ``OUTAGE_STREAK`` failed refreshes in + a row. The issue clears once the group refreshes again. * While the rate budget of ``rate_resource`` is low, polling slows down. """ @@ -72,6 +77,7 @@ def __init__( self._active = frozenset(active_groups) & self._groups.keys() self._base_interval = update_interval self._rate_resource = rate_resource + self._outage_streaks: dict[str, int] = {} @property def active_groups(self) -> frozenset[str]: @@ -113,22 +119,15 @@ def _issue_id(self, group: str, kind: str) -> str: def _sync_repair_issues( self, successes: Mapping[str, Any], failures: Mapping[str, GitHubError] ) -> None: - """Raise a repair issue per rate-limited or forbidden group, clear the rest.""" + """Raise a repair issue per failing group and clear those that recovered.""" for group in successes: - for kind in _ISSUE_KINDS: - ir.async_delete_issue(self.hass, DOMAIN, self._issue_id(group, kind)) + self._outage_streaks.pop(group, None) + self._clear_issues(group) for group, error in failures.items(): - if isinstance(error, GitHubRateLimitError): - kind = ISSUE_RATE_LIMITED - elif isinstance(error, GitHubForbiddenError): - kind = ISSUE_FORBIDDEN - else: + kind = self._issue_kind(group, error) + if kind is None: continue - for other in _ISSUE_KINDS: - if other != kind: - ir.async_delete_issue( - self.hass, DOMAIN, self._issue_id(group, other) - ) + self._clear_issues(group, keep=kind) ir.async_create_issue( self.hass, DOMAIN, @@ -144,6 +143,27 @@ def _sync_repair_issues( }, ) + def _issue_kind(self, group: str, error: GitHubError) -> str | None: + """Return the repair issue kind for a failure, or ``None`` for no issue.""" + if isinstance(error, GitHubRateLimitError): + return ISSUE_RATE_LIMITED + if isinstance(error, GitHubForbiddenError): + return ISSUE_FORBIDDEN + is_outage = isinstance(error, GitHubTransportError) or ( + error.status is not None and error.status >= HTTP_SERVER_ERROR + ) + if not is_outage: + self._outage_streaks.pop(group, None) + return None + streak = self._outage_streaks.get(group, 0) + 1 + self._outage_streaks[group] = streak + return ISSUE_UNAVAILABLE if streak >= OUTAGE_STREAK else None + + def _clear_issues(self, group: str, keep: str | None = None) -> None: + for kind in _ISSUE_KINDS: + if kind != keep: + ir.async_delete_issue(self.hass, DOMAIN, self._issue_id(group, kind)) + def _adapt_interval(self) -> None: """Slow polling down while the rate budget is nearly spent.""" low = self.client.budget.is_low(self._rate_resource) diff --git a/custom_components/github_pulse/repository_coordinator.py b/custom_components/github_pulse/repository_coordinator.py index dfcb554..6e99620 100644 --- a/custom_components/github_pulse/repository_coordinator.py +++ b/custom_components/github_pulse/repository_coordinator.py @@ -82,6 +82,7 @@ async def _fetch_overview(self) -> dict[str, RepositorySnapshot | None]: self.repositories, today=dt_util.now(self._zone).date(), zone=self._zone, + previous=(self.data or {}).get(GROUP_OVERVIEW), ) async def _fetch_downloads(self) -> dict[str, int]: diff --git a/custom_components/github_pulse/repository_fetch.py b/custom_components/github_pulse/repository_fetch.py index fdcb527..474cd9c 100644 --- a/custom_components/github_pulse/repository_fetch.py +++ b/custom_components/github_pulse/repository_fetch.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass from datetime import date, datetime from typing import Any @@ -15,7 +15,14 @@ month_to_date, to_utc_window, ) -from .api import GitHubClient +from .api import ( + GitHubAuthError, + GitHubClient, + GitHubError, + GitHubForbiddenError, + GitHubRateLimitError, +) +from .const import LOGGER BATCH_SIZE = 10 COMMIT_PAGE = 100 @@ -237,17 +244,33 @@ async def fetch_snapshots( *, today: date, zone: ZoneInfo, + previous: Mapping[str, RepositorySnapshot | None] | None = None, ) -> dict[str, RepositorySnapshot | None]: """Fetch every repository; one that cannot be read maps to ``None``. All names go into one request (in batches of ``BATCH_SIZE`` for very long lists), so tracking another repository adds no request. + + A batch that fails with a transient error keeps the repositories of the + other batches intact: its repositories fall back to their ``previous`` + snapshot. Authentication, permission and rate-limit errors abort the whole + fetch, and so does a failure of every batch. """ result: dict[str, RepositorySnapshot | None] = {} + failures: list[GitHubError] = [] for start in range(0, len(repositories), BATCH_SIZE): batch = repositories[start : start + BATCH_SIZE] query, variables = build_query(batch, today, zone) - response = await client.graphql(query, variables) + try: + response = await client.graphql(query, variables) + except GitHubAuthError, GitHubForbiddenError, GitHubRateLimitError: + raise + except GitHubError as err: + LOGGER.debug("Repository batch %s failed: %s", start // BATCH_SIZE, err) + failures.append(err) + for full_name in batch: + result[full_name] = (previous or {}).get(full_name) + continue for index, full_name in enumerate(batch): raw = response.data.get(f"r{index}") result[full_name] = ( @@ -261,6 +284,8 @@ async def fetch_snapshots( issues=response.data.get(f"i{index}"), ) ) + if failures and len(failures) == -(-len(repositories) // BATCH_SIZE): + raise failures[0] return result diff --git a/custom_components/github_pulse/translations/de.json b/custom_components/github_pulse/translations/de.json index 9548089..fba710b 100644 --- a/custom_components/github_pulse/translations/de.json +++ b/custom_components/github_pulse/translations/de.json @@ -405,6 +405,10 @@ "forbidden": { "title": "GitHub hat eine Anfrage abgelehnt", "description": "GitHub Pulse konnte {name} ({group}) nicht aktualisieren, weil GitHub die Anfrage abgelehnt hat. Dem Zugriffstoken fehlt womöglich eine Berechtigung oder ein Scope. GitHub meldete: {detail}" + }, + "unavailable": { + "title": "GitHub antwortet nicht", + "description": "GitHub Pulse konnte {name} ({group}) mehrmals hintereinander nicht aktualisieren, weil GitHub nicht richtig geantwortet hat. Die Werte bleiben auf dem letzten bekannten Stand, der nächste Abruf versucht es erneut. GitHub meldete: {detail}" } }, "config_subentries": { diff --git a/custom_components/github_pulse/translations/en.json b/custom_components/github_pulse/translations/en.json index 1488031..f5dd1ee 100644 --- a/custom_components/github_pulse/translations/en.json +++ b/custom_components/github_pulse/translations/en.json @@ -405,6 +405,10 @@ "forbidden": { "title": "GitHub refused a request", "description": "GitHub Pulse could not refresh {name} ({group}) because GitHub refused the request. The access token may lack a permission or scope. GitHub said: {detail}" + }, + "unavailable": { + "title": "GitHub is not responding", + "description": "GitHub Pulse could not refresh {name} ({group}) several times in a row because GitHub did not answer properly. Values stay at their last known state and the next refresh tries again. GitHub said: {detail}" } }, "config_subentries": { diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py index 96925a7..74efb2d 100644 --- a/tests/test_coordinator.py +++ b/tests/test_coordinator.py @@ -10,6 +10,7 @@ from custom_components.github_pulse.api import ( GitHubAuthError, GitHubClient, + GitHubError, GitHubForbiddenError, GitHubRateLimitError, GitHubTransportError, @@ -252,10 +253,74 @@ async def test_other_failures_raise_no_repair_issue( coordinator = _coordinator( hass, entry, - {"a": _value(1), "b": _failing(GitHubTransportError("down"))}, + {"a": _value(1), "b": _failing(GitHubError("odd", status=418))}, {"a", "b"}, ) + for _ in range(3): + await coordinator._async_update_data() + + assert _issue_ids(hass) == set() + + +@pytest.mark.parametrize( + "error", + [GitHubTransportError("down"), GitHubError("bad gateway", status=502)], +) +async def test_a_repeated_outage_raises_a_repair_issue( + hass: HomeAssistant, + patch_session: Callable[[FakeSession], None], + error: GitHubError, +) -> None: + entry = await _entry(hass, patch_session) + coordinator = _coordinator( + hass, entry, {"a": _value(1), "b": _failing(error)}, {"a", "b"} + ) + issue_id = f"{entry.entry_id}_test_b_unavailable" + + await coordinator._async_update_data() + assert issue_id not in _issue_ids(hass) + + await coordinator._async_update_data() + assert issue_id in _issue_ids(hass) + + +async def test_a_single_outage_between_successes_raises_no_issue( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + down = False + + async def flaky() -> int: + if down: + raise GitHubTransportError("down") + return 2 + + coordinator = _coordinator(hass, entry, {"a": _value(1), "b": flaky}, {"a", "b"}) + for state in (True, False, True, False): + down = state + await coordinator._async_update_data() + + assert _issue_ids(hass) == set() + + +async def test_an_outage_issue_clears_after_a_successful_refresh( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + entry = await _entry(hass, patch_session) + down = True + + async def flaky() -> int: + if down: + raise GitHubTransportError("down") + return 2 + + coordinator = _coordinator(hass, entry, {"a": _value(1), "b": flaky}, {"a", "b"}) + await coordinator._async_update_data() + await coordinator._async_update_data() + assert _issue_ids(hass) + + down = False await coordinator._async_update_data() assert _issue_ids(hass) == set() diff --git a/tests/test_repository_fetch.py b/tests/test_repository_fetch.py index a46441c..23e647c 100644 --- a/tests/test_repository_fetch.py +++ b/tests/test_repository_fetch.py @@ -9,7 +9,14 @@ from unittest.mock import AsyncMock from zoneinfo import ZoneInfo -from custom_components.github_pulse.api import GitHubClient, GraphQLResult +import pytest +from custom_components.github_pulse.api import ( + GitHubAuthError, + GitHubClient, + GitHubError, + GitHubRateLimitError, + GraphQLResult, +) from custom_components.github_pulse.api.query_validation import parse_query from custom_components.github_pulse.api.repository import _LIST_QUERY from custom_components.github_pulse.const import ( @@ -145,6 +152,67 @@ async def test_very_long_lists_are_split_into_batches() -> None: assert len(result) == BATCH_SIZE + 1 +def _client_failing_batch(error: GitHubError, failing_call: int) -> Any: + """Answer like ``_client`` but raise ``error`` on the given 1-based call.""" + inner = _client() + answer = inner.graphql.side_effect + calls = 0 + + async def graphql(query: str, variables: Any = None) -> GraphQLResult: + nonlocal calls + calls += 1 + if calls == failing_call: + raise error + return await answer(query, variables) + + inner.graphql.side_effect = graphql + return inner + + +def _names() -> list[str]: + return [f"a/r{i}" for i in range(BATCH_SIZE + 1)] + + +async def test_a_failed_batch_keeps_the_other_batches() -> None: + client = _client_failing_batch(GitHubError("bad gateway", status=502), 2) + + result = await fetch_snapshots(client, _names(), today=TODAY, zone=ZONE) + + assert all(result[name] is not None for name in _names()[:BATCH_SIZE]) + assert result[_names()[-1]] is None + + +async def test_a_failed_batch_keeps_the_previous_snapshots() -> None: + first = await fetch_snapshots(_client(), _names(), today=TODAY, zone=ZONE) + client = _client_failing_batch(GitHubError("bad gateway", status=502), 2) + + result = await fetch_snapshots( + client, _names(), today=TODAY, zone=ZONE, previous=first + ) + + assert result[_names()[-1]] is first[_names()[-1]] + assert result[_names()[-1]] is not None + + +async def test_every_batch_failing_raises_the_first_error() -> None: + client = _client() + client.graphql.side_effect = GitHubError("bad gateway", status=502) + + with pytest.raises(GitHubError, match="bad gateway"): + await fetch_snapshots(client, _names(), today=TODAY, zone=ZONE) + + +@pytest.mark.parametrize( + "error", + [GitHubAuthError("bad credentials"), GitHubRateLimitError("limit")], +) +async def test_auth_and_rate_limit_errors_abort_the_fetch(error: GitHubError) -> None: + client = _client_failing_batch(error, 2) + + with pytest.raises(type(error)): + await fetch_snapshots(client, _names(), today=TODAY, zone=ZONE) + + async def test_a_repository_without_release_or_ci_still_parses() -> None: bare = {**RAW, "defaultBranchRef": None, "latestRelease": None}