use std::convert::Infallible;
use std::fmt;
use std::str::FromStr;
pub type Result<T, E = DecaneError> = std::result::Result<T, E>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AuthErrorReason {
InvalidToken,
MissingUid,
ProjectMismatch,
}
impl AuthErrorReason {
pub fn as_str(&self) -> &'static str {
match self {
Self::InvalidToken => "invalid_token",
Self::MissingUid => "missing_uid",
Self::ProjectMismatch => "project_mismatch",
}
}
}
impl fmt::Display for AuthErrorReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
macro_rules! api_error_codes {
($( $(#[$meta:meta])* $variant:ident => $wire:literal ),* $(,)?) => {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ApiErrorCode {
$( $(#[$meta])* $variant, )*
Other(String),
}
impl ApiErrorCode {
pub fn as_str(&self) -> &str {
match self {
$( Self::$variant => $wire, )*
Self::Other(code) => code,
}
}
}
impl FromStr for ApiErrorCode {
type Err = Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Infallible> {
Ok(match s {
$( $wire => Self::$variant, )*
other => Self::Other(other.to_owned()),
})
}
}
};
}
api_error_codes! {
InvalidCode => "INVALID_CODE",
AuthFailed => "AUTH_FAILED",
InvalidToken => "INVALID_TOKEN",
NoProvider => "NO_PROVIDER",
AmbiguousProvider => "AMBIGUOUS_PROVIDER",
MissingClaim => "MISSING_CLAIM",
BadRequest => "BAD_REQUEST",
InvalidApiKey => "INVALID_API_KEY",
AppIdMismatch => "APP_ID_MISMATCH",
SmsNotConfigured => "SMS_NOT_CONFIGURED",
KingsChatNotConfigured => "KINGSCHAT_NOT_CONFIGURED",
KingsChatUnavailable => "KINGSCHAT_UNAVAILABLE",
RevokeFailed => "REVOKE_FAILED",
InvalidRecord => "INVALID_RECORD",
NotFound => "NOT_FOUND",
Unauthorized => "UNAUTHORIZED",
ServerWalletsDisabled => "SERVER_WALLETS_DISABLED",
InvalidIdentifier => "INVALID_IDENTIFIER",
WalletExists => "WALLET_EXISTS",
WalletFrozen => "WALLET_FROZEN",
LoginInUse => "LOGIN_IN_USE",
EnclaveUnavailable => "ENCLAVE_UNAVAILABLE",
RetryLater => "RETRY_LATER",
RateLimited => "RATE_LIMITED",
Unknown => "UNKNOWN",
NetworkError => "NETWORK_ERROR",
}
impl fmt::Display for ApiErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl From<&str> for ApiErrorCode {
fn from(s: &str) -> Self {
s.parse().unwrap_or_else(|never| match never {})
}
}
pub type Source = Box<dyn std::error::Error + Send + Sync + 'static>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DecaneError {
#[error("{message}")]
Auth {
reason: AuthErrorReason,
message: String,
#[source]
source: Option<Source>,
},
#[error("{message} ({code}, HTTP {status})")]
Api {
code: ApiErrorCode,
status: u16,
message: String,
#[source]
source: Option<Source>,
},
#[error("{0}")]
Config(String),
}
impl DecaneError {
pub(crate) fn auth(reason: AuthErrorReason, message: impl Into<String>) -> Self {
Self::Auth {
reason,
message: message.into(),
source: None,
}
}
pub(crate) fn config(message: impl Into<String>) -> Self {
Self::Config(message.into())
}
pub fn is_auth(&self) -> bool {
matches!(self, Self::Auth { .. })
}
pub fn auth_reason(&self) -> Option<AuthErrorReason> {
match self {
Self::Auth { reason, .. } => Some(*reason),
_ => None,
}
}
pub fn api_code(&self) -> Option<&ApiErrorCode> {
match self {
Self::Api { code, .. } => Some(code),
_ => None,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Api { status, .. } => Some(*status),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn api_error_code_round_trips_the_wire_string() {
let known: ApiErrorCode = "KINGSCHAT_UNAVAILABLE".parse().unwrap();
assert_eq!(known, ApiErrorCode::KingsChatUnavailable);
assert_eq!(known.to_string(), "KINGSCHAT_UNAVAILABLE");
let other: ApiErrorCode = "SOMETHING_NEW".parse().unwrap();
assert_eq!(other, ApiErrorCode::Other("SOMETHING_NEW".into()));
assert_eq!(other.to_string(), "SOMETHING_NEW");
}
#[test]
fn auth_reason_matches_node_spelling() {
assert_eq!(
AuthErrorReason::ProjectMismatch.to_string(),
"project_mismatch"
);
assert_eq!(AuthErrorReason::MissingUid.as_str(), "missing_uid");
assert_eq!(AuthErrorReason::InvalidToken.as_str(), "invalid_token");
}
}