onwardz 0.1.0

Server-side SDK for managing Onwardz rooms (create rooms, issue join tokens, manage settings).
Documentation
//! Error types for the Onwardz server SDK.

use thiserror::Error;

/// An error returned by an [`OnwardzClient`](crate::OnwardzClient) call.
#[derive(Error, Debug)]
pub enum OnwardzError {
    /// The server returned a JSON-RPC error envelope. Match on
    /// [`OnwardzError::rpc_code`] to handle known conditions by name.
    #[error("RPC error {code}: {message}")]
    Rpc {
        /// The JSON-RPC error code (see [`RpcErrorCode`]).
        code: i64,
        /// Human-readable message from the server.
        message: String,
    },

    /// The server responded with a non-success HTTP status.
    #[error("HTTP {0}")]
    Http(reqwest::StatusCode),

    /// The request could not be sent, or the connection failed.
    #[error(transparent)]
    Transport(#[from] reqwest::Error),

    /// The response body was not the expected JSON shape.
    #[error("failed to decode response: {0}")]
    Decode(String),
}

impl OnwardzError {
    /// The known [`RpcErrorCode`] for this error, if it is an RPC error.
    ///
    /// ```no_run
    /// # use onwardz::{OnwardzClient, RpcErrorCode};
    /// # async fn f(onwardz: OnwardzClient, room_id: &str) {
    /// if let Err(err) = onwardz.delete_room(room_id).await {
    ///     if err.rpc_code() == Some(RpcErrorCode::RoomNotFound) {
    ///         eprintln!("already gone");
    ///     }
    /// }
    /// # }
    /// ```
    pub fn rpc_code(&self) -> Option<RpcErrorCode> {
        match self {
            OnwardzError::Rpc { code, .. } => Some(RpcErrorCode::from_code(*code)),
            _ => None,
        }
    }
}

/// Named JSON-RPC error codes returned by the Onwardz server, mirroring the
/// `RpcErrors` constants in `@onwardz/node`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RpcErrorCode {
    /// `-32000` — room ID does not exist or has been deleted.
    RoomNotFound,
    /// `-32001` — peer ID is not present in the room's signaling state.
    PeerNotFound,
    /// `-32003` — invalid or missing API key / token, or operation not permitted.
    Forbidden,
    /// `-32004` — room has reached its maximum participant cap.
    RoomFull,
    /// `-32005` — room's expiry timestamp has passed.
    RoomExpired,
    /// `-32006` — account has exhausted its monthly participant-minute quota.
    CapReached,
    /// Any other code (standard JSON-RPC codes, or codes added in the future).
    Other(i64),
}

impl RpcErrorCode {
    /// Map a raw JSON-RPC code to a [`RpcErrorCode`].
    pub fn from_code(code: i64) -> Self {
        match code {
            -32000 => RpcErrorCode::RoomNotFound,
            -32001 => RpcErrorCode::PeerNotFound,
            -32003 => RpcErrorCode::Forbidden,
            -32004 => RpcErrorCode::RoomFull,
            -32005 => RpcErrorCode::RoomExpired,
            -32006 => RpcErrorCode::CapReached,
            other => RpcErrorCode::Other(other),
        }
    }
}

/// Convenience alias for results returned by this crate.
pub type Result<T> = std::result::Result<T, OnwardzError>;

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

    #[test]
    fn maps_known_codes() {
        assert_eq!(RpcErrorCode::from_code(-32000), RpcErrorCode::RoomNotFound);
        assert_eq!(RpcErrorCode::from_code(-32004), RpcErrorCode::RoomFull);
        assert_eq!(RpcErrorCode::from_code(-32006), RpcErrorCode::CapReached);
        assert_eq!(RpcErrorCode::from_code(-32700), RpcErrorCode::Other(-32700));
    }

    #[test]
    fn rpc_code_only_for_rpc_errors() {
        let rpc = OnwardzError::Rpc {
            code: -32000,
            message: "gone".into(),
        };
        assert_eq!(rpc.rpc_code(), Some(RpcErrorCode::RoomNotFound));
        assert_eq!(
            OnwardzError::Http(reqwest::StatusCode::BAD_GATEWAY).rpc_code(),
            None
        );
    }
}