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
21 changes: 21 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ jobs:
- name: Checkout
uses: actions/checkout@v7

# The tag (v1.0.0-rc.2) and pyproject.toml (1.0.0rc2) spell the same release differently;
# compare them as versions so a forgotten bump can't ship an image showing another version.
- name: Check the tag matches pyproject.toml
run: |
python3 - <<'PY'
import os, re, tomllib

def normalize(version: str) -> str:
"""Reduce SemVer (1.0.0-rc.2) and PEP 440 (1.0.0rc2) to one spelling."""
version = version.lstrip("v").split("+")[0]
version = re.sub(r"[-.]?(alpha|a)[-.]?(\d+)", r"a\2", version)
version = re.sub(r"[-.]?(beta|b)[-.]?(\d+)", r"b\2", version)
return re.sub(r"[-.]?rc[-.]?(\d+)", r"rc\1", version)

tag = os.environ["GITHUB_REF_NAME"]
declared = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"]
if normalize(tag) != normalize(declared):
raise SystemExit(f"Tag {tag} does not match pyproject.toml version {declared}")
print(f"Tag {tag} matches pyproject.toml version {declared}")
PY

- name: Compute image name (registry paths must be lowercase)
run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV"

Expand Down
5 changes: 5 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ RUN pip install --no-deps .
ENV NUMBA_CACHE_DIR=/app/.numba_cache
RUN mkdir -p /app/.numba_cache && chown app:app /app/.numba_cache

# Marks images built outside a release tag (``+<build>`` after the version in the UI); empty for
# release images. Declared late so changing it never invalidates the layers above.
ARG APP_BUILD=""
ENV APP_BUILD=${APP_BUILD}

USER app
RUN python -c "from app.processor.dither import warm_up; warm_up()"
VOLUME ["/data"]
Expand Down
9 changes: 8 additions & 1 deletion app/api/routes/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from app.services.delivery import FrameTelemetry, LastDelivery, PendingUpload
from app.services.ephemeral import EphemeralView
from app.services.scheduler import SchedulerSnapshot
from app.version import release_label

router = APIRouter(prefix="/api", tags=["system"])

Expand Down Expand Up @@ -83,7 +84,12 @@ class ServiceConfigured(BaseModel):
class StatusResponse(BaseModel):
"""Overall system status."""

