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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ SESSION_SECRET=
PUBLIC_IMAGE_ENDPOINTS=true
# Advertise _smartframe._tcp.local. over mDNS (Docker needs network_mode: host for it).
ZEROCONF_ENABLED=true
# Name of this engine (mDNS service name, shown to clients). Default: "Smart Frame Engine"
# plus the first characters of its random id (kept in /data/instance.json), so two engines on
# one network never share a name.
INSTANCE_NAME=
# Max size of uploaded/downloaded images, in MB.
MAX_UPLOAD_MB=20
# Reject external image URLs (posters, album covers, Home Assistant pictures) resolving to
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jobs:
lint-test:
name: Lint & test (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
Expand Down Expand Up @@ -47,7 +48,7 @@ jobs:
run: mypy app

- name: Pytest
run: pytest
run: pytest -v

- name: Pytest (slow / performance)
run: pytest -m slow
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pr-labels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
pull-requests: write
steps:
- name: Apply the label
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const title = context.payload.pull_request.title;
Expand Down
7 changes: 7 additions & 0 deletions app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from app.core.auth import AuthState
from app.core.config_store import ConfigStore
from app.core.history_store import HistoryStore
from app.core.identity import InstanceIdentity
from app.core.security import URLPolicy
from app.core.settings import EnvSettings
from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory
Expand All @@ -32,6 +33,11 @@ def get_auth_state(request: Request) -> AuthState:
return cast(AuthState, request.app.state.auth_state)


def get_identity(request: Request) -> InstanceIdentity:
"""This engine's stable id and name (initialized during app startup)."""
return cast(InstanceIdentity, request.app.state.identity)


def get_config_store(request: Request) -> ConfigStore:
"""The runtime configuration store (initialized during app startup)."""
return cast(ConfigStore, request.app.state.config_store)
Expand Down Expand Up @@ -109,6 +115,7 @@ def get_people_directory(request: Request) -> PeopleDirectory:

SettingsDep = Annotated[EnvSettings, Depends(get_settings)]
AuthStateDep = Annotated[AuthState, Depends(get_auth_state)]
IdentityDep = Annotated[InstanceIdentity, Depends(get_identity)]
ConfigStoreDep = Annotated[ConfigStore, Depends(get_config_store)]
HistoryStoreDep = Annotated[HistoryStore, Depends(get_history_store)]
CurrentImageStoreDep = Annotated[CurrentImageStore, Depends(get_current_image_store)]
Expand Down
10 changes: 9 additions & 1 deletion app/api/routes/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
CurrentImageStoreDep,
DeliveryServiceDep,
EphemeralServiceDep,
IdentityDep,
SchedulerDep,
SettingsDep,
)
Expand All @@ -39,6 +40,11 @@ class HealthResponse(BaseModel):
description="Oldest contract version still served; a client implementing contract N "
"is compatible when min_api_version <= N <= api_version"
)
instance_id: str = Field(
description="Stable random UUID of this engine, generated once and kept in the data "
"volume; use it as the client-side unique key"
)
instance_name: str = Field(description="Human-readable name (also the mDNS service name)")
auth: Literal["open", "key", "password"] = Field(
description="Credentials the other endpoints need (same values as the Zeroconf record)"
)
Expand Down Expand Up @@ -95,12 +101,14 @@ class StatusResponse(BaseModel):


@router.get("/health", response_model=HealthResponse, summary="Liveness probe")
async def health(auth: AuthStateDep) -> HealthResponse:
async def health(auth: AuthStateDep, identity: IdentityDep) -> HealthResponse:
"""Liveness plus the compatibility handshake, readable before any credential is set up."""
return HealthResponse(
version=__version__,
api_version=API_VERSION,
min_api_version=MIN_API_VERSION,
instance_id=identity.instance_id,
instance_name=identity.instance_name,
auth=auth.mode,
capabilities=capability_names(),
)
Expand Down
61 changes: 61 additions & 0 deletions app/core/identity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Instance identity: a stable random ``instance_id`` and a human-readable ``instance_name``.

The id is generated once, stored in ``/data/instance.json`` and never changes while the data
volume lives, so clients (Home Assistant, scripts) can use it as a stable key even when the
engine's address changes. It is random: not derived from the MAC address, the hostname or
anything else about the machine, so exposing it publicly leaks nothing.

