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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::{
collections::{HashMap, VecDeque},
io,
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use futures::{
sink::SinkExt,
stream::{Stream, StreamExt},
};
use serde::{Deserialize, Serialize};
use tokio_util::codec::Framed;
use stream_codec::StreamCodec;
mod stream_codec;
pub struct Client<T> {
inner: Framed<T, StreamCodec>,
id: usize,
}
impl<T> Client<T>
where
T: tokio::io::AsyncWrite + tokio::io::AsyncRead + Unpin,
{
pub fn new(io: T) -> Client<T> {
let inner = Framed::new(io, StreamCodec::stream_incoming());
Client { inner, id: 0 }
}
pub async fn subscribe<F: for<'de> serde::de::Deserialize<'de>>(
mut self,
name: &str,
) -> io::Result<Handle<T, F>> {
let mut topic_list = HashMap::default();
let mut pending_recv = VecDeque::new();
subscribe(
&mut self.inner,
self.id,
name,
&mut topic_list,
&mut pending_recv,
)
.await?;
self.id = self.id.wrapping_add(1);
Ok(Handle {
inner: self.inner,
topic_list,
output: PhantomData::default(),
rpc_id: self.id,
pending_recv,
})
}
pub async fn subscribe_list<
F: for<'de> serde::de::Deserialize<'de>,
I: Iterator<Item = H>,
H: AsRef<str>,
>(
mut self,
name_list: I,
) -> io::Result<Handle<T, F>> {
let mut topic_list = HashMap::default();
let mut pending_recv = VecDeque::new();
for topic in name_list {
subscribe(
&mut self.inner,
self.id,
topic,
&mut topic_list,
&mut pending_recv,
)
.await?;
self.id = self.id.wrapping_add(1);
}
Ok(Handle {
inner: self.inner,
topic_list,
output: PhantomData::default(),
rpc_id: self.id,
pending_recv,
})
}
}
pub struct Handle<T, F> {
inner: Framed<T, StreamCodec>,
topic_list: HashMap<String, String>,
output: PhantomData<F>,
rpc_id: usize,
pending_recv: VecDeque<bytes::BytesMut>,
}
impl<T, F> Handle<T, F>
where
T: tokio::io::AsyncWrite + tokio::io::AsyncRead + Unpin,
{
pub fn ids(&self) -> impl Iterator<Item = &String> {
self.topic_list.keys()
}
pub fn topics(&self) -> impl Iterator<Item = &String> {
self.topic_list.values()
}
pub fn try_into(self) -> Result<Client<T>, Self> {
if self.topic_list.is_empty() {
Ok(Client {
inner: self.inner,
id: self.rpc_id,
})
} else {
Err(self)
}
}
pub async fn subscribe(mut self, topic: &str) -> io::Result<Self> {
if self.topic_list.iter().any(|(_, v)| *v == topic) {
return Ok(self);
}
subscribe(
&mut self.inner,
self.rpc_id,
topic,
&mut self.topic_list,
&mut self.pending_recv,
)
.await?;
self.rpc_id = self.rpc_id.wrapping_add(1);
Ok(self)
}
pub async fn unsubscribe(&mut self, topic: &str) -> io::Result<()> {
let id = {
let id = self
.topic_list
.iter()
.find_map(|(k, v)| if v == topic { Some(k) } else { None })
.cloned();
if id.is_none() {
return Ok(());
}
id.unwrap()
};
let req_json = format!(
r#"{{"id": {}, "jsonrpc": "2.0", "method": "unsubscribe", "params": ["{}"]}}"#,
self.rpc_id, id
);
self.rpc_id = self.rpc_id.wrapping_add(1);
self.inner.send(req_json).await?;
let output = loop {
let resp = self.inner.next().await;
let resp = resp.ok_or_else::<io::Error, _>(|| io::ErrorKind::BrokenPipe.into())??;
match serde_json::from_slice::<jsonrpc_core::response::Output>(&resp) {
Ok(output) => break output,
Err(_) => self.pending_recv.push_back(resp),
}
};
match output {
jsonrpc_core::response::Output::Success(_) => {
self.topic_list.remove(&id);
Ok(())
}
jsonrpc_core::response::Output::Failure(e) => {
Err(io::Error::new(io::ErrorKind::InvalidData, e.error))
}
}
}
pub async fn unsubscribe_all(mut self) -> io::Result<Client<T>> {
for topic in self.topic_list.clone().values() {
self.unsubscribe(topic).await?
}
Ok(Client {
inner: self.inner,
id: self.rpc_id,
})
}
}
impl<T, F> Stream for Handle<T, F>
where
F: for<'de> serde::de::Deserialize<'de> + Unpin,
T: tokio::io::AsyncWrite + tokio::io::AsyncRead + Unpin,
{
type Item = io::Result<(String, F)>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let parse = |data: bytes::BytesMut,
topic_list: &HashMap<String, String>|
-> io::Result<(String, F)> {
let output = serde_json::from_slice::<jsonrpc_core::request::Notification>(&data)
.expect("must parse to notification");
let message = output
.params
.parse::<Message>()
.expect("must parse to message");
serde_json::from_str::<F>(&message.result)
.map(|r| (topic_list.get(&message.subscription).cloned().unwrap(), r))
.map_err(|_| io::ErrorKind::InvalidData.into())
};
if let Some(data) = self.pending_recv.pop_front() {
return Poll::Ready(Some(parse(data, &self.topic_list)));
}
match self.inner.poll_next_unpin(cx) {
Poll::Ready(Some(Ok(frame))) => Poll::Ready(Some(parse(frame, &self.topic_list))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))),
}
}
}
#[derive(Deserialize, Serialize, Debug)]
struct Message {
result: String,
subscription: String,
}
async fn subscribe<T: tokio::io::AsyncWrite + tokio::io::AsyncRead + Unpin>(
io: &mut Framed<T, StreamCodec>,
id: usize,
topic: impl AsRef<str>,
topic_list: &mut HashMap<String, String>,
pending_recv: &mut VecDeque<bytes::BytesMut>,
) -> io::Result<()> {
let req_json = format!(
r#"{{"id": {}, "jsonrpc": "2.0", "method": "subscribe", "params": ["{}"]}}"#,
id,
topic.as_ref()
);
io.send(req_json).await?;
loop {
let resp = io.next().await;
let resp = resp.ok_or_else::<io::Error, _>(|| io::ErrorKind::BrokenPipe.into())??;
match serde_json::from_slice::<jsonrpc_core::response::Output>(&resp) {
Ok(output) => match output {
jsonrpc_core::response::Output::Success(success) => {
let res = serde_json::from_value::<String>(success.result).unwrap();
topic_list.insert(res, topic.as_ref().to_owned());
break Ok(());
}
jsonrpc_core::response::Output::Failure(e) => {
return Err(io::Error::new(io::ErrorKind::InvalidData, e.error))
}
},
Err(_) => pending_recv.push_back(resp),
}
}
}