Compare commits

...
2 Commits
Author SHA1 Message Date
kiskaadee 27fd03df59 test(appctl): scaffold v2 engine and TDD test suite
- Implement AppFactory fixture for isolated application manifest testing
- Add green tests for v2 app resolution, default injection, and normalization
- Add xfail red tests for get_docker_status and cmd_sync_homepage to guide TDD
- Add pyyaml, pytest, and pyright to NixOS and flake development environments
- Enforce HOMELAB_DOMAIN and CORE_DIR presence via validate_environment()
2026-09-21 01:58:26 -05:00
kiskaadee 55933afa17 feat(appctl): scaffold strongly-typed v2 metadata engine
Introduce appctl_engine-v2.py as a parallel implementation to begin
replacing the procedural dictionary-based orchestrator with a formalized
dataclass domain model (SitesApp, CoreService).

- Replace brittle custom YAML parser with standard PyYAML safe_load
- Add pyyaml to system packages in nixos/configuration.nix
- Update flake.nix devShell with pyyaml, pyright, and pytest for testing
- Add .direnv and .envrc to .gitignore for local workspace configurations
2026-09-18 12:05:21 -05:00
9 changed files with 567 additions and 12 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
use flake
+2 -1
View File
@@ -3,6 +3,8 @@
.env.*
secrets.txt
backup.zip
.envrc
.direnv
# SSL / ACME Certificates & Keys
config/letsencrypt/*
@@ -47,4 +49,3 @@ __pycache__/
# Local Bootstrap & Operational Scripts
scripts/bootstrap_lldap_users.py
scripts/bootstrap_*.py
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1789006805,
"narHash": "sha256-q+GdZ3yq4Y2LXHRK0vKTM32Hwy7RCgUgy+hjwZLI5pY=",
"rev": "8ce4ef6cb6f871616146b9fe26d2a5ae594e94fe",
"lastModified": 1789785513,
"narHash": "sha256-BMbikTjbh5H7ac/OjwGoJrlooh4dgNqhs51ABM83M7g=",
"rev": "20b1ddd1aa5ace70c9468305030aa4f9ef79671b",
"type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1070770.8ce4ef6cb6f8/nixexprs.tar.zst"
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1076192.20b1ddd1aa5a/nixexprs.tar.zst"
},
"original": {
"type": "tarball",
@@ -26,11 +26,11 @@
]
},
"locked": {
"lastModified": 1788914643,
"narHash": "sha256-4GuMPW90JSxXWDPUB9M+1m7fYbe3H0apOd86/zBQ2Kw=",
"lastModified": 1789890976,
"narHash": "sha256-GKwH3zpy7tartuJMG0Rv/xUsdetG1QLmTVv8UKgJLmA=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "13616fff713a9f94055c66f15687ebdc17a335df",
"rev": "7214124c20c1542c90deb54af50e2f53ae02711f",
"type": "github"
},
"original": {
+6 -3
View File
@@ -27,9 +27,12 @@
devShells.${system}.default = pkgs.mkShell {
buildInputs = with pkgs; [
python3
python3Packages.pytest
python3Packages.pyyaml
(python3.withPackages (ps: with ps; [
pyyaml
types-pyyaml
pytest
]))
pyright
ruff
];
shellHook = ''
+3 -1
View File
@@ -115,7 +115,9 @@
sops
age
# Python runtime (hard requirement for appctl and gitops_dispatcher.py)
python3
python3.withPackages(ps: with ps; [
pyyaml
])
# Modern shell utilities
eza # ls replacement
ripgrep # rg — fast grep
+2
View File
@@ -0,0 +1,2 @@
[tool.pyright]
extraPaths = ["scripts"]
+353
View File
@@ -0,0 +1,353 @@
import os
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
import yaml
# Dynamic Environment Paths
CORE_DIR = os.environ.get(
"CORE_DIR", os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
)
SITES_DIR = os.environ.get(
"SITES_DIR",
os.path.join(os.path.dirname(CORE_DIR), "Sites")
if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites"))
else os.path.expanduser("~/Sites"),
)
HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") or os.environ.get("DOMAIN", "")
def validate_environment() -> None:
"""Ensure mandatory environment configuration is valid before CLI execution."""
errors: list[str] = []
if not HOMELAB_DOMAIN:
errors.append(
"• Missing 'HOMELAB_DOMAIN' (or 'DOMAIN') environment variable.\n"
" Please export it (e.g. export HOMELAB_DOMAIN='roadtotech.me') or set it in your environment file."
)
if not os.path.isdir(CORE_DIR):
errors.append(f"• Core directory not found at: {CORE_DIR}")
if errors:
print("❌ Environment Validation Failed:\n", file=sys.stderr)
for err in errors:
print(f" {err}", file=sys.stderr)
sys.exit(1)
class ManifestError(Exception):
pass
@dataclass
class HomepageConfig:
title: str
group: str = "Applications"
icon: str = "default.png"
container: str = ""
weight: int = 50
@dataclass
class App:
name: str # Canonical identified (e.g., "traefik", "jellyfin")
description: str # Human-readable summary for dashboards and CLI info
domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
@property
def is_internal(self) -> bool:
"""Returns True if the service does not expose a public TLS endpoint."""
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
def to_dict(self) -> dict[str, Any]:
"""Serialize for JSON consumption by scripts/appctl"""
data = asdict(self)
data["type"] = getattr(self, "app_type", "app")
return data
@dataclass
class CoreService(App):
container: str = "" # Target container name inside Core's root docker-compose.yml (e.g., "authelia", "stalwart")
weight: int = 50 # Homepage ordering weight (optional, for dashboard synchronization)
icon: str = "default.png" # Dashboard icon filename
app_type: str = "core_service"
dir_path: str = CORE_DIR
@dataclass
class SitesApp(App):
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
aliases: list[str] = field(default_factory=list) # CLI resolution aliases (e.g., "vw", "vaultwarden")
visible: bool = True # Defines whether the icon is visible in the Homepage Dashboard
auth: bool = True # Authelia protection guard indicator; Defaulting to True is safer
has_compose: bool = False # Whether a docker-compose.yaml exists at ~/Sites/dir_name.
networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments (def ["proxy-net"])
env: dict[str, Any] = field(default_factory=dict) # Dynamic environment variable overrides
homepage: HomepageConfig | None = None # Dashboard Card Configuration
manifest_error: str | None = None # Captured syntax/loading errors if app.yaml was malformed/absent
app_type: str = "app"
def load_manifest(manifest_path: str) -> dict[str, Any]:
"""Load and parese the app manifest file
Raises:
FileNotFoundError: if the manifest file does not exist.
ValueError: if YAML object is malformed.
TypeError: If root is not a directory
"""
if not os.path.isfile(manifest_path):
raise FileNotFoundError(f"Manifest file not found at {manifest_path}")
try:
with open(manifest_path, "r", encoding="utf-8") as file:
manifest_data = yaml.safe_load(file) or {}
except (yaml.YAMLError, OSError) as err:
raise ManifestError(f"YAML parsing failed: {err}") from err
if not isinstance(manifest_data, dict):
raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`")
return manifest_data
def sites_app_from_manifest(
app_dir: str,
manifest: dict[str, Any],
manifest_error: str | None = None
) -> SitesApp:
"""Construct and normalize a SitesApp domain model from raw manifest data."""
raw_dir_name = os.path.basename(app_dir)
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
# Normalize aliases into list[str]
raw_aliases = manifest.get("aliases") or []
if isinstance(raw_aliases, str):
aliases = [raw_aliases]
elif isinstance(raw_aliases, list):
aliases = [str(alias) for alias in raw_aliases]
else:
aliases = []
# Homepage card normalization
homepage_config: HomepageConfig | None = None
raw_hp = manifest.get("homepage")
if isinstance(raw_hp, dict):
homepage_config = HomepageConfig(
title=str(raw_hp.get("title") or canonical_name),
group=str(raw_hp.get("group") or "Applications"),
icon=str(raw_hp.get("icon") or "default.png"),
container=str(raw_hp.get("container") or canonical_name),
weight=int(raw_hp.get("weight", 50))
)
has_compose = (
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
)
# Manifest Data parsing
raw_desc = manifest.get("description")
app_desc: str = str(raw_desc) if raw_desc is not None else ""
raw_dom = manifest.get("domain")
app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}"
app_net = manifest.get("networks")
if not isinstance(app_net, list):
app_net = ["proxy-net"]
app_env = manifest.get("env")
if not isinstance(app_env, dict):
app_env = {}
def _as_bool(value: Any, default: bool) -> bool:
if isinstance(value, bool):
return value
return default
app_vis = _as_bool(manifest.get("visible"), True)
app_auth = _as_bool(manifest.get("auth"), True)
return SitesApp(
name=canonical_name,
dir_name=raw_dir_name,
description=app_desc,
domain=app_dom,
dir_path=app_dir,
has_compose=has_compose,
aliases=aliases,
visible=app_vis,
auth=app_auth,
networks=app_net,
env=app_env,
homepage= homepage_config,
manifest_error=manifest_error,
)
def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
"""
Scan the given sites directory (defaulting to SITES_DIR) for application.
"""
target_dir = sites_dir or SITES_DIR
apps: list[SitesApp] = []
if not os.path.isdir(target_dir):
return apps
for entry in sorted(os.listdir(target_dir)):
app_dir = os.path.join(target_dir, entry)
# skip hidden or null directories
if entry.startswith(".") or not os.path.isdir(app_dir):
continue
manifest_path = os.path.join(app_dir, "app.yaml")
manifest: dict[str, Any] = {}
manifest_error: str | None = None
if os.path.isfile(manifest_path):
try:
manifest = load_manifest(manifest_path=manifest_path)
except ManifestError as err:
manifest_error = str(err)
apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error))
return apps
def resolve_app(
query: str,
apps: list[SitesApp] | None = None,
sites_dir: str | None = None
) -> SitesApp | None:
if apps is None:
apps = get_sites_apps(sites_dir= sites_dir if sites_dir is not None else SITES_DIR)
query_clean = query.strip().lower()
# 1. Extract match on canonical name
for app in apps:
if app.name.lower() == query_clean:
return app
# 2. Match on alias
for app in apps:
if any(alias.lower() == query_clean for alias in app.aliases):
return app
# 3. Match directory name
for app in apps:
if app.dir_name.lower() == query_clean:
return app
# 4. Match stripped 'homelab-' prefix
for app in apps:
if app.dir_name.lower() == f"homelab-{query_clean}":
return app
return None
def get_core_services(core_dir: str | None = None) -> list[CoreService]:
"""Return the strongly-typed registry of Core platform services."""
return [
CoreService(
name="traefik",
domain=f"traefik.{HOMELAB_DOMAIN}",
container="traefik",
description="Edge Reverse Proxy & ACME TLS",
icon="traefik.png",
weight=10,
),
CoreService(
name="authelia",
domain=f"auth.{HOMELAB_DOMAIN}",
container="authelia",
description="Identity & SSO Access Control",
icon="authelia.png",
weight=20,
),
CoreService(
name="lldap",
domain=f"users.{HOMELAB_DOMAIN}",
container="lldap",
description="Lightweight LDAP User Directory",
icon="lldap.png",
weight=25,
),
CoreService(
name="stalwart",
domain=f"mail.{HOMELAB_DOMAIN}",
container="stalwart",
description="All-in-one Mail Server",
icon="email.png",
weight=26,
),
CoreService(
name="snappymail",
domain=f"webmail.{HOMELAB_DOMAIN}",
container="snappymail",
description="Modern Lightweight Webmail Client",
icon="email.png",
weight=27,
),
CoreService(
name="portainer",
domain=f"portainer.{HOMELAB_DOMAIN}",
container="portainer",
description="Container Management GUI",
icon="portainer.png",
weight=30,
),
CoreService(
name="dozzle",
domain=f"logs.{HOMELAB_DOMAIN}",
container="dozzle",
description="Real-time Log Viewer",
icon="dozzle.png",
weight=40,
),
CoreService(
name="socket-proxy",
domain="internal",
container="socket-proxy",
description="Docker Socket Security Proxy",
),
CoreService(
name="homepage",
domain=f"dashboard.{HOMELAB_DOMAIN}",
container="homepage",
description="Application Dashboard & System Portal",
icon="homepage.png",
weight=5,
),
CoreService(
name="diun",
domain="internal",
container="diun",
description="Docker Image Update Notifier",
),
CoreService(
name="watchtower",
domain="internal",
container="watchtower",
description="Automated Container Updates",
),
]
def get_docker_status(
dir_path: str | Path,
container_name: str | None = None
) -> str:
path: Path = Path(dir_path)
def _do_something(path: Path = path):
return ""
return _do_something()
def cmd_sync_homepage(args) -> None:
pass
+190
View File
@@ -0,0 +1,190 @@
import sys
from dataclasses import dataclass
from pathlib import Path
from unittest.mock import MagicMock
import pytest
# Import appctl engine v2
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts"))
import appctl_engine_v2 as engine
@dataclass
class AppFactory:
"""Helper class to generate mock app directories and configurations"""
sites_dir: Path
def create(
self,
dir_name: str,
manifest_yaml: str = "",
has_compose: bool = True,
) -> Path:
app_dir: Path = self.sites_dir / dir_name
app_dir.mkdir(parents=True, exist_ok=True)
if manifest_yaml:
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
if has_compose:
(app_dir / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8")
return app_dir
@pytest.fixture
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
sites = tmp_path / "Sites"
monkeypatch.setattr(engine, "SITES_DIR", str(sites))
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
return sites
@pytest.fixture
def app_factory(mock_sites_dir: Path) -> AppFactory:
"""Fixture that provides the AppFactory instance to test"""
return AppFactory(mock_sites_dir)
@pytest.fixture
def mock_core_dir(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch
) -> Path:
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
core = tmp_path / "CORE"
core.mkdir(parents=True, exist_ok=True)
return core
## GREEN TEST: Existing implementation should not break
def test_resolve_app_hierarchy(app_factory: AppFactory):
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: media-server
aliases:
- movies
""",
)
apps = engine.get_sites_apps()
assert engine.resolve_app("media-server", apps) is not None
assert engine.resolve_app("movies", apps) is not None
assert engine.resolve_app("homelab-jellyfin", apps) is not None
assert engine.resolve_app("unknown", apps) is None
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
"""Ensure app.yaml values successfully override the system defaults"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: custom-app
domain: custom.roadtotech.local
auth: false
visible: false
networks:
- custom-net
"""
)
apps = engine.get_sites_apps()
app = engine.resolve_app("custom-app", apps)
assert app is not None
assert app.domain == "custom.roadtotech.local"
assert app.auth is False
assert app.networks == ["custom-net"]
def test_sites_app_normalization(app_factory: AppFactory):
"""Ensure missing or badly typed manifest fields are safely normalized"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: testapp
# Missing domain - should fallback to <name>.roadtotech.me
aliases: single-string-alias # should become a list[str]
auth: "False" # should evaluate based on boolean casting
homepage:
weight: "99" # this should be casted as an int
"""
)
apps = engine.get_sites_apps()
app = engine.resolve_app("testapp", apps)
assert app is not None
assert app.name == "testapp"
assert app.domain == "testapp.mydomain.test"
assert app.aliases == ["single-string-alias"]
assert app.auth is True
assert app.homepage is not None
assert app.homepage.weight == 99
## RED TESTS: TDD Goals for next implementation
@pytest.mark.xfail(reason="TDD in progress: get_docker_status not yet implemented")
def test_docker_status_parser_running(monkeypatch):
"""
TDD Goal: Port `get_docker_status` to V2
It must shell out to `docker-compse ps` and `docker inspect`
then return the correct UI badge
"""
def mock_run(args, **kwargs):
"""Mocking a running"""
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "true\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🟢 Running (1)"
@pytest.mark.xfail(reason="TDD in progress: cmd_sync_homepage not yet implemented")
def test_homepage_sync_groups_and_sorts_correctly(
mock_core_dir: Path,
app_factory: AppFactory,
monkeypatch):
"""
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
It must group by `homepage.group` and sort by `homepage.weight`.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
app_factory.create(
dir_name="homelab-app1",
manifest_yaml="""
name: App1
domain: app1.local.test
homepage:
title: App1
group: Group B
weight: 20
"""
)
app_factory.create(
dir_name="homelab-app2",
manifest_yaml="""
name: App2
domain: app2.local.test
homepage:
title: App2
group: Group A
weight: 10
"""
)
monkeypatch.setattr(engine, "get_core_services", list)
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists(), "The services.yaml file must be generated"
content = output_file.read_text()
assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B
assert "App2" in content # App 2 is in the file
Generated
+3
View File
@@ -0,0 +1,3 @@
version = 1
revision = 3
requires-python = ">=3.11"