chore(phase-0): dev environment, docs, and project rename
- Rename crate from dynu-monitor to ddns-monitor - Add flake.nix: pinned Rust stable (rust-overlay), devShell with cargo-watch, cargo-nextest, cargo-audit, curl, jq; package and checks outputs scaffolded - Update .gitignore: cover Rust/Nix build artefacts, secrets, runtime state files (state.json, *.jsonl), editor cruft; keep flake.lock tracked - Rewrite README.md: reflects broadened multi-provider scope, architecture overview, dev-shell quick start, config example, NixOS integration plan, invariants - Add ROADMAP.md: 10-phase plan from cleanup through additional providers; fan-out semantics and partial-success policy documented - Fix models.rs: correct IpDiscoveryResult syntax error, upgrade types to Option<usize> / Ipv4Addr, add doc comments - Update main.rs: scaffold stub that initialises logging and exits cleanly instead of hello-world placeholder - Add Cargo.toml dependencies through Phase 5: serde, serde_json, toml, reqwest (blocking), thiserror, log, env_logger, mockito cargo check: passes with only expected dead_code warnings
This commit is contained in:
1 parent
19e0fa69a6
commit
c25eefa8a2
8 files changed
+2186
-396
No files matched your search
+38
@@ -0,0 +1,38 @@
|
||||
# ── Rust / Cargo ───────────────────────────────────────────────────────────────
|
||||
/target/
|
||||
Cargo.lock # library crates omit it; for binaries keep it — uncomment if you want
|
||||
|
||||
# ── Nix ────────────────────────────────────────────────────────────────────────
|
||||
result
|
||||
result-*
|
||||
.direnv/
|
||||
|
||||
# ── Secrets & credentials ───────────────────────────────────────────────────────
|
||||
# Never commit plaintext secrets, tokens, or API keys.
|
||||
*.secret
|
||||
*.key
|
||||
*.pem
|
||||
*.p12
|
||||
*.pfx
|
||||
secrets/
|
||||
.env
|
||||
.env.*
|
||||
config.toml # local dev config may contain credential paths — keep out
|
||||
|
||||
# ── Runtime state ──────────────────────────────────────────────────────────────
|
||||
# Generated by the binary at runtime; not source artifacts.
|
||||
state.json
|
||||
*.jsonl
|
||||
ip_history.jsonl
|
||||
|
||||
# ── Editor / OS ────────────────────────────────────────────────────────────────
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# ── Misc ───────────────────────────────────────────────────────────────────────
|
||||
*.log
|
||||
Generated
+1506
File diff suppressed because it is too large.
Load diff
+33
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "ddns-monitor"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Provider-agnostic DDNS monitor with plugin architecture"
|
||||
license = "Unlicense"
|
||||
|
||||
[[bin]]
|
||||
name = "ddns-monitor"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# Serialization — state JSON and config TOML
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
toml = "0.8"
|
||||
|
||||
# HTTP client — blocking (no async needed for a oneshot binary)
|
||||
reqwest = { version = "0.12", features = ["blocking"], default-features = false }
|
||||
|
||||
# TLS backend — uses the system's OpenSSL
|
||||
reqwest-middleware = { version = "0.4", optional = true } # future: retry middleware
|
||||
|
||||
# Error handling
|
||||
thiserror = "2"
|
||||
|
||||
# Logging
|
||||
log = "0.4"
|
||||
env_logger = "0.11"
|
||||
|
||||
[dev-dependencies]
|
||||
# Lightweight HTTP mock server for testing IpResolver without real network
|
||||
mockito = "1"
|
||||
@@ -1,447 +1,125 @@
|
||||
# dynu-monitor
|
||||
# ddns-monitor
|
||||
|
||||
## Overview
|
||||
A provider-agnostic Dynamic DNS monitor written in Rust.
|
||||
|
||||
`dynu-monitor` is a small Rust service that monitors the machine's public IPv4 address and triggers a Dynamic DNS update only when a verified IP change is detected.
|
||||
|
||||
The project exists primarily as a Rust learning project, but the resulting binary should be usable as a real component of a NixOS-based homelab.
|
||||
|
||||
The system follows a local-first approach:
|
||||
|
||||
1. Discover the current public IPv4 address.
|
||||
2. Compare it against locally persisted state.
|
||||
3. If unchanged, do nothing.
|
||||
4. If changed, trigger `ddclient.service`.
|
||||
5. Persist the new IP only after the update succeeds.
|
||||
Monitors the machine's public WAN IPv4 address and, when a change is detected, notifies
|
||||
all configured DDNS provider subscribers. Designed to replace `ddclient` on NixOS homelabs
|
||||
and to work on any standard Linux system.
|
||||
|
||||
---
|
||||
|
||||
## Problem Statement
|
||||
## Why this exists
|
||||
|
||||
A DDNS updater can be invoked periodically regardless of whether the public IP address has changed. This can result in unnecessary requests to the DNS provider.
|
||||
DDNS updaters like `ddclient` couple the IP-detection step to a single provider. When that
|
||||
provider has an outage, the entire update chain breaks — even though your IP may not have
|
||||
changed and other providers could accept the update.
|
||||
|
||||
`dynu-monitor` acts as a local change detector in front of the existing DDNS updater.
|
||||
`ddns-monitor`:
|
||||
|
||||
The monitor should answer one question:
|
||||
|
||||
> Has the machine's public IPv4 address changed since the last successfully completed DDNS update?
|
||||
|
||||
If the answer is no, the DDNS updater should not be invoked.
|
||||
|
||||
If the answer is yes, the monitor should request an update and record the new address only after that update succeeds.
|
||||
- Separates **IP discovery** (round-robin across multiple checkers) from **DNS updating**
|
||||
(fan-out to multiple DDNS provider plugins).
|
||||
- Stores the last-known-good IP locally and skips updates when nothing has changed.
|
||||
- Notifies all configured subscribers on a detected change.
|
||||
- Runs as a systemd oneshot timer, consuming no resources between invocations.
|
||||
|
||||
---
|
||||
|
||||
## Goals
|
||||
## Status
|
||||
|
||||
### Functional Goals
|
||||
**Phase 0 — in progress.** Laying foundations: flake, documentation, module structure.
|
||||
|
||||
* Discover the machine's public IPv4 address using external IP providers.
|
||||
* Rotate through configured providers between executions.
|
||||
* Validate that discovered addresses are valid public IPv4 addresses.
|
||||
* Persist the last successfully updated IP address locally.
|
||||
* Detect changes between the current and last successfully updated IP.
|
||||
* Trigger `ddclient.service` when an IP change is detected.
|
||||
* Preserve the previous successful IP if the DDNS update fails.
|
||||
* Record successful and failed update attempts in an append-only history log.
|
||||
* Exit with an appropriate non-zero status when the monitor cannot complete its operation.
|
||||
|
||||
### Learning Goals
|
||||
|
||||
The project should provide practical exposure to:
|
||||
|
||||
* Rust project structure and Cargo.
|
||||
* Structs and enums.
|
||||
* `Option<T>` and `Result<T, E>`.
|
||||
* Ownership and borrowing.
|
||||
* Traits.
|
||||
* Generics.
|
||||
* Dependency injection through constructor parameters.
|
||||
* Error propagation with `?`.
|
||||
* File I/O.
|
||||
* JSON serialization.
|
||||
* HTTP clients.
|
||||
* Subprocess execution.
|
||||
* Unit testing.
|
||||
See [`ROADMAP.md`](./ROADMAP.md) for the full plan.
|
||||
|
||||
---
|
||||
|
||||
## Core Architecture
|
||||
## Quick Start (development)
|
||||
|
||||
The application should separate orchestration from infrastructure.
|
||||
Prerequisites: Nix with flakes enabled.
|
||||
|
||||
```text
|
||||
┌───────────────┐
|
||||
│ main.rs │
|
||||
│ composition │
|
||||
│ root │
|
||||
└───────┬───────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────┐
|
||||
│ IpMonitorService │
|
||||
│ application │
|
||||
│ logic │
|
||||
└───────┬───────┘
|
||||
│
|
||||
┌─────────────┼─────────────┐
|
||||
▼ ▼ ▼
|
||||
IpResolver StateRepository DdnsUpdater
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
HTTP JSON systemctl
|
||||
```bash
|
||||
# Enter the development shell (downloads pinned Rust toolchain)
|
||||
nix develop
|
||||
|
||||
│
|
||||
▼
|
||||
HistoryRepository
|
||||
│
|
||||
▼
|
||||
JSONL
|
||||
```
|
||||
# Build
|
||||
cargo build
|
||||
|
||||
The application service should contain the decision-making logic.
|
||||
# Run tests
|
||||
cargo nextest run
|
||||
|
||||
Infrastructure components should contain external concerns such as:
|
||||
|
||||
* HTTP.
|
||||
* Filesystem access.
|
||||
* JSON serialization.
|
||||
* Subprocess execution.
|
||||
* systemd interaction.
|
||||
|
||||
---
|
||||
|
||||
## Main Entities
|
||||
|
||||
### MonitorState
|
||||
|
||||
Represents the persisted state of the monitor.
|
||||
|
||||
```text
|
||||
MonitorState
|
||||
├── last_provider_index: Option<usize>
|
||||
└── last_ip: Option<Ipv4Addr>
|
||||
```
|
||||
|
||||
`last_ip` represents the last public IP for which a DDNS update completed successfully.
|
||||
|
||||
It must not be updated merely because a new IP was discovered.
|
||||
|
||||
---
|
||||
|
||||
### IpDiscoveryResult
|
||||
|
||||
Represents a successful public IP discovery.
|
||||
|
||||
```text
|
||||
IpDiscoveryResult
|
||||
├── ip: Ipv4Addr
|
||||
├── provider: String
|
||||
└── provider_index: usize
|
||||
# Live-reload on save
|
||||
cargo watch -x check
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### HistoryEntry
|
||||
## Architecture (target)
|
||||
|
||||
Represents an event recorded for observability.
|
||||
|
||||
```text
|
||||
HistoryEntry
|
||||
├── timestamp
|
||||
├── ip
|
||||
├── status
|
||||
└── details
|
||||
```
|
||||
main.rs (composition root)
|
||||
└── IpMonitorService (orchestration)
|
||||
├── IpResolver — discovers WAN IP via rotating external checkers
|
||||
├── StateRepository — persists last-known-good IP as JSON
|
||||
├── NotificationBus — fans out to all configured DDNS updaters
|
||||
│ ├── DynuUpdater (Phase 6)
|
||||
│ └── «future plugins»
|
||||
└── HistoryRepository — append-only JSONL audit log
|
||||
```
|
||||
|
||||
The history log is an audit trail, not the primary source of runtime state.
|
||||
The application service contains all decision logic. Infrastructure components (HTTP, fs,
|
||||
subprocess) are hidden behind traits and swappable in tests.
|
||||
|
||||
---
|
||||
|
||||
## Roles and Responsibilities
|
||||
## Configuration
|
||||
|
||||
### IpMonitorService
|
||||
The binary reads from (in priority order):
|
||||
|
||||
Responsible for the application's core workflow.
|
||||
1. NixOS module options (declarative, build-time injection)
|
||||
2. `~/.config/ddns-monitor/config.toml` (runtime, for non-NixOS)
|
||||
|
||||
It should:
|
||||
Example:
|
||||
|
||||
1. Load persisted state.
|
||||
2. Determine which provider should be queried next.
|
||||
3. Discover the current public IP.
|
||||
4. Compare it with the previous successful IP.
|
||||
5. Exit without updating if the IP is unchanged.
|
||||
6. Trigger the DDNS updater if the IP changed.
|
||||
7. Persist the new IP only after a successful update.
|
||||
8. Record the update result.
|
||||
```toml
|
||||
[ip_providers]
|
||||
urls = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
]
|
||||
timeout_secs = 5
|
||||
|
||||
It should not know:
|
||||
|
||||
* how HTTP requests are performed,
|
||||
* how JSON files are read,
|
||||
* how systemctl is invoked.
|
||||
|
||||
---
|
||||
|
||||
### IpResolver
|
||||
|
||||
Responsible for discovering a public IPv4 address.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
* Query configured providers.
|
||||
* Start with the requested provider index.
|
||||
* Fall back through remaining providers if necessary.
|
||||
* Validate returned addresses.
|
||||
* Return information about the successful provider.
|
||||
|
||||
---
|
||||
|
||||
### StateRepository
|
||||
|
||||
Responsible for persistent monitor state.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
* Load state.
|
||||
* Save state atomically.
|
||||
* Report persistence failures.
|
||||
|
||||
The state repository is the authoritative source of the monitor's runtime state.
|
||||
|
||||
---
|
||||
|
||||
### HistoryRepository
|
||||
|
||||
Responsible for recording monitor events.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
* Append successful update events.
|
||||
* Append failed update events.
|
||||
|
||||
The history log must not control normal application decisions.
|
||||
|
||||
---
|
||||
|
||||
### DdnsUpdater
|
||||
|
||||
Responsible for triggering the existing DDNS mechanism.
|
||||
|
||||
The initial implementation will invoke:
|
||||
|
||||
```text
|
||||
systemctl start --wait ddclient.service
|
||||
[[subscribers]]
|
||||
provider = "dynu"
|
||||
domain = "example.dyndns.org"
|
||||
credentials_env = "DYNU_PASSWORD"
|
||||
```
|
||||
|
||||
A successful invocation should represent a successful completion of the configured DDNS service.
|
||||
|
||||
The exact semantics of `ddclient.service` should be verified during NixOS integration.
|
||||
> **Never store plaintext credentials in `config.toml`.** Use env vars or sops-nix secrets.
|
||||
|
||||
---
|
||||
|
||||
## Core Workflow
|
||||
## NixOS
|
||||
|
||||
```text
|
||||
START
|
||||
│
|
||||
▼
|
||||
Load MonitorState
|
||||
│
|
||||
▼
|
||||
Select next IP provider
|
||||
│
|
||||
▼
|
||||
Discover public IPv4
|
||||
│
|
||||
├── Failure
|
||||
│ │
|
||||
│ ▼
|
||||
│ Try fallback providers
|
||||
│
|
||||
└── Success
|
||||
│
|
||||
▼
|
||||
Compare with last_ip
|
||||
│
|
||||
├── Same
|
||||
│ │
|
||||
│ ▼
|
||||
│ Save provider rotation state
|
||||
│ │
|
||||
│ ▼
|
||||
│ EXIT 0
|
||||
│
|
||||
└── Different / first run
|
||||
│
|
||||
▼
|
||||
Trigger DDNS update
|
||||
│
|
||||
├── Failure
|
||||
│ │
|
||||
│ ▼
|
||||
│ Record failure
|
||||
│ │
|
||||
│ ▼
|
||||
│ Keep previous last_ip
|
||||
│ │
|
||||
│ ▼
|
||||
│ EXIT != 0
|
||||
│
|
||||
└── Success
|
||||
│
|
||||
▼
|
||||
Update last_ip
|
||||
│
|
||||
▼
|
||||
Persist state
|
||||
│
|
||||
▼
|
||||
Record success
|
||||
│
|
||||
▼
|
||||
EXIT 0
|
||||
```
|
||||
The NixOS module (Phase 8) will:
|
||||
|
||||
- Build the binary as a Nix derivation.
|
||||
- Expose `services.ddns-monitor.subscribers` as a list of option sets.
|
||||
- Inject credentials from `sops.secrets` via `LoadCredential`.
|
||||
- Run as a oneshot systemd timer (30-minute default, configurable).
|
||||
|
||||
---
|
||||
|
||||
## Initial Technical Requirements
|
||||
|
||||
The first implementation should use:
|
||||
|
||||
* Rust stable.
|
||||
* Cargo.
|
||||
* A synchronous HTTP client.
|
||||
* JSON for persistent state.
|
||||
* JSON Lines for history.
|
||||
* `std::process::Command` for systemd integration.
|
||||
|
||||
Likely dependencies:
|
||||
|
||||
```text
|
||||
serde
|
||||
serde_json
|
||||
reqwest
|
||||
thiserror
|
||||
```
|
||||
|
||||
Async execution is intentionally not required for the first version.
|
||||
|
||||
---
|
||||
|
||||
## Non-Goals
|
||||
|
||||
The first version should not include:
|
||||
|
||||
* A web API.
|
||||
* A GUI.
|
||||
* A database.
|
||||
* Authentication.
|
||||
* Direct Dynu API integration.
|
||||
* IPv6 support.
|
||||
* Async networking.
|
||||
* Concurrent provider queries.
|
||||
* A dependency injection framework.
|
||||
* A plugin system.
|
||||
* Provider auto-discovery.
|
||||
* Configuration hot reloading.
|
||||
|
||||
The project should remain a small system utility.
|
||||
|
||||
---
|
||||
|
||||
## Important Invariants
|
||||
|
||||
The following rules should remain true throughout the project:
|
||||
|
||||
1. `last_ip` means the last IP successfully submitted through the DDNS update process.
|
||||
|
||||
2. Discovering an IP does not modify `last_ip`.
|
||||
|
||||
3. A failed DDNS update must leave `last_ip` unchanged.
|
||||
|
||||
4. The monitor should not trigger DDNS when the discovered IP matches `last_ip`.
|
||||
## Invariants
|
||||
|
||||
1. `last_ip` = the IP from the last fully successful fan-out (all subscribers succeeded).
|
||||
2. Discovering an IP does **not** update `last_ip`.
|
||||
3. A partial or total update failure leaves `last_ip` unchanged.
|
||||
4. The monitor does not fire DDNS when the discovered IP matches `last_ip`.
|
||||
5. Provider rotation state may be persisted independently of IP changes.
|
||||
|
||||
6. Infrastructure implementations should be replaceable in tests.
|
||||
6. All infrastructure dependencies are injectable via traits (testable without network/fs).
|
||||
|
||||
---
|
||||
|
||||
## Suggested Implementation Milestones
|
||||
|
||||
### Milestone 1 — Domain
|
||||
|
||||
Implement:
|
||||
|
||||
* `MonitorState`.
|
||||
* `IpDiscoveryResult`.
|
||||
* IPv4 parsing and validation.
|
||||
* Provider rotation logic.
|
||||
|
||||
No external dependencies.
|
||||
|
||||
### Milestone 2 — State
|
||||
|
||||
Add:
|
||||
|
||||
* JSON serialization.
|
||||
* `StateRepository`.
|
||||
* Atomic state persistence.
|
||||
|
||||
### Milestone 3 — Application
|
||||
|
||||
Implement:
|
||||
|
||||
* Traits for dependencies.
|
||||
* `IpMonitorService`.
|
||||
* Fake implementations for unit tests.
|
||||
|
||||
### Milestone 4 — HTTP
|
||||
|
||||
Implement:
|
||||
|
||||
* HTTP-based `IpResolver`.
|
||||
* Provider fallback.
|
||||
* Timeouts.
|
||||
|
||||
### Milestone 5 — DDNS
|
||||
|
||||
Implement:
|
||||
|
||||
* `SystemdDdnsUpdater`.
|
||||
* Subprocess error handling.
|
||||
|
||||
### Milestone 6 — History
|
||||
|
||||
Implement:
|
||||
|
||||
* JSONL history.
|
||||
* Success and failure event recording.
|
||||
|
||||
### Milestone 7 — NixOS Integration
|
||||
|
||||
Replace the existing Python monitor with the Rust binary and verify:
|
||||
|
||||
* Timer execution.
|
||||
* State persistence.
|
||||
* DDNS triggering.
|
||||
* Failure recovery.
|
||||
|
||||
---
|
||||
|
||||
## Definition of Done
|
||||
|
||||
The first usable version is complete when:
|
||||
|
||||
* The binary can be executed manually.
|
||||
* It can discover the machine's public IPv4 address.
|
||||
* It persists monitor state.
|
||||
* Repeated execution with the same IP does not invoke `ddclient`.
|
||||
* A changed IP invokes `ddclient.service`.
|
||||
* A failed DDNS update does not overwrite the previous successful IP.
|
||||
* Provider failures fall back to another provider.
|
||||
* Core application behavior is covered by unit tests without real HTTP, filesystem, or systemd dependencies.
|
||||
* The binary can replace the existing Python implementation in the NixOS configuration.
|
||||
|
||||
## License
|
||||
|
||||
[Unlicense](./UNLICENSE) — public domain.
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
# ddns-monitor — Project ROADMAP
|
||||
|
||||
> [!NOTE]
|
||||
> This document supersedes the `dynu-monitor` README. The project is being renamed and
|
||||
> broadened from a single-provider Dynu wrapper into a generic, provider-agnostic DDNS
|
||||
> monitor with a plugin architecture.
|
||||
|
||||
---
|
||||
|
||||
## What Already Exists
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| [`nixos/scripts/monitor.py`](file:///home/kiskaadee/Homelab/Core/nixos/scripts/monitor.py) | Python prototype — round-robins IP providers, compares to history, fires `ddclient` |
|
||||
| [`nixos/modules/dynu.nix`](file:///home/kiskaadee/Homelab/Core/nixos/modules/dynu.nix) | NixOS module wiring monitor.py + ddclient + sops secrets via systemd oneshot timer |
|
||||
| [`src/main.rs`](file:///home/kiskaadee/Projects/active/ddns-monitor/src/main.rs) | Rust scaffold — placeholder `main()` |
|
||||
| [`src/models.rs`](file:///home/kiskaadee/Projects/active/ddns-monitor/src/models.rs) | Draft structs: `MonitorState`, `IpDiscoveryResult` (syntax error present) |
|
||||
| `README.md` | Architecture blueprint for a single-provider Rust rewrite (good bones, narrower scope) |
|
||||
|
||||
**Root cause of today's outage:** Dynu API went down (data corruption incident). The monitor
|
||||
currently couples the IP-check layer *and* the update-submission layer to a single provider
|
||||
ecosystem. If Dynu is unreachable, the entire update chain breaks regardless of what the IP
|
||||
checkers report.
|
||||
|
||||
---
|
||||
|
||||
## Motivation for the Redesign
|
||||
|
||||
The Python script already solves the **IP-detection** problem well. What it lacks is:
|
||||
|
||||
1. **Provider independence for updates** — it delegates to `ddclient`, which is Dynu-specific.
|
||||
2. **Fan-out** — one IP change must notify *all* configured domains, possibly across different
|
||||
DDNS providers or multiple accounts on the same provider.
|
||||
3. **Resilience** — if one DDNS provider is down, others should still be notified.
|
||||
4. **NixOS portability + non-FSH Linux support** — the binary should be usable on both.
|
||||
5. **No runtime Python dep** — a statically linked Rust binary compiles cleanly into a
|
||||
Nix derivation and works on non-NixOS systems without a Python interpreter.
|
||||
|
||||
---
|
||||
|
||||
## Target Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["main.rs\nComposition Root"] --> B["IpMonitorService\nApplication Logic"]
|
||||
B --> C["IpResolver\nRound-Robin IP Check"]
|
||||
B --> D["StateRepository\nJSON State"]
|
||||
B --> E["NotificationBus\nFan-out dispatcher"]
|
||||
E --> F1["DynuPlugin\nDDNS Updater"]
|
||||
E --> F2["CloudflarePlugin\nDDNS Updater"]
|
||||
E --> F3["«future»\nAny provider"]
|
||||
C --> G1["api.ipify.org"]
|
||||
C --> G2["ifconfig.me"]
|
||||
C --> G3["icanhazip.com"]
|
||||
D --> H["~/.config/ddns-monitor/state.json\nor /var/lib/ddns-monitor/"]
|
||||
B --> I["HistoryRepository\nJSONL audit log"]
|
||||
```
|
||||
|
||||
### Separation of Concerns
|
||||
|
||||
| Layer | Responsibility | Knows about |
|
||||
|---|---|---|
|
||||
| **IpMonitorService** | Orchestration & decisions | Traits only |
|
||||
| **IpResolver** | WAN IP discovery + rotation | HTTP |
|
||||
| **StateRepository** | Persisted last-known-good IP | JSON / fs |
|
||||
| **NotificationBus** | Fan-out to all subscribers | Vec of `DdnsUpdater` |
|
||||
| **DdnsUpdater trait** | Contract for one provider plugin | Nothing external |
|
||||
| **DynuUpdater** | Dynu HTTP API v2 | reqwest |
|
||||
| **CloudflareUpdater** | Cloudflare DNS API | reqwest |
|
||||
| **HistoryRepository** | Append-only audit trail | JSONL / fs |
|
||||
|
||||
---
|
||||
|
||||
## Core Entities
|
||||
|
||||
### MonitorState
|
||||
```text
|
||||
MonitorState
|
||||
├── last_provider_index: Option<usize> -- which IP-check provider goes next
|
||||
└── last_ip: Option<Ipv4Addr> -- IP from last *fully successful* update round
|
||||
```
|
||||
`last_ip` advances only when **every** subscriber in the notification bus reports success.
|
||||
|
||||
---
|
||||
|
||||
### DdnsUpdater (trait — the plugin contract)
|
||||
```text
|
||||
DdnsUpdater
|
||||
├── name() -> &str
|
||||
└── update(ip: Ipv4Addr) -> Result<(), UpdateError>
|
||||
```
|
||||
All provider-specific HTTP, auth, and retry logic lives behind this trait.
|
||||
|
||||
---
|
||||
|
||||
### SubscriberConfig (from config file or NixOS options)
|
||||
```text
|
||||
SubscriberConfig
|
||||
├── provider: String -- "dynu" | "cloudflare" | ...
|
||||
├── domain: String
|
||||
└── credentials: ... -- per-provider fields
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### IpDiscoveryResult
|
||||
```text
|
||||
IpDiscoveryResult
|
||||
├── ip: Ipv4Addr
|
||||
├── provider: String -- which checker responded
|
||||
└── provider_index: usize -- for rotation persistence
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### HistoryEntry
|
||||
```text
|
||||
HistoryEntry
|
||||
├── timestamp: DateTime<Utc>
|
||||
├── ip: Ipv4Addr
|
||||
├── subscribers: Vec<SubscriberResult> -- one record per provider
|
||||
└── overall_status: "success" | "partial" | "failed"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Update Semantics
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Partial success rule:** if 3 of 4 subscribers succeed and 1 fails, `last_ip` is **not**
|
||||
> updated. The next cycle will retry all subscribers. This is conservative: a transient
|
||||
> failure on one subscriber won't cause the other three to re-update unnecessarily on
|
||||
> subsequent cycles because `last_ip` hasn't advanced.
|
||||
>
|
||||
> This is a deliberate trade-off. An alternative (advance `last_ip` per-subscriber) is more
|
||||
> complex and deferred to a future enhancement.
|
||||
|
||||
---
|
||||
|
||||
## Core Workflow
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S([START]) --> LD[Load MonitorState]
|
||||
LD --> IP[Discover WAN IP\nRound-robin provider]
|
||||
IP -->|All fail| XF([EXIT 1])
|
||||
IP -->|Success| CMP{IP == last_ip?}
|
||||
CMP -->|Same| ROT[Save rotation index]
|
||||
ROT --> X0([EXIT 0])
|
||||
CMP -->|Different or first run| FAN[Fan-out to all subscribers]
|
||||
FAN --> RES{All succeeded?}
|
||||
RES -->|Yes| UPD[Update last_ip\nPersist state\nLog success]
|
||||
UPD --> X0
|
||||
RES -->|Partial or all failed| LOG[Log partial/failure\nKeep last_ip unchanged]
|
||||
LOG --> X1([EXIT 1])
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
The service should accept configuration from two sources, in priority order:
|
||||
|
||||
1. **NixOS module options** (declarative, build-time)
|
||||
2. **`~/.config/ddns-monitor/config.toml`** (runtime, for non-NixOS)
|
||||
|
||||
```toml
|
||||
# Example config.toml
|
||||
[ip_providers]
|
||||
urls = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
]
|
||||
timeout_secs = 5
|
||||
|
||||
[[subscribers]]
|
||||
provider = "dynu"
|
||||
domain = "roadtotech.me"
|
||||
credentials_env = "DYNU_PASSWORD" # or path to a secrets file
|
||||
|
||||
[[subscribers]]
|
||||
provider = "dynu"
|
||||
domain = "backupserver.me"
|
||||
credentials_env = "DYNU_PASSWORD_2"
|
||||
|
||||
# future
|
||||
# [[subscribers]]
|
||||
# provider = "cloudflare"
|
||||
# domain = "example.com"
|
||||
# zone_id = "..."
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Credentials should never be stored in the config file in plaintext. On NixOS, sops-nix
|
||||
> provides secrets via environment or file. On non-NixOS, the binary accepts env var names
|
||||
> or secret-file paths.
|
||||
|
||||
---
|
||||
|
||||
## NixOS Integration Target
|
||||
|
||||
Replace `dynu.nix` with a new module that:
|
||||
|
||||
- Builds `ddns-monitor` as a Nix derivation (native Rust build)
|
||||
- Exposes `services.ddns-monitor.subscribers` as a list of NixOS option sets
|
||||
- Injects credentials from `sops.secrets` via systemd `LoadCredential`
|
||||
- Runs as a oneshot systemd timer (same 30-minute cadence, configurable)
|
||||
- **Does not depend on `ddclient`** — the binary calls provider APIs directly
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 0 — Cleanup & Rename *(Now)*
|
||||
- [ ] Fix syntax error in `models.rs`
|
||||
- [ ] Rename crate from `dynu-monitor` to `ddns-monitor` in `Cargo.toml`
|
||||
- [ ] Add `Cargo.toml` dependencies: `serde`, `serde_json`, `toml`, `reqwest` (blocking), `thiserror`
|
||||
- [ ] Stub out module tree: `domain/`, `infra/`, `config.rs`, `plugins/`
|
||||
|
||||
---
|
||||
|
||||
### Phase 1 — Domain Layer
|
||||
*No external dependencies. Pure Rust types and logic.*
|
||||
|
||||
- [ ] `MonitorState` with correct types (`Option<Ipv4Addr>`, `Option<usize>`)
|
||||
- [ ] `IpDiscoveryResult`
|
||||
- [ ] `HistoryEntry` + `SubscriberResult`
|
||||
- [ ] IPv4 public-address validation (port Python's RFC-aware logic)
|
||||
- [ ] Provider rotation logic (next index from state)
|
||||
- [ ] `DdnsUpdater` trait
|
||||
- [ ] `UpdateError` enum with `thiserror`
|
||||
- [ ] Unit tests: rotation, validation, state transitions
|
||||
|
||||
**Learning targets:** structs, enums, `Option<T>`, traits, `Result<T, E>`, unit tests
|
||||
|
||||
---
|
||||
|
||||
### Phase 2 — Configuration
|
||||
*Parse config file and build subscriber list.*
|
||||
|
||||
- [ ] `Config` struct with `serde` + `toml`
|
||||
- [ ] `SubscriberConfig` with per-provider credential resolution (env var → file → error)
|
||||
- [ ] NixOS module integration stubs (paths, env vars, state dir)
|
||||
- [ ] Unit tests: config parsing, credential resolution errors
|
||||
|
||||
**Learning targets:** `serde`, generics, `Result` propagation with `?`
|
||||
|
||||
---
|
||||
|
||||
### Phase 3 — Application Service
|
||||
*Wire domain + config into orchestration logic.*
|
||||
|
||||
- [ ] `IpMonitorService` struct taking trait objects
|
||||
- [ ] Full workflow (load → discover → compare → fan-out → persist → log)
|
||||
- [ ] In-memory fake implementations for all trait dependencies
|
||||
- [ ] Integration-style unit tests: no HTTP, no fs, no systemd
|
||||
|
||||
**Learning targets:** dependency injection via traits, `Box<dyn Trait>`, borrowing, lifetime basics
|
||||
|
||||
---
|
||||
|
||||
### Phase 4 — IP Resolution (HTTP)
|
||||
*Real network calls.*
|
||||
|
||||
- [ ] `HttpIpResolver` using blocking `reqwest`
|
||||
- [ ] Timeout configuration
|
||||
- [ ] Provider fallback loop
|
||||
- [ ] Address validation on response
|
||||
- [ ] Unit tests: mock server or `mockito`
|
||||
|
||||
**Learning targets:** HTTP clients, blocking async in Rust, error propagation
|
||||
|
||||
---
|
||||
|
||||
### Phase 5 — State & History (Filesystem)
|
||||
*Persistent JSON state and JSONL audit log.*
|
||||
|
||||
- [ ] `JsonStateRepository`: atomic write (write-to-tmp → rename)
|
||||
- [ ] `JsonlHistoryRepository`: append-only writes
|
||||
- [ ] State directory creation (respects `StateDirectory=` systemd or XDG on non-NixOS)
|
||||
- [ ] Unit tests: serialization round-trips, atomic write behavior
|
||||
|
||||
**Learning targets:** file I/O, `serde_json`, atomic FS patterns
|
||||
|
||||
---
|
||||
|
||||
### Phase 6 — Dynu Plugin
|
||||
*First real DDNS provider.*
|
||||
|
||||
- [ ] `DynuUpdater` implementing `DdnsUpdater`
|
||||
- [ ] Calls Dynu HTTP API v2 directly (no ddclient)
|
||||
- [ ] Credential loading from env / sops file
|
||||
- [ ] Parses Dynu API response to confirm success
|
||||
- [ ] Unit tests with mocked HTTP
|
||||
|
||||
> [!NOTE]
|
||||
> The Python script currently goes through `ddclient`. This phase eliminates that dependency.
|
||||
> The Dynu API is simple: a single HTTPS GET with credentials and the new IP in query params.
|
||||
|
||||
---
|
||||
|
||||
### Phase 7 — Fan-out & NotificationBus
|
||||
*Multiple subscribers.*
|
||||
|
||||
- [ ] `NotificationBus` iterating all configured `DdnsUpdater`s
|
||||
- [ ] Collects per-subscriber results
|
||||
- [ ] Applies partial-success rule (all-or-nothing `last_ip` advance)
|
||||
- [ ] Integration test: 1 success + 1 failure → state unchanged
|
||||
|
||||
---
|
||||
|
||||
### Phase 8 — NixOS Module Rewrite
|
||||
*Replace dynu.nix.*
|
||||
|
||||
- [ ] New `ddns-monitor.nix` module with subscriber list options
|
||||
- [ ] Rust binary as Nix derivation (via `rustPlatform.buildRustPackage`)
|
||||
- [ ] Credential injection via `LoadCredential` + sops-nix
|
||||
- [ ] Timer configuration (interval, boot delay)
|
||||
- [ ] Smoke test on homelab server
|
||||
|
||||
---
|
||||
|
||||
### Phase 9 — Non-NixOS Support *(stretch)*
|
||||
*Make it usable on Debian/Arch/etc.*
|
||||
|
||||
- [ ] XDG config dir fallback (`~/.config/ddns-monitor/`)
|
||||
- [ ] State dir fallback (`~/.local/share/ddns-monitor/` or `/var/lib/ddns-monitor/`)
|
||||
- [ ] `systemd.service` unit file (generic, for non-NixOS install)
|
||||
- [ ] Install instructions for manual systemd setup
|
||||
|
||||
---
|
||||
|
||||
### Phase 10 — Additional Providers *(stretch)*
|
||||
|
||||
- [ ] `CloudflareUpdater`
|
||||
- [ ] `DuckDNSUpdater`
|
||||
- [ ] Provider auto-detection from config `provider =` field
|
||||
- [ ] Consider: compile-time feature flags per provider
|
||||
|
||||
---
|
||||
|
||||
## What This Project Is NOT (in scope now)
|
||||
|
||||
- No GUI or web API
|
||||
- No IPv6 (explicitly deferred)
|
||||
- No async networking (blocking reqwest is fine for a oneshot binary)
|
||||
- No hot config reloading
|
||||
- No concurrent provider queries
|
||||
- No database
|
||||
- No authentication layer on the binary itself
|
||||
|
||||
---
|
||||
|
||||
## Definition of Done (Phase 6 complete = "v1 usable")
|
||||
|
||||
- [ ] Binary discovers WAN IP via rotating providers
|
||||
- [ ] Persists state across executions
|
||||
- [ ] Detects IP changes correctly
|
||||
- [ ] Calls Dynu API directly (no ddclient dependency)
|
||||
- [ ] Notifies all configured subscribers on change
|
||||
- [ ] Leaves `last_ip` unchanged on any subscriber failure
|
||||
- [ ] Core logic is fully covered by unit tests (no real HTTP / fs / network)
|
||||
- [ ] NixOS module replaces `dynu.nix` and `monitor.py`
|
||||
- [ ] Tested live on homelab server
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Partial success policy** — should `last_ip` advance per-subscriber (more complex, avoids
|
||||
duplicate updates on retry) or stay all-or-nothing (simpler, may cause harmless re-updates)?
|
||||
Current plan: all-or-nothing. Revisit after Phase 7.
|
||||
|
||||
2. **Binary distribution** — Nix derivation is the primary path. Should a static musl build
|
||||
also be published for non-NixOS users?
|
||||
|
||||
3. **Credential model** — env var → file → error is the current plan. Should we also support
|
||||
a `pass` / `age`-encrypted file directly?
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
description = "ddns-monitor — provider-agnostic DDNS monitor with plugin architecture";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
|
||||
# Pinned Rust toolchain — gives us stable + clippy + rustfmt + rust-analyzer
|
||||
rust-overlay = {
|
||||
url = "github:oxalica/rust-overlay";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, rust-overlay, ... }:
|
||||
let
|
||||
system = "x86_64-linux";
|
||||
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
overlays = [ rust-overlay.overlays.default ];
|
||||
};
|
||||
|
||||
# Pin to stable Rust. Edit the date to roll forward.
|
||||
# rustc, cargo, clippy, rustfmt, and rust-analyzer are all included.
|
||||
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
|
||||
extensions = [ "rust-src" "rust-analyzer" "clippy" "rustfmt" ];
|
||||
};
|
||||
|
||||
# Shared native build inputs used by both the devShell and the package
|
||||
nativeBuildInputs = with pkgs; [
|
||||
rustToolchain
|
||||
pkg-config
|
||||
];
|
||||
|
||||
# Runtime / link-time dependencies
|
||||
buildInputs = with pkgs; [
|
||||
openssl # reqwest TLS backend
|
||||
];
|
||||
|
||||
in
|
||||
{
|
||||
# ── Development shell ─────────────────────────────────────────────────────
|
||||
# Enter with: nix develop
|
||||
devShells.${system}.default = pkgs.mkShell {
|
||||
inherit nativeBuildInputs buildInputs;
|
||||
|
||||
packages = with pkgs; [
|
||||
# Linting & formatting (also available via rustToolchain, listed
|
||||
# here for clarity)
|
||||
cargo-watch # cargo watch -x check -- live recompile on save
|
||||
cargo-nextest # faster test runner (drop-in for cargo test)
|
||||
|
||||
# Dependency auditing
|
||||
cargo-audit
|
||||
|
||||
# Useful during DDNS API development
|
||||
curl
|
||||
jq
|
||||
];
|
||||
|
||||
# Point OpenSSL build scripts at the Nix store paths
|
||||
OPENSSL_NO_VENDOR = "1";
|
||||
PKG_CONFIG_PATH = "${pkgs.openssl.dev}/lib/pkgconfig";
|
||||
|
||||
shellHook = ''
|
||||
echo ""
|
||||
echo " ddns-monitor dev shell"
|
||||
echo " ─────────────────────────────────────────────"
|
||||
echo " rustc $(rustc --version)"
|
||||
echo " cargo $(cargo --version)"
|
||||
echo ""
|
||||
echo " Useful commands:"
|
||||
echo " cargo build compile the binary"
|
||||
echo " cargo test run unit tests"
|
||||
echo " cargo nextest run run tests with nextest"
|
||||
echo " cargo watch -x check live check on save"
|
||||
echo " cargo audit scan dependencies for CVEs"
|
||||
echo " cargo clippy lint"
|
||||
echo " cargo fmt format"
|
||||
echo ""
|
||||
'';
|
||||
};
|
||||
|
||||
# ── Package ───────────────────────────────────────────────────────────────
|
||||
# Build the binary: nix build
|
||||
packages.${system} = rec {
|
||||
ddns-monitor = pkgs.rustPlatform.buildRustPackage {
|
||||
pname = "ddns-monitor";
|
||||
version = "0.1.0";
|
||||
src = ./.;
|
||||
|
||||
# Update this hash after running: nix build 2>&1 | grep "got:"
|
||||
cargoHash = pkgs.lib.fakeHash;
|
||||
|
||||
inherit nativeBuildInputs buildInputs;
|
||||
|
||||
meta = with pkgs.lib; {
|
||||
description = "Provider-agnostic DDNS monitor with plugin architecture";
|
||||
license = licenses.unlicense;
|
||||
maintainers = [ ];
|
||||
};
|
||||
};
|
||||
|
||||
default = ddns-monitor;
|
||||
};
|
||||
|
||||
# ── Checks ────────────────────────────────────────────────────────────────
|
||||
# Run with: nix flake check
|
||||
checks.${system} = {
|
||||
# cargo test inside a sandbox — proves tests pass without network/fs
|
||||
cargo-test = pkgs.rustPlatform.buildRustPackage {
|
||||
pname = "ddns-monitor-tests";
|
||||
version = "0.1.0";
|
||||
src = ./.;
|
||||
cargoHash = pkgs.lib.fakeHash;
|
||||
inherit nativeBuildInputs buildInputs;
|
||||
doCheck = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
mod models;
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
log::info!("ddns-monitor starting");
|
||||
|
||||
// TODO (Phase 3): wire IpMonitorService and run the full workflow.
|
||||
eprintln!("ddns-monitor: not yet implemented");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
/// Persisted state of the monitor.
|
||||
///
|
||||
/// Loaded at startup and saved after each successful update cycle.
|
||||
/// `last_ip` is the IP address from the last *fully successful* fan-out —
|
||||
/// it is not updated merely because a new IP was discovered.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MonitorState {
|
||||
/// Index of the IP-check provider to query on the next run.
|
||||
pub last_provider_index: Option<usize>,
|
||||
/// Public IP address from the last successfully completed DDNS update.
|
||||
pub last_ip: Option<Ipv4Addr>,
|
||||
}
|
||||
|
||||
/// Result of a successful public IP discovery.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IpDiscoveryResult {
|
||||
/// The discovered public IPv4 address.
|
||||
pub ip: Ipv4Addr,
|
||||
/// Display name of the provider that responded.
|
||||
pub provider: String,
|
||||
/// Index of the provider in the configured list (for rotation persistence).
|
||||
pub provider_index: usize,
|
||||
}
|
||||
Reference in new issue
Block a user