summaryrefslogtreecommitdiff
path: root/core/updater.py
diff options
context:
space:
mode:
authorChristian Kolset <ckolset@colostate.edu>2026-07-31 15:52:28 -0600
committerChristian Kolset <ckolset@colostate.edu>2026-07-31 15:52:28 -0600
commitbfbdd0c19910f464e779fa64cc0ec8590f8e37c1 (patch)
tree37ea9b29a925d24928b71b054f1ea955b2b90105 /core/updater.py
parentf1aaffbc3eb1e2c154315c556d2555803eea7997 (diff)
Add PyInstaller packaging and tufup-based auto-update pipeline
Full pipeline, verified end-to-end against the real installed tufup 0.10.0 API (initial docs/summaries turned out inaccurate in places — e.g. the apply method is download_and_apply_update, not update; confirmed by inspecting installed package source directly rather than trusting docs alone): - core/version.py: single-source app version constant. - labdaq.spec: PyInstaller onedir build (must be onedir, not onefile — tufup replaces individual files in the install dir on update). Bundles ui/*.qss, plugins/ (needed for runtime plugin discovery), and repository/metadata/root.json once repo_init.py has produced one. Built and smoke-tested: the frozen exe launches and stays running. - scripts/release/{repo_init,repo_release}.py: maintainer-run release tooling using tufup.repo.Repository, manual local signing (keys never touch CI). Both actually run end-to-end during development of this feature against a real build, not just written and assumed correct. Longer expiration_days than tufup-example's CI-oriented defaults (targets/snapshot/timestamp 90d instead of 7d/7d/1d), since we're signing manually, not on an automated daily schedule — see scripts/release/README.md for the re-signing cadence this still requires even between releases. - core/updater.py: thin Client wrapper. Refuses to run outside a frozen build (getattr(sys, "frozen", False)) since there's no installed bundle for tufup to update in `python main.py` dev mode. Bootstraps the bundled root.json into the metadata cache dir on first run — tuf.ngclient.Updater loads root.json from local disk on construction, it does not fetch it remotely by design (the root of trust can't come from the same server being verified). - core/app_settings.py: factored out app_data_dir() (was inline in _settings_path()) so the updater's metadata/target cache dirs live in the same per-user location as settings.json, deliberately outside the install directory an update can replace/move. - Settings > General: version display + "Check for Updates" button, manual-only per discussion (no silent background network calls or surprise restarts for a lab-instrument-control app). Metadata/targets are hosted on this repo's "updates" GitHub Release — a fixed tag, not a normal per-version tag, because TUF's top-level metadata needs a stable URL across app versions. No such GitHub-Releases- hosting example exists in tufup or tufup-example; verified this by fetching tufup-example's actual GitHub Actions workflow file directly after a web search wrongly suggested one existed — the design here is ours, not copied from upstream. Not yet done, deliberately left for the user: running repo_init.py for real (generates production signing keys), and creating the actual "updates" GitHub Release. Both are irreversible-ish, security-sensitive, externally-visible actions outside what should happen without the user directly driving them. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'core/updater.py')
-rw-r--r--core/updater.py107
1 files changed, 107 insertions, 0 deletions
diff --git a/core/updater.py b/core/updater.py
new file mode 100644
index 0000000..d22cd42
--- /dev/null
+++ b/core/updater.py
@@ -0,0 +1,107 @@
+"""
+core/updater.py
+
+Thin wrapper around tufup.client.Client — checks for and applies app
+updates. Only meaningful inside a PyInstaller-frozen build (see
+is_frozen()); calling check_for_update()/apply_update() from a
+`python main.py` dev run raises, since there's no installed bundle for
+tufup to update.
+
+Update metadata/targets are hosted on this repo's "updates" GitHub Release
+— a fixed tag that never changes between app versions, unlike a normal
+per-version release tag, because TUF's top-level metadata (timestamp.json,
+snapshot.json, ...) must live at a stable URL the client always checks.
+See scripts/release/README.md for the publishing side.
+"""
+
+import sys
+from pathlib import Path
+from typing import Optional
+
+from core.app_settings import app_data_dir
+from core.version import __version__ as CURRENT_VERSION
+
+APP_NAME = "labdaq"
+
+_RELEASE_BASE_URL = "https://github.com/c-kolset/labUI-python/releases/download/updates/"
+METADATA_BASE_URL = _RELEASE_BASE_URL
+TARGET_BASE_URL = _RELEASE_BASE_URL
+
+_client = None # lazily-created tufup.client.Client, reused across calls so
+ # apply_update() can act on what check_for_update() found
+
+
+def is_frozen() -> bool:
+ """True only inside a PyInstaller-built exe — never for `python main.py`."""
+ return bool(getattr(sys, "frozen", False))
+
+
+def _require_frozen():
+ if not is_frozen():
+ raise RuntimeError(
+ "Updates are only available in the packaged app, not `python main.py`."
+ )
+
+
+def _bootstrap_root_json(metadata_dir: Path) -> None:
+ """
+ tuf.ngclient.Updater (tufup.client.Client's base class) loads root.json
+ from metadata_dir automatically on construction — it does NOT fetch it
+ remotely on first use, by design (TUF's root of trust has to come from
+ somewhere already trusted, not from the same server being verified).
+
+ So the copy bundled into the app (labdaq.spec bundles
+ scripts/release/repository/metadata/root.json to "repository/metadata")
+ has to be seeded into metadata_dir before the first Client is ever
+ constructed on a given machine. sys._MEIPASS is where PyInstaller puts
+ bundled data files at runtime, for both onefile and onedir builds.
+ """
+ dest = metadata_dir / "root.json"
+ if dest.exists():
+ return
+ bundled = Path(getattr(sys, "_MEIPASS", "")) / "repository" / "metadata" / "root.json"
+ if not bundled.is_file():
+ raise RuntimeError(f"Bundled root.json not found at {bundled} — was the app built "
+ f"before scripts/release/repo_init.py had been run?")
+ metadata_dir.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(bundled.read_bytes())
+
+
+def _get_client():
+ global _client
+ if _client is None:
+ from tufup.client import Client
+
+ cache_dir = app_data_dir() / "tufup"
+ metadata_dir = cache_dir / "metadata"
+ _bootstrap_root_json(metadata_dir)
+ _client = Client(
+ app_name=APP_NAME,
+ app_install_dir=Path(sys.executable).resolve().parent,
+ current_version=CURRENT_VERSION,
+ metadata_dir=metadata_dir,
+ metadata_base_url=METADATA_BASE_URL,
+ target_dir=cache_dir / "targets",
+ target_base_url=TARGET_BASE_URL,
+ )
+ return _client
+
+
+def check_for_update() -> Optional[str]:
+ """Return the new version string if an update is available, else None."""
+ _require_frozen()
+ new_target = _get_client().check_for_updates()
+ return str(new_target.version) if new_target else None
+
+
+def apply_update() -> None:
+ """
+ Download, TUF-verify, and install the update found by the most recent
+ check_for_update() call on this process. Only call after
+ check_for_update() returned a version — tufup raises otherwise.
+
+ tufup's default install step replaces the app's files and relaunches it;
+ the calling UI should assume the process may exit during this call.
+ """
+ _require_frozen()
+ _get_client().download_and_apply_update(skip_confirmation=True)