15 KiB
type, status, project, date, tags
| type | status | project | date | tags | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| plan | active | homelab | 2026-09-21 |
|
🚀 appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan
1. Executive Summary & Intent
The appctl control utility is the central metadata, discovery, and inspection engine for the roadtotech.me homelab. It derives operational views (Docker status, Git sync status, SSL/TLS validation, Homepage dashboard generation, shell completion) from application manifests (Sites/*/app.yaml) and Core platform definitions.
This plan modernizes the engine from a procedural ~900-line script with a hand-rolled YAML parser into a clean, strongly-typed, test-driven Python engine (appctl_engine_v2.py) with zero breaking changes to the bash caller interface (scripts/appctl).
2. Problem Statement & Motivation
| Issue in V1 Engine | Architectural Risk | V2 Solution |
|---|---|---|
Handmade YAML Parser (parse_yaml_simple) |
Fragile indentation parser; silently mishandled complex structures, quotes, multiline strings, or standard YAML types. | Replace with standard yaml.safe_load() via PyYAML (flake.nix & nixos). |
Silent Error Suppression (contextlib.suppress) |
Swallowed all YAML errors; syntax mistakes in app.yaml silently degraded into empty defaults without operator notification. |
Define class ManifestError(Exception) and capture errors into app.manifest_error for explicit reporting. |
| Stringly-Typed Dictionaries | Unstructured dict[str, Any] passed everywhere with loose key lookups (app["domain"], app["name"]). |
Strict @dataclass hierarchy: App, SitesApp, CoreService, HomepageConfig, SSLCertResult. |
| Domain Hardcoding | Hardcoded roadtotech.me strings throughout code, violating portability and open-source reusability. |
Dynamic HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") + fail-fast validate_environment(). |
| Zero Test Coverage | No automated tests for resolution precedence, manifest parsing, or Homepage compilation. | Comprehensive TDD test suite in tests/unit/test_appctl_engine_v2.py with AppFactory fixture. |
3. Architecture & Domain Model
┌─────────────────────────────────────────────────────────────┐
│ scripts/appctl (Bash) │
│ (Mutation: up, down, restart, update, logs) │
└──────────────────────────────┬──────────────────────────────┘
│ JSON via `resolve` & stdout
▼
┌─────────────────────────────────────────────────────────────┐
│ scripts/appctl_engine_v2.py │
│ (Inspection, Metadata, Discovery & Sync) │
├─────────────────────────────────────────────────────────────┤
│ 1. Domain Hierarchy │
│ ├── SourceConfig (Provenance: type, url, ref) │
│ ├── App (Base: name, description, domain, dir_path) │
│ ├── SitesApp (Sites: source, aliases, visible, auth) │
│ └── CoreService (Core: container, weight, icon) │
├─────────────────────────────────────────────────────────────┤
│ 2. Ingestion & Normalization │
│ ├── load_manifest() -> raw dict (PyYAML) │
│ └── sites_app_from_manifest() -> SitesApp (Pure Seam) │
├─────────────────────────────────────────────────────────────┤
│ 3. Inspection Engines │
│ ├── Docker Status & OCI Image Label Inspection │
│ ├── Deployment Git Status (local Sites repository) │
│ ├── Source Provenance Resolver (git ls-remote --fetch) │
│ └── TLS/SSL Validation (stdlib socket/ssl via ThreadPool)│
├─────────────────────────────────────────────────────────────┤
│ 4. CLI Dispatch Layer │
│ ├── cmd_list / cmd_status (polymorphic table rendering) │
│ ├── cmd_info (unified diagnostics & provenance view) │
│ ├── cmd_ssl (TLS overview across apps and Core) │
│ ├── cmd_resolve (JSON emitter for bash caller) │
│ ├── cmd_sync_homepage (compiles services.yaml) │
│ └── cmd_complete (bash autocomplete generator) │
└─────────────────────────────────────────────────────────────┘
4. Deliverables & Execution Roadmap
Deliverable 1: Domain Model, Manifest Ingestion & TDD Scaffold (COMPLETE / GREEN)
- Create isolated Git worktree at
~/Projects/active/appctl-refactor. - Configure Pyright and Nix devShell (
python3.withPackages [ pyyaml types-pyyaml pytest ruff pyright ]). - Implement
@dataclass class SourceConfig(type, url, ref)with explicit ref semantics. - Implement
@dataclass class App,SitesApp(source: SourceConfig | None),CoreService, andHomepageConfig. - Implement
load_manifest(manifest_path)withManifestError. - Implement pure normalization seam
sites_app_from_manifest(app_dir, manifest, manifest_error). - Implement dynamic discovery
get_sites_apps(sites_dir)andresolve_app(query, apps). - Implement typed Core registry
get_core_services(core_dir). - Implement
validate_environment()for fail-fast domain and path verification. - Scaffold test suite in
tests/unit/test_appctl_engine_v2.pywithmock_sites_dir,mock_core_dir, andAppFactory.
Deliverable 2: Inspection Layer (IN PROGRESS)
- Docker Inspection Engine:
- Implement
get_docker_status(dir_path: Path | str, container_name: str | None = None) -> str. - Handle Compose directory inspection (
docker compose ps -q+ inspect). - Handle Core single container inspection (
docker inspect -f '{{.State.Running}}' <name>). - Return standardized status badges (
🟢 Running (N),🟡 Degraded (M/N),🔴 Stopped,⚪ Not Stack,❓ Unknown). - Extract container image labels: specifically
org.opencontainers.image.revisionfor software provenance.
- Implement
- Two-Axis Git & Source Provenance Engine:
- Axis 1: Deployment Git Status:
- Implement
get_deployment_git_status(dir_path: Path | str) -> str. - Parse
git status --porcelainandgit rev-list --left-right --count HEAD...@{u}. - Return standardized badges (
✓ Synced,⬆ N Ahead,⬇ N Behind,⚡ N⬆ M⬇,⚪ Untracked,*dirty indicator).
- Implement
- Axis 2: Source Provenance Resolver:
- Implement
get_source_provenance_status(app: SitesApp, fetch_remote: bool = False) -> str. - If
app.source is None: return⚪ Image Only(display container image tag). - If
app.source.refis a pinned tag or commit SHA: return📌 Pinned (<ref>). - Extract running container's
org.opencontainers.image.revision(deployed SHA). - If
fetch_remote=True: resolve remote ref SHA viagit ls-remote <url> refs/heads/<ref>. - Compare revisions:
- Remote SHA == Deployed SHA:
✓ Up to date (<sha>) - Remote SHA != Deployed SHA:
⚡ Revision Changed
- Remote SHA == Deployed SHA:
- Implement
- Implement
get_git_diagnostics(dir_path: Path | str, app: SitesApp | None = None) -> dict[str, Any] | None.
- Axis 1: Deployment Git Status:
- SSL / TLS Inspection Engine:
- Define
@dataclass class SSLCertResult. - Implement
check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> SSLCertResult. - Implement
check_all_ssl_certs(domains: list[str]) -> dict[str, SSLCertResult]withThreadPoolExecutor.
- Define
- Concurrent Remote Fetching:
- Implement
fetch_all_repositories(apps: list[SitesApp], include_core: bool = True)with worker pool. - Concurrently resolves
git fetchfor local deployment repositories andgit ls-remotefor source-backed workloads.
- Implement
Deliverable 3: Presentation & CLI Dispatch Layer
cmd_list/cmd_status:- Support
--core/-c,--fetch/-f,--ssl/-s, and--all/-aflags. - Polymorphic table formatting for both
SitesAppandCoreService. - Display two-axis status: Deployment checkout state + Upstream revision badge.
- Render manifest warning indicators if
app.manifest_erroris populated.
- Support
cmd_info:- Formatted deep diagnostic view for a single application or Core service.
- Display metadata, Authelia guard status, Compose status, Git diagnostics, and TLS certificate info.
- Display dedicated Source Provenance Block: Upstream Git URL, Tracking Ref, Deployed Commit SHA, and Remote HEAD SHA.
cmd_ssl:- Formatted TLS certificate table for all public domains or deep inspection of a single target.
cmd_resolve:- Emit JSON payload via
app.to_dict()ensuring 100% compatibility withscripts/appctl.
- Emit JSON payload via
cmd_sync_homepage:- Compile
SitesAppcards andCoreServicedefinitions intoCore/config/homepage/services.yaml. - Group by
homepage.group, sort byhomepage.weight, and resolve local SVG/PNG icons fromicons/.
- Compile
cmd_complete:- Generate bash autocompletion candidates for commands, apps, aliases, and Core services.
Deliverable 4: Verification, Cutover & Documentation
- Run full automated test suite:
pytest tests/(100% Green). - Run code linter:
ruff check .with zero errors. - Run type checker:
pyrightwith zero errors. - Topology Synchronization (Roadmap v4 P1 alignment):
- Update
scripts/appctl_engine_v2.pyget_core_services():stalwart: domainsmtp.${HOMELAB_DOMAIN}.- Remove
snappymail(discovered dynamically in~/Sites/snappymail). - Remove deprecated
portainer.
- Update
- Manifest Engine Convergence (Roadmap v4 P3 alignment):
- In
~/Projects/active/appctl-refactor, cherry-pick the atomic commit frommainthat introducesCore/scripts/core_manifest.py. - Refactor
appctl_engine_v2.pyto ingest manifests viacore_manifest.pyin place of standaloneload_manifest(). - Update unit test fixtures in
tests/unit/test_appctl_engine_v2.pyto validate against schema v1.0 models.
- In
- Promote
scripts/appctl_engine_v2.pytoscripts/appctl_engine.pywithinrefactor/appctl-rework. - Merge
refactor/appctl-reworkintomain. - Run
./scripts/testand live verification (appctl list,appctl info,appctl sync) onmain. - Update
docs/appctl.mdwith V2 architecture and developer documentation.
4.5 Cross-Track Coordination with Architecture Roadmap v3
The appctl-v2 refactor operates as Track B (modernizing implementation in worktree ~/Projects/active/appctl-refactor on branch refactor/appctl-rework), running parallel to the Homelab Architecture Consolidation Roadmap v3 (Track A on main).
Track B: appctl-v2 (refactor/appctl-rework)
│ (internal modernizations: dataclasses, PyYAML, TDD)
│
│ integration seam (cherry-pick core_manifest.py commit from main)
▼
Track A: Homelab Architecture (main)
├── P1: Mail topology (minimal compatibility patch to legacy engine on main)
├── P2: GitOps authority (independent of appctl)
└── P3: Manifest convergence (DELIBERATE JOIN POINT where Track B merges to main)
Branch Operating Rules
- Isolated Development:
refactor/appctl-reworkis NOT rebased or merged intomainduring P1 or P2. Frequent cross-merging between active branches is strictly avoided. - Minimal Legacy Patching: P1 modifies legacy
appctl_engine.pyonmainstrictly to update thestalwartdomain and removesnappymail. Track B applies the identical semantic change directly to its typedCoreServicedefinitions without merging git branches. - P3 Controlled Convergence Direction:
core_manifest.pyoriginates onmain(tested with GitOps and existing platform tests).- Track B brings that specific commit into
refactor/appctl-reworkviagit cherry-pick. appctl-v2adapts its normalization seam tocore_manifest.pyand confirms all unit tests pass in its worktree.- On
refactor/appctl-rework,scripts/appctl_engine_v2.pyis promoted toscripts/appctl_engine.py. - The tested, compliant
refactor/appctl-reworkbranch is then merged intomain.
5. Invariants & Acceptance Criteria
- Zero Breaking Changes to Bash Contract:
scripts/appctlmust function identically withappctl list,appctl info <app>,appctl up <app>,appctl sync, and autocompletions without requiring syntax or argument changes. - Deterministic Test Suite:
Unit tests in
tests/unit/test_appctl_engine_v2.pymust run hermetically without requiring a live Docker daemon, live network access, or mutating the user's real~/Sitesor~/Core. - The Unlicense Integrity: All new files and refactored code preserve public domain status under The Unlicense.
- Architectural Seams Preserved for Roadmap v3:
appctl_engine_v2.pymust preserve the 5 architectural seams until convergence at P3:- CLI Syntax: Invocation syntax, subcommands, and flags unchanged.
resolveJSON Contract: Emits exact keys required byscripts/appctl: requiredname,dir_path,type("app"or"core_service"),domain, plus contextualcontainerandenv. Backed by an automated test fixture.- Canonical Identity: Service identifiers remain stable within the systems that own them; Core services and Sites workloads use their canonical names consistently.
- Core vs. Sites Taxonomy: Platform capabilities in Core vs. independent workloads in Sites strictly maintained.
- Homepage Sync Semantics:
services.yamlcompilation matches existing schema.