refactor(homelab): restructure project taxonomy and rewrite documentation
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s

- Formalize tripartite project organization (guides/, plans/, discussions/)
- Localize homelab architectural discussions and restructure dynu-monitor into a trade-off discussion and active Rust daemon plan
- Author core operational runbooks: onboarding services, managing secrets/Authelia users, and server maintenance
- Rewrite projects/homelab/README with 4-tier architecture, Gitea forge links, open discussions, and active WIP tracking
- Standardize subproject nesting under nixos/ and update AGENTS.md conventions
This commit is contained in:
kiskaadee committed 2026-09-11 22:01:53 -05:00
1 parent 310c2435c2
commit 5b677880e9
27 files changed
+693 -383

No files matched your search

+20 -3
View File
@@ -34,11 +34,28 @@ Sub-directories:
Knowledge documents do not become the canonical location for project-specific information. A knowledge document describes *what something is*; a project document describes *how this project uses it*. Knowledge documents do not become the canonical location for project-specific information. A knowledge document describes *what something is*; a project document describes *how this project uses it*.
### `projects/` ### `projects/`
Each project lives in its own sub-folder (e.g., `projects/homelab/`, `projects/magnetflix/`). The canonical entrypoint and landing page for any project must always be named `README.md` (e.g., `projects/homelab/README.md`) so that documentation renderers (such as `doc2site`) automatically compile it as the directory's index/landing page. Do not use `overview.md`. Each project lives in its own sub-folder (e.g., `projects/homelab/`, `projects/nixos/`, `projects/magnetflix/`). The canonical entrypoint and landing page for any project must always be named `README.md` (e.g., `projects/homelab/README.md`) so that documentation renderers (such as `doc2site`) automatically compile it as the directory's index/landing page. Do not use `overview.md`.
Projects may have their own `plans/`, `guides/`, `decisions/`, or `research/` sub-directories. #### Standard Project Directory Structure
Every project follows a three-part lifecycle structure under its folder:
The folder establishes context (ownership/locality). The document's `type` field establishes its semantic role. 1. **`discussions/` — "Why & What If?"**
- Architectural inquiries, problem statements, exploratory trade-off analyses, and evaluation of alternative paths (Model A vs. Model B).
- *Format*: Problem Statement → Context & Analysis → Options Evaluation (Pros & Cons) → Consensus / Resolution / Open Questions.
- *Role*: The foundation from which actionable plans originate.
- *Frontmatter*: `type: discussion`, `project: <name>`, `date: YYYY-MM-DD`.
2. **`plans/` — "How & When?"**
- Actionable implementation roadmaps, milestone breakdowns, and phased technical executions.
- *Prerequisite*: A plan should ideally be the concrete output of a resolved discussion.
- *Frontmatter*: `type: plan`, `status: draft | active | completed | abandoned`, `project: <name>`.
3. **`guides/` — "How to Use & Operate?"**
- Practical, operational runbooks and user-facing standard operating procedures (SOPs).
- *Content*: Answers concrete operational questions: *How to deploy a new service*, *How to rotate secrets*, *How to troubleshoot WAN rotation*. A guide explains how to **use and maintain** existing capabilities, not how to architect or implement new ones.
- *Frontmatter*: `type: guide`, `project: <name>`.
The folder establishes context (ownership/locality). The document's `type` field establishes its semantic role. Projects may reference documents in other projects via relative links.
### `records/` ### `records/`
Historical artifacts. The original messy thinking is worth preserving — often what you want to recover later is not just the conclusion, but *why* you reached it. Historical artifacts. The original messy thinking is worth preserving — often what you want to recover later is not just the conclusion, but *why* you reached it.
+2 -2
View File
@@ -56,8 +56,8 @@ projects/
**Key documents:** **Key documents:**
- [NixOS Fleet Overview](projects/nixos/README.md) - [NixOS Fleet Overview](projects/nixos/README.md)
- [Homelab Overview](projects/homelab/README.md) - [Homelab Overview](projects/homelab/README.md)
- [Dynu Monitor Overview](projects/dynu-monitor/README.md) - [Dynu Monitor Overview](projects/homelab/plans/dynu-monitor/README.md)
- [New-Repo CLI Overview](projects/new-repo/README.md) - [New-Repo CLI Overview](projects/nixos/new-repo/README.md)
- [MagNetFlix Overview](projects/magnetflix/README.md) - [MagNetFlix Overview](projects/magnetflix/README.md)
- [Nekoweb Overview](projects/nekoweb/README.md) - [Nekoweb Overview](projects/nekoweb/README.md)
-81
View File
@@ -1,81 +0,0 @@
---
type: project
status: active
tags:
- dynu
- ddns
- rust
- python
- homelab
---
# 🔄 dynu-monitor — High-Frequency Smart DDNS Monitor
## 🎯 Project Overview
`dynu-monitor` is a lightweight, local-first dynamic DNS change detector and smart trigger daemon. It monitors the machine's public IPv4 address and triggers dynamic DNS updates (via `ddclient.service`) only when a verified IP change has occurred.
By acting as a local gatekeeper in front of the DNS updater, it prevents unnecessary API spam to DNS providers, avoids IP change detection latency, and distributes external IP lookup queries across multiple external echo services using a stateful round-robin rotation strategy.
---
## 🏛️ System Architecture
```mermaid
sequenceDiagram
autonumber
participant Timer as systemd.timers.dynu-monitor (30s)
participant Monitor as dynu-ip-monitor
participant State as /var/lib/dynu/state.json
participant Resolvers as IP Resolvers (Round-Robin Pool)
participant History as /var/lib/dynu/ip_history.jsonl
participant DDClient as ddclient.service
Timer->>Monitor: Trigger execution
Monitor->>State: Read last successful provider index & last IP
Monitor->>Resolvers: Query next provider (index + 1 mod N)
alt Provider succeeds
Resolvers-->>Monitor: Valid Public IPv4
Monitor->>State: Persist updated provider index
else Provider fails
Monitor->>Resolvers: Fallback to next provider in sequence
end
alt IP changed (current_ip != last_ip)
Monitor->>DDClient: systemctl start ddclient.service
DDClient-->>Monitor: DDNS record updated
Monitor->>History: Record transition event (status: success)
Monitor->>State: Update last_ip = current_ip
else IP unchanged
Monitor->>Monitor: Exit 0 (zero API overhead)
end
```
---
## 🗺️ Implementation Tracks
The project spans two iterative phases:
### 1. Python / NixOS Implementation *(Completed)*
- **Status**: Completed and verified on branch `refactor/dynu-monitor`.
- **Key Features**:
- 30-second polling interval via `systemd.timers.dynu-monitor`.
- Stateful round-robin rotation across 5 public providers (`api.ipify.org`, `icanhazip.com`, `ifconfig.me`, `checkip.dynu.com`, `wtfismyip.com`).
- Atomic persistence to `/var/lib/dynu/state.json`.
- Modernized UTC timezone handling (`datetime.now(timezone.utc)`).
- **Documentation**: [**High-Frequency Provider-Rotating Monitor Plan**](plans/provider-rotating-monitor-plan.md)
### 2. Standalone Rust Binary *(Active / In Planning)*
- **Status**: Planning and domain modeling phase at `/home/kiskaadee/Projects/active/dynu-monitor`.
- **Goals**:
- Clean separation between domain orchestration (`IpMonitorService`) and external infrastructure (`IpResolver`, `StateRepository`, `DdnsUpdater`).
- Zero Python runtime dependencies for minimal footprint on headless servers.
- Comprehensive unit test coverage with dependency injection and trait mocks.
- **Documentation**: [**Rust Migration Plan & Milestones**](plans/rust-migration-plan.md)
---
## 📑 Project Documents & Plans
- [**High-Frequency Provider-Rotating Monitor Plan & Walkthrough**](plans/provider-rotating-monitor-plan.md) — Architectural design, 5-provider pool, systemd timer config, and verification results for the Python implementation.
- [**Rust Migration Plan**](plans/rust-migration-plan.md) — Architecture, domain entities, invariants, and phased milestones for the native Rust daemon.
@@ -1,119 +0,0 @@
---
type: plan
status: completed
project: dynu-monitor
tags:
- dynu
- ddns
- python
- nixos
- architecture
---
# 🔄 High-Frequency Provider-Rotating Dynu DDNS Monitor
## 🎯 Motivation & Goals
The default Dynu DDNS change detection mechanism operated on a 30-minute interval and queried a single external IP discovery provider. During ISP WAN IP rotations, services on `roadtotech.me` remained inaccessible for extended durations before the rotation was detected.
### Architectural Objectives:
1. **Near-Instant WAN Change Detection**: Reduce the polling interval from 30 minutes to **30 seconds** so that WAN rotations are detected in seconds.
2. **Stateful Round-Robin Provider Rotation**: Query an expanded pool of 5 reputable echo providers sequentially. This distributes requests such that each provider is queried at most once every 2.5 minutes (~24 requests/hour), well within public terms of service.
3. **Atomic State Persistence**: Save current IP and resolver rotation index to `/var/lib/dynu/state.json`.
4. **Modernized Datetime Handling**: Replace deprecated `datetime.utcnow()` with `datetime.now(timezone.utc)`.
---
## 🏛️ Architecture & Sequence
```mermaid
sequenceDiagram
autonumber
participant Timer as systemd.timers.dynu-monitor (30s)
participant Monitor as dynu-ip-monitor (Python)
participant State as /var/lib/dynu/state.json
participant Resolvers as IP Resolvers (Round-Robin Pool)
participant History as /var/lib/dynu/ip_history.jsonl
participant DDClient as ddclient.service
Timer->>Monitor: Trigger execution
Monitor->>State: Read last successful provider index & last IP
Monitor->>Resolvers: Query next provider (index + 1 mod N)
alt Provider succeeds
Resolvers-->>Monitor: Valid Public IPv4
Monitor->>State: Persist updated provider index
else Provider fails
Monitor->>Resolvers: Fallback to next provider in sequence
end
alt IP changed (current_ip != last_ip)
Monitor->>DDClient: systemctl start ddclient.service
DDClient-->>Monitor: DDNS record updated
Monitor->>History: Record transition event (status: success)
Monitor->>State: Update last_ip = current_ip
else IP unchanged
Monitor->>Monitor: Exit 0 (zero API overhead)
end
```
---
## 🛠️ Implementation Details
### 1. Resolver Pool & Script (`hosts/server/monitor.py`)
- **Configured Resolver Providers**:
1. `https://api.ipify.org`
2. `https://icanhazip.com`
3. `https://ifconfig.me/ip`
4. `https://checkip.dynu.com`
5. `https://wtfismyip.com/text`
- **State Persistence**: Atomic read and write to `STATE_FILE` (`/var/lib/dynu/state.json`):
```json
{
"last_provider_index": 2,
"last_ip": "186.168.137.93"
}
```
- **Fallback Ring Buffer**: Circular traversal starting at `(last_provider_index + 1) % len(PROVIDERS)` with automatic fallback to next providers upon timeout or connection errors.
### 2. Declarative Systemd Units (`hosts/server/dynu.nix`)
- **Timer Configuration**:
```nix
systemd.timers.dynu-monitor = {
description = "Timer for Dynu DDNS Smart IP Change Monitor";
timerConfig = {
OnBootSec = "10s";
OnUnitActiveSec = "30s";
AccuracySec = "1s";
Persistent = true;
};
wantedBy = [ "timers.target" ];
};
```
- **Service Environment**:
```nix
systemd.services.dynu-monitor.serviceConfig.Environment = [
"STATE_FILE=/var/lib/dynu/state.json"
];
```
---
## 🔄 Verification & Testing
### 1. Flake & Derivation Builds
```bash
# Validate flake expressions
nix flake check
# Dry build server host configuration
nix build .#nixosConfigurations.server.config.system.build.toplevel --no-link
# Dry build workstation configurations
nix build .#nixosConfigurations.desktop.config.system.build.toplevel --no-link
nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link
```
### 2. Runtime Verification
- **Timer Frequency**: `systemctl list-timers dynu-monitor.timer` shows active 30s recurrence.
- **Provider Rotation**: `journalctl -u dynu-monitor.service -f` logs successive queries rotating cleanly across the 5 resolvers.
- **State File**: `/var/lib/dynu/state.json` updates atomically after each successful poll.
@@ -1,95 +0,0 @@
---
type: plan
status: active
project: dynu-monitor
tags:
- dynu
- ddns
- rust
- migration
---
# 🦀 Rust Migration Plan: Standalone `dynu-monitor` Daemon
## 🎯 Motivation & Objectives
While the Python implementation in `hosts/server/monitor.py` verified the core logic (30-second polling, 5-provider round-robin rotation, atomic state persistence), migrating the monitor to a native **Rust** binary provides:
1. **Zero Runtime Dependencies**: Removes Python runtime and interpreter startup overhead from headless NixOS servers.
2. **Strict Type Safety & Robust Error Handling**: Eliminates runtime type errors and unhandled exceptions using `Option<T>`, `Result<T, E>`, and custom error types.
3. **Decoupled Architecture**: Clean domain orchestration (`IpMonitorService`) abstracted from I/O mechanisms via traits for unit testing without network or systemd dependencies.
4. **Hands-on Rust Learning**: Serves as a practical project for idiomatic Rust patterns (traits, structs/enums, dependency injection, and Cargo).
**Project Location**: `/home/kiskaadee/Projects/active/dynu-monitor`
---
## 🏛️ Target Architecture
```text
┌───────────────┐
│ main.rs │
│ (Composition) │
└───────┬───────┘
│
▼
┌───────────────┐
│IpMonitorService│
│(Domain Engine)│
└───────┬───────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
IpResolver StateRepository DdnsUpdater
│ │ │
▼ ▼ ▼
HTTP JSON systemctl
│
▼
HistoryRepository
│
▼
JSONL
```
---
## 🔒 Critical Invariants
1. `last_ip` strictly represents the IP address for which a DDNS update **completed successfully**.
2. Discovering a new IP does **not** update `last_ip` until `ddclient.service` exits with success.
3. A failed DDNS update preserves the previous `last_ip` in `state.json`.
4. If current IP matches `last_ip`, `ddclient.service` is never invoked.
5. Provider rotation index is persisted on every poll independently of IP changes.
---
## 📋 Implementation Milestones
### Milestone 1: Domain Core & Provider Rotation
- Define `MonitorState`, `IpDiscoveryResult`, and `HistoryEntry`.
- Implement IPv4 validation and circular round-robin provider rotation logic.
- Pure Rust standard library with zero external dependencies.
### Milestone 2: State Persistence
- Implement `StateRepository` trait and atomic JSON file writer (`state.json.tmp` -> `state.json`).
- Ensure state loading gracefully handles missing or corrupt initial state.
### Milestone 3: Application Orchestration (`IpMonitorService`)
- Implement `IpMonitorService` coordinating discovery, comparison, update dispatch, and state recording.
- Write full unit test suite with mock dependencies for resolvers and updaters.
### Milestone 4: HTTP Resolvers & Fallbacks
- Implement `IpResolver` using `reqwest` (blocking) or lightweight HTTP client.
- Implement fallback sequence across the 5 providers upon timeouts or non-200 responses.
### Milestone 5: Systemd Updater
- Implement `DdnsUpdater` invoking `systemctl start --wait ddclient.service`.
- Handle subprocess exit codes and timeout safety.
### Milestone 6: Audit History Logging
- Implement `HistoryRepository` appending structured events to `/var/lib/dynu/ip_history.jsonl`.
### Milestone 7: NixOS Integration & Packaging
- Package `dynu-monitor` via Nix flake (`pkgs.rustPlatform.buildRustPackage`).
- Replace Python `dynu-ip-monitor` derivation in `hosts/server/dynu.nix`.
- Verify 30-second timer execution and live rotation on the server.
+86 -46
View File
@@ -5,63 +5,103 @@ tags:
- homelab - homelab
- infrastructure - infrastructure
--- ---
# 🌐 Homelab & Infrastructure Planning
This project documents the architectural roadmaps, infrastructure designs, deployment automation, and system administration workflows for the homelab ecosystem. # 🌐 Homelab Ecosystem & Core Infrastructure
The **Homelab** project encompasses the architecture, automation, deployment pipelines, and operational runbooks powering the 24/7 personal infrastructure ecosystem hosted at `roadtotech.me`.
The environment runs on dedicated hardware as a declarative NixOS appliance, providing self-hosted productivity tools, internal developer platforms, edge routing, and automated GitOps workflows.
--- ---
## 📑 Plans & Execution Roadmaps ## 🏛️ System Topology & Architecture
### 🖥️ Server 24/7 & Infrastructure The homelab is organized into four decoupled architectural layers to isolate failures and maintain zero-downtime operations:
1. 🟢 [**NixOS Server & Laptop Migration**](plans/server-24-7/nixos-server-laptop-migration.md) `[Completed]`
- Headless conversion of the server host and laptop workstation provisioning.
- Declarative Flake management across `hosts/server` and `hosts/laptop`.
2. 🟢 [**Domain Migration (`roadtotech.me`)**](plans/server-24-7/domain-migration-roadtotech.md) `[Completed]`
- Cutover from legacy `arch-services.mywire.org` to apex `roadtotech.me`.
- Wildcard SSL via Traefik ACME and Authelia cookie updates.
3. 🟢 [**Production Folder Structure Reorganization**](plans/server-24-7/folder-structure-reorganization.md) `[Completed]`
- Established strict production boundaries: `~/Core`, `~/Sites`, `~/Brain`, and `~/Config`.
4. 🟡 [**LVM Storage Optimization & Partition Resizing Strategy**](plans/server-24-7/lvm-storage-optimization-and-resizing.md) `[Active]`
- Storage topology analysis, desktop indexer cache reclamation, and zero-data-loss LVM resize runbook.
### 📦 Orchestration (`appctl`) 1. **Edge & Security Layer**:
1. 🟢 [**Core & Sites Cutover and Testing Plan**](plans/appctl/core-sites-cutover-testing-plan.md) `[Completed]` - **Traefik Reverse Proxy**: Dynamic ingress routing over HTTPS with automated Let's Encrypt wildcard TLS certificates (`*.roadtotech.me`).
- Zero-downtime, progressive cutover runbook from `~/Deployments` to decoupled `~/Core` and `~/Sites`. - **Authelia SSO**: ForwardAuth single sign-on with multi-factor authentication (2FA) protecting private services and dashboards.
2. 🟢 [**appctl Refactor & Decentralized `app.yaml` Metadata Architecture**](plans/appctl/refactor-and-metadata-sync.md) `[Completed]` - **Dynu Dynamic DNS**: Automated WAN address synchronization and fallback monitoring.
- Decentralized service manifests, canonical aliasing, and Homepage `services.yaml` compilation. 2. **Core Control Plane (`~/Core`)**:
3. 🟢 [**appctl Git Synchronization & Full-Stack Lifecycle Strategy**](plans/appctl/git-sync-and-lifecycle.md) `[Completed]` - Central homelab services managed as a declarative NixOS appliance, including Gitea (Git forge & CI/CD runner), Nextcloud, Vaultwarden, Homepage dashboard, and deployment webhooks.
- Real-time Git tracking status (`✓ Synced`, `⬆ Ahead`, `⬇ Behind`, `* Dirty`), `--fetch`, and atomic `appctl update`. 3. **Workload Plane (`~/Sites`)**:
- Autonomous, containerized application stacks (Docker Compose) completely decoupled from Core infrastructure. Each service repository declares its own metadata, routing rules, and lifecycle via an `app.yaml` manifest.
4. **Host Foundation**:
- Headless NixOS host system configured with encrypted secrets via SOPS-nix (`age`), strict firewall isolation, and standardized systemd timers for maintenance.
---
## 📍 Source Code & Repositories
| Target | Location / URL | Description |
| :--- | :--- | :--- |
| **Gitea Forge** | [homelab-core](https://gitea.roadtotech.me/kiskaadee/homelab-core) | Primary Git repository housing the NixOS appliance and Core services |
| **Clone (SSH)** | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-core.git` | Developer clone URL using SSH port 2223 |
| **Workstation Path** | `/home/kiskaadee/Projects/active/homelab/Core` | Active local development checkout on laptop workstation |
| **Production Target** | `server-remote:~/Core` | Production deployment checkout on the 24/7 server host |
---
## 💬 Open Discussions
Architectural inquiries and problem statements currently under evaluation that have **not yet produced an active implementation plan**:
* ❓ [**WhatsApp & Telegram AI Assistant Backend Architecture**](discussions/chatbot-assistant-design.md)
- **Focus**: Evaluates architecture, webhook ingress, and trade-offs between Telegram Bot API and WhatsApp Cloud API for a personal AI assistant microservice (`~/Sites/homelab-assistant`) connected to the Brain vault.
- **Current Status**: Open inquiry examining authorization models, message formatting, cron triggers, and RAG search capabilities before formalizing an implementation plan.
---
## 🚧 Work in Progress (Active Plans)
Implementation roadmaps currently in progress (`status: active`) that are actively being executed or scheduled for deployment:
1. 🟡 [**Architecture Consolidation & Hardening Roadmap**](plans/architecture-consolidation-roadmap.md) `[Active]`
- Formalizing the four-tier architectural boundaries, hardening the dynamic GitOps dispatcher with closed action enums, and codifying the `app.yaml` schema contract.
2. 🟡 [**Rust Daemon Migration Plan: Standalone `dynu-monitor`**](plans/dynu-monitor-rust-daemon.md) `[Active]`
- Implementing a standalone Rust daemon with 30-second polling and round-robin public DNS resolution across 5 independent providers (Cloudflare, Quad9, Google, OpenDNS, Dynu).
3. 🟡 [**Custom API Security Hardening & Threat Analysis**](plans/api-security-hardening.md) `[Active]`
- Defense-in-depth security hardening for custom microservice APIs (Learning Hub and Minecraft dashboard) using Authelia ForwardAuth, token validation, and rate limiting.
4. 🟡 [**Smart Selective Deployment Pipeline for Homelab Core**](plans/appctl/smart-deployment-pipeline.md) `[Active]` 4. 🟡 [**Smart Selective Deployment Pipeline for Homelab Core**](plans/appctl/smart-deployment-pipeline.md) `[Active]`
- Change-aware Gitea GitOps & CLI deployment, selective container restarts, and bash autocompletion sync. - Enhancing `appctl` and Gitea Actions with change-aware selective container restarts to prevent unnecessary service interruptions during routine deployments.
5. 🟡 [**GitHub to Gitea Automated Batch Migration Plan**](plans/gitea/github-to-gitea-migration-plan.md) `[Active]`
### 🍵 Gitea & GitOps - Automated migration tooling using `gh` and `tea` APIs to migrate ~35 repositories from GitHub to self-hosted Gitea with push mirrors for redundancy.
1. 🟢 [**CI/CD & Deployment Strategy**](plans/gitea/deployment-and-cicd-strategy.md) `[Completed]` 6. 🟡 [**LVM Storage Optimization & Partition Resizing Strategy**](plans/server-24-7/lvm-storage-optimization-and-resizing.md) `[Active]`
- Design of automated deployment pipelines, self-hosted Gitea runner, and dynamic webhook dispatching. - Storage space audit, disk cleanup runbooks, and a non-destructive LVM logical volume expansion procedure for the server's root filesystem.
2. 🟢 [**Real-Time Brain Synchronization & Gitea Push Mirroring**](plans/gitea/brain-sync-and-gitea-mirroring.md) `[Completed]`
- Pilot pipeline: zero-delay hooks, Gitea Actions CI, and instant reflection on `docs.roadtotech.me`.
3. 🟡 [**GitHub to Gitea Automated Batch Migration Plan**](plans/gitea/github-to-gitea-migration-plan.md) `[Active]`
- Batch migration automation (~35 repos) via `gh` and `tea` API, visibility retention, and recovery runbook.
--- ---
## 📑 Canonical Guides & Production References ## 🛠️ Canonical Guides & Runbooks
1. [**Homelab Architecture: Appctl & Decentralized Repositories**](guides/homelab-appctl-architecture.md) Operational runbooks and procedures for daily administration:
- The authoritative reference for `appctl`, `app.yaml` manifests, and multi-repo orchestration.
2. [**Dynamic Decentralized GitOps Dispatcher Architecture**](guides/homelab-gitops-dispatcher-architecture.md) * [**Onboarding a New Application Stack**](guides/onboarding-a-new-service.md) — Step-by-step procedure for deploying new Docker Compose services in `~/Sites` with `app.yaml` and Traefik routing.
- Zero-Core-restart webhook architecture on port 9000, dynamic discovery, and deployment primitives. * [**Managing Secrets and Authelia Users**](guides/managing-secrets-and-authelia-users.md) — Guide for editing SOPS-encrypted secrets and managing user authentication credentials.
3. [**Brain GitOps & Auto-Sync Deployment Pipeline**](guides/brain-gitops-deployment-pipeline.md) * [**Server Maintenance and System Updates Runbook**](guides/server-maintenance-and-updates.md) — Standard operating procedure for NixOS updates, garbage collection, and container pruning.
- End-to-end knowledge graph pipeline: local pre-commit gate, post-commit push, Gitea Actions CI, and live doc2site rendering. * [**Appctl & Application Manifests (`app.yaml`) User Guide**](guides/appctl-operations-and-manifest-guide.md) — Comprehensive reference for the `appctl` CLI tool and `app.yaml` schema.
4. [**Dynu DDNS Domain Configuration Troubleshooting Runbook**](guides/dynu-ddns-troubleshooting.md) * [**Brain GitOps & Auto-Sync Deployment Pipeline**](guides/brain-gitops-deployment-pipeline.md) — Technical runbook on how Brain commits automatically validate and publish to `docs.roadtotech.me`.
- Root cause analysis and resolution for WAN IP rotations, SOPS key authorization, and `ddclient` updates. * [**Dynu DDNS Domain Configuration Troubleshooting Runbook**](guides/dynu-ddns-troubleshooting.md) — Diagnostic and recovery steps for WAN address synchronization issues.
5. [**Custom API Security Hardening & Threat Analysis**](guides/custom-api-security-and-hardening.md)
- Attack surface review, Authelia ForwardAuth integration, rate limiting, and JWT fail-fast validation.
6. [**WhatsApp & Telegram AI Assistant Backend Architecture**](guides/chatbot-assistant-backend-architecture.md)
- Architecture, channel trade-offs (Telegram vs WhatsApp), APScheduler cron triggers, and Brain vault RAG integration.
--- ---
## 🏛️ Architectural Discussions & Records ## 🏛️ Completed Roadmaps & Resolved Discussions
* [Discussion: Gitea Git Credential Helper, Protocol Trade-Offs & Hybrid Backup Architecture](../../records/discussions/2026-09-gitea-git-helper-and-backup-strategy.md)
* [Discussion: NixOS Monorepo vs. Multi-Repo Architecture for Homelab & Workstations](../../records/discussions/2026-09-nixos-monorepo-vs-multirepo-architecture.md) Archived and foundational documentation for completed milestones:
### Resolved Architectural Discussions
* [**NixOS Monorepo vs. Multi-Repo Architecture**](discussions/nixos-monorepo-vs-multirepo.md) — Evaluated workstation and server decoupling; resolved via appliance migration.
* [**Decoupling `nixos-config` and `homelab-core`**](discussions/nixos-monorepo-decoupling.md) — Migration inventory and separation plan; resolved via repository split.
* [**Dynamic Decentralized GitOps Dispatcher Architecture**](discussions/gitops-dispatcher-architecture.md) — Decoupled deployment webhook design; implemented in production.
* [**Gitea Git Credential Helper and Backup Strategy**](discussions/gitea-credentials-and-backup-strategy.md) — Evaluated credential helpers and push mirroring; resolved via Git credential helper configuration.
* [**Dynu DDNS Polling Frequency and Rust Migration**](discussions/dynu-monitor-polling-and-language-tradeoffs.md) — Investigated polling intervals and language trade-offs; resolved via `dynu-monitor-rust-daemon.md` plan.
### Completed Plans
* 🟢 [**Turn `homelab-core` into a Declarative NixOS Appliance**](plans/nixos-appliance-migration.md)
* 🟢 [**Core & Sites Cutover and Testing Plan**](plans/appctl/core-sites-cutover-testing-plan.md)
* 🟢 [**appctl Refactor & Decentralized `app.yaml` Metadata Architecture**](plans/appctl/refactor-and-metadata-sync.md)
* 🟢 [**appctl Git Synchronization & Full-Stack Lifecycle Strategy**](plans/appctl/git-sync-and-lifecycle.md)
* 🟢 [**CI/CD & Deployment Strategy**](plans/gitea/deployment-and-cicd-strategy.md)
* 🟢 [**Real-Time Brain Synchronization & Gitea Push Mirroring**](plans/gitea/brain-sync-and-gitea-mirroring.md)
* 🟢 [**NixOS Server & Laptop Migration**](plans/server-24-7/nixos-server-laptop-migration.md)
* 🟢 [**Domain Migration (`roadtotech.me`)**](plans/server-24-7/domain-migration-roadtotech.md)
* 🟢 [**Production Folder Structure Reorganization**](plans/server-24-7/folder-structure-reorganization.md)
@@ -1,6 +1,7 @@
--- ---
type: guide type: discussion
project: homelab project: homelab
date: 2026-09-08
tags: tags:
- homelab - homelab
- ai - ai
@@ -0,0 +1,61 @@
---
type: discussion
project: homelab
date: 2026-09-11
tags:
- homelab
- dynu
- ddns
- python
- rust
- architecture
---
# 🔄 Discussion: Dynu DDNS Polling Frequency, Resolver Rotation, and Rust Migration
## 1. Problem Statement
The production Dynu dynamic DNS monitor on the server currently runs on a **30-minute systemd timer** (`OnUnitActiveSec = "30min"`) and queries a sequential fallback list of 4 external echo providers. When the residential ISP rotates the server's public WAN IPv4 address, external domains on `roadtotech.me` can remain unreachable for up to 30 minutes before the monitor detects the transition and triggers `ddclient.service`.
### Core Tension:
* **Speed of Recovery**: To minimize service downtime, the monitor should detect WAN rotations within **30 to 60 seconds**.
* **Provider Abuse & Rate Limits**: Polling a single public echo API (such as `api.ipify.org` or `icanhazip.com`) every 30 seconds yields 2,880 requests per day from a single IP, which risks temporary bans or API blocking.
* **Language & Runtime Overhead**: The current implementation is written in Python (`pkgs.writers.writePython3Bin`), invoking the full Python 3.14 interpreter and standard libraries on every execution of a headless server appliance.
---
## 2. Exploration: The 5-Provider Stateful Pool Prototype
On an experimental branch (`refactor/dynu-monitor`), an alternative Python prototype was designed:
* Increase systemd timer frequency to **30 seconds**.
* Distribute queries across an expanded pool of **5 external providers** (`api.ipify.org`, `icanhazip.com`, `ifconfig.me`, `checkip.dynu.com`, `wtfismyip.com`).
* Use a stateful round-robin pointer stored in `/var/lib/dynu/state.json`.
### Evaluation of the Prototype:
* **Pros**:
- Each individual provider is queried at most once every 2.5 minutes (~24 requests/hour), well within public usage guidelines.
- WAN rotations are detected in under 30 seconds.
* **Cons & Complications**:
- Requires writing local state back and forth from disk on every 30s tick.
- Python startup overhead running 2,880 times a day creates unnecessary CPU and I/O noise on a low-power home server.
- The prototype remained unmerged because maintaining complex state machines in an embedded Nix Python script is brittle.
---
## 3. The Resolution: Direct Migration to a Native Rust Daemon
Rather than merging the intermediate Python rewrite into `Core`, the preferred architectural path is to migrate `dynu-monitor` directly to a lightweight, compiled **Rust daemon**.
### Why Rust?
1. **Zero Runtime Dependencies**: The compiled binary requires no Python interpreter, virtualenv, or dynamic store dependencies, aligning with the headless appliance philosophy.
2. **Minimal Footprint**: A native daemon can either run as a persistent background process with an internal async timer (`tokio`), or as an ultra-fast oneshot binary with zero startup penalty.
3. **Decoupled Architecture**: Domain logic (`IpMonitorService`) is separated from I/O mechanisms (`IpResolver`, `StateRepository`, `DdnsUpdater`) via traits, allowing comprehensive unit testing without real network or systemd calls.
4. **Hands-on Rust Engineering**: Serves as a practical project for idiomatic Rust patterns (traits, structs/enums, dependency injection, and Cargo packaging in Nix).
---
## 4. Architectural Invariants for the Rust Implementation
1. **Gatekeeper Pattern**: `dynu-monitor` only triggers `ddclient.service` when a public IP change is verified.
2. **Update Confirmation**: `last_ip` in `state.json` is updated **only after** `ddclient` exits successfully. A failed update preserves the previous IP so retries continue.
3. **Graceful Resolver Failover**: If the current provider in the round-robin sequence fails or times out (5s), the daemon falls back to the next provider immediately without failing the tick.
@@ -1,6 +1,7 @@
--- ---
type: guide type: discussion
project: homelab project: homelab
date: 2026-09-08
tags: tags:
- homelab - homelab
- gitops - gitops
@@ -1,6 +1,6 @@
--- ---
type: discussion type: discussion
project: nixos project: homelab
tags: tags:
- nixos - nixos
- architecture - architecture
@@ -9,12 +9,20 @@ tags:
- git - git
--- ---
# 📦 Homelab Architecture: Appctl & Decentralized Repositories # 📦 Appctl & Application Manifests (`app.yaml`) User Guide
## 🎯 Architecture Model & Goals This guide covers everyday operations for managing containerized applications in `~/Sites` using the `appctl` CLI and authoring self-describing `app.yaml` service manifests.
1. **Decoupled Application Repositories (`~/Sites`)**: Each application lives in an isolated, independently version-controlled Git repository containing its own Docker Compose stack and self-describing `app.yaml` manifest.
2. **Hardened Control Plane (`~/Core`)**: Core reverse proxy (Traefik v3.6), authentication gateway (Authelia), container isolation (`socket-proxy`), management GUI (Portainer), and real-time logs (Dozzle). ---
3. **Decentralized Metadata & Orchestration (`appctl`)**: Unified CLI tool powered by Python/Bash that dynamically parses `app.yaml` manifests, manages aliases, injects environment configurations, monitors Git repository synchronization, and auto-compiles the Homepage dashboard (`services.yaml`).
## 🎯 What `appctl` Does
`appctl` is the central orchestration CLI on the server. It:
1. Discovers stacks in `~/Sites/` dynamically by scanning for `app.yaml`.
2. Resolves service aliases (`appctl up docs` or `appctl up doc2site`).
3. Injects shared environment variables and decrypted secrets from `/run/secrets/rendered/traefik-deployments.env`.
4. Tracks real-time Git synchronization status (`ahead`, `behind`, `dirty`).
5. Auto-compiles active services into the Homepage dashboard configuration (`homelab-dashboard/config/services.yaml`).
--- ---
@@ -174,37 +174,28 @@ creation_rules:
# Store the server's private age key (-t allows interactive sudo password prompt) # Store the server's private age key (-t allows interactive sudo password prompt)
ssh -t server-local "sudo nix run nixpkgs#ssh-to-age -- -private-key -i /etc/ssh/ssh_host_ed25519_key" ssh -t server-local "sudo nix run nixpkgs#ssh-to-age -- -private-key -i /etc/ssh/ssh_host_ed25519_key"
SOPS_AGE_KEY=<previous output> sops updatekeys hosts/server/secrets.yaml SOPS_AGE_KEY=<previous output> sops updatekeys nixos/secrets.yaml
``` ```
**4. Edit Encrypted Secrets**: **4. Edit Encrypted Secrets**:
```shell ```shell
sops hosts/server/secrets.yaml sops nixos/secrets.yaml
``` ```
Set `dynu_domain` to: Ensure `dynu` credentials match your account:
```yaml ```yaml
dynu_domain: roadtotech.me dynu:
domain: roadtotech.me
user: "your_username"
password: "your_password"
``` ```
**5. Deploy and Rebuild to Server**: **5. Deploy and Rebuild Server Appliance**:
To apply the configuration updates to the running server appliance:
A CI/CD pipeline has not been established yet. To apply the configuration, we'll trigger the upstream fetch via ssh and then rebuild the system.
```shell ```shell
# Review flake status # Switch to the new generation on the server
nix flake check sudo nixos-rebuild switch --flake ~/Core#server
# (or use the built-in alias: nix-switch)
# Once local changes are synced with upstream
ssh -t server-local \
"cd Config && \
git fetch && \
git pull"
# rebuild the NixOS system
ssh -t server-local \
"cd Config && \
sudo nixos-rebuild switch --flake .#server"
``` ```
**6. Force One-Off DDNS Update**: **6. Force One-Off DDNS Update**:
@@ -0,0 +1,130 @@
---
type: guide
project: homelab
tags:
- homelab
- sops
- secrets
- authelia
- auth
---
# 🔐 Managing Secrets and Authelia Users
This guide describes how to update encrypted runtime secrets, add or modify Authelia user accounts, and generate secure password hashes in the **Homelab Core** appliance.
---
## 🏛️ How Secrets Work in Homelab Core
All secrets are encrypted with [SOPS](https://github.com/getsops/sops) using [age](https://github.com/FiloSottile/age) keys and stored inside `nixos/secrets.yaml` in the `~/Core` repository.
At server boot, the `sops-nix` systemd module decrypts these secrets and renders them to RAM-backed environment files:
- `/run/secrets/rendered/homeserver.env` — Consumed by Core infrastructure (Traefik, Authelia, Socket-Proxy).
- `/run/secrets/rendered/traefik-deployments.env` — Consumed by application workloads via `appctl`.
- `/run/secrets/rendered/users.yml` — The user database mounted into the Authelia container.
---
## 👤 Adding or Modifying Authelia Users
Authelia users are declared declaratively in `~/Core/nixos/modules/homeserver.nix`, while their password hashes are stored encrypted in `nixos/secrets.yaml`.
### Step 1: Generate an Argon2 Password Hash
Run the official Authelia CLI in a temporary container to compute a secure Argon2id hash:
```bash
docker run --rm -it authelia/authelia:latest authelia crypto hash generate argon2
```
Enter your password when prompted. The output will look like:
```text
$argon2id$v=19$m=65536,t=3,p=4$qH...
```
### Step 2: Store the Password Hash in SOPS
1. Navigate to the core repository:
```bash
cd ~/Core
```
2. Open the encrypted secrets file:
```bash
sops nixos/secrets.yaml
```
3. Add the user's password hash under `authelia.users`:
```yaml
authelia:
users:
newuser:
password_hash: "$argon2id$v=19$m=65536,t=3,p=4$..."
```
4. Save and close. SOPS will re-encrypt the file automatically.
### Step 3: Register the User in `homeserver.nix`
Open `nixos/modules/homeserver.nix` and add the user metadata to `autheliaUsers`:
```nix
autheliaUsers = {
# Existing users...
newuser = {
displayName = "New User";
email = "newuser@example.com";
groups = [ "users" ]; # or [ "admins" "dev" ]
passwordPlaceholder = config.sops.placeholder."authelia/users/newuser/password_hash";
};
};
```
Also register the secret key in `sops.secrets`:
```nix
sops.secrets = lib.genAttrs [
# Existing secrets...
"authelia/users/newuser/password_hash"
] (name: { owner = "kiskaadee"; });
```
### Step 4: Apply the Update
Rebuild the NixOS server generation to regenerate `/run/secrets/rendered/users.yml` and reload Authelia:
```bash
sudo nixos-rebuild switch --flake ~/Core#server
docker restart authelia
```
---
## 🔑 Updating General Secrets (Tokens, DB Passwords, API Keys)
To update API keys or database passwords:
1. Open the encrypted file:
```bash
sops ~/Core/nixos/secrets.yaml
```
2. Edit the required value (e.g. `dynu/api_key`, `postgres/password`).
3. Save and close.
4. Apply changes to the host:
```bash
sudo nixos-rebuild switch --flake ~/Core#server
```
5. Restart affected container stacks using `appctl`:
```bash
appctl restart <service-name>
```
---
## 🚨 Troubleshooting Secret Decryption
If a container fails to start due to missing environment variables:
1. Verify rendered secret files exist on the host:
```bash
sudo ls -la /run/secrets/rendered/
```
2. Inspect the content of the generated environment file:
```bash
sudo head /run/secrets/rendered/homeserver.env
```
3. Check `sops-nix` activation logs:
```bash
systemctl status sops-nix.service
```
@@ -0,0 +1,143 @@
---
type: guide
project: homelab
tags:
- homelab
- appctl
- traefik
- docker
- onboarding
---
# 🚀 Onboarding a New Application to the Homelab
This guide provides the complete, step-by-step procedure for deploying a new web service into the `roadtotech.me` homelab ecosystem, integrating it with the **Traefik** edge proxy, **Authelia SSO**, and the **`appctl`** orchestration tool.
---
## 🏗️ The 4-Step Onboarding Workflow
Deploying a new application consists of 4 steps:
1. **Create the application repository in `~/Sites/<app>`**
2. **Author the `app.yaml` manifest**
3. **Author the `docker-compose.yml` with Traefik routing labels**
4. **Deploy and verify using `appctl`**
---
## Step 1: Create the Project Repository
All user applications reside in independent repositories under `/home/kiskaadee/Sites/`:
```bash
mkdir -p ~/Sites/homelab-myapp
cd ~/Sites/homelab-myapp
git init -b main
```
---
## Step 2: Author the `app.yaml` Manifest
Create `~/Sites/homelab-myapp/app.yaml`. This file describes your application metadata, CLI aliases, and presentation card for the Homepage dashboard:
```yaml
name: "myapp"
aliases:
- "my-app"
- "custom-app"
domain: "myapp.roadtotech.me"
description: "My New Self-Hosted Web Application"
visible: true # Set to true to display on Homepage dashboard
auth: true # Indicates Authelia protection is enabled
networks:
- proxy-net
env:
CUSTOM_SETTING: "standard_value"
homepage:
title: "My App"
group: "Tools & Utilities" # Dashboard category
icon: "custom.png" # Icon name or URL
container: "myapp"
weight: 40 # Sort order in the dashboard
deployment:
branch: "main"
actions:
- git_pull
- compose_up
```
---
## Step 3: Author the `docker-compose.yml`
Create `~/Sites/homelab-myapp/docker-compose.yml`. Applications connect to Traefik via the external `proxy-net` Docker network.
### Example: Application with Authelia SSO Protection (`auth: true`)
```yaml
services:
myapp:
image: myapp/image:latest
container_name: myapp
restart: unless-stopped
networks:
- proxy-net
environment:
- PORT=8080
- DOMAIN_SUFFIX=${DOMAIN_SUFFIX:-roadtotech.me}
labels:
- "traefik.enable=true"
# 1. Secure HTTPS Entrypoint
- "traefik.http.routers.myapp.rule=Host(`myapp.${DOMAIN_SUFFIX:-roadtotech.me}`)"
- "traefik.http.routers.myapp.entrypoints=websecure"
- "traefik.http.routers.myapp.tls=true"
- "traefik.http.routers.myapp.service=myapp-svc"
# 2. Attach Authelia SSO ForwardAuth Middleware
- "traefik.http.routers.myapp.middlewares=authelia-auth@docker"
# 3. HTTP to HTTPS Automatic Redirect Router
- "traefik.http.routers.myapp-red.rule=Host(`myapp.${DOMAIN_SUFFIX:-roadtotech.me}`)"
- "traefik.http.routers.myapp-red.entrypoints=web"
- "traefik.http.routers.myapp-red.middlewares=https-redirect@docker"
# 4. Target Service Port (inside the container)
- "traefik.http.services.myapp-svc.loadbalancer.server.port=8080"
networks:
proxy-net:
name: ${PROXY_NETWORK:-proxy-net}
external: true
```
> **Note on Public Apps**: If your app has its own native authentication (like Jellyfin or Gitea) or is public, simply omit the `authelia-auth@docker` middleware label.
---
## Step 4: Deploy and Verify with `appctl`
1. Validate the Compose syntax:
```bash
appctl config myapp
```
2. Start the application stack:
```bash
appctl up myapp
```
*`appctl` automatically injects shared environment variables from `/run/secrets/rendered/traefik-deployments.env` and triggers `appctl sync` to register the new card in Homepage.*
3. Inspect running status and logs:
```bash
appctl info myapp
appctl logs myapp
```
4. Verify in the browser:
Navigate to `https://myapp.roadtotech.me`. Traefik will negotiate a wildcard certificate automatically, and Authelia will prompt for credentials if gated.
@@ -0,0 +1,125 @@
---
type: guide
project: homelab
tags:
- homelab
- nixos
- maintenance
- systemd
- docker
---
# 🛠️ Server Maintenance and System Updates Runbook
This runbook outlines routine maintenance procedures for the **Homelab Core** appliance, including NixOS system upgrades, service health verification, garbage collection, and Docker pruning.
---
## 🔄 Updating the NixOS Server Appliance
The server operating system is defined entirely inside `~/Core`.
### Step 1: Update Flake Inputs
To fetch the latest versions of Nixpkgs and `sops-nix`:
```bash
cd ~/Core
nix flake update
```
### Step 2: Validate the Build Dryly
Always dry-build before switching to catch compilation, syntax, or package evaluation errors:
```bash
nix flake check
nix build .#nixosConfigurations.server.config.system.build.toplevel --no-link
```
### Step 3: Switch to the New System Generation
Once the dry build completes cleanly:
```bash
sudo nixos-rebuild switch --flake ~/Core#server
# (or simply run: nix-switch)
```
---
## 🏥 Post-Update Health Checklist
Run this quick verification checklist following any system switch or server reboot:
1. **Systemd Daemon Health**:
Ensure no core background units failed:
```bash
systemctl --failed
```
2. **Core Homelab Stack**:
Verify Traefik, Authelia, and the control plane containers are active:
```bash
systemctl status homeserver-core.service
```
3. **Dynamic DNS (Dynu) Monitor**:
Ensure the IP change detector timer and service are active:
```bash
systemctl status dynu-monitor.timer
systemctl status dynu-monitor.service
```
4. **GitOps Webhook Dispatcher**:
Verify the webhook listener is listening on port 9000:
```bash
systemctl status homelab-gitops.service
```
5. **Secrets Integrity**:
Verify rendered environment files were generated in RAM:
```bash
sudo ls -la /run/secrets/rendered/
```
6. **Application Workload Status**:
Inspect the status of all application stacks:
```bash
appctl list
```
---
## 🧹 Disk Space Reclamation & Garbage Collection
Over time, older Nix generations, build artifacts, and Docker layers accumulate on disk. Follow this clean-up routine:
### 1. Collect Nix Garbage
To prune unreachable store paths and older generations:
```bash
# Delete older system generations (older than 7 days)
sudo nix-env --delete-generations +7d --profile /nix/var/nix/profiles/system
# Prune the store
sudo nix-collect-garbage -d
```
### 2. Prune Unused Docker Resources
Remove dangling container images, stopped containers, and build cache:
```bash
# Prune dangling images and build cache safely
docker system prune -a --volumes --filter "until=168h"
```
*(Only prunes containers stopped for longer than 7 days).*
---
## 🚨 Emergency System Rollback
If a newly applied NixOS generation causes system issues:
```bash
# Roll back to the previous generation immediately
sudo nixos-rebuild switch --rollback
```
*(Or select the previous generation from the systemd-boot menu upon reboot).*
@@ -1,5 +1,6 @@
--- ---
type: guide type: plan
status: active
project: homelab project: homelab
tags: tags:
- homelab - homelab
@@ -93,4 +93,4 @@ appctl update --all
--- ---
## 🔗 Production Guide ## 🔗 Production Guide
* [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/homelab-appctl-architecture.md) * [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/appctl-operations-and-manifest-guide.md)
@@ -88,4 +88,4 @@ All 11 homelab applications will include an `app.yaml` defining their identity,
--- ---
## 🔗 Production Guide ## 🔗 Production Guide
* [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/homelab-appctl-architecture.md) * [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/appctl-operations-and-manifest-guide.md)
@@ -0,0 +1,86 @@
---
type: plan
status: active
project: homelab
tags:
- homelab
- dynu
- ddns
- rust
- migration
---
# 🦀 Rust Daemon Migration Plan: Standalone `dynu-monitor`
## 🎯 Goal Description
Migrate the dynamic DNS gatekeeper daemon from the current Python script to a native, statically compiled **Rust daemon** located at `/home/kiskaadee/Projects/active/dynu-monitor`.
This implementation introduces high-frequency 30-second polling and stateful round-robin resolver rotation across 5 public echo providers while eliminating Python interpreter overhead on the headless server.
---
## 🏛️ Target Domain Architecture
```
┌────────────────────────┐
│ main.rs │
│ (Dependency Wiring) │
└───────────┬────────────┘
│
▼
┌────────────────────────┐
│ IpMonitorService │
│ (Domain Core) │
└───────────┬────────────┘
│
┌────────────────┼────────────────┐
▼ ▼ ▼
Box<dyn IpResolver> Box<dyn StateRepo> Box<dyn DdnsUpdater>
│ │ │
▼ ▼ ▼
HttpEchoPool StateFile Systemctl
(5 endpoints) (state.json) (ddclient.service)
│
▼
HistoryFile
(ip_history.jsonl)
```
---
## 🔒 Non-Negotiable Invariants
1. `last_ip` strictly represents the IP address for which a DDNS update **completed successfully**.
2. Discovering a new IP does **not** update `last_ip` until `ddclient.service` exits with code 0.
3. A failed DDNS update preserves the previous `last_ip` in `state.json` to trigger a retry on the next tick.
4. Resolver queries must enforce a strict 5-second timeout to prevent stalling the monitoring loop.
---
## 🗺️ Phased Implementation Milestones
### Milestone 1: Domain Entities & In-Memory Logic *(In Progress)*
- [x] Define domain types: `Ipv4Addr`, `ProviderId`, `MonitorEvent`.
- [ ] Implement `IpMonitorService` pure business logic.
- [ ] Mock traits `MockIpResolver`, `MockStateRepository`, `MockDdnsUpdater`.
- [ ] Unit tests verifying:
- No change detected $\rightarrow$ zero updater calls.
- Change detected $\rightarrow$ updater triggered $\rightarrow$ state updated.
- Updater fails $\rightarrow$ state remains unchanged.
### Milestone 2: Infrastructure Adapters (HTTP, File, Systemd)
- [ ] Implement `ReqwestIpResolver` with 5-endpoint pool (`ipify`, `icanhazip`, `ifconfig.me`, `checkip.dynu`, `wtfismyip`).
- [ ] Implement `JsonStateRepository` with atomic write (write to `.tmp` then rename).
- [ ] Implement `JsonlHistoryRepository` for append-only audit logs.
- [ ] Implement `SystemdDdnsUpdater` calling `systemctl start ddclient.service`.
### Milestone 3: Nix Packaging & Flake Integration
- [ ] Write `flake.nix` in `Projects/active/dynu-monitor` producing a static package.
- [ ] Package `dynu-monitor` into `homelab-core/nixos/modules/dynu.nix`.
- [ ] Replace `ipMonitorScript = pkgs.writers.writePython3Bin ...` with the native binary derivation.
### Milestone 4: Production Deployment & Verification
- [ ] Deploy generation via `sudo nixos-rebuild switch --flake ~/Core#server`.
- [ ] Verify 30-second timer cadence and resolver rotation in `/var/lib/dynu/state.json`.
- [ ] Verify zero memory leaks or zombie processes.
@@ -151,4 +151,4 @@ Configured under repository **Settings** $\rightarrow$ **Repository** $\rightarr
## 🔗 Related Production Guides ## 🔗 Related Production Guides
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../guides/brain-gitops-deployment-pipeline.md) * [Brain GitOps & Auto-Sync Deployment Pipeline](../../guides/brain-gitops-deployment-pipeline.md)
* [Dynamic Decentralized GitOps Dispatcher Architecture](../../guides/homelab-gitops-dispatcher-architecture.md) * [Dynamic Decentralized GitOps Dispatcher Architecture](../../discussions/gitops-dispatcher-architecture.md)
@@ -55,6 +55,6 @@ Rather than relying on continuous image polling via Watchtower, the homelab adop
--- ---
## 🔗 Production Guides & Specifications ## 🔗 Production Guides & Specifications
* [Dynamic Decentralized GitOps Dispatcher Architecture](../../guides/homelab-gitops-dispatcher-architecture.md) * [Dynamic Decentralized GitOps Dispatcher Architecture](../../discussions/gitops-dispatcher-architecture.md)
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../guides/brain-gitops-deployment-pipeline.md) * [Brain GitOps & Auto-Sync Deployment Pipeline](../../guides/brain-gitops-deployment-pipeline.md)
* [GitHub to Gitea Automated Batch Migration Plan](github-to-gitea-migration-plan.md) * [GitHub to Gitea Automated Batch Migration Plan](github-to-gitea-migration-plan.md)
@@ -19,7 +19,7 @@ Establish clear, unambiguous directory boundaries across both the Server and Lap
## 🗺️ Realized Production Layout ## 🗺️ Realized Production Layout
> [!NOTE] > [!NOTE]
> The initial proposal for a monolithic `~/Deployments` directory was superseded by the decoupled `~/Core` and `~/Sites` architecture documented in [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/homelab-appctl-architecture.md) and executed in [Core & Sites Cutover and Testing Plan](../appctl/core-sites-cutover-testing-plan.md). > The initial proposal for a monolithic `~/Deployments` directory was superseded by the decoupled `~/Core` and `~/Sites` architecture documented in [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/appctl-operations-and-manifest-guide.md) and executed in [Core & Sites Cutover and Testing Plan](../appctl/core-sites-cutover-testing-plan.md).
### 🖥️ Production Server Layout (`/home/kiskaadee/`) ### 🖥️ Production Server Layout (`/home/kiskaadee/`)
```text ```text
@@ -52,5 +52,5 @@ Establish clear, unambiguous directory boundaries across both the Server and Lap
--- ---
## 🔗 Related Documents ## 🔗 Related Documents
* [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/homelab-appctl-architecture.md) * [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/appctl-operations-and-manifest-guide.md)
* [Core & Sites Cutover and Testing Plan](../appctl/core-sites-cutover-testing-plan.md) * [Core & Sites Cutover and Testing Plan](../appctl/core-sites-cutover-testing-plan.md)
+2 -1
View File
@@ -68,7 +68,8 @@ graph TD
## 🏛️ Architectural Discussions & Records ## 🏛️ Architectural Discussions & Records
* [Discussion: NixOS Monorepo vs. Multi-Repo Architecture for Homelab & Workstations](../../records/discussions/2026-09-nixos-monorepo-vs-multirepo-architecture.md) * [Discussion: NixOS Monorepo vs. Multi-Repo Architecture for Homelab & Workstations](../homelab/discussions/nixos-monorepo-vs-multirepo.md)
* [Discussion: Decoupling `nixos-config` and `homelab-core`](../homelab/discussions/nixos-monorepo-decoupling.md)
--- ---
File renamed without changes.