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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
mod recv;
use std::sync::atomic::{AtomicUsize, Ordering};

use async_timer_rs::{hashed::Timeout, Timer};
use completeq_rs::oneshot::EventReceiver;
use futures::{
    channel::mpsc::{self, Sender},
    SinkExt,
};
use recv::*;
mod send;
use send::*;
mod user_event;
use serde::{Deserialize, Serialize};
use user_event::*;

use crate::{
    channel::{RPCData, TransportChannel},
    map_error, RPCResult, Request,
};

#[derive(Clone)]
pub struct Client {
    output_sender: Sender<RPCData>,
    completed_q: RPCCompletedQ,
}

impl Client {
    pub fn new<C, S>(tag: S, channel: C) -> Self
    where
        C: TransportChannel,
        S: AsRef<str>,
    {
        static ID: AtomicUsize = AtomicUsize::new(1);

        let client_id = format!("{}_{}", tag.as_ref(), ID.fetch_add(1, Ordering::SeqCst));

        let (output_sender, output_receiver) = mpsc::channel(100);

        let completed_q = RPCCompletedQ::new();

        let (input, output) = channel.framed();

        C::spawn(send_loop::<C, String>(
            client_id.clone(),
            output,
            output_receiver,
            completed_q.clone(),
        ));

        C::spawn(recv_loop::<C, String>(
            client_id,
            input,
            completed_q.clone(),
        ));

        Self {
            output_sender,
            completed_q,
        }
    }

    pub async fn send<P>(&mut self, method: &str, params: P) -> RPCResult<Responser<Timeout>>
    where
        P: Serialize,
    {
        let receiver = self.completed_q.wait_one();

        let request = Request {
            id: Some(receiver.event_id()),
            method,
            params,
            jsonrpc: crate::Version::default(),
        };

        let data = serde_json::to_vec(&request).expect("Inner error, assembly json request");

        self.output_sender
            .send(data.into())
            .await
            .map_err(map_error)?;

        Ok(Responser {
            receiver: Some(receiver),
        })
    }

    pub async fn call<P, R>(&mut self, method: &str, params: P) -> RPCResult<R>
    where
        P: Serialize,
        for<'b> R: Deserialize<'b> + Send + 'static,
    {
        self.send(method, params).await?.recv().await
    }

    pub async fn send_with_timer<P, T>(
        &mut self,
        method: &str,
        params: P,
        timer: T,
    ) -> RPCResult<Responser<T>>
    where
        P: Serialize,
        T: Timer + Unpin + 'static,
    {
        let receiver = self.completed_q.wait_one_with_timer(timer);

        let request = Request {
            id: Some(receiver.event_id()),
            method,
            params,
            jsonrpc: crate::Version::default(),
        };

        let data = serde_json::to_vec(&request).expect("Inner error, assembly json request");

        self.output_sender
            .send(data.into())
            .await
            .map_err(map_error)?;

        Ok(Responser {
            receiver: Some(receiver),
        })
    }

    pub async fn call_with_timer<P, T, R>(
        &mut self,
        method: &str,
        params: P,
        timer: T,
    ) -> RPCResult<R>
    where
        T: Timer + Unpin + 'static,
        P: Serialize,
        for<'b> R: Deserialize<'b> + Send + 'static,
    {
        self.send_with_timer(method, params, timer)
            .await?
            .recv()
            .await
    }

    pub async fn notification<P>(&mut self, method: &str, params: P) -> RPCResult<()>
    where
        P: Serialize,
    {
        let request = Request {
            method,
            params,
            id: None,
            jsonrpc: crate::Version::default(),
        };

        let data = serde_json::to_vec(&request)?;

        self.output_sender
            .send(data.into())
            .await
            .map_err(map_error)?;

        Ok(())
    }
}

pub struct Responser<T: Timer> {
    receiver: Option<EventReceiver<RPCEvent, T>>,
}

impl<T: Timer> Responser<T>
where
    T: Unpin,
{
    pub async fn recv<R>(&mut self) -> RPCResult<R>
    where
        for<'b> R: Deserialize<'b> + Send + 'static,
    {
        let value = self
            .receiver
            .take()
            .unwrap()
            .await
            .success()
            .map_err(map_error)??;

        serde_json::from_value(value.clone()).map_err(map_error)
    }
}