2018-09-14 13:18:10 +02:00
|
|
|
// Copyright 2018 Parity Technologies (UK) Ltd.
|
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a
|
|
|
|
// copy of this software and associated documentation files (the "Software"),
|
|
|
|
// to deal in the Software without restriction, including without limitation
|
|
|
|
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
|
|
// and/or sell copies of the Software, and to permit persons to whom the
|
|
|
|
// Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in
|
|
|
|
// all copies or substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
|
|
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
|
|
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
2018-11-15 17:41:11 +01:00
|
|
|
use crate::{
|
|
|
|
PeerId,
|
|
|
|
muxing::StreamMuxer,
|
|
|
|
nodes::{
|
|
|
|
node::Substream,
|
2018-12-11 15:36:41 +01:00
|
|
|
handled_node_tasks::{HandledNodesEvent, HandledNodesTasks, TaskClosedEvent},
|
2019-01-14 14:22:25 +01:00
|
|
|
handled_node_tasks::{IntoNodeHandler, Task as HandledNodesTask, TaskId},
|
2018-12-11 15:36:41 +01:00
|
|
|
handled_node::{HandledNodeError, NodeHandler}
|
2018-11-15 17:41:11 +01:00
|
|
|
}
|
|
|
|
};
|
2018-09-14 13:18:10 +02:00
|
|
|
use fnv::FnvHashMap;
|
2018-09-21 17:31:52 +02:00
|
|
|
use futures::prelude::*;
|
2019-01-23 17:44:40 +01:00
|
|
|
use std::{collections::hash_map::Entry, error, fmt, hash::Hash, mem};
|
2018-09-14 13:18:10 +02:00
|
|
|
|
2019-01-09 15:48:56 +01:00
|
|
|
mod tests;
|
|
|
|
|
2018-09-14 13:18:10 +02:00
|
|
|
/// Implementation of `Stream` that handles a collection of nodes.
|
2019-01-23 17:44:40 +01:00
|
|
|
pub struct CollectionStream<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId = PeerId> {
|
2018-09-21 17:31:52 +02:00
|
|
|
/// Object that handles the tasks.
|
2019-01-23 17:44:40 +01:00
|
|
|
inner: HandledNodesTasks<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>,
|
2018-09-21 17:31:52 +02:00
|
|
|
/// List of nodes, with the task id that handles this node. The corresponding entry in `tasks`
|
|
|
|
/// must always be in the `Connected` state.
|
2019-01-23 17:44:40 +01:00
|
|
|
nodes: FnvHashMap<TPeerId, TaskId>,
|
2018-09-21 17:31:52 +02:00
|
|
|
/// List of tasks and their state. If `Connected`, then a corresponding entry must be present
|
|
|
|
/// in `nodes`.
|
2019-01-23 17:44:40 +01:00
|
|
|
tasks: FnvHashMap<TaskId, TaskState<TPeerId>>,
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId> fmt::Debug for
|
|
|
|
CollectionStream<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
where
|
|
|
|
TPeerId: fmt::Debug,
|
|
|
|
{
|
2018-10-01 14:49:17 +02:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
|
|
let mut list = f.debug_list();
|
|
|
|
for (id, task) in &self.tasks {
|
|
|
|
match *task {
|
|
|
|
TaskState::Pending => {
|
|
|
|
list.entry(&format!("Pending({:?})", ReachAttemptId(*id)))
|
|
|
|
},
|
|
|
|
TaskState::Connected(ref peer_id) => {
|
|
|
|
list.entry(&format!("Connected({:?})", peer_id))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
list.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-21 17:31:52 +02:00
|
|
|
/// State of a task.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
2019-01-23 17:44:40 +01:00
|
|
|
enum TaskState<TPeerId> {
|
2018-09-14 13:18:10 +02:00
|
|
|
/// Task is attempting to reach a peer.
|
2018-09-21 17:31:52 +02:00
|
|
|
Pending,
|
2018-09-14 13:18:10 +02:00
|
|
|
/// The task is connected to a peer.
|
2019-01-23 17:44:40 +01:00
|
|
|
Connected(TPeerId),
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Event that can happen on the `CollectionStream`.
|
2019-01-23 17:44:40 +01:00
|
|
|
pub enum CollectionEvent<'a, TInEvent:'a , TOutEvent: 'a, THandler: 'a, TReachErr, THandlerErr, TPeerId> {
|
2018-10-01 14:49:17 +02:00
|
|
|
/// A connection to a node has succeeded. You must use the provided event in order to accept
|
|
|
|
/// the connection.
|
2019-01-23 17:44:40 +01:00
|
|
|
NodeReached(CollectionReachEvent<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>),
|
2018-09-14 13:18:10 +02:00
|
|
|
|
|
|
|
/// A connection to a node has been closed.
|
|
|
|
///
|
|
|
|
/// This happens once both the inbound and outbound channels are closed, and no more outbound
|
|
|
|
/// substream attempt is pending.
|
|
|
|
NodeClosed {
|
|
|
|
/// Identifier of the node.
|
2019-01-23 17:44:40 +01:00
|
|
|
peer_id: TPeerId,
|
2018-09-14 13:18:10 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
/// A connection to a node has errored.
|
2018-10-17 10:17:40 +01:00
|
|
|
///
|
|
|
|
/// Can only happen after a node has been successfully reached.
|
2018-09-14 13:18:10 +02:00
|
|
|
NodeError {
|
|
|
|
/// Identifier of the node.
|
2019-01-23 17:44:40 +01:00
|
|
|
peer_id: TPeerId,
|
2018-09-14 13:18:10 +02:00
|
|
|
/// The error that happened.
|
2018-12-11 15:36:41 +01:00
|
|
|
error: HandledNodeError<THandlerErr>,
|
2018-09-14 13:18:10 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
/// An error happened on the future that was trying to reach a node.
|
|
|
|
ReachError {
|
|
|
|
/// Identifier of the reach attempt that failed.
|
|
|
|
id: ReachAttemptId,
|
|
|
|
/// Error that happened on the future.
|
2018-12-11 15:36:41 +01:00
|
|
|
error: TReachErr,
|
2018-10-17 10:17:40 +01:00
|
|
|
/// The handler that was passed to `add_reach_attempt`.
|
|
|
|
handler: THandler,
|
2018-09-14 13:18:10 +02:00
|
|
|
},
|
|
|
|
|
2018-09-19 16:33:29 +02:00
|
|
|
/// A node has produced an event.
|
|
|
|
NodeEvent {
|
2018-09-14 13:18:10 +02:00
|
|
|
/// Identifier of the node.
|
2019-01-23 17:44:40 +01:00
|
|
|
peer_id: TPeerId,
|
2018-09-19 16:33:29 +02:00
|
|
|
/// The produced event.
|
|
|
|
event: TOutEvent,
|
2018-09-14 13:18:10 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId> fmt::Debug for
|
|
|
|
CollectionEvent<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
2018-12-11 15:36:41 +01:00
|
|
|
where TOutEvent: fmt::Debug,
|
|
|
|
TReachErr: fmt::Debug,
|
|
|
|
THandlerErr: fmt::Debug,
|
2019-01-23 17:44:40 +01:00
|
|
|
TPeerId: Eq + Hash + Clone + fmt::Debug,
|
2018-10-01 14:49:17 +02:00
|
|
|
{
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
|
|
match *self {
|
|
|
|
CollectionEvent::NodeReached(ref inner) => {
|
|
|
|
f.debug_tuple("CollectionEvent::NodeReached")
|
|
|
|
.field(inner)
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
CollectionEvent::NodeClosed { ref peer_id } => {
|
|
|
|
f.debug_struct("CollectionEvent::NodeClosed")
|
|
|
|
.field("peer_id", peer_id)
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
CollectionEvent::NodeError { ref peer_id, ref error } => {
|
|
|
|
f.debug_struct("CollectionEvent::NodeError")
|
|
|
|
.field("peer_id", peer_id)
|
|
|
|
.field("error", error)
|
|
|
|
.finish()
|
|
|
|
},
|
2018-10-17 10:17:40 +01:00
|
|
|
CollectionEvent::ReachError { ref id, ref error, .. } => {
|
2018-10-01 14:49:17 +02:00
|
|
|
f.debug_struct("CollectionEvent::ReachError")
|
|
|
|
.field("id", id)
|
|
|
|
.field("error", error)
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
CollectionEvent::NodeEvent { ref peer_id, ref event } => {
|
|
|
|
f.debug_struct("CollectionEvent::NodeEvent")
|
|
|
|
.field("peer_id", peer_id)
|
|
|
|
.field("event", event)
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Event that happens when we reach a node.
|
|
|
|
#[must_use = "The node reached event is used to accept the newly-opened connection"]
|
2019-01-23 17:44:40 +01:00
|
|
|
pub struct CollectionReachEvent<'a, TInEvent: 'a, TOutEvent: 'a, THandler: 'a, TReachErr, THandlerErr: 'a, TPeerId: 'a = PeerId> {
|
2018-10-01 14:49:17 +02:00
|
|
|
/// Peer id we connected to.
|
2019-01-23 17:44:40 +01:00
|
|
|
peer_id: TPeerId,
|
2018-10-01 14:49:17 +02:00
|
|
|
/// The task id that reached the node.
|
|
|
|
id: TaskId,
|
|
|
|
/// The `CollectionStream` we are referencing.
|
2019-01-23 17:44:40 +01:00
|
|
|
parent: &'a mut CollectionStream<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>,
|
2018-10-01 14:49:17 +02:00
|
|
|
}
|
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
CollectionReachEvent<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
where
|
|
|
|
TPeerId: Eq + Hash + Clone,
|
|
|
|
{
|
2018-11-29 09:57:06 +00:00
|
|
|
/// Returns the peer id of the node that has been reached.
|
2018-10-01 14:49:17 +02:00
|
|
|
#[inline]
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn peer_id(&self) -> &TPeerId {
|
2018-10-01 14:49:17 +02:00
|
|
|
&self.peer_id
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the reach attempt that reached the node.
|
|
|
|
#[inline]
|
|
|
|
pub fn reach_attempt_id(&self) -> ReachAttemptId {
|
|
|
|
ReachAttemptId(self.id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if accepting this reached node would replace an existing connection to that
|
|
|
|
/// node.
|
|
|
|
#[inline]
|
|
|
|
pub fn would_replace(&self) -> bool {
|
|
|
|
self.parent.nodes.contains_key(&self.peer_id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Accepts the new node.
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn accept(self) -> (CollectionNodeAccept, TPeerId) {
|
2018-10-01 14:49:17 +02:00
|
|
|
// Set the state of the task to `Connected`.
|
|
|
|
let former_task_id = self.parent.nodes.insert(self.peer_id.clone(), self.id);
|
|
|
|
let _former_state = self.parent.tasks.insert(self.id, TaskState::Connected(self.peer_id.clone()));
|
2019-01-23 17:44:40 +01:00
|
|
|
debug_assert!(_former_state == Some(TaskState::Pending));
|
2018-10-01 14:49:17 +02:00
|
|
|
|
|
|
|
// It is possible that we already have a task connected to the same peer. In this
|
|
|
|
// case, we need to emit a `NodeReplaced` event.
|
|
|
|
let ret_value = if let Some(former_task_id) = former_task_id {
|
|
|
|
self.parent.inner.task(former_task_id)
|
|
|
|
.expect("whenever we receive a TaskClosed event or close a node, we remove the \
|
2018-10-29 20:38:32 +11:00
|
|
|
corresponding entry from self.nodes; therefore all elements in \
|
2018-11-29 15:38:52 +00:00
|
|
|
self.nodes are valid tasks in the HandledNodesTasks; QED")
|
2018-10-01 14:49:17 +02:00
|
|
|
.close();
|
|
|
|
let _former_other_state = self.parent.tasks.remove(&former_task_id);
|
2019-01-23 17:44:40 +01:00
|
|
|
debug_assert!(_former_other_state == Some(TaskState::Connected(self.peer_id.clone())));
|
2018-10-01 14:49:17 +02:00
|
|
|
|
|
|
|
// TODO: we unfortunately have to clone the peer id here
|
|
|
|
(CollectionNodeAccept::ReplacedExisting, self.peer_id.clone())
|
|
|
|
} else {
|
|
|
|
// TODO: we unfortunately have to clone the peer id here
|
|
|
|
(CollectionNodeAccept::NewEntry, self.peer_id.clone())
|
|
|
|
};
|
|
|
|
|
|
|
|
// Don't run the destructor.
|
|
|
|
mem::forget(self);
|
|
|
|
|
|
|
|
ret_value
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Denies the node.
|
|
|
|
///
|
|
|
|
/// Has the same effect as dropping the event without accepting it.
|
|
|
|
#[inline]
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn deny(self) -> TPeerId {
|
2018-10-01 14:49:17 +02:00
|
|
|
// TODO: we unfortunately have to clone the id here, in order to be explicit
|
|
|
|
let peer_id = self.peer_id.clone();
|
|
|
|
drop(self); // Just to be explicit
|
|
|
|
peer_id
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId> fmt::Debug for
|
|
|
|
CollectionReachEvent<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
where
|
|
|
|
TPeerId: Eq + Hash + Clone + fmt::Debug,
|
|
|
|
{
|
2018-10-01 14:49:17 +02:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
|
|
f.debug_struct("CollectionReachEvent")
|
|
|
|
.field("peer_id", &self.peer_id)
|
|
|
|
.field("reach_attempt_id", &self.reach_attempt_id())
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId> Drop for
|
|
|
|
CollectionReachEvent<'a, TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
{
|
2018-10-01 14:49:17 +02:00
|
|
|
fn drop(&mut self) {
|
|
|
|
let task_state = self.parent.tasks.remove(&self.id);
|
|
|
|
debug_assert!(if let Some(TaskState::Pending) = task_state { true } else { false });
|
|
|
|
self.parent.inner.task(self.id)
|
2018-10-29 20:38:32 +11:00
|
|
|
.expect("we create the CollectionReachEvent with a valid task id; the \
|
2018-10-01 14:49:17 +02:00
|
|
|
CollectionReachEvent mutably borrows the collection, therefore nothing \
|
2018-10-29 20:38:32 +11:00
|
|
|
can delete this task during the lifetime of the CollectionReachEvent; \
|
2018-11-29 15:38:52 +00:00
|
|
|
therefore the task is still valid when we delete it; QED")
|
2018-10-01 14:49:17 +02:00
|
|
|
.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Outcome of accepting a node.
|
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
|
|
|
pub enum CollectionNodeAccept {
|
|
|
|
/// We replaced an existing node.
|
|
|
|
ReplacedExisting,
|
|
|
|
/// We didn't replace anything existing.
|
|
|
|
NewEntry,
|
|
|
|
}
|
|
|
|
|
2018-09-14 13:18:10 +02:00
|
|
|
/// Identifier for a future that attempts to reach a node.
|
|
|
|
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
2018-09-21 17:31:52 +02:00
|
|
|
pub struct ReachAttemptId(TaskId);
|
2018-09-14 13:18:10 +02:00
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
CollectionStream<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>
|
|
|
|
where
|
|
|
|
TPeerId: Eq + Hash + Clone,
|
|
|
|
{
|
2018-09-14 13:18:10 +02:00
|
|
|
/// Creates a new empty collection.
|
|
|
|
#[inline]
|
|
|
|
pub fn new() -> Self {
|
|
|
|
CollectionStream {
|
2018-09-21 17:31:52 +02:00
|
|
|
inner: HandledNodesTasks::new(),
|
2018-09-14 13:18:10 +02:00
|
|
|
nodes: Default::default(),
|
|
|
|
tasks: Default::default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Adds to the collection a future that tries to reach a remote.
|
|
|
|
///
|
|
|
|
/// This method spawns a task dedicated to resolving this future and processing the node's
|
|
|
|
/// events.
|
2018-10-17 10:17:40 +01:00
|
|
|
pub fn add_reach_attempt<TFut, TMuxer>(&mut self, future: TFut, handler: THandler)
|
2018-09-19 16:33:29 +02:00
|
|
|
-> ReachAttemptId
|
2018-09-14 13:18:10 +02:00
|
|
|
where
|
2019-01-23 17:44:40 +01:00
|
|
|
TFut: Future<Item = (TPeerId, TMuxer), Error = TReachErr> + Send + 'static,
|
|
|
|
THandler: IntoNodeHandler<TPeerId> + Send + 'static,
|
2019-01-14 14:22:25 +01:00
|
|
|
THandler::Handler: NodeHandler<Substream = Substream<TMuxer>, InEvent = TInEvent, OutEvent = TOutEvent, Error = THandlerErr> + Send + 'static,
|
|
|
|
<THandler::Handler as NodeHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be required?
|
2018-12-11 15:36:41 +01:00
|
|
|
TReachErr: error::Error + Send + 'static,
|
|
|
|
THandlerErr: error::Error + Send + 'static,
|
2018-09-19 16:33:29 +02:00
|
|
|
TInEvent: Send + 'static,
|
|
|
|
TOutEvent: Send + 'static,
|
|
|
|
TMuxer: StreamMuxer + Send + Sync + 'static, // TODO: Send + Sync + 'static shouldn't be required
|
|
|
|
TMuxer::OutboundSubstream: Send + 'static, // TODO: shouldn't be required
|
2019-01-23 17:44:40 +01:00
|
|
|
TPeerId: Send + 'static,
|
2018-09-14 13:18:10 +02:00
|
|
|
{
|
2018-09-21 17:31:52 +02:00
|
|
|
let id = self.inner.add_reach_attempt(future, handler);
|
|
|
|
self.tasks.insert(id, TaskState::Pending);
|
|
|
|
ReachAttemptId(id)
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Interrupts a reach attempt.
|
|
|
|
///
|
|
|
|
/// Returns `Ok` if something was interrupted, and `Err` if the ID is not or no longer valid.
|
2018-12-05 13:47:06 +00:00
|
|
|
pub fn interrupt(&mut self, id: ReachAttemptId) -> Result<(), InterruptError> {
|
2018-09-21 17:31:52 +02:00
|
|
|
match self.tasks.entry(id.0) {
|
2018-12-05 13:47:06 +00:00
|
|
|
Entry::Vacant(_) => Err(InterruptError::ReachAttemptNotFound),
|
2018-09-21 17:31:52 +02:00
|
|
|
Entry::Occupied(entry) => {
|
2018-09-14 13:18:10 +02:00
|
|
|
match entry.get() {
|
2018-12-05 13:47:06 +00:00
|
|
|
TaskState::Connected(_) => return Err(InterruptError::AlreadyReached),
|
2018-11-02 13:15:17 +01:00
|
|
|
TaskState::Pending => (),
|
2018-09-14 13:18:10 +02:00
|
|
|
};
|
|
|
|
|
2018-09-21 17:31:52 +02:00
|
|
|
entry.remove();
|
|
|
|
self.inner.task(id.0)
|
|
|
|
.expect("whenever we receive a TaskClosed event or interrupt a task, we \
|
2018-10-29 20:38:32 +11:00
|
|
|
remove the corresponding entry from self.tasks; therefore all \
|
2018-09-21 17:31:52 +02:00
|
|
|
elements in self.tasks are valid tasks in the \
|
2018-11-29 15:38:52 +00:00
|
|
|
HandledNodesTasks; QED")
|
2018-09-21 17:31:52 +02:00
|
|
|
.close();
|
|
|
|
|
|
|
|
Ok(())
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-19 16:33:29 +02:00
|
|
|
/// Sends an event to all nodes.
|
2018-09-21 17:31:52 +02:00
|
|
|
#[inline]
|
2018-09-19 16:33:29 +02:00
|
|
|
pub fn broadcast_event(&mut self, event: &TInEvent)
|
|
|
|
where TInEvent: Clone,
|
|
|
|
{
|
2018-09-21 17:31:52 +02:00
|
|
|
// TODO: remove the ones we're not connected to?
|
|
|
|
self.inner.broadcast_event(event)
|
2018-09-19 16:33:29 +02:00
|
|
|
}
|
|
|
|
|
2018-09-21 17:31:52 +02:00
|
|
|
/// Grants access to an object that allows controlling a peer of the collection.
|
2018-09-14 13:18:10 +02:00
|
|
|
///
|
|
|
|
/// Returns `None` if we don't have a connection to this peer.
|
|
|
|
#[inline]
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn peer_mut(&mut self, id: &TPeerId) -> Option<PeerMut<TInEvent, TPeerId>> {
|
2018-09-21 17:31:52 +02:00
|
|
|
let task = match self.nodes.get(id) {
|
|
|
|
Some(&task) => task,
|
|
|
|
None => return None,
|
|
|
|
};
|
|
|
|
|
|
|
|
match self.inner.task(task) {
|
|
|
|
Some(inner) => Some(PeerMut {
|
2018-09-14 13:18:10 +02:00
|
|
|
inner,
|
|
|
|
tasks: &mut self.tasks,
|
2018-09-21 17:31:52 +02:00
|
|
|
nodes: &mut self.nodes,
|
2018-09-14 13:18:10 +02:00
|
|
|
}),
|
2018-09-21 17:31:52 +02:00
|
|
|
None => None,
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns true if we are connected to the given peer.
|
|
|
|
///
|
|
|
|
/// This will return true only after a `NodeReached` event has been produced by `poll()`.
|
|
|
|
#[inline]
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn has_connection(&self, id: &TPeerId) -> bool {
|
2018-09-14 13:18:10 +02:00
|
|
|
self.nodes.contains_key(id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a list of all the active connections.
|
|
|
|
///
|
|
|
|
/// Does not include reach attempts that haven't reached any target yet.
|
|
|
|
#[inline]
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn connections(&self) -> impl Iterator<Item = &TPeerId> {
|
2018-09-14 13:18:10 +02:00
|
|
|
self.nodes.keys()
|
|
|
|
}
|
|
|
|
|
2018-10-01 14:49:17 +02:00
|
|
|
/// Provides an API similar to `Stream`, except that it cannot error.
|
2018-09-14 13:18:10 +02:00
|
|
|
///
|
2018-10-01 14:49:17 +02:00
|
|
|
/// > **Note**: we use a regular `poll` method instead of implementing `Stream` in order to
|
|
|
|
/// > remove the `Err` variant, but also because we want the `CollectionStream` to stay
|
|
|
|
/// > borrowed if necessary.
|
2019-01-23 17:44:40 +01:00
|
|
|
pub fn poll(&mut self) -> Async<CollectionEvent<TInEvent, TOutEvent, THandler, TReachErr, THandlerErr, TPeerId>> {
|
2018-10-01 14:49:17 +02:00
|
|
|
let item = match self.inner.poll() {
|
|
|
|
Async::Ready(item) => item,
|
|
|
|
Async::NotReady => return Async::NotReady,
|
2018-09-21 17:31:52 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
match item {
|
2018-10-17 10:17:40 +01:00
|
|
|
HandledNodesEvent::TaskClosed { id, result, handler } => {
|
|
|
|
match (self.tasks.remove(&id), result, handler) {
|
2018-12-11 15:36:41 +01:00
|
|
|
(Some(TaskState::Pending), Err(TaskClosedEvent::Reach(err)), Some(handler)) => {
|
2018-10-17 10:17:40 +01:00
|
|
|
Async::Ready(CollectionEvent::ReachError {
|
2018-09-21 17:31:52 +02:00
|
|
|
id: ReachAttemptId(id),
|
|
|
|
error: err,
|
2018-10-17 10:17:40 +01:00
|
|
|
handler,
|
|
|
|
})
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-12-11 15:36:41 +01:00
|
|
|
(Some(TaskState::Pending), Ok(()), _) => {
|
|
|
|
panic!("The API of HandledNodesTasks guarantees that a task cannot \
|
|
|
|
gracefully closed before being connected to a node, in which case \
|
|
|
|
its state should be Connected and not Pending; QED");
|
|
|
|
},
|
|
|
|
(Some(TaskState::Pending), Err(TaskClosedEvent::Node(_)), _) => {
|
|
|
|
panic!("We switch the task state to Connected once we're connected, and \
|
|
|
|
a TaskClosedEvent::Node can only happen after we're \
|
|
|
|
connected; QED");
|
|
|
|
},
|
|
|
|
(Some(TaskState::Pending), Err(TaskClosedEvent::Reach(_)), None) => {
|
|
|
|
// TODO: this could be improved in the API of HandledNodesTasks
|
|
|
|
panic!("The HandledNodesTasks is guaranteed to always return the handler \
|
|
|
|
when producing a TaskClosedEvent::Reach error");
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-10-17 10:17:40 +01:00
|
|
|
(Some(TaskState::Connected(peer_id)), Ok(()), _handler) => {
|
|
|
|
debug_assert!(_handler.is_none());
|
2018-09-21 17:31:52 +02:00
|
|
|
let _node_task_id = self.nodes.remove(&peer_id);
|
|
|
|
debug_assert_eq!(_node_task_id, Some(id));
|
2018-10-17 10:17:40 +01:00
|
|
|
Async::Ready(CollectionEvent::NodeClosed {
|
2018-09-14 13:18:10 +02:00
|
|
|
peer_id,
|
2018-10-17 10:17:40 +01:00
|
|
|
})
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-12-11 15:36:41 +01:00
|
|
|
(Some(TaskState::Connected(peer_id)), Err(TaskClosedEvent::Node(err)), _handler) => {
|
2018-10-17 10:17:40 +01:00
|
|
|
debug_assert!(_handler.is_none());
|
2018-09-21 17:31:52 +02:00
|
|
|
let _node_task_id = self.nodes.remove(&peer_id);
|
|
|
|
debug_assert_eq!(_node_task_id, Some(id));
|
2018-10-17 10:17:40 +01:00
|
|
|
Async::Ready(CollectionEvent::NodeError {
|
2018-09-14 13:18:10 +02:00
|
|
|
peer_id,
|
2018-09-21 17:31:52 +02:00
|
|
|
error: err,
|
2018-10-17 10:17:40 +01:00
|
|
|
})
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-12-11 15:36:41 +01:00
|
|
|
(Some(TaskState::Connected(_)), Err(TaskClosedEvent::Reach(_)), _) => {
|
|
|
|
panic!("A TaskClosedEvent::Reach can only happen before we are connected \
|
|
|
|
to a node; therefore the TaskState won't be Connected; QED");
|
|
|
|
},
|
2018-10-17 10:17:40 +01:00
|
|
|
(None, _, _) => {
|
2018-10-29 20:38:32 +11:00
|
|
|
panic!("self.tasks is always kept in sync with the tasks in self.inner; \
|
2018-09-21 17:31:52 +02:00
|
|
|
when we add a task in self.inner we add a corresponding entry in \
|
2018-10-29 20:38:32 +11:00
|
|
|
self.tasks, and remove the entry only when the task is closed; \
|
2018-11-29 15:38:52 +00:00
|
|
|
QED")
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-10-17 10:17:40 +01:00
|
|
|
HandledNodesEvent::NodeReached { id, peer_id } => {
|
|
|
|
Async::Ready(CollectionEvent::NodeReached(CollectionReachEvent {
|
2018-10-01 14:49:17 +02:00
|
|
|
parent: self,
|
|
|
|
id,
|
|
|
|
peer_id,
|
2018-10-17 10:17:40 +01:00
|
|
|
}))
|
2018-09-21 17:31:52 +02:00
|
|
|
},
|
2018-10-17 10:17:40 +01:00
|
|
|
HandledNodesEvent::NodeEvent { id, event } => {
|
2018-09-21 17:31:52 +02:00
|
|
|
let peer_id = match self.tasks.get(&id) {
|
|
|
|
Some(TaskState::Connected(peer_id)) => peer_id.clone(),
|
|
|
|
_ => panic!("we can only receive NodeEvent events from a task after we \
|
2018-10-29 20:38:32 +11:00
|
|
|
received a corresponding NodeReached event from that same task; \
|
2018-09-21 17:31:52 +02:00
|
|
|
when we receive a NodeReached event, we ensure that the entry in \
|
2018-11-29 15:38:52 +00:00
|
|
|
self.tasks is switched to the Connected state; QED"),
|
2018-09-19 16:33:29 +02:00
|
|
|
};
|
2018-09-14 13:18:10 +02:00
|
|
|
|
2018-10-17 10:17:40 +01:00
|
|
|
Async::Ready(CollectionEvent::NodeEvent {
|
2018-09-21 17:31:52 +02:00
|
|
|
peer_id,
|
|
|
|
event,
|
2018-10-17 10:17:40 +01:00
|
|
|
})
|
2018-09-14 13:18:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-10-01 14:49:17 +02:00
|
|
|
|
2019-01-14 14:22:25 +01:00
|
|
|
/// Reach attempt interrupt errors.
|
2018-12-05 13:47:06 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum InterruptError {
|
|
|
|
/// An invalid reach attempt has been used to try to interrupt. The task
|
|
|
|
/// entry is vacant; it needs to be added first via add_reach_attempt
|
|
|
|
/// (with the TaskState set to Pending) before we try to connect.
|
|
|
|
ReachAttemptNotFound,
|
|
|
|
/// The task has already connected to the node; interrupting a reach attempt
|
|
|
|
/// is thus redundant as it has already completed. Thus, the reach attempt
|
|
|
|
/// that has tried to be used is no longer valid, since already reached.
|
|
|
|
AlreadyReached,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for InterruptError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match *self {
|
2019-01-14 14:22:25 +01:00
|
|
|
InterruptError::ReachAttemptNotFound =>
|
2018-12-05 13:47:06 +00:00
|
|
|
write!(f, "The reach attempt could not be found."),
|
|
|
|
InterruptError::AlreadyReached =>
|
|
|
|
write!(f, "The reach attempt has already completed or reached the node."),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl error::Error for InterruptError {}
|
|
|
|
|
2018-10-01 14:49:17 +02:00
|
|
|
/// Access to a peer in the collection.
|
2019-01-23 17:44:40 +01:00
|
|
|
pub struct PeerMut<'a, TInEvent: 'a, TPeerId: 'a = PeerId> {
|
2018-10-01 14:49:17 +02:00
|
|
|
inner: HandledNodesTask<'a, TInEvent>,
|
2019-01-23 17:44:40 +01:00
|
|
|
tasks: &'a mut FnvHashMap<TaskId, TaskState<TPeerId>>,
|
|
|
|
nodes: &'a mut FnvHashMap<TPeerId, TaskId>,
|
2018-10-01 14:49:17 +02:00
|
|
|
}
|
|
|
|
|
2019-01-23 17:44:40 +01:00
|
|
|
impl<'a, TInEvent, TPeerId> PeerMut<'a, TInEvent, TPeerId>
|
|
|
|
where
|
|
|
|
TPeerId: Eq + Hash,
|
|
|
|
{
|
2018-10-01 14:49:17 +02:00
|
|
|
/// Sends an event to the given node.
|
|
|
|
#[inline]
|
|
|
|
pub fn send_event(&mut self, event: TInEvent) {
|
|
|
|
self.inner.send_event(event)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Closes the connections to this node.
|
|
|
|
///
|
|
|
|
/// No further event will be generated for this node.
|
|
|
|
pub fn close(self) {
|
|
|
|
let task_state = self.tasks.remove(&self.inner.id());
|
|
|
|
if let Some(TaskState::Connected(peer_id)) = task_state {
|
|
|
|
let old_task_id = self.nodes.remove(&peer_id);
|
|
|
|
debug_assert_eq!(old_task_id, Some(self.inner.id()));
|
|
|
|
} else {
|
2018-10-29 20:38:32 +11:00
|
|
|
panic!("a PeerMut can only be created if an entry is present in nodes; an entry in \
|
2018-11-29 15:38:52 +00:00
|
|
|
nodes always matched a Connected entry in tasks; QED");
|
2018-10-01 14:49:17 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
self.inner.close();
|
|
|
|
}
|
|
|
|
}
|