The name defaults to ``Smart Frame Engine <first 6 characters of the id>`` so two engines on one
LAN advertise different mDNS names without any configuration; ``INSTANCE_NAME`` overrides it.
"""

from __future__ import annotations

import logging
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Final

from app.core.json_store import atomic_write_json, read_json

logger = logging.getLogger(__name__)

DEFAULT_NAME: Final = "Smart Frame Engine"
MAX_NAME_LENGTH: Final = 60


@dataclass(frozen=True)
class InstanceIdentity:
"""Who this engine is."""

instance_id: str
instance_name: str


def _valid_id(value: object) -> str | None:
if not isinstance(value, str):
return None
try:
return str(uuid.UUID(value))
except ValueError:
return None


def default_name(instance_id: str) -> str:
"""The unique default name built from the start of the id."""
return f"{DEFAULT_NAME} {instance_id[:6]}"


def load_identity(path: Path, name_override: str = "") -> InstanceIdentity:
"""Read the stored id (generating and persisting it on first run) and resolve the name."""
raw = read_json(path, dict)
instance_id = _valid_id(raw.get("instance_id") if isinstance(raw, dict) else None)
if instance_id is None:
instance_id = str(uuid.uuid4())
try:
atomic_write_json(path, {"instance_id": instance_id})
except OSError as exc: # read-only volume: keep running with a per-process id
logger.warning("Cannot persist the instance id (%s); it will change on restart", exc)
name = " ".join(name_override.split())[:MAX_NAME_LENGTH] or default_name(instance_id)
return InstanceIdentity(instance_id=instance_id, instance_name=name)
11 changes: 11 additions & 0 deletions app/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ class EnvSettings(BaseSettings):
description="Advertise _smartframe._tcp.local. over mDNS (needs host networking in Docker)",
)

instance_name: str = Field(
default="",
description="Name of this engine (mDNS service name, shown to clients); "
"default 'Smart Frame Engine <id prefix>'",
)

max_upload_mb: int = Field(default=20, ge=1, le=200, description="Max image size in MB")
block_private_urls: bool = Field(
default=False,
Expand Down Expand Up @@ -207,6 +213,11 @@ def last_delivery_path(self) -> Path:
"""Location of the last successful frame delivery (what the frame shows)."""
return self.data_dir / "last_delivery.json"

@property
def instance_path(self) -> Path:
"""Stable random instance id (not a secret)."""
return self.data_dir / "instance.json"

@property
def secrets_path(self) -> Path:
"""Generated secrets (API key, session signing key), readable by the owner only."""
Expand Down
10 changes: 8 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from app.core.config_models import RuntimeConfig
from app.core.config_store import ConfigStore
from app.core.history_store import HistoryStore
from app.core.identity import load_identity
from app.core.limits import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
from app.core.logging_config import masking_filter, setup_logging
from app.core.proxy import RootPathMiddleware
Expand Down Expand Up @@ -110,6 +111,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
activity.attach()
_prepare_data_dir(settings)
auth_state.load()
identity = load_identity(settings.instance_path, settings.instance_name)
app.state.identity = identity

config_store = ConfigStore(settings.config_path, settings.runtime_seed())
config_store.load()
Expand Down Expand Up @@ -206,13 +209,16 @@ async def _on_config_change(_: RuntimeConfig) -> None:
version=__version__,
root_path=settings.root_path,
auth=auth_state.mode,
instance=identity.instance_name,
instance_id=identity.instance_id,
)
await advertiser.start()
config = config_store.config
logger.info(
"Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s, "
"power_mode=%s, pending=%s, scheduler=%s)",
"Smart Frame Engine %s started (instance=%s, data_dir=%s, auth=%s, root_path=%r, "
"panel=%s, power_mode=%s, pending=%s, scheduler=%s)",
__version__,
identity.instance_id,
settings.data_dir,
auth_state.mode,
settings.root_path,
Expand Down
5 changes: 4 additions & 1 deletion app/services/delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,10 @@ async def _run(self) -> None:
if timeout is None:
await self._wake.wait()
else:
await asyncio.wait_for(self._wake.wait(), timeout)
# asyncio.timeout, not wait_for: on Python 3.11 wait_for can swallow a
# cancellation, and stop() would then wait for this loop forever.
async with asyncio.timeout(timeout):
await self._wake.wait()
except TimeoutError:
timed_out = True
self._wake.clear()
Expand Down
15 changes: 9 additions & 6 deletions app/services/discovery.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""mDNS / Zeroconf: advertise ``_smartframe._tcp.local.`` so other devices can find the engine.

The record carries TXT properties ``version``, ``api_version``, ``min_api_version`` (the
compatibility handshake of ``docs/API_CONTRACT.md``), ``path`` (``ROOT_PATH``) and ``auth``
(``open``, ``key`` or ``password``). The capability list is not mirrored (a TXT string is
capped at 255 bytes): clients read it from ``GET /api/health`` after discovery.
Advertising is best effort: any failure (no multicast
in a bridged container, no network...) is logged and ignored, the engine runs regardless.
compatibility handshake of ``docs/API_CONTRACT.md``), ``instance_id`` (stable random id),
``path`` (``ROOT_PATH``) and ``auth`` (``open``, ``key`` or ``password``). The service name is
the unique ``instance_name``. The capability list is not mirrored (a TXT string is capped at 255
bytes): clients read it from ``GET /api/health`` after discovery.
Advertising is best effort: any failure (no multicast in a bridged container, no network...)
is logged and ignored, the engine runs regardless.
In Docker, mDNS needs ``network_mode: host``.
"""