version: str
version: str = Field(description="Engine version (PEP 440, same as /api/health)")
release: str = Field(
description="Version as spelled by the git tag and the Docker image tag (SemVer, e.g. "
"1.0.0-rc.2), with +<build> appended for images built outside a release tag; "
"informational, for display only"
)
uptime_s: float
auth_enabled: bool
auth_mode: str = Field(description="open, key (API key only) or password (admin login)")
Expand Down Expand Up @@ -131,6 +137,7 @@ async def status(
started_at: float = request.app.state.started_at
return StatusResponse(
version=__version__,
release=release_label(),
uptime_s=round(time.monotonic() - started_at, 1),
auth_enabled=auth.mode != "open",
auth_mode=auth.mode,
Expand Down
3 changes: 2 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
from app.services.ephemeral import EphemeralService
from app.services.now_playing import NowPlayingService
from app.services.scheduler import SchedulerService, immich_runner, tmdb_runner
from app.version import release_label

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -217,7 +218,7 @@ async def _on_config_change(_: RuntimeConfig) -> None:
logger.info(
"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__,
release_label(),
identity.instance_id,
settings.data_dir,
auth_state.mode,
Expand Down
2 changes: 1 addition & 1 deletion app/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ <h3 class="card-title">Services</h3>
<li class="flex justify-between"><span>Immich</span><span class="text-xs" :class="status && status.services.immich ? 'text-green-600 dark:text-green-400' : 'text-slate-400'" x-text="status && status.services.immich ? 'configured' : 'not configured'"></span></li>
<li class="flex justify-between"><span>TMDB</span><span class="text-xs" :class="status && status.services.tmdb ? 'text-green-600 dark:text-green-400' : 'text-slate-400'" x-text="status && status.services.tmdb ? 'configured' : 'not configured'"></span></li>
<li class="flex justify-between"><span>Smart Mix</span><span class="text-xs" x-text="status && status.scheduler.smart_mix.enabled ? 'on' : 'off'"></span></li>
<li class="flex justify-between"><span>Version</span><span class="text-xs text-slate-500" x-text="status && status.version"></span></li>
<li class="flex justify-between"><span>Version</span><span class="text-xs text-slate-500" x-text="status && (status.release || status.version)"></span></li>
</ul>
</div>
</div>
Expand Down
68 changes: 68 additions & 0 deletions app/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""Human-facing release label, spelled like the git tag and the Docker image tag.

``pyproject.toml`` carries a PEP 440 version (``1.0.0rc2``) while the git tag and the published
image tag are SemVer (``v1.0.0-rc.2`` / ``1.0.0-rc.2``). The API keeps reporting the PEP 440
spelling (``GET /api/health`` -> ``version``, see ``docs/API_CONTRACT.md``); the UI shows the
SemVer spelling so it matches what users pulled.
"""

from __future__ import annotations

import os
import re
from typing import Final

from app import __version__

_PRE_RELEASE_NAMES: Final = {"a": "alpha", "b": "beta", "rc": "rc"}

_PEP440: Final = re.compile(
r"""^
(?P<release>\d+(?:\.\d+)*)
(?:(?P<pre>a|b|rc)(?P<pre_n>\d+))?
(?:\.post(?P<post>\d+))?
(?:\.dev(?P<dev>\d+))?
(?:\+(?P<local>[A-Za-z0-9.]+))?
$""",
re.VERBOSE,
)

#: Environment variable set at image build time (``--build-arg APP_BUILD=<short sha>``).
BUILD_ENV: Final = "APP_BUILD"


def display_version(version: str) -> str:
"""Convert a normalized PEP 440 version to the SemVer spelling used by tags.

``1.0.0rc2`` -> ``1.0.0-rc.2``; ``1.0.0`` and unparseable values are returned unchanged.
"""
match = _PEP440.match(version.strip())
if match is None:
return version
result = match["release"]
identifiers: list[str] = []
if match["pre"]:
identifiers.append(f"{_PRE_RELEASE_NAMES[match['pre']]}.{int(match['pre_n'])}")
if match["post"]:
identifiers.append(f"post.{int(match['post'])}")
if match["dev"]:
identifiers.append(f"dev.{int(match['dev'])}")
if identifiers:
result += "-" + ".".join(identifiers)
if match["local"]:
result += "+" + match["local"]
return result


def release_label(version: str = __version__, build: str | None = None) -> str:
"""The version as shown in the UI: SemVer spelling, plus ``+<build>`` for non-tag builds.

``build`` defaults to the ``APP_BUILD`` environment variable (empty for release images).
"""
label = display_version(version)
if build is None:
build = os.environ.get(BUILD_ENV, "")
build = re.sub(r"[^A-Za-z0-9.]", "", build.strip())[:40]
if build and "+" not in label:
label += f"+{build}"
return label
6 changes: 5 additions & 1 deletion docker-compose.build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
# ./data by default so it is easy to inspect while developing.
services:
smart-frame-engine:
build: .
build:
context: .
args:
# Shown as "<version>+dev" in the UI so a local build is never mistaken for a release.
APP_BUILD: ${APP_BUILD:-dev}
image: smart-frame-engine:dev
container_name: smart-frame-engine
restart: unless-stopped
Expand Down
7 changes: 7 additions & 0 deletions docs/API_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,13 @@ changelog) and run `python scripts/export_openapi.py` (see `CLAUDE.md`).

## Contract Changelog

### 1.2 (unreleased), additive

- `GET /api/status` gains `release`: the engine version spelled like the git tag and the Docker
image tag (SemVer, `1.0.0-rc.2`), with `+<build>` appended for images built outside a release
tag. It is for display only; `version` (PEP 440) on `/api/status` and `/api/health` is
unchanged. No `api_version` change.

### 1.1 (engine 1.0.0rc2), additive

- `GET /api/health` gains `instance_id` and `instance_name`; Zeroconf TXT gains `instance_id` and
Expand Down
7 changes: 7 additions & 0 deletions docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3484,6 +3484,11 @@
"title": "Public Image Endpoints",
"type": "boolean"
},
"release": {
"description": "Version as spelled by the git tag and the Docker image tag (SemVer, e.g. 1.0.0-rc.2), with +<build> appended for images built outside a release tag; informational, for display only",
"title": "Release",
"type": "string"
},
"scheduler": {
"$ref": "#/components/schemas/SchedulerSnapshot",
"description": "Autonomous refresh: timer and last run"
Expand All @@ -3496,12 +3501,14 @@
"type": "number"
},
"version": {
"description": "Engine version (PEP 440, same as /api/health)",
"title": "Version",
"type": "string"
}
},
"required": [
"version",
"release",
"uptime_s",
"auth_enabled",
"auth_mode",
Expand Down
61 changes: 61 additions & 0 deletions tests/test_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Release label shown in the UI: spelled like the git tag and the Docker image tag."""

from __future__ import annotations

import pytest

from app import __version__
from app.version import display_version, release_label
from tests.conftest import ClientFactory


@pytest.mark.parametrize(
("pep440", "expected"),
[
("1.0.0", "1.0.0"),
("1.0.0rc2", "1.0.0-rc.2"),
("1.2.0b1", "1.2.0-beta.1"),
("2.0.0a3", "2.0.0-alpha.3"),
("1.0.1.post1", "1.0.1-post.1"),
("1.1.0.dev4", "1.1.0-dev.4"),
("1.0.0rc2+g1a2b3c", "1.0.0-rc.2+g1a2b3c"),
("0.0.0+unknown", "0.0.0+unknown"),
("not a version", "not a version"),
],
)
def test_display_version(pep440: str, expected: str) -> None:
assert display_version(pep440) == expected


def test_release_label_without_build() -> None:
assert release_label("1.0.0rc2", build="") == "1.0.0-rc.2"


def test_release_label_marks_non_release_builds() -> None:
assert release_label("1.0.0rc2", build="abc1234") == "1.0.0-rc.2+abc1234"
assert release_label("1.0.0rc2", build="dev") == "1.0.0-rc.2+dev"


def test_release_label_does_not_double_the_local_segment() -> None:
assert release_label("1.0.0rc2+g1a2b3c", build="abc") == "1.0.0-rc.2+g1a2b3c"


def test_release_label_sanitizes_the_build() -> None:
assert release_label("1.0.0", build=" a/b c!\n") == "1.0.0+abc"


def test_release_label_reads_the_environment(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("APP_BUILD", "deadbee")
assert release_label("1.0.0") == "1.0.0+deadbee"
monkeypatch.delenv("APP_BUILD")
assert release_label("1.0.0") == "1.0.0"


def test_status_reports_both_spellings(
make_client: ClientFactory, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("APP_BUILD", raising=False)
body = make_client().get("/api/status").json()
assert body["version"] == __version__
assert body["release"] == display_version(__version__)
assert make_client().get("/api/health").json()["version"] == __version__