web5_rust/dwn/
json_rpc.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use super::Error;

use super::traits::Router;
use super::structs::{Packet, DwnResponse};

use crate::common::structs::Url;

use crate::dids::structs::Did;

#[jsonrpc_client::api]
pub trait Methods {
    async fn process_packet(&self, recipient: Did, payload: Vec<u8>) -> DwnResponse;
    async fn debug(&self) -> String;
    async fn health(&self) -> String;
}

#[jsonrpc_client::implement(Methods)]
#[derive(Debug)]
struct Client {
    #[jsonrpc_client(inner)]
    my_client: reqwest::Client,
    #[jsonrpc_client(base_url)]
    url: reqwest::Url,
}

#[derive(Debug, Clone, Default)]
pub struct JsonRpc {}

impl JsonRpc {
    pub fn new() -> Self {JsonRpc{}}
    pub async fn debug(&self, url: &str) -> Result<String, Error> {
        Client{
            my_client: reqwest::Client::new(),
            url: reqwest::Url::parse(url)?
        }.debug().await.map_err(|e| Error::JsonRpc(e.to_string()))
    }
    pub async fn health(&self, url: &str) -> Result<String, Error> {
        Client{
            my_client: reqwest::Client::new(),
            url: reqwest::Url::parse(url)?
        }.health().await.map_err(|e| Error::JsonRpc(e.to_string()))
    }
}

#[async_trait::async_trait]
impl Router for JsonRpc {
    async fn send_packet(
        &self,
        p: Packet,
        url: Url
    ) -> Result<DwnResponse, Error> {
        let client = Client{
            my_client: reqwest::Client::new(),
            url: reqwest::Url::parse(&url.to_string())?
        };
        Ok(match client.process_packet(p.recipient, p.payload).await {
            Ok(res) => res,
            Err(e) => Error::JsonRpc(e.to_string()).into()
        })
    }
}