jsonrpc_macros/
pubsub.rs

1//! PUB-SUB auto-serializing structures.
2
3use std::marker::PhantomData;
4
5use jsonrpc_core as core;
6use jsonrpc_pubsub as pubsub;
7use serde;
8use util::to_value;
9
10use self::core::futures::{self, Sink as FuturesSink, sync};
11
12pub use self::pubsub::SubscriptionId;
13
14/// New PUB-SUB subcriber.
15#[derive(Debug)]
16pub struct Subscriber<T, E = core::Error> {
17	subscriber: pubsub::Subscriber,
18	_data: PhantomData<(T, E)>,
19}
20
21impl<T, E> Subscriber<T, E> {
22	/// Wrap non-typed subscriber.
23	pub fn new(subscriber: pubsub::Subscriber) -> Self {
24		Subscriber {
25			subscriber: subscriber,
26			_data: PhantomData,
27		}
28	}
29
30	/// Create new subscriber for tests.
31	pub fn new_test<M: Into<String>>(method: M) -> (
32		Self,
33		sync::oneshot::Receiver<Result<SubscriptionId, core::Error>>,
34		sync::mpsc::Receiver<String>,
35	) {
36		let (subscriber, id, subscription) = pubsub::Subscriber::new_test(method);
37		(Subscriber::new(subscriber), id, subscription)
38	}
39
40	/// Reject subscription with given error.
41	pub fn reject(self, error: core::Error) -> Result<(), ()> {
42		self.subscriber.reject(error)
43	}
44
45	/// Assign id to this subscriber.
46	/// This method consumes `Subscriber` and returns `Sink`
47	/// if the connection is still open or error otherwise.
48	pub fn assign_id(self, id: SubscriptionId) -> Result<Sink<T, E>, ()> {
49		let sink = self.subscriber.assign_id(id.clone())?;
50		Ok(Sink {
51			id: id,
52			sink: sink,
53			buffered: None,
54			_data: PhantomData,
55		})
56	}
57}
58
59/// Subscriber sink.
60#[derive(Debug, Clone)]
61pub struct Sink<T, E = core::Error> {
62	sink: pubsub::Sink,
63	id: SubscriptionId,
64	buffered: Option<core::Params>,
65	_data: PhantomData<(T, E)>,
66}
67
68impl<T: serde::Serialize, E: serde::Serialize> Sink<T, E> {
69	/// Sends a notification to the subscriber.
70	pub fn notify(&self, val: Result<T, E>) -> pubsub::SinkResult {
71		self.sink.notify(self.val_to_params(val))
72	}
73
74	fn val_to_params(&self, val: Result<T, E>) -> core::Params {
75		let id = self.id.clone().into();
76		let val = val.map(to_value).map_err(to_value);
77
78		core::Params::Map(vec![
79			("subscription".to_owned(), id),
80			match val {
81				Ok(val) => ("result".to_owned(), val),
82				Err(err) => ("error".to_owned(), err),
83			},
84		].into_iter().collect())
85	}
86
87	fn poll(&mut self) -> futures::Poll<(), pubsub::TransportError> {
88		if let Some(item) = self.buffered.take() {
89			let result = self.sink.start_send(item)?;
90			if let futures::AsyncSink::NotReady(item) = result {
91				self.buffered = Some(item);
92			}
93		}
94
95		if self.buffered.is_some() {
96			Ok(futures::Async::NotReady)
97		} else {
98			Ok(futures::Async::Ready(()))
99		}
100	}
101}
102
103impl<T: serde::Serialize, E: serde::Serialize> futures::sink::Sink for Sink<T, E> {
104	type SinkItem = Result<T, E>;
105	type SinkError = pubsub::TransportError;
106
107	fn start_send(&mut self, item: Self::SinkItem) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
108		// Make sure to always try to process the buffered entry.
109		// Since we're just a proxy to real `Sink` we don't need
110		// to schedule a `Task` wakeup. It will be done downstream.
111		if self.poll()?.is_not_ready() {
112			return Ok(futures::AsyncSink::NotReady(item));
113		}
114
115		let val = self.val_to_params(item);
116		self.buffered = Some(val);
117		self.poll()?;
118
119		Ok(futures::AsyncSink::Ready)
120	}
121
122	fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
123		self.poll()?;
124		self.sink.poll_complete()
125	}
126
127	fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
128		self.poll()?;
129		self.sink.close()
130	}
131}