2019-01-07 11:33:07 +01:00
|
|
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
|
|
|
// This file is part of Parity Ethereum.
|
2017-05-06 13:24:18 +02:00
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is free software: you can redistribute it and/or modify
|
2017-05-06 13:24:18 +02:00
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is distributed in the hope that it will be useful,
|
2017-05-06 13:24:18 +02:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
2019-01-07 11:33:07 +01:00
|
|
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
2017-05-06 13:24:18 +02:00
|
|
|
|
|
|
|
//! Generic poll manager for Pub-Sub.
|
|
|
|
|
|
|
|
use std::sync::Arc;
|
2017-07-10 13:23:19 +02:00
|
|
|
use std::sync::atomic::{self, AtomicBool};
|
2017-09-02 20:09:13 +02:00
|
|
|
use parking_lot::Mutex;
|
2017-05-06 13:24:18 +02:00
|
|
|
|
|
|
|
use jsonrpc_core::futures::future::{self, Either};
|
|
|
|
use jsonrpc_core::futures::sync::mpsc;
|
2017-10-05 12:35:01 +02:00
|
|
|
use jsonrpc_core::futures::{Sink, Future};
|
2017-11-14 11:38:17 +01:00
|
|
|
use jsonrpc_core::{self as core, MetaIoHandler};
|
2017-05-17 16:20:41 +02:00
|
|
|
use jsonrpc_pubsub::SubscriptionId;
|
2017-05-06 13:24:18 +02:00
|
|
|
|
2017-05-17 16:20:41 +02:00
|
|
|
use v1::helpers::Subscribers;
|
2017-05-06 13:24:18 +02:00
|
|
|
use v1::metadata::Metadata;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Subscription {
|
|
|
|
metadata: Metadata,
|
|
|
|
method: String,
|
|
|
|
params: core::Params,
|
|
|
|
sink: mpsc::Sender<Result<core::Value, core::Error>>,
|
2017-07-10 13:23:19 +02:00
|
|
|
/// a flag if subscription is still active and last returned value
|
|
|
|
last_result: Arc<(AtomicBool, Mutex<Option<core::Output>>)>,
|
2017-05-06 13:24:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A struct managing all subscriptions.
|
|
|
|
/// TODO [ToDr] Depending on the method decide on poll interval.
|
|
|
|
/// For most of the methods it will be enough to poll on new block instead of time-interval.
|
|
|
|
pub struct GenericPollManager<S: core::Middleware<Metadata>> {
|
2017-05-17 16:20:41 +02:00
|
|
|
subscribers: Subscribers<Subscription>,
|
2017-05-06 13:24:18 +02:00
|
|
|
rpc: MetaIoHandler<Metadata, S>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S: core::Middleware<Metadata>> GenericPollManager<S> {
|
|
|
|
/// Creates new poll manager
|
|
|
|
pub fn new(rpc: MetaIoHandler<Metadata, S>) -> Self {
|
|
|
|
GenericPollManager {
|
2017-05-17 16:20:41 +02:00
|
|
|
subscribers: Default::default(),
|
2019-03-22 12:01:11 +01:00
|
|
|
rpc,
|
2017-05-06 13:24:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-13 17:36:39 +02:00
|
|
|
/// Creates new poll manager with deterministic ids.
|
|
|
|
#[cfg(test)]
|
|
|
|
pub fn new_test(rpc: MetaIoHandler<Metadata, S>) -> Self {
|
|
|
|
let mut manager = Self::new(rpc);
|
|
|
|
manager.subscribers = Subscribers::new_test();
|
|
|
|
manager
|
|
|
|
}
|
|
|
|
|
2017-05-06 13:24:18 +02:00
|
|
|
/// Subscribes to update from polling given method.
|
|
|
|
pub fn subscribe(&mut self, metadata: Metadata, method: String, params: core::Params)
|
2017-05-17 16:20:41 +02:00
|
|
|
-> (SubscriptionId, mpsc::Receiver<Result<core::Value, core::Error>>)
|
2017-05-06 13:24:18 +02:00
|
|
|
{
|
|
|
|
let (sink, stream) = mpsc::channel(1);
|
|
|
|
let subscription = Subscription {
|
2017-07-10 13:23:19 +02:00
|
|
|
metadata,
|
|
|
|
method,
|
|
|
|
params,
|
|
|
|
sink,
|
2017-05-06 13:24:18 +02:00
|
|
|
last_result: Default::default(),
|
|
|
|
};
|
2017-05-17 16:20:41 +02:00
|
|
|
let id = self.subscribers.insert(subscription);
|
2017-05-06 13:24:18 +02:00
|
|
|
(id, stream)
|
|
|
|
}
|
|
|
|
|
2017-05-17 16:20:41 +02:00
|
|
|
pub fn unsubscribe(&mut self, id: &SubscriptionId) -> bool {
|
2017-05-06 13:24:18 +02:00
|
|
|
debug!(target: "pubsub", "Removing subscription: {:?}", id);
|
2017-07-10 13:23:19 +02:00
|
|
|
self.subscribers.remove(id).map(|subscription| {
|
|
|
|
subscription.last_result.0.store(true, atomic::Ordering::SeqCst);
|
|
|
|
}).is_some()
|
2017-05-06 13:24:18 +02:00
|
|
|
}
|
|
|
|
|
2017-11-14 11:38:17 +01:00
|
|
|
pub fn tick(&self) -> Box<Future<Item=(), Error=()> + Send> {
|
2017-05-06 13:24:18 +02:00
|
|
|
let mut futures = Vec::new();
|
|
|
|
// poll all subscriptions
|
2017-05-17 16:20:41 +02:00
|
|
|
for (id, subscription) in self.subscribers.iter() {
|
2017-05-06 13:24:18 +02:00
|
|
|
let call = core::MethodCall {
|
|
|
|
jsonrpc: Some(core::Version::V2),
|
2017-06-13 17:36:39 +02:00
|
|
|
id: core::Id::Str(id.as_string()),
|
2017-05-06 13:24:18 +02:00
|
|
|
method: subscription.method.clone(),
|
2018-10-22 09:40:50 +02:00
|
|
|
params: subscription.params.clone(),
|
2017-05-06 13:24:18 +02:00
|
|
|
};
|
|
|
|
trace!(target: "pubsub", "Polling method: {:?}", call);
|
|
|
|
let result = self.rpc.handle_call(call.into(), subscription.metadata.clone());
|
|
|
|
|
|
|
|
let last_result = subscription.last_result.clone();
|
|
|
|
let sender = subscription.sink.clone();
|
|
|
|
|
|
|
|
let result = result.and_then(move |response| {
|
2017-07-10 13:23:19 +02:00
|
|
|
// quick check if the subscription is still valid
|
|
|
|
if last_result.0.load(atomic::Ordering::SeqCst) {
|
|
|
|
return Either::B(future::ok(()))
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut last_result = last_result.1.lock();
|
2017-05-06 13:24:18 +02:00
|
|
|
if *last_result != response && response.is_some() {
|
|
|
|
let output = response.expect("Existence proved by the condition.");
|
|
|
|
debug!(target: "pubsub", "Got new response, sending: {:?}", output);
|
|
|
|
*last_result = Some(output.clone());
|
|
|
|
|
|
|
|
let send = match output {
|
|
|
|
core::Output::Success(core::Success { result, .. }) => Ok(result),
|
|
|
|
core::Output::Failure(core::Failure { error, .. }) => Err(error),
|
|
|
|
};
|
|
|
|
Either::A(sender.send(send).map(|_| ()).map_err(|_| ()))
|
|
|
|
} else {
|
|
|
|
trace!(target: "pubsub", "Response was not changed: {:?}", response);
|
|
|
|
Either::B(future::ok(()))
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
futures.push(result)
|
|
|
|
}
|
|
|
|
|
|
|
|
// return a future represeting all the polls
|
2017-10-05 12:35:01 +02:00
|
|
|
Box::new(future::join_all(futures).map(|_| ()))
|
2017-05-06 13:24:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use std::sync::atomic::{self, AtomicBool};
|
|
|
|
|
|
|
|
use jsonrpc_core::{MetaIoHandler, NoopMiddleware, Value, Params};
|
|
|
|
use jsonrpc_core::futures::{Future, Stream};
|
2017-05-17 16:20:41 +02:00
|
|
|
use jsonrpc_pubsub::SubscriptionId;
|
2018-10-22 09:40:50 +02:00
|
|
|
use http::tokio::runtime::Runtime;
|
2017-05-06 13:24:18 +02:00
|
|
|
|
|
|
|
use super::GenericPollManager;
|
|
|
|
|
|
|
|
fn poll_manager() -> GenericPollManager<NoopMiddleware> {
|
|
|
|
let mut io = MetaIoHandler::default();
|
|
|
|
let called = AtomicBool::new(false);
|
|
|
|
io.add_method("hello", move |_| {
|
|
|
|
if !called.load(atomic::Ordering::SeqCst) {
|
|
|
|
called.store(true, atomic::Ordering::SeqCst);
|
|
|
|
Ok(Value::String("hello".into()))
|
|
|
|
} else {
|
|
|
|
Ok(Value::String("world".into()))
|
|
|
|
}
|
|
|
|
});
|
2017-06-13 17:36:39 +02:00
|
|
|
GenericPollManager::new_test(io)
|
2017-05-06 13:24:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_poll_subscribed_method() {
|
|
|
|
// given
|
2018-10-22 09:40:50 +02:00
|
|
|
let mut el = Runtime::new().unwrap();
|
2017-05-06 13:24:18 +02:00
|
|
|
let mut poll_manager = poll_manager();
|
|
|
|
let (id, rx) = poll_manager.subscribe(Default::default(), "hello".into(), Params::None);
|
2017-06-13 17:36:39 +02:00
|
|
|
assert_eq!(id, SubscriptionId::String("0x416d77337e24399d".into()));
|
2017-05-06 13:24:18 +02:00
|
|
|
|
|
|
|
// then
|
|
|
|
poll_manager.tick().wait().unwrap();
|
2018-10-22 09:40:50 +02:00
|
|
|
let (res, rx) = el.block_on(rx.into_future()).unwrap();
|
2017-05-06 13:24:18 +02:00
|
|
|
assert_eq!(res, Some(Ok(Value::String("hello".into()))));
|
|
|
|
|
|
|
|
// retrieve second item
|
|
|
|
poll_manager.tick().wait().unwrap();
|
2018-10-22 09:40:50 +02:00
|
|
|
let (res, rx) = el.block_on(rx.into_future()).unwrap();
|
2017-05-06 13:24:18 +02:00
|
|
|
assert_eq!(res, Some(Ok(Value::String("world".into()))));
|
|
|
|
|
|
|
|
// and no more notifications
|
|
|
|
poll_manager.tick().wait().unwrap();
|
|
|
|
// we need to unsubscribe otherwise the future will never finish.
|
2017-05-17 16:20:41 +02:00
|
|
|
poll_manager.unsubscribe(&id);
|
2018-10-22 09:40:50 +02:00
|
|
|
assert_eq!(el.block_on(rx.into_future()).unwrap().0, None);
|
2017-05-06 13:24:18 +02:00
|
|
|
}
|
|
|
|
}
|