Files
FabledSteward/plugins/homeassistant/scheduler.py
T
bvandeusenandClaude Opus 5.5 0aed863c67
CI / lint (push) Successful in 2s
CI / unit (push) Successful in 1m37s
CI / integration (push) Failing after 1m55s
CI / publish (push) Skipped
feat(homeassistant): an admin signs in to Home Assistant, with nothing added to it (#6355)
Replaces the read-only token and the webhook automation, which every install
would have had to paste into its own Home Assistant. Connect now goes to Home
Assistant's own sign-in page, and Steward keeps the refresh token that comes
back, encrypted, and calls backup.create_automatic and update.install directly.

The connection page warns that the stored credential has the same access as
the user who signed in, and recommends a service account so Steward's actions
are easy to tell apart in Home Assistant's logs. A user who isn't an
administrator gets the status page and no Install.

Those actions answer only when finished, so a request cut off once sent counts
as sent and the outcome is read from the entities. Removing the connection, or
signing in again, ends the old sign-in on Home Assistant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:14:34 -04:00

95 lines
3.8 KiB
Python

# plugins/homeassistant/scheduler.py
from __future__ import annotations
import asyncio
import logging
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from sqlalchemy import select
from steward.core.scheduler import ScheduledTask
from . import client
from .models import HomeAssistantConnection
from .service import RESOURCE, SOURCE, backup_age_hours, installable, read_snapshot
from .updates import advance
if TYPE_CHECKING:
from quart import Quart
logger = logging.getLogger(__name__)
# An update under way is followed each tick, with one small read of its entity.
TICK_SECONDS = 15
# The whole entity list is a few hundred KB, and updates and backups change rarely.
POLL_SECONDS = 300
# A step past this is given up until the next tick, whatever the client's own
# timeouts did: a slow drip of bytes can keep each read inside its timeout for ever.
STEP_DEADLINE_SECONDS = 60
def make_tick_task(app: "Quart") -> ScheduledTask:
busy = asyncio.Lock()
async def tick() -> None:
if busy.locked():
return
async with busy:
for step in (poll, advance):
try:
await asyncio.wait_for(step(app), STEP_DEADLINE_SECONDS)
except TimeoutError:
logger.warning("Home Assistant %s gave up after %d s", step.__name__, STEP_DEADLINE_SECONDS)
return ScheduledTask(name="homeassistant_tick", coro_factory=tick,
interval_seconds=TICK_SECONDS, run_on_startup=True)
def is_due(connection, now: datetime) -> bool:
"""Whether to poll. Never after a refusal: another refused request counts
toward Home Assistant banning this address."""
if connection.refused:
return False
if connection.last_polled_at is None:
return True
return (now - connection.last_polled_at).total_seconds() >= POLL_SECONDS - TICK_SECONDS / 2
async def poll(app: "Quart", transport=None) -> None:
from steward.core.alerts import MetricBatch
now = datetime.now(timezone.utc)
async with app.db_sessionmaker() as session:
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
if connection is None or not is_due(connection, now):
return
snapshot, error, refused = None, None, False
try:
token = await client.access_token(connection, transport)
snapshot = read_snapshot(await client.read_states(connection.url, token, connection.verify_tls, transport))
except client.Refused as exc:
error, refused = str(exc), True
except client.Unreachable as exc:
error = str(exc)
async with app.db_sessionmaker() as session:
async with session.begin():
row = await session.get(HomeAssistantConnection, connection.id)
if row is None: # removed while it was being polled
return
batch = MetricBatch()
row.last_polled_at, row.last_error, row.refused = now, error, refused
if snapshot is None:
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="is_up", value=0.0, recorded_at=now)
else:
row.last_ok_at = now
row.updates, row.backup = snapshot["updates"], snapshot["backup"]
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="is_up", value=1.0, recorded_at=now)
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="updates_waiting",
value=len(installable(row)), recorded_at=now)
age = backup_age_hours(snapshot["backup"], now)
if age is not None:
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="backup_age_hours",
value=age, recorded_at=now)
await batch.record(session)