chainrpc_core/
transport.rs1use async_trait::async_trait;
4use serde::de::DeserializeOwned;
5use serde_json::Value;
6
7use crate::error::TransportError;
8use crate::request::{JsonRpcRequest, JsonRpcResponse};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum HealthStatus {
13 Healthy,
15 Degraded,
17 Unhealthy,
19 Unknown,
21}
22
23impl std::fmt::Display for HealthStatus {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 match self {
26 Self::Healthy => write!(f, "healthy"),
27 Self::Degraded => write!(f, "degraded"),
28 Self::Unhealthy => write!(f, "unhealthy"),
29 Self::Unknown => write!(f, "unknown"),
30 }
31 }
32}
33
34#[async_trait]
42pub trait RpcTransport: Send + Sync + 'static {
43 async fn send(&self, req: JsonRpcRequest) -> Result<JsonRpcResponse, TransportError>;
45
46 async fn send_batch(
50 &self,
51 reqs: Vec<JsonRpcRequest>,
52 ) -> Result<Vec<JsonRpcResponse>, TransportError> {
53 let mut responses = Vec::with_capacity(reqs.len());
54 for req in reqs {
55 responses.push(self.send(req).await?);
56 }
57 Ok(responses)
58 }
59
60 fn health(&self) -> HealthStatus {
62 HealthStatus::Unknown
63 }
64
65 fn url(&self) -> &str;
67
68 async fn call<T: DeserializeOwned>(
70 &self,
71 id: u64,
72 method: &str,
73 params: Vec<Value>,
74 ) -> Result<T, TransportError>
75 where
76 Self: Sized,
77 {
78 let req = JsonRpcRequest::new(id, method, params);
79 let resp = self.send(req).await?;
80 let result = resp.into_result().map_err(TransportError::Rpc)?;
81 serde_json::from_value(result).map_err(TransportError::Deserialization)
82 }
83}