feat(domain): implement core models, validation, and traits
- Add MonitorState, IpDiscoveryResult, SubscriberResult, and HistoryEntry - Implement RFC-compliant public IPv4 validation and round-robin index calculation - Define IpResolver, DdnsUpdater, StateRepository, and HistoryRepository traits - Establish domain error hierarchy with thiserror - Add unit tests verifying validation, rotation, and serialization
This commit is contained in:
1 parent
9befe4af52
commit
9ece94c988
11 files changed
+335
-28
No files matched your search
@@ -36,3 +36,4 @@ Thumbs.db
|
||||
|
||||
# ── Misc ───────────────────────────────────────────────────────────────────────
|
||||
*.log
|
||||
.agents/
|
||||
@@ -5,6 +5,10 @@ edition = "2024"
|
||||
description = "Provider-agnostic DDNS monitor with plugin architecture"
|
||||
license = "Unlicense"
|
||||
|
||||
[lib]
|
||||
name = "ddns_monitor"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ddns-monitor"
|
||||
path = "src/main.rs"
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
use thiserror::Error;
|
||||
|
||||
/// Errors arising during WAN IP resolution.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ResolveError {
|
||||
#[error("All configured IP discovery providers failed: {0}")]
|
||||
AllProvidersFailed(String),
|
||||
|
||||
#[error("No IP discovery providers configured")]
|
||||
NoProvidersConfigured,
|
||||
|
||||
#[error("Invalid IP returned by provider '{provider}': {raw_ip}")]
|
||||
InvalidIp { provider: String, raw_ip: String },
|
||||
|
||||
#[error("HTTP request to '{provider}' failed: {details}")]
|
||||
HttpError { provider: String, details: String },
|
||||
}
|
||||
|
||||
/// Errors arising during DDNS provider updates.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum UpdateError {
|
||||
#[error("DDNS provider '{provider}' rejected update: {message}")]
|
||||
ProviderRejected { provider: String, message: String },
|
||||
|
||||
#[error("Authentication failed for provider '{provider}': {details}")]
|
||||
AuthError { provider: String, details: String },
|
||||
|
||||
#[error("Network error updating provider '{provider}': {details}")]
|
||||
NetworkError { provider: String, details: String },
|
||||
|
||||
#[error("Misconfiguration for provider '{provider}': {details}")]
|
||||
ConfigurationError { provider: String, details: String },
|
||||
}
|
||||
|
||||
/// Errors arising from state repository persistence.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum StateError {
|
||||
#[error("I/O error accessing state file '{path}': {source}")]
|
||||
Io {
|
||||
path: String,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
#[error("Failed to parse state JSON: {0}")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
/// Errors arising from history log persistence.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum HistoryError {
|
||||
#[error("I/O error writing history log '{path}': {source}")]
|
||||
Io {
|
||||
path: String,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
#[error("Failed to serialize history entry: {0}")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
/// Top-level configuration errors.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("I/O error reading config file '{path}': {source}")]
|
||||
Io {
|
||||
path: String,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
#[error("Failed to parse TOML configuration: {0}")]
|
||||
ParseToml(#[from] toml::de::Error),
|
||||
|
||||
#[error("Missing required environment variable '{var}': {source}")]
|
||||
MissingEnvVar {
|
||||
var: String,
|
||||
#[source]
|
||||
source: std::env::VarError,
|
||||
},
|
||||
|
||||
#[error("Validation error: {0}")]
|
||||
Validation(String),
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod errors;
|
||||
pub mod models;
|
||||
pub mod traits;
|
||||
pub mod validation;
|
||||
@@ -0,0 +1,49 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
/// Persisted state of the monitor across executions.
|
||||
///
|
||||
/// `last_ip` reflects the IP address from the last *fully successful* fan-out cycle.
|
||||
/// It must never be updated if any subscriber fails.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
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, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct IpDiscoveryResult {
|
||||
/// The discovered public IPv4 address.
|
||||
pub ip: Ipv4Addr,
|
||||
/// Display name or URL of the provider that responded.
|
||||
pub provider: String,
|
||||
/// Index of the provider in the configured list (for rotation persistence).
|
||||
pub provider_index: usize,
|
||||
}
|
||||
|
||||
/// Result of notifying an individual DDNS subscriber.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SubscriberResult {
|
||||
/// The name of the DDNS provider (e.g. "dynu").
|
||||
pub provider: String,
|
||||
/// Whether the update was accepted by the provider.
|
||||
pub success: bool,
|
||||
/// Optional error details if the update failed.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// A persistent audit record appended to the JSONL history log.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct HistoryEntry {
|
||||
/// ISO 8601 UTC timestamp.
|
||||
pub timestamp: String,
|
||||
/// Public IP discovered for this run.
|
||||
pub ip: Ipv4Addr,
|
||||
/// Overall run status ("success", "partial", "failed", "no_change").
|
||||
pub status: String,
|
||||
/// Results for each individual subscriber notified.
|
||||
pub subscribers: Vec<SubscriberResult>,
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use crate::domain::errors::{HistoryError, ResolveError, StateError, UpdateError};
|
||||
use crate::domain::models::{HistoryEntry, IpDiscoveryResult, MonitorState};
|
||||
|
||||
/// Contract for resolving the current public WAN IPv4 address.
|
||||
pub trait IpResolver: Send + Sync {
|
||||
/// Discovers the current public IPv4 address, starting from or prioritizing
|
||||
/// rotation based on `last_index`.
|
||||
fn resolve(&self, last_index: Option<usize>) -> Result<IpDiscoveryResult, ResolveError>;
|
||||
}
|
||||
|
||||
/// Contract for updating a dynamic DNS provider with a new IP.
|
||||
pub trait DdnsUpdater: Send + Sync {
|
||||
/// Human-readable identifier for the updater (e.g. "dynu:example.com").
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Dispatches the update to the DNS provider.
|
||||
fn update(&self, ip: Ipv4Addr) -> Result<(), UpdateError>;
|
||||
}
|
||||
|
||||
/// Contract for persisting and loading the monitor state across runs.
|
||||
pub trait StateRepository: Send + Sync {
|
||||
/// Loads the stored monitor state, returning `MonitorState::default()` if absent.
|
||||
fn load(&self) -> Result<MonitorState, StateError>;
|
||||
|
||||
/// Atomically persists the updated monitor state.
|
||||
fn save(&self, state: &MonitorState) -> Result<(), StateError>;
|
||||
}
|
||||
|
||||
/// Contract for appending execution records to the audit history log.
|
||||
pub trait HistoryRepository: Send + Sync {
|
||||
/// Appends an entry to the log.
|
||||
fn append(&self, entry: &HistoryEntry) -> Result<(), HistoryError>;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
/// Checks if an IPv4 address is a valid, publicly routable WAN address.
|
||||
///
|
||||
/// Excludes RFC 1918 private ranges, RFC 6598 carrier-grade NAT,
|
||||
/// loopback, link-local, multicast, and broadcast addresses.
|
||||
pub fn is_valid_public_ipv4(ip: Ipv4Addr) -> bool {
|
||||
let octets = ip.octets();
|
||||
let (a, b) = (octets[0], octets[1]);
|
||||
|
||||
// Unspecified / "This host on this network" (0.0.0.0/8)
|
||||
if a == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Loopback (127.0.0.0/8)
|
||||
if a == 127 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// RFC 1918 Private networks
|
||||
// 10.0.0.0/8
|
||||
if a == 10 {
|
||||
return false;
|
||||
}
|
||||
// 172.16.0.0/12
|
||||
if a == 172 && (16..=31).contains(&b) {
|
||||
return false;
|
||||
}
|
||||
// 192.168.0.0/16
|
||||
if a == 192 && b == 168 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// RFC 6598 Carrier-Grade NAT (100.64.0.0/10)
|
||||
if a == 100 && (64..=127).contains(&b) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// RFC 3927 Link-local (169.254.0.0/16)
|
||||
if a == 169 && b == 254 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Multicast (224.0.0.0/4: 224..=239) and Reserved / Broadcast (240.0.0.0/4: 240..=255)
|
||||
if a >= 224 {
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Computes the next provider index using round-robin rotation.
|
||||
///
|
||||
/// Returns `None` if `provider_count` is 0.
|
||||
pub fn next_provider_index(last_index: Option<usize>, provider_count: usize) -> Option<usize> {
|
||||
if provider_count == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
match last_index {
|
||||
Some(idx) => Some((idx + 1) % provider_count),
|
||||
None => Some(0),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod domain;
|
||||
+1
-3
@@ -1,10 +1,8 @@
|
||||
mod models;
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
log::info!("ddns-monitor starting");
|
||||
|
||||
// TODO (Phase 3): wire IpMonitorService and run the full workflow.
|
||||
// TODO: wire IpMonitorService and run the full workflow.
|
||||
eprintln!("ddns-monitor: not yet implemented");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use ddns_monitor::domain::models::{HistoryEntry, IpDiscoveryResult, MonitorState, SubscriberResult};
|
||||
use ddns_monitor::domain::validation::{is_valid_public_ipv4, next_provider_index};
|
||||
|
||||
#[test]
|
||||
fn test_is_valid_public_ipv4() {
|
||||
// Valid public IPv4 addresses
|
||||
assert!(is_valid_public_ipv4("8.8.8.8".parse().unwrap()));
|
||||
assert!(is_valid_public_ipv4("1.1.1.1".parse().unwrap()));
|
||||
assert!(is_valid_public_ipv4("93.184.216.34".parse().unwrap()));
|
||||
|
||||
// RFC 1918 Private ranges
|
||||
assert!(!is_valid_public_ipv4("10.0.0.1".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("10.255.255.255".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("172.16.0.1".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("172.31.255.255".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("192.168.0.1".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("192.168.255.255".parse().unwrap()));
|
||||
|
||||
// RFC 6598 Carrier-Grade NAT (100.64.0.0/10)
|
||||
assert!(!is_valid_public_ipv4("100.64.0.1".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("100.127.255.254".parse().unwrap()));
|
||||
|
||||
// Loopback (127.0.0.0/8)
|
||||
assert!(!is_valid_public_ipv4("127.0.0.1".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("127.255.255.255".parse().unwrap()));
|
||||
|
||||
// Link-local (169.254.0.0/16)
|
||||
assert!(!is_valid_public_ipv4("169.254.0.1".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("169.254.255.255".parse().unwrap()));
|
||||
|
||||
// Broadcast, unspecified, multicast
|
||||
assert!(!is_valid_public_ipv4("0.0.0.0".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("255.255.255.255".parse().unwrap()));
|
||||
assert!(!is_valid_public_ipv4("224.0.0.1".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_next_provider_index() {
|
||||
assert_eq!(next_provider_index(None, 3), Some(0));
|
||||
assert_eq!(next_provider_index(Some(0), 3), Some(1));
|
||||
assert_eq!(next_provider_index(Some(1), 3), Some(2));
|
||||
assert_eq!(next_provider_index(Some(2), 3), Some(0)); // wraps around
|
||||
assert_eq!(next_provider_index(None, 0), None);
|
||||
assert_eq!(next_provider_index(Some(0), 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_monitor_state_serialization() {
|
||||
let state = MonitorState {
|
||||
last_provider_index: Some(2),
|
||||
last_ip: Some(Ipv4Addr::new(93, 184, 216, 34)),
|
||||
};
|
||||
|
||||
let serialized = serde_json::to_string(&state).expect("serialize monitor state");
|
||||
let deserialized: MonitorState =
|
||||
serde_json::from_str(&serialized).expect("deserialize monitor state");
|
||||
|
||||
assert_eq!(state, deserialized);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_history_entry_serialization() {
|
||||
let discovery = IpDiscoveryResult {
|
||||
ip: Ipv4Addr::new(93, 184, 216, 34),
|
||||
provider: "https://api.ipify.org".to_string(),
|
||||
provider_index: 0,
|
||||
};
|
||||
let disc_serialized = serde_json::to_string(&discovery).expect("serialize discovery");
|
||||
let disc_deserialized: IpDiscoveryResult =
|
||||
serde_json::from_str(&disc_serialized).expect("deserialize discovery");
|
||||
assert_eq!(discovery, disc_deserialized);
|
||||
|
||||
let entry = HistoryEntry {
|
||||
timestamp: "2026-10-27T12:00:00Z".to_string(),
|
||||
ip: Ipv4Addr::new(93, 184, 216, 34),
|
||||
status: "success".to_string(),
|
||||
subscribers: vec![SubscriberResult {
|
||||
provider: "dynu".to_string(),
|
||||
success: true,
|
||||
error: None,
|
||||
}],
|
||||
};
|
||||
|
||||
let serialized = serde_json::to_string(&entry).expect("serialize history entry");
|
||||
let deserialized: HistoryEntry =
|
||||
serde_json::from_str(&serialized).expect("deserialize history entry");
|
||||
|
||||
assert_eq!(entry, deserialized);
|
||||
}
|
||||
Reference in new issue
Block a user