Skip to content
This repository has been archived by the owner on Jun 25, 2021. It is now read-only.

Commit

Permalink
feat!: minor changes to the Event enum
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `Event` changes:

- Remove `Event::Connected` - not needed because `Routing::new` now returns fully connected routing instance.
- Add `Event::Relocated` - replaces `Event::Connected(Connected::Relocate)`
- Remove `Event::InfantJoined` - merged with `MemberJoined`
- Change `Event::MemberJoined::previous_name` to `Option` to allow distinguishing between new and relocated peers.
  • Loading branch information
madadam committed Nov 9, 2020
1 parent e8cd1ad commit 56e658f
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 126 deletions.
49 changes: 18 additions & 31 deletions examples/minimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@
use futures::future::join_all;
use hex_fmt::HexFmt;
use log::{info, LevelFilter};
use sn_routing::{
event::{Connected, Event},
Config, EventStream, Routing, TransportConfig,
};
use sn_routing::{event::Event, Config, EventStream, Routing, TransportConfig};
use std::{
collections::HashSet,
convert::TryInto,
Expand Down Expand Up @@ -200,6 +197,14 @@ async fn start_node(
let contact_info = node
.our_connection_info()
.expect("Failed to obtain node's contact info.");

info!(
"Node #{} connected - name: {}, contact: {}",
index,
node.name().await,
contact_info
);

let handle = run_node(index, node, event_stream);

(contact_info, handle)
Expand All @@ -219,26 +224,6 @@ fn run_node(index: usize, mut node: Routing, mut event_stream: EventStream) -> J
// Handles the event emitted by the node.
async fn handle_event(index: usize, node: &mut Routing, event: Event) -> bool {
match event {
Event::Connected(Connected::First) => {
let contact_info = node
.our_connection_info()
.expect("failed to retrieve node contact info");

info!(
"Node #{} connected - name: {}, contact: {}",
index,
node.name().await,
contact_info
);
}
Event::Connected(Connected::Relocate { previous_name }) => {
info!(
"Node #{} relocated - old name: {}, new name: {}",
index,
previous_name,
node.name().await
);
}
Event::PromotedToElder => {
info!("Node #{} promoted to Elder", index);
}
Expand All @@ -254,16 +239,10 @@ async fn handle_event(index: usize, node: &mut Routing, event: Event) -> bool {
age,
} => {
info!(
"Node #{} member joined - name: {}, previous_name: {}, age: {}",
"Node #{} member joined - name: {}, previous_name: {:?}, age: {}",
index, name, previous_name, age
);
}
Event::InfantJoined { name, age } => {
info!(
"Node #{} infant joined - name: {}, age: {}",
index, name, age
);
}
Event::MemberLeft { name, age } => {
info!("Node #{} member left - name: {}, age: {}", index, name, age);
}
Expand All @@ -288,6 +267,14 @@ async fn handle_event(index: usize, node: &mut Routing, event: Event) -> bool {
"Node #{} relocation started - previous_name: {}",
index, previous_name
),
Event::Relocated { previous_name } => {
info!(
"Node #{} relocated - old name: {}, new name: {}",
index,
previous_name,
node.name().await
);
}
Event::RestartRequired => {
info!("Node #{} requires restart", index);
return false;
Expand Down
44 changes: 13 additions & 31 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,6 @@ use std::{
};
use xor_name::{Prefix, XorName};

/// An Event raised as node complete joining
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Connected {
/// Node first joining the network
First,
/// Node relocating from one section to another
Relocate {
/// Previous name before relocation.
previous_name: XorName,
},
}

/// An Event raised by a `Node` or `Client` via its event sender.
///
/// These are sent by sn_routing to the library's user. It allows the user to handle requests and
Expand All @@ -40,8 +28,6 @@ pub enum Connected {
// FIXME - See https://maidsafe.atlassian.net/browse/MAID-2026 for info on removing this exclusion.
#[allow(clippy::large_enum_variant)]
pub enum Event {
/// The node has successfully connected to the network.
Connected(Connected),
/// Received a message.
MessageReceived {
/// The content of the message.
Expand All @@ -57,19 +43,12 @@ pub enum Event {
PromotedToAdult,
/// The node has been demoted from elder
Demoted,
/// An adult or elder joined our section.
/// A new peer joined our section.
MemberJoined {
/// Name of the node
name: XorName,
/// Previous name before relocation
previous_name: XorName,
/// Age of the node
age: u8,
},
/// An infant node joined our section.
InfantJoined {
/// Name of the node
name: XorName,
/// Previous name before relocation or `None` if it is a new node.
previous_name: Option<XorName>,
/// Age of the node
age: u8,
},
Expand All @@ -90,11 +69,16 @@ pub enum Event {
elders: BTreeSet<XorName>,
},
/// This node has started relocating to other section. Will be followed by
/// `Connected(Relocate)` when the node finishes joining the destination section.
/// `Relocated` when the node finishes joining the destination section.
RelocationStarted {
/// Previous name before relocation
previous_name: XorName,
},
/// This node has completed relocation to other section.
Relocated {
/// Old name before the relocation.
previous_name: XorName,
},
/// Disconnected or failed to connect - restart required.
RestartRequired,
/// Received a message from a client node.
Expand All @@ -113,7 +97,6 @@ pub enum Event {
impl Debug for Event {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
match self {
Self::Connected(connect_type) => write!(formatter, "Connected({:?})", connect_type),
Self::MessageReceived { content, src, dst } => write!(
formatter,
"MessageReceived {{ content: \"{:<8}\", src: {:?}, dst: {:?} }}",
Expand All @@ -134,11 +117,6 @@ impl Debug for Event {
.field("previous_name", previous_name)
.field("age", age)
.finish(),
Self::InfantJoined { name, age } => formatter
.debug_struct("InfantJoined")
.field("name", name)
.field("age", age)
.finish(),
Self::MemberLeft { name, age } => formatter
.debug_struct("MemberLeft")
.field("name", name)
Expand All @@ -158,6 +136,10 @@ impl Debug for Event {
.debug_struct("RelocationStarted")
.field("previous_name", previous_name)
.finish(),
Self::Relocated { previous_name } => formatter
.debug_struct("Relocated")
.field("previous_name", previous_name)
.finish(),
Self::RestartRequired => write!(formatter, "RestartRequired"),
Self::ClientMessageReceived { content, src, .. } => write!(
formatter,
Expand Down
17 changes: 5 additions & 12 deletions src/routing/approved.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1135,18 +1135,11 @@ impl Approved {
commands.extend(self.relocate_peers(peer.name(), &signature)?);
commands.extend(self.promote_and_demote_elders()?);

if let Some(previous_name) = previous_name {
self.send_event(Event::MemberJoined {
name: *peer.name(),
previous_name,
age: peer.age(),
});
} else {
self.send_event(Event::InfantJoined {
name: *peer.name(),
age: peer.age(),
});
}
self.send_event(Event::MemberJoined {
name: *peer.name(),
previous_name,
age: peer.age(),
});

self.print_network_stats();
}
Expand Down
5 changes: 1 addition & 4 deletions src/routing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use self::{
use crate::{
crypto,
error::{Error, Result},
event::{Connected, Event},
event::Event,
location::{DstLocation, SrcLocation},
node::Node,
peer::Peer,
Expand Down Expand Up @@ -96,7 +96,6 @@ impl Routing {
let node = Node::new(keypair, comm.our_connection_info()?);
let state = Approved::first_node(node, event_tx)?;

state.send_event(Event::Connected(Connected::First));
state.send_event(Event::PromotedToElder);

(state, comm, incoming_msgs, vec![])
Expand All @@ -110,8 +109,6 @@ impl Routing {
bootstrap::infant(node, &comm, &mut incoming_msgs, bootstrap_addr).await?;
let state = Approved::new(node, section, None, event_tx);

state.send_event(Event::Connected(Connected::First));

(state, comm, incoming_msgs, backlog)
};

Expand Down
9 changes: 2 additions & 7 deletions src/routing/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@
// permissions and limitations relating to use of the SAFE Network Software.

use super::{bootstrap, Approved, Comm, Command};
use crate::{
error::Result,
event::{Connected, Event},
messages::Message,
relocation::SignedRelocateDetails,
};
use crate::{error::Result, event::Event, messages::Message, relocation::SignedRelocateDetails};
use bytes::Bytes;
use std::{net::SocketAddr, sync::Arc, time::Duration};
use tokio::{
Expand Down Expand Up @@ -194,7 +189,7 @@ impl Stage {
let event_tx = state.event_tx.clone();
*state = Approved::new(node, section, None, event_tx);

state.send_event(Event::Connected(Connected::Relocate { previous_name }));
state.send_event(Event::Relocated { previous_name });

let commands = backlog
.into_iter()
Expand Down
2 changes: 1 addition & 1 deletion src/routing/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ async fn handle_consensus_on_online_of_infant(phase: NetworkPhase) -> Result<()>
assert!(event_rx.try_recv().is_err());
}
NetworkPhase::Regular => {
assert_matches!(event_rx.try_recv(), Ok(Event::InfantJoined { name, age, }) => {
assert_matches!(event_rx.try_recv(), Ok(Event::MemberJoined { name, age, .. }) => {
assert_eq!(name, *new_peer.name());
assert_eq!(age, MIN_AGE);
});
Expand Down
14 changes: 3 additions & 11 deletions tests/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ mod utils;
use anyhow::{Error, Result};
use ed25519_dalek::Keypair;
use futures::future;
use sn_routing::{
event::{Connected, Event},
EventStream, ELDER_SIZE,
};
use sn_routing::{event::Event, EventStream, ELDER_SIZE};
use tokio::time;
use utils::*;

Expand All @@ -30,7 +27,6 @@ async fn test_genesis_node() -> Result<()> {

assert_eq!(pub_key, node.public_key().await);

assert_next_event!(event_stream, Event::Connected(Connected::First));
assert_next_event!(event_stream, Event::PromotedToElder);

assert!(node.is_elder().await);
Expand All @@ -44,7 +40,6 @@ async fn test_node_bootstrapping() -> Result<()> {

// spawn genesis node events listener
let genesis_handler = tokio::spawn(async move {
assert_next_event!(event_stream, Event::Connected(Connected::First));
assert_next_event!(event_stream, Event::PromotedToElder);
assert_next_event!(event_stream, Event::MemberJoined { .. });
// TODO: we should expect `EldersChanged` too.
Expand All @@ -53,13 +48,11 @@ async fn test_node_bootstrapping() -> Result<()> {

// bootstrap a second node with genesis
let genesis_contact = genesis_node.our_connection_info()?;
let (node1, mut event_stream) = RoutingBuilder::new(None)
let (node1, _event_stream) = RoutingBuilder::new(None)
.with_contact(genesis_contact)
.create()
.await?;

assert_next_event!(event_stream, Event::Connected(Connected::First));

// just await for genesis node to finish receiving all events
genesis_handler.await?;

Expand Down Expand Up @@ -102,9 +95,8 @@ async fn test_startup_section_bootstrapping() -> Result<()> {
.await?;

// During the startup phase, joining nodes are instantly relocated.
assert_next_event!(event_stream, Event::Connected(Connected::First));
assert_next_event!(event_stream, Event::RelocationStarted { .. });
assert_next_event!(event_stream, Event::Connected(Connected::Relocate { .. }));
assert_next_event!(event_stream, Event::Relocated { .. });

Ok::<_, Error>(node)
})
Expand Down
7 changes: 2 additions & 5 deletions tests/drop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ mod utils;
use self::utils::*;
use anyhow::{format_err, Result};
use bytes::Bytes;
use sn_routing::{
event::{Connected, Event},
DstLocation, SrcLocation,
};
use sn_routing::{event::Event, DstLocation, SrcLocation};
use tokio::time;

#[tokio::test]
Expand All @@ -24,7 +21,7 @@ async fn test_node_drop() -> Result<()> {
// We are in the startup phase, so the second node is instantly relocated. Let's wait until it
// re-joins.
assert_next_event!(nodes[1].1, Event::RelocationStarted { .. });
assert_next_event!(nodes[1].1, Event::Connected(Connected::Relocate { .. }));
assert_next_event!(nodes[1].1, Event::Relocated { .. });

// Drop one node
let dropped_name = nodes.remove(1).0.name().await;
Expand Down
8 changes: 2 additions & 6 deletions tests/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ mod utils;
use anyhow::{format_err, Result};
use bytes::Bytes;
use qp2p::QuicP2p;
use sn_routing::{
event::{Connected, Event},
DstLocation, Error, SrcLocation, TransportConfig,
};
use sn_routing::{event::Event, DstLocation, Error, SrcLocation, TransportConfig};
use std::net::{IpAddr, Ipv4Addr};
use utils::*;

Expand Down Expand Up @@ -90,9 +87,8 @@ async fn test_messages_between_nodes() -> Result<()> {
.await?;

// We are in the startup phase, so node2 is instantly relocated. Let's wait until it re-joins.
assert_next_event!(event_stream, Event::Connected(Connected::First));
assert_next_event!(event_stream, Event::RelocationStarted { .. });
assert_next_event!(event_stream, Event::Connected(Connected::Relocate { .. }));
assert_next_event!(event_stream, Event::Relocated { .. });

let node2_name = node2.name().await;

Expand Down

0 comments on commit 56e658f

Please sign in to comment.