puffin/
stream.rs

1//! The communication streams between [`Agent`](crate::agent::Agent)s.
2//!
3//! These are currently implemented by using an in-memory buffer.
4//!
5//! One might ask why we want two channels. There two very practical reasons
6//! for this. Note that these are advantages for the implementation and are not
7//! strictly required from a theoretical point of view.
8//!
9//! * Having two buffers resembles how networking works in reality: Each computer has an input and
10//!   an output buffer. In case of TCP the input buffer can become full and therefore the
11//!   transmission is throttled.
12//! * It is beneficial to model each agent with two buffers according to the Single-responsibility
13//!   principle. When sending or receiving data each agent only has to look at its own two buffer.
14//!   If each agent had only one buffer, then you would need to read from another agent which has
15//!   the data you want. Or if you design it the other way around you would need to write to the
16//!   buffer of the agent to which you want to send data.
17//!
18//! The [`Agent`](crate::agent::Agent) Alice can add data to the *inbound channel* of Bob.
19//! Bob can then read the data from his *inbound channel* and put data in his *outbound channel*.
20//! If Bob is an [`Agent`](crate::agent::Agent), which has an underlying *PUT state* then OpenSSL
21//! may write into the *outbound channel* of Bob.
22
23use std::io::{self, Read, Write};
24
25use crate::algebra::ConcreteMessage;
26use crate::codec::Codec;
27use crate::error::Error;
28use crate::protocol::ProtocolBehavior;
29
30pub trait Stream<PB: ProtocolBehavior> {
31    fn add_to_inbound(&mut self, message: &ConcreteMessage);
32
33    /// Takes a single TLS message from the outbound channel
34    fn take_message_from_outbound(
35        &mut self,
36        output_flight: &mut Option<PB::OpaqueProtocolMessageFlight>,
37    ) -> Result<(), Error>;
38}
39
40/// Describes in- or outbound channels of an [`crate::agent::Agent`].
41///
42/// Each [`crate::agent::Agent`] can send and receive data. This is modeled by two separate Channels
43/// in [`MemoryStream`]. Internally a Channel is just an in-memory seekable buffer.
44pub type Channel = io::Cursor<Vec<u8>>;
45
46/// A `MemoryStream` has two [`Channel`]s. The Stream also implements the [`Write`] and [`Read`]
47/// trait.
48/// * When writing to a `MemoryStream` its outbound channel gets filled.
49/// * When reading from a `MemoryStream` data is taken from the inbound channel.
50///
51/// This makes it possible for an [`crate::agent::Agent`] to treat a [`MemoryStream`] like a TLS
52/// socket! By writing to this socket you are sending data out. By reading from it you receive data.
53///
54/// **Note: There need to be two separate buffer! Else for example a TLS socket would read and write
55/// into the same buffer**
56#[derive(Default, Debug)]
57pub struct MemoryStream {
58    inbound: Channel,
59    outbound: Channel,
60}
61
62impl MemoryStream {
63    #[must_use]
64    pub fn new() -> Self {
65        Self {
66            inbound: io::Cursor::new(Vec::new()),
67            outbound: io::Cursor::new(Vec::new()),
68        }
69    }
70}
71
72impl<PB: ProtocolBehavior> Stream<PB> for MemoryStream {
73    fn add_to_inbound(&mut self, message: &ConcreteMessage) {
74        message.encode(self.inbound.get_mut());
75    }
76
77    fn take_message_from_outbound(
78        &mut self,
79        output_flight: &mut Option<PB::OpaqueProtocolMessageFlight>,
80    ) -> Result<(), Error> {
81        *output_flight =
82            PB::OpaqueProtocolMessageFlight::read_bytes(self.outbound.get_ref().as_slice());
83        self.outbound.set_position(0);
84        self.outbound.get_mut().clear();
85
86        Ok(())
87    }
88}
89
90impl Read for MemoryStream {
91    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
92        let n = self.inbound.read(buf)?;
93
94        // Clear as soon as we read all data
95        if self.inbound.position() == self.inbound.get_ref().len() as u64 {
96            self.inbound.set_position(0);
97            self.inbound.get_mut().clear();
98        }
99        if n == 0 {
100            return Err(io::Error::new(
101                io::ErrorKind::WouldBlock,
102                "no data available",
103            ));
104        }
105        Ok(n)
106    }
107}
108
109impl Write for MemoryStream {
110    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
111        self.outbound.write(buf)
112    }
113
114    fn flush(&mut self) -> io::Result<()> {
115        Ok(())
116    }
117}