use crate::config::Provider;
use std::time::Duration;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{provider}: authentication failed: {message}")]
Auth {
provider: String,
message: String,
},
#[error("{provider}: rate limited{}", .retry_after.map(|d| format!(", retry after {}s", d.as_secs())).unwrap_or_default())]
RateLimited {
provider: String,
retry_after: Option<Duration>,
},
#[error("network: {0}")]
Network(String),
#[error("{provider} API: {message}")]
Provider {
provider: String,
message: String,
},
#[error("refusing to modify records: {0}")]
Ambiguous(String),
#[error("no global address: {0}")]
NoGlobalAddress(String),
#[error("address lookup: {0}")]
AddressLookup(String),
#[error("invalid record: {0}")]
InvalidRecord(String),
#[error("invalid configuration: {0}")]
Config(String),
#[error("{context}: {source}")]
Io {
context: String,
#[source]
source: std::io::Error,
},
#[error("insecure path: {0}")]
InsecurePath(String),
#[error("already running: {0}")]
Locked(String),
#[error("wrong password or recovery phrase, or the vault was tampered with")]
WrongSecret,
#[error("invalid recovery phrase: {0}")]
InvalidRecoveryPhrase(String),
#[error("unsupported vault: {0}")]
UnsupportedVault(String),
#[error("corrupt vault: {0}")]
CorruptVault(String),
#[error("no {0} token is stored in the vault")]
TokenMissing(Provider),
#[error("crypto failure: {0}")]
Crypto(String),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
impl Error {
pub(crate) fn io(context: impl Into<String>, source: std::io::Error) -> Self {
Error::Io {
context: context.into(),
source,
}
}
pub fn provider(provider: impl Into<String>, message: impl std::fmt::Display) -> Self {
Error::Provider {
provider: provider.into(),
message: message.to_string(),
}
}
pub fn is_retryable(&self) -> bool {
matches!(
self,
Error::Network(_)
| Error::RateLimited { .. }
| Error::Provider { .. }
| Error::AddressLookup(_)
)
}
}
impl From<std::io::Error> for Error {
fn from(source: std::io::Error) -> Self {
Error::Io {
context: "I/O".into(),
source,
}
}
}
#[cfg(feature = "vault")]
impl From<weirdnet_keys::KeysError> for Error {
fn from(e: weirdnet_keys::KeysError) -> Self {
match e {
weirdnet_keys::KeysError::Unlock(_) => Error::WrongSecret,
other => Error::Crypto(other.to_string()),
}
}
}
#[allow(dead_code)]
pub(crate) trait IoContext<T> {
fn ctx(self, f: impl FnOnce() -> String) -> Result<T>;
}
impl<T> IoContext<T> for std::io::Result<T> {
fn ctx(self, f: impl FnOnce() -> String) -> Result<T> {
self.map_err(|e| Error::io(f(), e))
}
}