Expand Down Expand Up @@ -55,6 +56,7 @@ def __init__(
api_version: int = API_VERSION,
min_api_version: int = MIN_API_VERSION,
instance: str = "Smart Frame Engine",
instance_id: str = "",
zeroconf_factory: Callable[[], Any] = lambda: AsyncZeroconf(ip_version=IPVersion.V4Only),
addresses: Callable[[], list[str]] = local_addresses,
) -> None:
Expand All @@ -70,6 +72,7 @@ def __init__(
"min_api_version": str(min_api_version),
"path": root_path or "/",
"auth": auth,
**({"instance_id": instance_id} if instance_id else {}),
},
server=f"{host}.local.",
parsed_addresses=addresses(),
Expand All @@ -86,7 +89,7 @@ async def start(self) -> bool:
"""Advertise the service; ``False`` (logged) when it could not be registered."""
try:
zeroconf = self._factory()
await zeroconf.async_register_service(self._info)
await zeroconf.async_register_service(self._info, allow_name_change=True)
except Exception as exc:
logger.warning("Zeroconf advertising disabled: %s: %s", type(exc).__name__, exc)
return False
Expand Down
5 changes: 4 additions & 1 deletion app/services/ephemeral.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,10 @@ def _timeout(self) -> float:
async def _run(self) -> None:
while True:
with contextlib.suppress(TimeoutError):
await asyncio.wait_for(self._wake.wait(), self._timeout())
# asyncio.timeout, not wait_for: on Python 3.11 wait_for can swallow a
# cancellation, and stop() would then wait for this loop forever.
async with asyncio.timeout(self._timeout()):
await self._wake.wait()
self._wake.clear()
try:
await self.expire_if_due()
Expand Down
17 changes: 15 additions & 2 deletions docs/API_CONTRACT.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Smart Frame Engine API Contract (v1.0)
# Smart Frame Engine API Contract (v1.1)

