use std::fmt;
use serde::{Deserialize, Serialize};
pub mod message;
mod peer;
pub mod trace;
pub mod transport;
pub use peer::{Connection, Options, Peer, Router, connect};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ErrorCode(pub i32);
impl ErrorCode {
pub const PARSE_ERROR: Self = Self(-32700);
pub const INVALID_REQUEST: Self = Self(-32600);
pub const METHOD_NOT_FOUND: Self = Self(-32601);
pub const INVALID_PARAMS: Self = Self(-32602);
pub const INTERNAL_ERROR: Self = Self(-32603);
pub const REQUEST_CANCELLED: Self = Self(-32800);
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RpcError {
pub code: ErrorCode,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
}
impl RpcError {
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: None,
}
}
pub fn internal(message: impl Into<String>) -> Self {
Self::new(ErrorCode::INTERNAL_ERROR, message)
}
}
impl fmt::Display for RpcError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} (code {})", self.message, self.code.0)
}
}
impl std::error::Error for RpcError {}
#[derive(Debug)]
pub enum Error {
Remote(RpcError),
Closed,
Timeout,
Codec(message::CodecError),
Io(std::io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Remote(e) => write!(f, "remote error: {e}"),
Error::Closed => f.write_str("connection closed"),
Error::Timeout => f.write_str("request timed out"),
Error::Codec(e) => write!(f, "codec error: {e}"),
Error::Io(e) => write!(f, "transport error: {e}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Remote(e) => Some(e),
Error::Codec(e) => Some(e),
Error::Io(e) => Some(e),
Error::Closed | Error::Timeout => None,
}
}
}
impl From<message::CodecError> for Error {
fn from(e: message::CodecError) -> Self {
Error::Codec(e)
}
}