Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ opt-level = 0
lto = false

[dependencies]
anyhow = "1.0.99"
async-trait = "0.1.89"
clap = { version = "4.5.39", features = ["derive", "unicode", "wrap_help"] }
dirs = "6.0.0"
Expand Down
4 changes: 2 additions & 2 deletions src/cli/generate_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use clap::Parser;
use lum_log::info;
use thiserror::Error;

use crate::{Config, cli::ExecutableCommand};
use crate::{Config, ConfigError, cli::ExecutableCommand};

#[derive(Debug)]
pub struct Input<'config> {
Expand All @@ -20,7 +20,7 @@ pub enum Error {
Yaml(#[from] serde_yaml_ng::Error),

#[error("Config error: {0}")]
Config(#[from] anyhow::Error),
Config(#[from] ConfigError),
}

/// Generate configuration directory structure
Expand Down
18 changes: 10 additions & 8 deletions src/cli/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
cli::ExecutableCommand,
config::provider::Provider as ProviderConfig,
provider::{
GetAllRecordsInput, GetRecordsInput, Provider, hetzner::HetznerProvider,
GetAllRecordsInput, GetRecordsInput, Provider, ProviderError, hetzner::HetznerProvider,
netcup::NetcupProvider, nitrado::NitradoProvider,
},
};
Expand All @@ -26,7 +26,13 @@ pub enum Error {
ProviderNotConfigured(String),

#[error("Provider error: {0}")]
ProviderError(#[from] anyhow::Error),
Provider(#[from] ProviderError),

#[error("Cannot specify both --all and specific subdomains")]
ConflictingArguments,

#[error("Must specify either --all or specific subdomains")]
MissingArguments,
}

#[derive(Debug, Args)]
Expand Down Expand Up @@ -94,16 +100,12 @@ impl<'command> ExecutableCommand<'command> for Command<'command> {
async fn execute(&self, input: &'command Self::I) -> Self::R {
if self.subdomain_args.all && !self.subdomain_args.subdomains.is_empty() {
error!("Cannot specify both --all and specific subdomains");
return Err(Error::ProviderError(anyhow::anyhow!(
"Cannot specify both --all and specific subdomains"
)));
return Err(Error::ConflictingArguments);
}

if !self.subdomain_args.all && self.subdomain_args.subdomains.is_empty() {
error!("Must specify either --all or specific subdomains");
return Err(Error::ProviderError(anyhow::anyhow!(
"Must specify either --all or specific subdomains"
)));
return Err(Error::MissingArguments);
}

let config = input.config;
Expand Down
60 changes: 36 additions & 24 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
//TODO: No anyhow
use anyhow::Result;
use lum_config::MergeFrom;
use lum_libs::serde::{Deserialize, Serialize};
use lum_log::{debug, error, info};
use std::{fs, path::Path};
use lum_log::{debug, info};
use std::{fs, io, path::Path};
use thiserror::Error;

use crate::{
config::provider::Provider,
Expand All @@ -14,6 +13,22 @@ pub mod dns;
pub mod provider;
pub mod resolver;

/// Error type for configuration loading and parsing.
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("IO error: {0}")]
Io(#[from] io::Error),

#[error("YAML parsing error: {0}")]
Yaml(#[from] serde_yaml_ng::Error),

#[error("Unknown provider config file: {0}")]
UnknownProvider(String),

#[error("Cannot determine DNS config type for file: {0}")]
UnknownDnsType(String),
}

Copy link
Contributor

@Kitt3120 Kitt3120 Jan 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you check if it makes sense to use individual Error enums for the different methods below instead of having them all return the same general ConfigError enum? Or does every method below actually need all of the enum values? Then using the same ConfigError enum for all of them makes sense. Otherwise, define specific error enums per method.

/// Configuration for the dnrs application.
///
/// This struct holds all the configuration required to run the application,
Expand All @@ -28,11 +43,11 @@ pub struct Config {
}

impl Config {
pub fn load_from_directory(config_dir: impl AsRef<Path>) -> Result<Self> {
pub fn load_from_directory(config_dir: impl AsRef<Path>) -> Result<Self, ConfigError> {
let config_dir = config_dir.as_ref();
let resolver = Self::load_resolver_config(config_dir)?;
let providers = Self::load_provider_configs(&config_dir.join("providers"))?;
let dns = Self::load_dns_configs(&config_dir.join("dns"))?;
let providers = Self::load_provider_configs(config_dir.join("providers"))?;
let dns = Self::load_dns_configs(config_dir.join("dns"))?;

let loaded_config = Config {
resolver,
Expand All @@ -44,7 +59,7 @@ impl Config {
Ok(default_config.merge_from(loaded_config))
}

fn load_resolver_config(config_dir: impl AsRef<Path>) -> Result<resolver::Config> {
fn load_resolver_config(config_dir: impl AsRef<Path>) -> Result<resolver::Config, ConfigError> {
let resolver_path = config_dir.as_ref().join("resolver.yaml");

//TODO: Fail with error if resolver config is missing
Expand All @@ -56,7 +71,9 @@ impl Config {
}
}

fn load_provider_configs(providers_dir: impl AsRef<Path>) -> Result<Vec<Provider>> {
fn load_provider_configs(
providers_dir: impl AsRef<Path>,
) -> Result<Vec<Provider>, ConfigError> {
let providers_dir = providers_dir.as_ref();
//TODO: Fail with error if providers config is missing
if !providers_dir.exists() {
Expand All @@ -78,7 +95,7 @@ impl Config {

if path
.extension()
.map_or(false, |ext| ext == "yaml" || ext == "yml")
.is_some_and(|ext| ext == "yaml" || ext == "yml")
{
let content = fs::read_to_string(&path)?;

Expand All @@ -105,7 +122,7 @@ impl Config {
debug!("Loaded Netcup provider config from {:?}", path);
}
_ => {
error!("Unknown provider config file: {}", path.display());
return Err(ConfigError::UnknownProvider(path.display().to_string()));
}
}
}
Expand All @@ -120,7 +137,7 @@ impl Config {
Ok(configs)
}

fn load_dns_configs(dns_dir: impl AsRef<Path>) -> Result<Vec<dns::Type>> {
fn load_dns_configs(dns_dir: impl AsRef<Path>) -> Result<Vec<dns::Type>, ConfigError> {
let dns_dir = dns_dir.as_ref();

//TODO: Fail with error if dns config is missing
Expand All @@ -139,7 +156,7 @@ impl Config {

if path
.extension()
.map_or(false, |ext| ext == "yaml" || ext == "yml")
.is_some_and(|ext| ext == "yaml" || ext == "yml")
{
let content = fs::read_to_string(&path)?;

Expand All @@ -162,10 +179,7 @@ impl Config {
configs.push(dns::Type::Netcup(config));
debug!("Loaded Netcup DNS config from {:?}", path);
} else {
error!(
"Cannot determine DNS config type for file: {}",
path.display()
);
return Err(ConfigError::UnknownDnsType(path.display().to_string()));
}
}
}
Expand All @@ -174,7 +188,7 @@ impl Config {
Ok(configs)
}

pub fn create_example_structure(config_dir: impl AsRef<Path>) -> Result<()> {
pub fn create_example_structure(config_dir: impl AsRef<Path>) -> Result<(), ConfigError> {
let config_dir = config_dir.as_ref();

fs::create_dir_all(config_dir.join("providers"))?;
Expand Down Expand Up @@ -271,12 +285,10 @@ mod tests {
let default_config = Config::default();
let other = Config {
resolver: resolver::Config::default(),
providers: vec![Provider::Nitrado(
nitrado::Config {
name: "OtherNitrado".to_string(),
..Default::default()
},
)],
providers: vec![Provider::Nitrado(nitrado::Config {
name: "OtherNitrado".to_string(),
..Default::default()
})],
dns: vec![],
};

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub mod types;
#[cfg(test)]
mod cli_tests;

pub use config::Config;
pub use config::{Config, ConfigError};
pub use logger::setup_logger;

pub const PROGRAM_NAME: &str = env!("CARGO_PKG_NAME");
Expand Down
22 changes: 11 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::{self, Debug};
use std::fs;

use dnrs::{Config, RuntimeError, run, setup_logger};
use dnrs::{Config, ConfigError, RuntimeError, run, setup_logger};
use lum_config::{ConfigPathError, EnvironmentConfigParseError, FileConfigParseError};
use lum_log::{info, log::SetLoggerError};
use thiserror::Error;
Expand Down Expand Up @@ -59,7 +59,7 @@ enum Error {
Io(#[from] std::io::Error),

#[error("Config error: {0}")]
Config(#[from] anyhow::Error),
Config(#[from] ConfigError),

#[error("Unable to determine config directory")]
NoConfigDirectory,
Expand All @@ -78,22 +78,22 @@ impl Debug for Error {
}
}

fn read_config() -> Result<Config, Error> {
fn read_config() -> Result<Config, Box<Error>> {
let config_dir = dirs::config_dir()
.ok_or(Error::NoConfigDirectory)?
.ok_or(Box::new(Error::NoConfigDirectory))?
.join(APP_NAME);

if config_dir.exists() && !config_dir.is_dir() {
return Err(Error::ConfigIsNotDirectory);
return Err(Box::new(Error::ConfigIsNotDirectory));
}

let config = if config_dir.exists() {
Config::load_from_directory(&config_dir)?
Config::load_from_directory(&config_dir).map_err(|e| Box::new(Error::from(e)))?
} else {
info!("Config directory does not exist, creating default structure...");
fs::create_dir_all(&config_dir)?;
fs::create_dir_all(&config_dir).map_err(|e| Box::new(Error::from(e)))?;

Config::create_example_structure(&config_dir)?;
Config::create_example_structure(&config_dir).map_err(|e| Box::new(Error::from(e)))?;
info!(
"Created default config structure at: {}",
config_dir.display()
Expand All @@ -108,11 +108,11 @@ fn read_config() -> Result<Config, Error> {
}

#[tokio::main]
async fn main() -> Result<(), Error> {
setup_logger()?;
async fn main() -> Result<(), Box<Error>> {
setup_logger().map_err(|e| Box::new(Error::from(e)))?;

let config = read_config()?;
run(config).await?;
run(config).await.map_err(|e| Box::new(Error::from(e)))?;

Ok(())
}
48 changes: 37 additions & 11 deletions src/provider.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use anyhow::Result;
use async_trait::async_trait;

use crate::types::dns::Record;

pub mod error;
pub mod hetzner;
pub mod netcup;
pub mod nitrado;

pub use error::ProviderError;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Feature {
GetRecords,
Expand Down Expand Up @@ -70,12 +72,12 @@ pub trait Provider: Send + Sync {
&self,
reqwest: reqwest::Client,
input: &GetRecordsInput,
) -> Result<Vec<Record>> {
) -> Result<Vec<Record>, ProviderError> {
let get_all_records_input = GetAllRecordsInput::from(input);
let records = self
.get_all_records(reqwest, &get_all_records_input)
.await?;
let records = records
let records: Vec<Record> = records
.into_iter()
.filter(|record| input.subdomains.contains(&record.domain.as_str()))
.collect();
Expand All @@ -87,11 +89,23 @@ pub trait Provider: Send + Sync {
&self,
reqwest: reqwest::Client,
input: &GetAllRecordsInput,
) -> Result<Vec<Record>>;
) -> Result<Vec<Record>, ProviderError>;

async fn add_record(&self, reqwest: reqwest::Client, record: &Record) -> Result<()>;
async fn update_record(&self, reqwest: reqwest::Client, record: &Record) -> Result<()>;
async fn delete_record(&self, reqwest: reqwest::Client, record: &Record) -> Result<()>;
async fn add_record(
&self,
reqwest: reqwest::Client,
record: &Record,
) -> Result<(), ProviderError>;
async fn update_record(
&self,
reqwest: reqwest::Client,
record: &Record,
) -> Result<(), ProviderError>;
async fn delete_record(
&self,
reqwest: reqwest::Client,
record: &Record,
) -> Result<(), ProviderError>;
}

#[cfg(test)]
Expand Down Expand Up @@ -119,19 +133,31 @@ mod tests {
&self,
_reqwest: reqwest::Client,
_input: &GetAllRecordsInput,
) -> Result<Vec<Record>> {
) -> Result<Vec<Record>, ProviderError> {
Ok(self.records.clone())
}

async fn add_record(&self, _reqwest: reqwest::Client, _record: &Record) -> Result<()> {
async fn add_record(
&self,
_reqwest: reqwest::Client,
_record: &Record,
) -> Result<(), ProviderError> {
unimplemented!()
}

async fn update_record(&self, _reqwest: reqwest::Client, _record: &Record) -> Result<()> {
async fn update_record(
&self,
_reqwest: reqwest::Client,
_record: &Record,
) -> Result<(), ProviderError> {
unimplemented!()
}

async fn delete_record(&self, _reqwest: reqwest::Client, _record: &Record) -> Result<()> {
async fn delete_record(
&self,
_reqwest: reqwest::Client,
_record: &Record,
) -> Result<(), ProviderError> {
unimplemented!()
}
}
Expand Down
Loading