Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(network): move in protocols #3

Merged
merged 17 commits into from
Jul 16, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(nework): ping message use protobuf instead
zeroqn committed Jul 14, 2020
commit 2540cadd954e4f3556476d5b6f0d1ac392bf1e8b
3 changes: 0 additions & 3 deletions core/network/src/protocols/ping.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
mod behaviour;
mod message;
#[allow(dead_code)]
#[allow(clippy::all)]
mod message_mol;
mod protocol;
use self::protocol::PingProtocol;
use behaviour::{EventTranslator, PingEventReporter};
19 changes: 0 additions & 19 deletions core/network/src/protocols/ping/message.mol

This file was deleted.

71 changes: 23 additions & 48 deletions core/network/src/protocols/ping/message.rs
Original file line number Diff line number Diff line change
@@ -1,62 +1,37 @@
use super::message_mol;

use molecule::prelude::{Builder, Entity, Reader};
use protocol::Bytes;
use prost::{EncodeError, Message, Oneof};
use protocol::{Bytes, BytesMut};

#[derive(Clone, Copy, PartialEq, Eq, Oneof)]
pub enum PingPayload {
#[prost(uint32, tag = "1")]
Ping(u32),
#[prost(uint32, tag = "2")]
Pong(u32),
}

pub struct PingMessage;
#[derive(Clone, PartialEq, Message)]
pub struct PingMessage {
#[prost(oneof = "PingPayload", tags = "1, 2")]
pub payload: Option<PingPayload>,
}

impl PingMessage {
pub fn build_ping(nonce: u32) -> Bytes {
let nonce_le = nonce.to_le_bytes();
let nonce = message_mol::Uint32::new_builder()
.nth0(nonce_le[0].into())
.nth1(nonce_le[1].into())
.nth2(nonce_le[2].into())
.nth3(nonce_le[3].into())
.build();
let ping = message_mol::Ping::new_builder().nonce(nonce).build();
let payload = message_mol::PingPayload::new_builder().set(ping).build();

message_mol::PingMessage::new_builder()
.payload(payload)
.build()
.as_bytes()
pub fn new_pong(nonce: u32) -> Self {
PingMessage {
payload: Some(PingPayload::Pong(nonce)),
}
}

pub fn build_pong(nonce: u32) -> Bytes {
let nonce_le = nonce.to_le_bytes();
let nonce = message_mol::Uint32::new_builder()
.nth0(nonce_le[0].into())
.nth1(nonce_le[1].into())
.nth2(nonce_le[2].into())
.nth3(nonce_le[3].into())
.build();
let pong = message_mol::Pong::new_builder().nonce(nonce).build();
let payload = message_mol::PingPayload::new_builder().set(pong).build();

message_mol::PingMessage::new_builder()
.payload(payload)
.build()
.as_bytes()
pub fn new_ping(nonce: u32) -> Self {
PingMessage {
payload: Some(PingPayload::Ping(nonce)),
}
}

#[allow(clippy::cast_ptr_alignment)]
pub fn decode(data: &[u8]) -> Option<PingPayload> {
let reader = message_mol::PingMessageReader::from_compatible_slice(data).ok()?;
match reader.payload().to_enum() {
message_mol::PingPayloadUnionReader::Ping(reader) => {
let le = reader.nonce().raw_data().as_ptr() as *const u32;
Some(PingPayload::Ping(u32::from_le(unsafe { *le })))
}
message_mol::PingPayloadUnionReader::Pong(reader) => {
let le = reader.nonce().raw_data().as_ptr() as *const u32;
Some(PingPayload::Pong(u32::from_le(unsafe { *le })))
}
}
pub fn to_bytes(self) -> Result<Bytes, EncodeError> {
let mut buf = BytesMut::with_capacity(self.encoded_len());
self.encode(&mut buf)?;

Ok(buf.freeze())
}
}
1,363 changes: 0 additions & 1,363 deletions core/network/src/protocols/ping/message_mol.rs

This file was deleted.

95 changes: 54 additions & 41 deletions core/network/src/protocols/ping/protocol.rs
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ use super::message::{PingMessage, PingPayload};

use futures::channel::mpsc::Sender;
use log::{debug, error, warn};
use prost::Message;
use tentacle::{
context::{ProtocolContext, ProtocolContextMutRef},
secio::PeerId,
@@ -151,46 +152,52 @@ impl ServiceProtocol for PingProtocol {
.get(&session.id)
.map(|ps| ps.peer_id.clone())
{
match PingMessage::decode(data.as_ref()) {
None => {
error!("decode message error");
self.send_event(PingEvent::UnexpectedError(peer_id));
match PingMessage::decode(data) {
Err(err) => {
warn!("decode message {}", err);
self.send_event(PingEvent::UnexpectedError(peer_id))
}
Some(msg) => {
match msg {
PingPayload::Ping(nonce) => {
if context
.send_message(PingMessage::build_pong(nonce))
.is_err()
{
debug!("send message fail");
Ok(PingMessage { payload: None }) => {
self.send_event(PingEvent::UnexpectedError(peer_id))
}
Ok(PingMessage { payload: Some(pld) }) => match pld {
PingPayload::Ping(nonce) => {
let pong = match PingMessage::new_pong(nonce).to_bytes() {
Ok(p) => p,
Err(err) => {
warn!("encode pong {}", err);
return;
}
self.send_event(PingEvent::Ping(peer_id));
};

if let Err(err) = context.send_message(pong) {
debug!("send message {}", err);
}
PingPayload::Pong(nonce) => {
// check pong
if self
.connected_session_ids
.get(&session.id)
.map(|ps| (ps.processing, ps.nonce()))
== Some((true, nonce))
{
let ping_time =
match self.connected_session_ids.get_mut(&session.id) {
Some(ps) => {
ps.processing = false;
ps.elapsed()
}
None => return,
};
self.send_event(PingEvent::Pong(peer_id, ping_time));
} else {
// ignore if nonce is incorrect
self.send_event(PingEvent::UnexpectedError(peer_id));
}
self.send_event(PingEvent::Ping(peer_id));
}
PingPayload::Pong(nonce) => {
// check pong
if self
.connected_session_ids
.get(&session.id)
.map(|ps| (ps.processing, ps.nonce()))
== Some((true, nonce))
{
let ping_time = match self.connected_session_ids.get_mut(&session.id) {
Some(ps) => {
ps.processing = false;
ps.elapsed()
}
None => return,
};
self.send_event(PingEvent::Pong(peer_id, ping_time));
} else {
// ignore if nonce is incorrect

self.send_event(PingEvent::UnexpectedError(peer_id));
}
}
}
},
}
}
}
@@ -214,17 +221,23 @@ impl ServiceProtocol for PingProtocol {
})
.collect();
if !peers.is_empty() {
let ping_msg = PingMessage::build_ping(peers[0].1);
let ping = match PingMessage::new_ping(peers[0].1).to_bytes() {
Ok(p) => p,
Err(err) => {
warn!("encode ping {}", err);
return;
}
};

let peer_ids: Vec<SessionId> = peers
.into_iter()
.map(|(session_id, _)| session_id)
.collect();
let proto_id = context.proto_id;
if context
.filter_broadcast(TargetSession::Multi(peer_ids), proto_id, ping_msg)
.is_err()
{
debug!("send message fail");
let target = TargetSession::Multi(peer_ids);

if let Err(err) = context.filter_broadcast(target, proto_id, ping) {
debug!("send message {}", err);
}
}
}