veloren_network_protocol/
lib.rs

1//! Network Protocol
2//!
3//! a I/O-Free protocol for the veloren network crate.
4//! This crate defines multiple different protocols over [`UnreliableDrain`] and
5//! [`UnreliableSink`] traits, which allows it to define the behavior of a
6//! protocol separated from the actual io.
7//!
8//! For example we define the TCP protocol on top of Drains and Sinks that can
9//! send chunks of bytes. You can now implement your own Drain And Sink that
10//! sends the data via tokio's or std's implementation. Or you just use a
11//! std::mpsc::channel for unit tests without needing a actual tcp socket.
12//!
13//! This crate currently defines:
14//!  - TCP
15//!  - MPSC
16//!  - QUIC
17//!
18//! eventually a pure UDP implementation will follow
19//!
20//! warning: don't mix protocol, using the TCP variant for actual UDP socket
21//! will result in dropped data  using UDP with a TCP socket will be a waste of
22//! resources.
23//!
24//! A *channel* in this crate is defined as a combination of *read* and *write*
25//! protocol.
26//!
27//! # adding a protocol
28//!
29//! We start by defining our DataFormat. For most this is prob [`Vec<u8>`] or
30//! [`Bytes`]. MPSC can directly send a msg without serialisation.
31//!
32//! Create 2 structs, one for the receiving and sending end. Based on a generic
33//! Drain/Sink with your required DataFormat.
34//! Implement the [`SendProtocol`] and [`RecvProtocol`] traits respectively.
35//!
36//! Implement the Handshake: [`InitProtocol`], alternatively you can also
37//! implement `ReliableDrain` and `ReliableSink`, by this, you use the default
38//! Handshake.
39//!
40//! This crate also contains consts and definitions for the network protocol.
41//!
42//! For an *example* see `TcpDrain` and `TcpSink` in the [tcp.rs](tcp.rs)
43//!
44//! [`UnreliableDrain`]: crate::UnreliableDrain
45//! [`UnreliableSink`]: crate::UnreliableSink
46//! [`Vec<u8>`]: std::vec::Vec
47//! [`Bytes`]: bytes::Bytes
48//! [`SendProtocol`]: crate::SendProtocol
49//! [`RecvProtocol`]: crate::RecvProtocol
50//! [`InitProtocol`]: crate::InitProtocol
51
52mod error;
53mod event;
54mod frame;
55mod handshake;
56mod message;
57mod metrics;
58mod mpsc;
59mod prio;
60mod quic;
61mod tcp;
62mod types;
63mod util;
64
65pub use error::{InitProtocolError, ProtocolError};
66pub use event::ProtocolEvent;
67pub use metrics::ProtocolMetricCache;
68#[cfg(feature = "metrics")]
69pub use metrics::ProtocolMetrics;
70pub use mpsc::{MpscMsg, MpscRecvProtocol, MpscSendProtocol};
71pub use quic::{QuicDataFormat, QuicDataFormatStream, QuicRecvProtocol, QuicSendProtocol};
72pub use tcp::{TcpRecvProtocol, TcpSendProtocol};
73pub use types::{Bandwidth, Cid, HIGHEST_PRIO, Pid, Prio, Promises, Sid, VELOREN_NETWORK_VERSION};
74
75///use at own risk, might change any time, for internal benchmarks
76pub mod _internal {
77    pub use crate::{
78        frame::{ITFrame, OTFrame},
79        util::SortedVec,
80    };
81}
82
83use async_trait::async_trait;
84
85/// Handshake: Used to connect 2 Channels.
86#[async_trait]
87pub trait InitProtocol {
88    type CustomErr: std::fmt::Debug + Send;
89
90    async fn initialize(
91        &mut self,
92        initializer: bool,
93        local_pid: Pid,
94        secret: u128,
95    ) -> Result<(Pid, Sid, u128), InitProtocolError<Self::CustomErr>>;
96}
97
98/// Generic Network Send Protocol.
99/// Implement this for your Protocol of choice ( tcp, udp, mpsc, quic)
100/// Allows the creation/deletions of `Streams` and sending messages via
101/// [`ProtocolEvent`].
102///
103/// A `Stream` MUST be bound to a specific Channel. You MUST NOT switch the
104/// channel to send a stream mid air. We will provide takeover options for
105/// Channel closure in the future to allow keeping a `Stream` over a broken
106/// Channel.
107///
108/// [`ProtocolEvent`]: crate::ProtocolEvent
109#[async_trait]
110pub trait SendProtocol {
111    type CustomErr: std::fmt::Debug + Send;
112
113    /// YOU MUST inform the `SendProtocol` by any Stream Open BEFORE using it in
114    /// `send` and Stream Close AFTER using it in `send` via this fn.
115    fn notify_from_recv(&mut self, event: ProtocolEvent);
116    /// Send a Event via this Protocol. The `SendProtocol` MAY require `flush`
117    /// to be called before actual data is send to the respective `Sink`.
118    async fn send(&mut self, event: ProtocolEvent) -> Result<(), ProtocolError<Self::CustomErr>>;
119    /// Flush all buffered messages according to their [`Prio`] and
120    /// [`Bandwidth`]. provide the current bandwidth budget (per second) as
121    /// well as the `dt` since last call. According to the budget the
122    /// respective messages will be flushed.
123    ///
124    /// [`Prio`]: crate::Prio
125    /// [`Bandwidth`]: crate::Bandwidth
126    async fn flush(
127        &mut self,
128        bandwidth: Bandwidth,
129        dt: std::time::Duration,
130    ) -> Result<Bandwidth, ProtocolError<Self::CustomErr>>;
131}
132
133/// Generic Network Recv Protocol. See: [`SendProtocol`]
134///
135/// [`SendProtocol`]: crate::SendProtocol
136#[async_trait]
137pub trait RecvProtocol {
138    type CustomErr: std::fmt::Debug + Send;
139
140    /// Either recv an event or fail the Protocol, once the Recv side is closed
141    /// it cannot recover from the error.
142    async fn recv(&mut self) -> Result<ProtocolEvent, ProtocolError<Self::CustomErr>>;
143}
144
145/// This crate makes use of UnreliableDrains, they are expected to provide the
146/// same guarantees like their IO-counterpart. E.g. ordered messages for TCP and
147/// nothing for UDP. The respective Protocol needs then to handle this.
148/// This trait is an abstraction above multiple Drains, e.g. [`tokio`](https://tokio.rs) [`async-std`] [`std`] or even [`async-channel`]
149///
150/// [`async-std`]: async-std
151/// [`std`]: std
152/// [`async-channel`]: async-channel
153#[async_trait]
154pub trait UnreliableDrain: Send {
155    type CustomErr: std::fmt::Debug + Send;
156    type DataFormat;
157    async fn send(&mut self, data: Self::DataFormat) -> Result<(), ProtocolError<Self::CustomErr>>;
158}
159
160/// Sink counterpart of [`UnreliableDrain`]
161///
162/// [`UnreliableDrain`]: crate::UnreliableDrain
163#[async_trait]
164pub trait UnreliableSink: Send {
165    type CustomErr: std::fmt::Debug + Send;
166    type DataFormat;
167    async fn recv(&mut self) -> Result<Self::DataFormat, ProtocolError<Self::CustomErr>>;
168}