This is the contract between the engine and **external clients**: the Home Assistant
integration, Node-RED flows, shell scripts, phone shortcuts. It says what a client can rely on
Expand All @@ -17,9 +17,11 @@ every authentication mode), so it works before any key or password is configured
```json
{
"status": "ok",
"version": "1.0.0rc1",
"version": "1.0.0rc2",
"api_version": 1,
"min_api_version": 1,
"instance_id": "3f2b8c1e-5d0a-4c7e-9b61-0a1d2e3f4a5b",
"instance_name": "Smart Frame Engine 3f2b8c",
"auth": "key",
"capabilities": ["activity_log", "ambient_context", "display_immich", "..."]
}
Expand All @@ -31,6 +33,8 @@ every authentication mode), so it works before any key or password is configured
| `version` | Engine release, [PEP 440](https://peps.python.org/pep-0440/) (`1.0.0`, `1.0.0rc1`). Informational: never gate behaviour on it, use `api_version` and `capabilities`. |
| `api_version` | Integer contract version the engine speaks. Incremented **only on a breaking change**. It is `1` for every v1.x release. |
| `min_api_version` | Oldest contract version this engine still serves (see the policy below). |
| `instance_id` | Stable random UUID of this engine, generated once and stored in the data volume (`instance.json`). **Use it as your unique key** for this engine: it survives restarts, upgrades and address changes. It is not derived from the hardware and is not a secret. A wiped data volume creates a new id. |
| `instance_name` | Human-readable name, also the mDNS service name. Defaults to `Smart Frame Engine <first 6 characters of the id>`; the operator can set `INSTANCE_NAME`. Not guaranteed unique when set by hand: key on `instance_id`. |
| `auth` | `open`, `key` or `password`: which credentials the other endpoints need (section 3). |
| `capabilities` | Sorted list of feature flags (section 2). |

Expand Down Expand Up @@ -119,9 +123,12 @@ it needs `network_mode: host`). TXT properties, all strings:
| `version` | Same as `/api/health`. |
| `api_version` | Same as `/api/health`, as a decimal string. |
| `min_api_version` | Same as `/api/health`, as a decimal string. |
| `instance_id` | Same as `/api/health`: match a discovered service to a saved engine with it. |
| `path` | `ROOT_PATH` (`/` when served at the root). |
| `auth` | `open`, `key` or `password`. |

The service **name** is the engine's `instance_name`, so several engines on one network coexist
(if a name is still taken, the responder renames the service rather than failing).
A client can reject an incompatible engine from the record alone. The capability list is **not**
in the record (a TXT string is limited to 255 bytes): read it from `GET /api/health` once you
have the address and port.
Expand Down Expand Up @@ -213,6 +220,12 @@ changelog) and run `python scripts/export_openapi.py` (see `CLAUDE.md`).

## Contract Changelog

### 1.1 (engine 1.0.0rc2), additive

- `GET /api/health` gains `instance_id` and `instance_name`; Zeroconf TXT gains `instance_id` and
the service name becomes the unique `instance_name`, so two engines on one LAN no longer
clash. Clients should use `instance_id` as the stable key of an engine. No `api_version` change.

### 1.0 (engine 1.0.0rc1)

- Initial contract: handshake on `GET /api/health` (`version`, `api_version`, `min_api_version`,
Expand Down
14 changes: 13 additions & 1 deletion docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1663,6 +1663,16 @@
"title": "Capabilities",
"type": "array"
},
"instance_id": {
"description": "Stable random UUID of this engine, generated once and kept in the data volume; use it as the client-side unique key",
"title": "Instance Id",
"type": "string"
},
"instance_name": {
"description": "Human-readable name (also the mDNS service name)",
"title": "Instance Name",
"type": "string"
},
"min_api_version": {
"description": "Oldest contract version still served; a client implementing contract N is compatible when min_api_version <= N <= api_version",
"title": "Min Api Version",
Expand All @@ -1684,6 +1694,8 @@
"version",
"api_version",
"min_api_version",
"instance_id",
"instance_name",
"auth",
"capabilities"
],
Expand Down Expand Up @@ -4051,7 +4063,7 @@
"info": {
"description": "\nFetch images from modular sources (Immich, TMDB posters, URLs), optimize them for a\ncolor eInk panel and push them to a Fraimic frame.\n\n**Authentication:** with `ADMIN_PASSWORD` set, every route except `/api/health`, the login\nand the public images needs a web UI session or the API key. With only `APP_API_KEY`, every\n`POST`/`PUT`/`DELETE` route and `/api/config` need the key. Send it as `X-API-Key`,\n`Authorization: Bearer <key>` or `?api_key=`; use **Authorize** above.\n",
"title": "Smart Frame Engine",
"version": "1.0.0rc1"
"version": "1.0.0rc2"
},
"openapi": "3.1.0",
"paths": {
Expand Down
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "smart-frame-engine"
version = "1.0.0rc1"
version = "1.0.0rc2"
description = "Fetch photos and posters from modular sources, optimize them for color eInk, and push them to a Fraimic frame."
readme = "README.md"
license = "MIT"
Expand Down Expand Up @@ -84,6 +84,8 @@ known-first-party = ["app"]
testpaths = ["tests"]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
# Dump every thread's stack when one test runs longer than this (diagnoses CI hangs).
faulthandler_timeout = 300
addopts = "-ra -m 'not slow'"
markers = ["slow: long-running performance tests (run with `pytest -m slow`)"]

Expand Down
Loading