kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! One error type for the whole core. Every error carries a protocol-style
//! `code` (PROTOCOL.md ยง12, plus a few client-side codes), a message, and,
//! where the server sent them, `details` and a `hint`.

use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Error {
    pub code: String,
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<Box<Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
    /// The rejected mutation, for `rejected` events.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mutation_id: Option<String>,
    /// The HTTP status, for REST errors.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

impl Error {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Error {
        Error { code: code.into(), message: message.into(), details: None, hint: None, mutation_id: None, status: None }
    }

    pub fn with_hint(mut self, hint: impl Into<String>) -> Error {
        self.hint = Some(hint.into());
        self
    }

    pub fn with_details(mut self, details: Value) -> Error {
        self.details = Some(Box::new(details));
        self
    }

    pub(crate) fn network(e: impl fmt::Display) -> Error {
        Error::new("network", e.to_string())
    }

    pub(crate) fn storage(e: impl fmt::Display) -> Error {
        Error::new("storage", e.to_string())
    }

    pub(crate) fn config(m: impl Into<String>) -> Error {
        Error::new("config", m)
    }

    /// `details.reason`, if any.
    pub fn reason(&self) -> Option<&str> {
        self.details.as_ref()?.get("reason")?.as_str()
    }

    /// True for a transient failure worth retrying (network, 5xx, rate limits).
    pub fn is_transient(&self) -> bool {
        matches!(self.code.as_str(), "network" | "internal" | "rate_limited" | "timeout" | "shutting_down")
            || self.status.is_some_and(|s| s >= 500 || s == 429)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code, self.message)?;
        if let Some(h) = &self.hint {
            write!(f, " ({h})")?;
        }
        Ok(())
    }
}

impl std::error::Error for Error {}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Error {
        Error::new("invalid_json", e.to_string())
    }
}

#[cfg(feature = "sqlite")]
impl From<rusqlite::Error> for Error {
    fn from(e: rusqlite::Error) -> Error {
        Error::storage(e)
    }
}