redseat-api 0.2.0

Rust client for Redseat media servers
Documentation
//! The error type of the crate. Its kinds follow the TypeScript `RedseatErrorKind`
//! (`@redseat/api` `transport.ts`), plus a few for sign-in and encryption.

/// What went wrong, without the details. Mirrors the TS `RedseatErrorKind`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The server or the cloud could not be reached.
    Network,
    /// No answer in time.
    Timeout,
    /// 401: missing, expired or refused credentials.
    Unauthorized,
    /// 403.
    Forbidden,
    /// 404.
    NotFound,
    /// 5xx.
    Server,
    /// The caller cancelled the operation.
    Cancelled,
    /// The answer could not be read (not JSON, wrong shape...).
    MalformedResponse,
    /// Any other transport failure, or a client that lacks what the call needs.
    Transport,
    /// The Google sign-in failed (refused consent, wrong `state`, token exchange error).
    SignIn,
    /// An encrypted library needs its passphrase first.
    PassphraseRequired,
    /// The passphrase does not decrypt the library.
    InvalidPassphrase,
    /// Encrypted data could not be decrypted.
    Crypto,
}

/// The error of every fallible call of the crate.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error("{message}")]
    Network {
        message: String,
        path: Option<String>,
    },
    #[error("{message}")]
    Timeout {
        message: String,
        path: Option<String>,
    },
    #[error("{message}")]
    Unauthorized {
        message: String,
        status: Option<u16>,
        path: Option<String>,
    },
    #[error("{message}")]
    Forbidden {
        message: String,
        path: Option<String>,
    },
    #[error("{message}")]
    NotFound {
        message: String,
        path: Option<String>,
    },
    #[error("{message}")]
    Server {
        message: String,
        status: u16,
        path: Option<String>,
    },
    #[error("{message}")]
    Cancelled { message: String },
    #[error("{message}")]
    MalformedResponse {
        message: String,
        path: Option<String>,
    },
    #[error("{message}")]
    Transport {
        message: String,
        status: Option<u16>,
        path: Option<String>,
    },
    #[error("{message}")]
    SignIn { message: String },
    #[error("the library is encrypted: set its passphrase first")]
    PassphraseRequired,
    #[error("invalid passphrase: it does not decrypt the library")]
    InvalidPassphrase,
    #[error(transparent)]
    Crypto(#[from] redseat_crypto::Error),
}

/// Result type of the crate.
pub type Result<T, E = Error> = std::result::Result<T, E>;

impl Error {
    /// The kind of the error.
    pub fn kind(&self) -> ErrorKind {
        match self {
            Error::Network { .. } => ErrorKind::Network,
            Error::Timeout { .. } => ErrorKind::Timeout,
            Error::Unauthorized { .. } => ErrorKind::Unauthorized,
            Error::Forbidden { .. } => ErrorKind::Forbidden,
            Error::NotFound { .. } => ErrorKind::NotFound,
            Error::Server { .. } => ErrorKind::Server,
            Error::Cancelled { .. } => ErrorKind::Cancelled,
            Error::MalformedResponse { .. } => ErrorKind::MalformedResponse,
            Error::Transport { .. } => ErrorKind::Transport,
            Error::SignIn { .. } => ErrorKind::SignIn,
            Error::PassphraseRequired => ErrorKind::PassphraseRequired,
            Error::InvalidPassphrase => ErrorKind::InvalidPassphrase,
            Error::Crypto(_) => ErrorKind::Crypto,
        }
    }

    /// The HTTP status (or its equivalent in another transport), when there was one.
    pub fn status(&self) -> Option<u16> {
        match self {
            Error::Unauthorized { status, .. } | Error::Transport { status, .. } => *status,
            Error::Forbidden { .. } => Some(403),
            Error::NotFound { .. } => Some(404),
            Error::Server { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// The request path, when the error is tied to one.
    pub fn path(&self) -> Option<&str> {
        match self {
            Error::Network { path, .. }
            | Error::Timeout { path, .. }
            | Error::Unauthorized { path, .. }
            | Error::Forbidden { path, .. }
            | Error::NotFound { path, .. }
            | Error::Server { path, .. }
            | Error::MalformedResponse { path, .. }
            | Error::Transport { path, .. } => path.as_deref(),
            _ => None,
        }
    }

    pub(crate) fn transport(message: impl Into<String>) -> Self {
        Error::Transport {
            message: message.into(),
            status: None,
            path: None,
        }
    }

    pub(crate) fn malformed(message: impl Into<String>, path: Option<&str>) -> Self {
        Error::MalformedResponse {
            message: message.into(),
            path: path.map(str::to_owned),
        }
    }

    pub(crate) fn sign_in(message: impl Into<String>) -> Self {
        Error::SignIn {
            message: message.into(),
        }
    }

    /// The error for a non-success HTTP status. The message is the `message`, `code` or
    /// `error` field of a JSON body when there is one, as in the mobile app's `failure()`.
    pub fn from_status(status: u16, path: Option<&str>, body: &[u8]) -> Self {
        let path = path.map(str::to_owned);
        let message = body_message(body).unwrap_or_else(|| format!("HTTP {status}"));
        match status {
            401 => Error::Unauthorized {
                message,
                status: Some(status),
                path,
            },
            403 => Error::Forbidden { message, path },
            404 => Error::NotFound { message, path },
            500.. => Error::Server {
                message,
                status,
                path,
            },
            _ => Error::Transport {
                message,
                status: Some(status),
                path,
            },
        }
    }
}

fn body_message(body: &[u8]) -> Option<String> {
    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
    ["message", "code", "error", "error_description"]
        .iter()
        .find_map(|field| {
            value
                .get(field)
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .map(str::to_owned)
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn maps_statuses_like_the_ts_transport() {
        assert_eq!(
            Error::from_status(401, None, b"").kind(),
            ErrorKind::Unauthorized
        );
        assert_eq!(
            Error::from_status(403, None, b"").kind(),
            ErrorKind::Forbidden
        );
        assert_eq!(
            Error::from_status(404, None, b"").kind(),
            ErrorKind::NotFound
        );
        assert_eq!(Error::from_status(502, None, b"").kind(), ErrorKind::Server);
        assert_eq!(
            Error::from_status(400, None, b"").kind(),
            ErrorKind::Transport
        );
        assert_eq!(Error::from_status(400, None, b"").status(), Some(400));
    }

    #[test]
    fn reads_the_message_of_a_json_body() {
        let error = Error::from_status(400, Some("/x"), br#"{"code":"INVALID_TOKEN"}"#);
        assert_eq!(error.to_string(), "INVALID_TOKEN");
        assert_eq!(error.path(), Some("/x"));
        assert_eq!(
            Error::from_status(400, None, b"<html>").to_string(),
            "HTTP 400"
        );
    }
}