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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use std::fmt;
use std::collections::HashMap;
use std::sync::Arc;
use parking_lot::Mutex;
use core::{self, BoxFuture};
use core::futures::{self, future, Sink as FuturesSink, Future};
use core::futures::sync::oneshot;
use handler::{SubscribeRpcMethod, UnsubscribeRpcMethod};
use types::{PubSubMetadata, SubscriptionId, TransportSender, TransportError, SinkResult};
pub struct Session {
active_subscriptions: Mutex<HashMap<(SubscriptionId, String), Box<Fn(SubscriptionId) + Send + 'static>>>,
transport: TransportSender,
on_drop: Mutex<Vec<Box<Fn() + Send>>>,
}
impl fmt::Debug for Session {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("pubsub::Session")
.field("active_subscriptions", &self.active_subscriptions.lock().len())
.field("transport", &self.transport)
.finish()
}
}
impl Session {
pub fn new(sender: TransportSender) -> Self {
Session {
active_subscriptions: Default::default(),
transport: sender,
on_drop: Default::default(),
}
}
pub fn sender(&self) -> TransportSender {
self.transport.clone()
}
pub fn on_drop(&self, on_drop: Box<Fn() + Send>) {
self.on_drop.lock().push(on_drop);
}
fn add_subscription(&self, name: &str, id: &SubscriptionId, remove: Box<Fn(SubscriptionId) + Send + 'static>) {
let ret = self.active_subscriptions.lock().insert((id.clone(), name.into()), remove);
if let Some(remove) = ret {
warn!("SubscriptionId collision. Unsubscribing previous client.");
remove(id.clone());
}
}
fn remove_subscription(&self, name: &str, id: &SubscriptionId) {
self.active_subscriptions.lock().remove(&(id.clone(), name.into()));
}
}
impl Drop for Session {
fn drop(&mut self) {
let mut active = self.active_subscriptions.lock();
for (id, remove) in active.drain() {
remove(id.0)
}
let mut on_drop = self.on_drop.lock();
for on_drop in on_drop.drain(..) {
on_drop();
}
}
}
#[derive(Debug, Clone)]
pub struct Sink {
notification: String,
transport: TransportSender,
}
impl Sink {
pub fn notify(&self, val: core::Params) -> SinkResult {
let val = self.params_to_string(val);
self.transport.clone().send(val.0)
}
fn params_to_string(&self, val: core::Params) -> (String, core::Params) {
let notification = core::Notification {
jsonrpc: Some(core::Version::V2),
method: self.notification.clone(),
params: Some(val),
};
(
core::to_string(¬ification).expect("Notification serialization never fails."),
notification.params.expect("Always Some"),
)
}
}
impl FuturesSink for Sink {
type SinkItem = core::Params;
type SinkError = TransportError;
fn start_send(&mut self, item: Self::SinkItem) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
let (val, params) = self.params_to_string(item);
self.transport.start_send(val).map(|result| match result {
futures::AsyncSink::Ready => futures::AsyncSink::Ready,
futures::AsyncSink::NotReady(_) => futures::AsyncSink::NotReady(params),
})
}
fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
self.transport.poll_complete()
}
fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
self.transport.close()
}
}
#[derive(Debug)]
pub struct Subscriber {
notification: String,
transport: TransportSender,
sender: oneshot::Sender<Result<SubscriptionId, core::Error>>,
}
impl Subscriber {
pub fn assign_id(self, id: SubscriptionId) -> Result<Sink, ()> {
self.sender.send(Ok(id)).map_err(|_| ())?;
Ok(Sink {
notification: self.notification,
transport: self.transport,
})
}
pub fn reject(self, error: core::Error) -> Result<(), ()> {
self.sender.send(Err(error)).map_err(|_| ())?;
Ok(())
}
}
pub fn new_subscription<M, F, G>(notification: &str, subscribe: F, unsubscribe: G) -> (Subscribe<F, G>, Unsubscribe<G>) where
M: PubSubMetadata,
F: SubscribeRpcMethod<M>,
G: UnsubscribeRpcMethod,
{
let unsubscribe = Arc::new(unsubscribe);
let subscribe = Subscribe {
notification: notification.to_owned(),
subscribe: subscribe,
unsubscribe: unsubscribe.clone(),
};
let unsubscribe = Unsubscribe {
notification: notification.into(),
unsubscribe: unsubscribe,
};
(subscribe, unsubscribe)
}
fn subscription_rejected() -> core::Error {
core::Error {
code: core::ErrorCode::ServerError(-32091),
message: "Subscription rejected".into(),
data: None,
}
}
fn subscriptions_unavailable() -> core::Error {
core::Error {
code: core::ErrorCode::ServerError(-32090),
message: "Subscriptions are not available on this transport.".into(),
data: None,
}
}
pub struct Subscribe<F, G> {
notification: String,
subscribe: F,
unsubscribe: Arc<G>,
}
impl<M, F, G> core::RpcMethod<M> for Subscribe<F, G> where
M: PubSubMetadata,
F: SubscribeRpcMethod<M>,
G: UnsubscribeRpcMethod,
{
fn call(&self, params: core::Params, meta: M) -> BoxFuture<core::Value, core::Error> {
match meta.session() {
Some(session) => {
let (tx, rx) = oneshot::channel();
let subscriber = Subscriber {
notification: self.notification.clone(),
transport: session.sender(),
sender: tx,
};
self.subscribe.call(params, meta, subscriber);
let unsub = self.unsubscribe.clone();
let notification = self.notification.clone();
let subscribe_future = rx
.map_err(|_| subscription_rejected())
.and_then(move |result| {
futures::done(match result {
Ok(id) => {
session.add_subscription(¬ification, &id, Box::new(move |id| {
let _ = unsub.call(id).wait();
}));
Ok(id.into())
},
Err(e) => Err(e),
})
});
Box::new(subscribe_future)
},
None => Box::new(future::err(subscriptions_unavailable())),
}
}
}
pub struct Unsubscribe<G> {
notification: String,
unsubscribe: Arc<G>,
}
impl<M, G> core::RpcMethod<M> for Unsubscribe<G> where
M: PubSubMetadata,
G: UnsubscribeRpcMethod,
{
fn call(&self, params: core::Params, meta: M) -> BoxFuture<core::Value, core::Error> {
let id = match params {
core::Params::Array(ref vec) if vec.len() == 1 => {
SubscriptionId::parse_value(&vec[0])
},
_ => None,
};
match (meta.session(), id) {
(Some(session), Some(id)) => {
session.remove_subscription(&self.notification, &id);
self.unsubscribe.call(id)
},
(Some(_), None) => Box::new(future::err(core::Error::invalid_params("Expected subscription id."))),
_ => Box::new(future::err(subscriptions_unavailable())),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use core;
use core::{BoxFuture, RpcMethod};
use core::futures::{future, Async, Future, Stream};
use core::futures::sync::{mpsc, oneshot};
use types::{SubscriptionId, PubSubMetadata};
use super::{Session, Sink, Subscriber, new_subscription};
fn session() -> (Session, mpsc::Receiver<String>) {
let (tx, rx) = mpsc::channel(1);
(Session::new(tx), rx)
}
#[test]
fn should_unregister_on_drop() {
let id = SubscriptionId::Number(1);
let called = Arc::new(AtomicBool::new(false));
let called2 = called.clone();
let session = session().0;
session.add_subscription("test", &id, Box::new(move |id| {
assert_eq!(id, SubscriptionId::Number(1));
called2.store(true, Ordering::SeqCst);
}));
drop(session);
assert_eq!(called.load(Ordering::SeqCst), true);
}
#[test]
fn should_remove_subscription() {
let id = SubscriptionId::Number(1);
let called = Arc::new(AtomicBool::new(false));
let called2 = called.clone();
let session = session().0;
session.add_subscription("test", &id, Box::new(move |id| {
assert_eq!(id, SubscriptionId::Number(1));
called2.store(true, Ordering::SeqCst);
}));
session.remove_subscription("test", &id);
drop(session);
assert_eq!(called.load(Ordering::SeqCst), false);
}
#[test]
fn should_unregister_in_case_of_collision() {
let id = SubscriptionId::Number(1);
let called = Arc::new(AtomicBool::new(false));
let called2 = called.clone();
let session = session().0;
session.add_subscription("test", &id, Box::new(move |id| {
assert_eq!(id, SubscriptionId::Number(1));
called2.store(true, Ordering::SeqCst);
}));
session.add_subscription("test", &id, Box::new(|_| {}));
assert_eq!(called.load(Ordering::SeqCst), true);
}
#[test]
fn should_send_notification_to_the_transport() {
let (tx, mut rx) = mpsc::channel(1);
let sink = Sink {
notification: "test".into(),
transport: tx,
};
sink.notify(core::Params::Array(vec![core::Value::Number(10.into())])).wait().unwrap();
assert_eq!(
rx.poll().unwrap(),
Async::Ready(Some(r#"{"jsonrpc":"2.0","method":"test","params":[10]}"#.into()))
);
}
#[test]
fn should_assign_id() {
let (transport, _) = mpsc::channel(1);
let (tx, mut rx) = oneshot::channel();
let subscriber = Subscriber {
notification: "test".into(),
transport: transport,
sender: tx,
};
let sink = subscriber.assign_id(SubscriptionId::Number(5)).unwrap();
assert_eq!(
rx.poll().unwrap(),
Async::Ready(Ok(SubscriptionId::Number(5)))
);
assert_eq!(sink.notification, "test".to_owned());
}
#[test]
fn should_reject() {
let (transport, _) = mpsc::channel(1);
let (tx, mut rx) = oneshot::channel();
let subscriber = Subscriber {
notification: "test".into(),
transport: transport,
sender: tx,
};
let error = core::Error {
code: core::ErrorCode::InvalidRequest,
message: "Cannot start subscription now.".into(),
data: None,
};
subscriber.reject(error.clone()).unwrap();
assert_eq!(
rx.poll().unwrap(),
Async::Ready(Err(error))
);
}
#[derive(Clone, Default)]
struct Metadata;
impl core::Metadata for Metadata {}
impl PubSubMetadata for Metadata {
fn session(&self) -> Option<Arc<Session>> {
Some(Arc::new(session().0))
}
}
#[test]
fn should_subscribe() {
let called = Arc::new(AtomicBool::new(false));
let called2 = called.clone();
let (subscribe, _) = new_subscription("test".into(), move |params, _meta, _subscriber| {
assert_eq!(params, core::Params::None);
called2.store(true, Ordering::SeqCst);
}, |_id| Box::new(future::ok(core::Value::Bool(true))) as BoxFuture<_, _>);
let meta = Metadata;
let result = subscribe.call(core::Params::None, meta);
assert_eq!(called.load(Ordering::SeqCst), true);
assert_eq!(result.wait(), Err(core::Error {
code: core::ErrorCode::ServerError(-32091),
message: "Subscription rejected".into(),
data: None,
}));
}
}