feat(cli): wire composition root and end-to-end service execution
- Implement main binary entry point with CLI and env configuration resolution - Wire HttpIpResolver, JsonStateRepository, JsonlHistoryRepository, and DynuUpdater - Enforce exit status semantics (0 on success or no-change, 1 on failure) - Add end-to-end integration test validating composition and lifecycle
This commit is contained in:
1 parent
ff1e15987a
commit
e9ea5a9f6a
2 files changed
+247
-3
No files matched your search
+136
-3
@@ -1,8 +1,141 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use ddns_monitor::config::AppConfig;
|
||||
use ddns_monitor::domain::traits::DdnsUpdater;
|
||||
use ddns_monitor::infra::history_store::JsonlHistoryRepository;
|
||||
use ddns_monitor::infra::http_resolver::HttpIpResolver;
|
||||
use ddns_monitor::infra::state_store::JsonStateRepository;
|
||||
use ddns_monitor::plugins::dynu::DynuUpdater;
|
||||
use ddns_monitor::service::{IpMonitorService, RunOutcome};
|
||||
|
||||
fn find_config_path() -> Result<PathBuf, String> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
if (args[i] == "-c" || args[i] == "--config") && i + 1 < args.len() {
|
||||
return Ok(PathBuf::from(&args[i + 1]));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if let Ok(env_path) = std::env::var("DDNS_CONFIG_PATH") {
|
||||
return Ok(PathBuf::from(env_path));
|
||||
}
|
||||
|
||||
let candidate = Path::new("config.toml");
|
||||
if candidate.exists() {
|
||||
return Ok(candidate.to_path_buf());
|
||||
}
|
||||
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
let xdg = PathBuf::from(home)
|
||||
.join(".config")
|
||||
.join("ddns-monitor")
|
||||
.join("config.toml");
|
||||
if xdg.exists() {
|
||||
return Ok(xdg);
|
||||
}
|
||||
}
|
||||
|
||||
let sys = Path::new("/etc/ddns-monitor/config.toml");
|
||||
if sys.exists() {
|
||||
return Ok(sys.to_path_buf());
|
||||
}
|
||||
|
||||
Err("No configuration file found. Specify via --config, DDNS_CONFIG_PATH, or ~/.config/ddns-monitor/config.toml".to_string())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
|
||||
log::info!("ddns-monitor starting");
|
||||
|
||||
// TODO: wire IpMonitorService and run the full workflow.
|
||||
eprintln!("ddns-monitor: not yet implemented");
|
||||
let config_path = match find_config_path() {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
log::error!("{}", e);
|
||||
eprintln!("Error: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
log::info!("Loading configuration from '{}'", config_path.display());
|
||||
let config = match AppConfig::load_from_path(&config_path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("Failed to load configuration: {}", e);
|
||||
eprintln!("Configuration error: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let timeout = Duration::from_secs(config.ip_providers.timeout_secs);
|
||||
let resolver = HttpIpResolver::new(config.ip_providers.urls.clone(), timeout);
|
||||
let state_repo = JsonStateRepository::new(config.resolve_state_path());
|
||||
let history_repo = JsonlHistoryRepository::new(config.resolve_history_path());
|
||||
|
||||
let mut updaters: Vec<Box<dyn DdnsUpdater>> = Vec::new();
|
||||
for sub in &config.subscribers {
|
||||
match sub.provider.as_str() {
|
||||
"dynu" => {
|
||||
let credential = match sub.resolve_credential() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("Failed resolving credentials for '{}': {}", sub.domain, e);
|
||||
eprintln!("Credential error for {}: {}", sub.domain, e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
updaters.push(Box::new(DynuUpdater::new(&sub.domain, &credential, timeout)));
|
||||
}
|
||||
unknown => {
|
||||
log::error!("Unsupported DDNS provider: '{}'", unknown);
|
||||
eprintln!("Unsupported provider: {}", unknown);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let service = IpMonitorService::new(
|
||||
Box::new(resolver),
|
||||
Box::new(state_repo),
|
||||
Box::new(history_repo),
|
||||
updaters,
|
||||
);
|
||||
|
||||
match service.run() {
|
||||
Ok(RunOutcome::NoChange { ip }) => {
|
||||
log::info!("Execution complete: No IP change detected (current: {}).", ip);
|
||||
std::process::exit(0);
|
||||
}
|
||||
Ok(RunOutcome::Updated { ip, subscribers }) => {
|
||||
log::info!(
|
||||
"Execution complete: Successfully updated {} subscriber(s) with IP {}.",
|
||||
subscribers.len(),
|
||||
ip
|
||||
);
|
||||
std::process::exit(0);
|
||||
}
|
||||
Ok(RunOutcome::PartialFailure { ip, subscribers }) => {
|
||||
log::error!(
|
||||
"Execution finished with partial failure: IP is {}, but not all subscribers succeeded: {:?}",
|
||||
ip,
|
||||
subscribers
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(RunOutcome::AllFailed { ip, subscribers }) => {
|
||||
log::error!(
|
||||
"Execution failed: IP is {}, but all subscribers failed: {:?}",
|
||||
ip,
|
||||
subscribers
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Service error: {}", e);
|
||||
eprintln!("Service error: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use ddns_monitor::config::AppConfig;
|
||||
use ddns_monitor::domain::traits::DdnsUpdater;
|
||||
use ddns_monitor::infra::history_store::JsonlHistoryRepository;
|
||||
use ddns_monitor::infra::http_resolver::HttpIpResolver;
|
||||
use ddns_monitor::infra::state_store::JsonStateRepository;
|
||||
use ddns_monitor::plugins::dynu::DynuUpdater;
|
||||
use ddns_monitor::service::{IpMonitorService, RunOutcome};
|
||||
use std::fs;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn test_end_to_end_wireup() {
|
||||
let mut ip_server = mockito::Server::new();
|
||||
let _m_ip = ip_server
|
||||
.mock("GET", "/ip")
|
||||
.with_status(200)
|
||||
.with_body("93.184.216.34\n")
|
||||
.create();
|
||||
|
||||
let mut dynu_server = mockito::Server::new();
|
||||
let _m_dynu = dynu_server
|
||||
.mock("GET", "/nic/update")
|
||||
.match_query(mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_body("good 93.184.216.34\n")
|
||||
.create();
|
||||
|
||||
let temp_dir = std::env::temp_dir().join("ddns_e2e_test");
|
||||
let _ = fs::remove_dir_all(&temp_dir);
|
||||
fs::create_dir_all(&temp_dir).unwrap();
|
||||
|
||||
let state_path = temp_dir.join("state.json");
|
||||
let history_path = temp_dir.join("history.jsonl");
|
||||
|
||||
let toml_content = format!(
|
||||
r#"
|
||||
[ip_providers]
|
||||
urls = ["{}/ip"]
|
||||
timeout_secs = 2
|
||||
|
||||
[[subscribers]]
|
||||
provider = "dynu"
|
||||
domain = "mytest.dyndns.org"
|
||||
credentials_env = "E2E_DYNU_SECRET"
|
||||
"#,
|
||||
ip_server.url()
|
||||
);
|
||||
|
||||
unsafe {
|
||||
std::env::set_var("E2E_DYNU_SECRET", "super_secret");
|
||||
}
|
||||
|
||||
let config = AppConfig::from_toml(&toml_content).unwrap();
|
||||
|
||||
let resolver = HttpIpResolver::new(
|
||||
config.ip_providers.urls.clone(),
|
||||
Duration::from_secs(config.ip_providers.timeout_secs),
|
||||
);
|
||||
let state_repo = JsonStateRepository::new(&state_path);
|
||||
let history_repo = JsonlHistoryRepository::new(&history_path);
|
||||
|
||||
let mut updaters: Vec<Box<dyn DdnsUpdater>> = Vec::new();
|
||||
for sub in &config.subscribers {
|
||||
let cred = sub.resolve_credential().unwrap();
|
||||
let dynu_endpoint = format!("{}/nic/update", dynu_server.url());
|
||||
let updater = DynuUpdater::with_endpoint(
|
||||
&sub.domain,
|
||||
&cred,
|
||||
dynu_endpoint,
|
||||
Duration::from_secs(config.ip_providers.timeout_secs),
|
||||
);
|
||||
updaters.push(Box::new(updater));
|
||||
}
|
||||
|
||||
let service = IpMonitorService::new(
|
||||
Box::new(resolver),
|
||||
Box::new(state_repo),
|
||||
Box::new(history_repo),
|
||||
updaters,
|
||||
);
|
||||
|
||||
// First run: detects IP, updates Dynu, saves state
|
||||
let outcome = service.run().expect("first run succeeds");
|
||||
match outcome {
|
||||
RunOutcome::Updated { ip, subscribers } => {
|
||||
assert_eq!(ip, Ipv4Addr::new(93, 184, 216, 34));
|
||||
assert_eq!(subscribers.len(), 1);
|
||||
assert!(subscribers[0].success);
|
||||
}
|
||||
other => panic!("Expected Updated, got {:?}", other),
|
||||
}
|
||||
|
||||
// Verify files created on disk
|
||||
assert!(state_path.exists());
|
||||
assert!(history_path.exists());
|
||||
|
||||
// Second run: IP hasn't changed -> NoChange outcome
|
||||
let second_outcome = service.run().expect("second run succeeds");
|
||||
match second_outcome {
|
||||
RunOutcome::NoChange { ip } => {
|
||||
assert_eq!(ip, Ipv4Addr::new(93, 184, 216, 34));
|
||||
}
|
||||
other => panic!("Expected NoChange, got {:?}", other),
|
||||
}
|
||||
|
||||
unsafe {
|
||||
std::env::remove_var("E2E_DYNU_SECRET");
|
||||
}
|
||||
let _ = fs::remove_dir_all(&temp_dir);
|
||||
}
|
||||
Reference in new issue
Block a user