feat(service): implement IpMonitorService orchestrator and fan-out workflow
- Implement orchestration logic adhering to hexagonal architecture - Enforce invariant: last_ip advances ONLY when all subscribers succeed - Preserve rotation state across no-change and failure cycles - Add in-memory fake test suite proving all state transition invariants
This commit is contained in:
1 parent
c60484a5b8
commit
2c14bf02dd
5 files changed
+466
No files matched your search
Generated
+18
@@ -152,6 +152,7 @@ name = "ddns-monitor"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"env_logger",
|
||||
"jiff",
|
||||
"log",
|
||||
"mockito",
|
||||
"serde",
|
||||
@@ -433,10 +434,12 @@ dependencies = [
|
||||
"defmt",
|
||||
"jiff-core",
|
||||
"jiff-static",
|
||||
"jiff-tzdb-platform",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"portable-atomic-util",
|
||||
"serde_core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -461,6 +464,21 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-tzdb"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7"
|
||||
|
||||
[[package]]
|
||||
name = "jiff-tzdb-platform"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"
|
||||
dependencies = [
|
||||
"jiff-tzdb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
|
||||
@@ -18,6 +18,7 @@ path = "src/main.rs"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
toml = "0.8"
|
||||
jiff = "0.2"
|
||||
|
||||
# HTTP client — synchronous, no tokio runtime, TLS via bundled rustls
|
||||
ureq = { version = "3", features = ["rustls"] }
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod config;
|
||||
pub mod domain;
|
||||
pub mod service;
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::domain::errors::{HistoryError, ResolveError, StateError};
|
||||
use crate::domain::models::{HistoryEntry, SubscriberResult};
|
||||
use crate::domain::traits::{DdnsUpdater, HistoryRepository, IpResolver, StateRepository};
|
||||
|
||||
/// High-level errors encountered by the monitor orchestrator.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ServiceError {
|
||||
#[error("WAN IP resolution failed: {0}")]
|
||||
Resolve(#[from] ResolveError),
|
||||
|
||||
#[error("State repository error: {0}")]
|
||||
State(#[from] StateError),
|
||||
|
||||
#[error("History audit logging error: {0}")]
|
||||
History(#[from] HistoryError),
|
||||
}
|
||||
|
||||
/// The outcome of an execution cycle.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RunOutcome {
|
||||
/// WAN IP has not changed since the last fully successful update.
|
||||
NoChange { ip: Ipv4Addr },
|
||||
|
||||
/// WAN IP changed and all DDNS subscribers were successfully updated.
|
||||
Updated {
|
||||
ip: Ipv4Addr,
|
||||
subscribers: Vec<SubscriberResult>,
|
||||
},
|
||||
|
||||
/// WAN IP changed, but only a subset of subscribers succeeded.
|
||||
/// `last_ip` was NOT updated.
|
||||
PartialFailure {
|
||||
ip: Ipv4Addr,
|
||||
subscribers: Vec<SubscriberResult>,
|
||||
},
|
||||
|
||||
/// WAN IP changed, but all subscribers failed.
|
||||
/// `last_ip` was NOT updated.
|
||||
AllFailed {
|
||||
ip: Ipv4Addr,
|
||||
subscribers: Vec<SubscriberResult>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Core orchestrator for WAN IP change detection and DDNS dispatching.
|
||||
pub struct IpMonitorService {
|
||||
pub resolver: Box<dyn IpResolver>,
|
||||
pub state_repo: Box<dyn StateRepository>,
|
||||
pub history_repo: Box<dyn HistoryRepository>,
|
||||
pub updaters: Vec<Box<dyn DdnsUpdater>>,
|
||||
}
|
||||
|
||||
impl IpMonitorService {
|
||||
pub fn new(
|
||||
resolver: Box<dyn IpResolver>,
|
||||
state_repo: Box<dyn StateRepository>,
|
||||
history_repo: Box<dyn HistoryRepository>,
|
||||
updaters: Vec<Box<dyn DdnsUpdater>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
resolver,
|
||||
state_repo,
|
||||
history_repo,
|
||||
updaters,
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes one cycle of IP discovery, comparison, and fan-out dispatching.
|
||||
pub fn run(&self) -> Result<RunOutcome, ServiceError> {
|
||||
let mut state = self.state_repo.load()?;
|
||||
log::debug!("Loaded existing state: {:?}", state);
|
||||
|
||||
let discovery = self.resolver.resolve(state.last_provider_index)?;
|
||||
log::info!(
|
||||
"Discovered public IP {} via provider '{}' (index {})",
|
||||
discovery.ip,
|
||||
discovery.provider,
|
||||
discovery.provider_index
|
||||
);
|
||||
|
||||
if state.last_ip == Some(discovery.ip) {
|
||||
log::info!("IP matches last successful IP ({}). No update needed.", discovery.ip);
|
||||
// Persist the updated provider index so rotation continues
|
||||
state.last_provider_index = Some(discovery.provider_index);
|
||||
self.state_repo.save(&state)?;
|
||||
return Ok(RunOutcome::NoChange { ip: discovery.ip });
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"IP change detected! Old: {:?}, New: {}. Fan-out to {} subscriber(s)",
|
||||
state.last_ip,
|
||||
discovery.ip,
|
||||
self.updaters.len()
|
||||
);
|
||||
|
||||
// Fan out to all subscribers
|
||||
let mut subscriber_results = Vec::new();
|
||||
let mut success_count = 0;
|
||||
|
||||
for updater in &self.updaters {
|
||||
let name = updater.name().to_string();
|
||||
match updater.update(discovery.ip) {
|
||||
Ok(()) => {
|
||||
log::info!("Subscriber '{}' update succeeded.", name);
|
||||
subscriber_results.push(SubscriberResult {
|
||||
provider: name,
|
||||
success: true,
|
||||
error: None,
|
||||
});
|
||||
success_count += 1;
|
||||
}
|
||||
Err(err) => {
|
||||
let err_msg = err.to_string();
|
||||
log::error!("Subscriber '{}' update failed: {}", name, err_msg);
|
||||
subscriber_results.push(SubscriberResult {
|
||||
provider: name,
|
||||
success: false,
|
||||
error: Some(err_msg),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let total = self.updaters.len();
|
||||
let (status_str, outcome) = if total == 0 || success_count == total {
|
||||
(
|
||||
"success",
|
||||
RunOutcome::Updated {
|
||||
ip: discovery.ip,
|
||||
subscribers: subscriber_results.clone(),
|
||||
},
|
||||
)
|
||||
} else if success_count > 0 {
|
||||
(
|
||||
"partial",
|
||||
RunOutcome::PartialFailure {
|
||||
ip: discovery.ip,
|
||||
subscribers: subscriber_results.clone(),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(
|
||||
"failed",
|
||||
RunOutcome::AllFailed {
|
||||
ip: discovery.ip,
|
||||
subscribers: subscriber_results.clone(),
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
// Record entry in audit history
|
||||
let timestamp = jiff::Timestamp::now().to_string();
|
||||
let entry = HistoryEntry {
|
||||
timestamp,
|
||||
ip: discovery.ip,
|
||||
status: status_str.to_string(),
|
||||
subscribers: subscriber_results,
|
||||
};
|
||||
if let Err(e) = self.history_repo.append(&entry) {
|
||||
log::warn!("Failed to append to history repository: {}", e);
|
||||
}
|
||||
|
||||
// Apply state advancement invariants
|
||||
state.last_provider_index = Some(discovery.provider_index);
|
||||
if status_str == "success" {
|
||||
state.last_ip = Some(discovery.ip);
|
||||
}
|
||||
self.state_repo.save(&state)?;
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
use ddns_monitor::domain::errors::{
|
||||
HistoryError, ResolveError, StateError, UpdateError,
|
||||
};
|
||||
use ddns_monitor::domain::models::{HistoryEntry, IpDiscoveryResult, MonitorState};
|
||||
use ddns_monitor::domain::traits::{DdnsUpdater, HistoryRepository, IpResolver, StateRepository};
|
||||
use ddns_monitor::service::{IpMonitorService, RunOutcome};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Mutex;
|
||||
|
||||
// --- Test Fakes ---
|
||||
|
||||
struct FakeResolver {
|
||||
result: Result<IpDiscoveryResult, String>,
|
||||
}
|
||||
|
||||
impl IpResolver for FakeResolver {
|
||||
fn resolve(&self, _last_index: Option<usize>) -> Result<IpDiscoveryResult, ResolveError> {
|
||||
self.result
|
||||
.clone()
|
||||
.map_err(ResolveError::AllProvidersFailed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeStateRepo {
|
||||
state: Mutex<MonitorState>,
|
||||
}
|
||||
|
||||
impl StateRepository for FakeStateRepo {
|
||||
fn load(&self) -> Result<MonitorState, StateError> {
|
||||
Ok(self.state.lock().unwrap().clone())
|
||||
}
|
||||
|
||||
fn save(&self, state: &MonitorState) -> Result<(), StateError> {
|
||||
*self.state.lock().unwrap() = state.clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeHistoryRepo {
|
||||
entries: Mutex<Vec<HistoryEntry>>,
|
||||
}
|
||||
|
||||
impl HistoryRepository for FakeHistoryRepo {
|
||||
fn append(&self, entry: &HistoryEntry) -> Result<(), HistoryError> {
|
||||
self.entries.lock().unwrap().push(entry.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeUpdater {
|
||||
name: String,
|
||||
succeed: bool,
|
||||
calls: Mutex<Vec<Ipv4Addr>>,
|
||||
}
|
||||
|
||||
impl FakeUpdater {
|
||||
fn new(name: &str, succeed: bool) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
succeed,
|
||||
calls: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DdnsUpdater for FakeUpdater {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn update(&self, ip: Ipv4Addr) -> Result<(), UpdateError> {
|
||||
self.calls.lock().unwrap().push(ip);
|
||||
if self.succeed {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(UpdateError::ProviderRejected {
|
||||
provider: self.name.clone(),
|
||||
message: "Simulated rejection".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Tests ---
|
||||
|
||||
#[test]
|
||||
fn test_no_change_when_ip_matches() {
|
||||
let old_ip = Ipv4Addr::new(93, 184, 216, 34);
|
||||
let state_repo = FakeStateRepo::default();
|
||||
state_repo
|
||||
.save(&MonitorState {
|
||||
last_provider_index: Some(0),
|
||||
last_ip: Some(old_ip),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let history_repo = FakeHistoryRepo::default();
|
||||
let resolver = FakeResolver {
|
||||
result: Ok(IpDiscoveryResult {
|
||||
ip: old_ip,
|
||||
provider: "fake_provider".to_string(),
|
||||
provider_index: 1,
|
||||
}),
|
||||
};
|
||||
|
||||
let updater = FakeUpdater::new("dynu", true);
|
||||
|
||||
let service = IpMonitorService::new(
|
||||
Box::new(resolver),
|
||||
Box::new(state_repo),
|
||||
Box::new(history_repo),
|
||||
vec![Box::new(updater)],
|
||||
);
|
||||
|
||||
let outcome = service.run().expect("service run succeeds");
|
||||
match outcome {
|
||||
RunOutcome::NoChange { ip } => assert_eq!(ip, old_ip),
|
||||
other => panic!("Expected NoChange, got: {:?}", other),
|
||||
}
|
||||
|
||||
// Verify last_ip unchanged, but last_provider_index rotated to 1
|
||||
let saved_state = service.state_repo.load().unwrap();
|
||||
assert_eq!(saved_state.last_ip, Some(old_ip));
|
||||
assert_eq!(saved_state.last_provider_index, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_successful_ip_change_updates_last_ip() {
|
||||
let old_ip = Ipv4Addr::new(93, 184, 216, 34);
|
||||
let new_ip = Ipv4Addr::new(198, 51, 100, 1);
|
||||
|
||||
let state_repo = FakeStateRepo::default();
|
||||
state_repo
|
||||
.save(&MonitorState {
|
||||
last_provider_index: Some(0),
|
||||
last_ip: Some(old_ip),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let history_repo = FakeHistoryRepo::default();
|
||||
let resolver = FakeResolver {
|
||||
result: Ok(IpDiscoveryResult {
|
||||
ip: new_ip,
|
||||
provider: "fake_provider".to_string(),
|
||||
provider_index: 1,
|
||||
}),
|
||||
};
|
||||
|
||||
let updater1 = FakeUpdater::new("dynu1", true);
|
||||
let updater2 = FakeUpdater::new("dynu2", true);
|
||||
|
||||
let service = IpMonitorService::new(
|
||||
Box::new(resolver),
|
||||
Box::new(state_repo),
|
||||
Box::new(history_repo),
|
||||
vec![Box::new(updater1), Box::new(updater2)],
|
||||
);
|
||||
|
||||
let outcome = service.run().expect("service run succeeds");
|
||||
match outcome {
|
||||
RunOutcome::Updated { ip, subscribers } => {
|
||||
assert_eq!(ip, new_ip);
|
||||
assert_eq!(subscribers.len(), 2);
|
||||
assert!(subscribers.iter().all(|s| s.success));
|
||||
}
|
||||
other => panic!("Expected Updated, got: {:?}", other),
|
||||
}
|
||||
|
||||
// Verify last_ip updated to new_ip
|
||||
let saved_state = service.state_repo.load().unwrap();
|
||||
assert_eq!(saved_state.last_ip, Some(new_ip));
|
||||
assert_eq!(saved_state.last_provider_index, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_partial_failure_preserves_old_last_ip() {
|
||||
let old_ip = Ipv4Addr::new(93, 184, 216, 34);
|
||||
let new_ip = Ipv4Addr::new(198, 51, 100, 1);
|
||||
|
||||
let state_repo = FakeStateRepo::default();
|
||||
state_repo
|
||||
.save(&MonitorState {
|
||||
last_provider_index: Some(0),
|
||||
last_ip: Some(old_ip),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let history_repo = FakeHistoryRepo::default();
|
||||
let resolver = FakeResolver {
|
||||
result: Ok(IpDiscoveryResult {
|
||||
ip: new_ip,
|
||||
provider: "fake_provider".to_string(),
|
||||
provider_index: 1,
|
||||
}),
|
||||
};
|
||||
|
||||
let updater1 = FakeUpdater::new("dynu1", true);
|
||||
let updater2 = FakeUpdater::new("dynu2", false); // fails!
|
||||
|
||||
let service = IpMonitorService::new(
|
||||
Box::new(resolver),
|
||||
Box::new(state_repo),
|
||||
Box::new(history_repo),
|
||||
vec![Box::new(updater1), Box::new(updater2)],
|
||||
);
|
||||
|
||||
let outcome = service.run().expect("service run returns partial status");
|
||||
match outcome {
|
||||
RunOutcome::PartialFailure { ip, subscribers } => {
|
||||
assert_eq!(ip, new_ip);
|
||||
assert_eq!(subscribers.len(), 2);
|
||||
assert!(subscribers.iter().any(|s| !s.success));
|
||||
}
|
||||
other => panic!("Expected PartialFailure, got: {:?}", other),
|
||||
}
|
||||
|
||||
// CRITICAL INVARIANT: last_ip MUST NOT advance on partial failure!
|
||||
let saved_state = service.state_repo.load().unwrap();
|
||||
assert_eq!(saved_state.last_ip, Some(old_ip));
|
||||
// But last_provider_index is updated to preserve rotation
|
||||
assert_eq!(saved_state.last_provider_index, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_failed_preserves_old_last_ip() {
|
||||
let old_ip = Ipv4Addr::new(93, 184, 216, 34);
|
||||
let new_ip = Ipv4Addr::new(198, 51, 100, 1);
|
||||
|
||||
let state_repo = FakeStateRepo::default();
|
||||
state_repo
|
||||
.save(&MonitorState {
|
||||
last_provider_index: Some(0),
|
||||
last_ip: Some(old_ip),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let history_repo = FakeHistoryRepo::default();
|
||||
let resolver = FakeResolver {
|
||||
result: Ok(IpDiscoveryResult {
|
||||
ip: new_ip,
|
||||
provider: "fake_provider".to_string(),
|
||||
provider_index: 2,
|
||||
}),
|
||||
};
|
||||
|
||||
let updater1 = FakeUpdater::new("dynu1", false);
|
||||
let updater2 = FakeUpdater::new("dynu2", false);
|
||||
|
||||
let service = IpMonitorService::new(
|
||||
Box::new(resolver),
|
||||
Box::new(state_repo),
|
||||
Box::new(history_repo),
|
||||
vec![Box::new(updater1), Box::new(updater2)],
|
||||
);
|
||||
|
||||
let outcome = service.run().expect("service run returns all failed status");
|
||||
match outcome {
|
||||
RunOutcome::AllFailed { ip, subscribers } => {
|
||||
assert_eq!(ip, new_ip);
|
||||
assert_eq!(subscribers.len(), 2);
|
||||
assert!(subscribers.iter().all(|s| !s.success));
|
||||
}
|
||||
other => panic!("Expected AllFailed, got: {:?}", other),
|
||||
}
|
||||
|
||||
let saved_state = service.state_repo.load().unwrap();
|
||||
assert_eq!(saved_state.last_ip, Some(old_ip));
|
||||
assert_eq!(saved_state.last_provider_index, Some(2));
|
||||
}
|
||||
Reference in new issue
Block a user