Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

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, 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

### Added
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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.

Expand Down
11 changes: 9 additions & 2 deletions custom_components/github_pulse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]:
Expand Down
88 changes: 85 additions & 3 deletions custom_components/github_pulse/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,30 @@

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,
GitHubTransportError,
)
from .const import DOMAIN, LOGGER
from .models import GitHubPulseConfigEntry

SLOWDOWN_FACTOR = 4

ISSUE_RATE_LIMITED = "rate_limited"
ISSUE_FORBIDDEN = "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]]


Expand All @@ -27,6 +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 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.
"""

Expand Down Expand Up @@ -58,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]:
Expand All @@ -77,6 +97,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:
Expand All @@ -92,9 +113,70 @@ 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 failing group and clear those that recovered."""
for group in successes:
self._outage_streaks.pop(group, None)
self._clear_issues(group)
for group, error in failures.items():
kind = self._issue_kind(group, error)
if kind is None:
continue
self._clear_issues(group, keep=kind)
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 _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)
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"
)
1 change: 1 addition & 0 deletions custom_components/github_pulse/repository_coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
33 changes: 29 additions & 4 deletions custom_components/github_pulse/repository_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -15,9 +15,16 @@
month_to_date,
to_utc_window,
)
from .api import GitHubClient
from .api import (
GitHubAuthError,
GitHubClient,
GitHubError,
GitHubForbiddenError,
GitHubRateLimitError,
)
from .const import LOGGER

BATCH_SIZE = 50
BATCH_SIZE = 10
COMMIT_PAGE = 100
_TIME = "%Y-%m-%dT%H:%M:%SZ"

Expand Down Expand Up @@ -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] = (
Expand All @@ -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


Expand Down
14 changes: 14 additions & 0 deletions custom_components/github_pulse/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,20 @@
"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}"
},
"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": {
"repository": {
"initiate_flow": {
Expand Down
14 changes: 14 additions & 0 deletions custom_components/github_pulse/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,20 @@
"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}"
},
"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": {
"repository": {
"initiate_flow": {
Expand Down
Loading
Loading