surreal_simple_client/
rpc.rs

1use std::fmt::Display;
2
3use tokio::sync::oneshot;
4use tokio_tungstenite::tungstenite;
5
6use crate::errors::SurrealError;
7
8pub type RpcResult<T> = Result<T, RpcChannelError>;
9
10#[derive(Debug)]
11pub enum RpcChannelError {
12  SurrealBodyParsingError { inner: serde_json::Error },
13  SocketError { inner: tungstenite::Error },
14  SurrealQueryError { inner: SurrealError },
15  OneshotError { inner: oneshot::error::RecvError },
16}
17
18impl From<tungstenite::Error> for RpcChannelError {
19  fn from(inner: tungstenite::Error) -> Self {
20    Self::SocketError { inner }
21  }
22}
23
24impl From<serde_json::Error> for RpcChannelError {
25  fn from(inner: serde_json::Error) -> Self {
26    Self::SurrealBodyParsingError { inner }
27  }
28}
29
30impl From<oneshot::error::RecvError> for RpcChannelError {
31  fn from(inner: oneshot::error::RecvError) -> Self {
32    Self::OneshotError { inner }
33  }
34}
35
36impl Display for RpcChannelError {
37  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38    match self {
39      RpcChannelError::SurrealBodyParsingError { inner } => {
40        write!(f, "Surreal body parsing errror: {}", inner)
41      }
42      RpcChannelError::SocketError { inner } => write!(f, "RPC socket error: {}", inner),
43      RpcChannelError::SurrealQueryError { inner } => {
44        write!(f, "Surreal query errror: {:?}", inner)
45      }
46      RpcChannelError::OneshotError { inner } => {
47        write!(f, "Oneshot receiver error: {inner}")
48      }
49    }
50  }
51}
52
53#[cfg(feature = "actix")]
54impl actix_web::ResponseError for RpcChannelError {
55  fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
56    actix_web::HttpResponse::build(self.status_code())
57      .insert_header(actix_web::http::header::ContentType::html())
58      .body(match self {
59        RpcChannelError::SurrealBodyParsingError { inner: _ } => {
60          "Failed to parse results from the database"
61        }
62        RpcChannelError::SocketError { inner: _ } => "RPC socket failure",
63        RpcChannelError::SurrealQueryError { inner: _ } => {
64          "Incorrect query was sent to the database"
65        }
66        RpcChannelError::OneshotError { inner: _ } => "SPSC channel failure",
67      })
68  }
69}