Skip to main content

rperf3/
protocol.rs

1use serde::{Deserialize, Serialize};
2use std::time::Duration;
3
4/// Current protocol version for client-server communication.
5///
6/// This version number is used to ensure compatibility between clients and servers.
7/// If the protocol changes in a breaking way, this version should be incremented.
8pub const PROTOCOL_VERSION: u32 = 1;
9
10/// Default stream ID, matching iperf3's behavior.
11///
12/// iperf3 uses stream ID 5 as the default for single stream tests.
13/// For parallel streams, IDs are typically sequential starting from this base.
14pub const DEFAULT_STREAM_ID: usize = 5;
15
16/// Generates a stream ID for parallel streams.
17///
18/// Returns a stream ID based on the stream index, matching iperf3's behavior
19/// where stream IDs are sequential starting from the default.
20///
21/// # Arguments
22///
23/// * `index` - Zero-based stream index (0 for first stream, 1 for second, etc.)
24///
25/// # Examples
26///
27/// ```
28/// use rperf3::protocol::stream_id_for_index;
29///
30/// assert_eq!(stream_id_for_index(0), 5);  // First stream
31/// assert_eq!(stream_id_for_index(1), 7);  // Second stream
32/// assert_eq!(stream_id_for_index(2), 9);  // Third stream
33/// ```
34pub fn stream_id_for_index(index: usize) -> usize {
35    DEFAULT_STREAM_ID + (index * 2)
36}
37
38/// Message types in the rperf3 protocol.
39///
40/// These messages are exchanged between the client and server during test execution.
41/// All messages are serialized as JSON with a `type` field discriminator.
42///
43/// # Protocol Flow
44///
45/// 1. Client sends `Setup` with test parameters
46/// 2. Server responds with `SetupAck`
47/// 3. Server sends `Start` to begin test
48/// 4. `Interval` messages are sent periodically during test
49/// 5. `Result` message contains final statistics
50/// 6. `Done` signals test completion
51/// 7. `Error` can be sent at any point to indicate failure
52///
53/// # Examples
54///
55/// ```
56/// use rperf3::protocol::Message;
57/// use std::time::Duration;
58///
59/// // Create a setup message
60/// let setup = Message::setup(
61///     "TCP".to_string(),
62///     Duration::from_secs(10),
63///     None,
64///     128 * 1024,
65///     1,
66///     false,
67/// );
68/// ```
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(tag = "type")]
71pub enum Message {
72    /// Initial handshake from client with test parameters
73    Setup {
74        version: u32,
75        protocol: String,
76        duration: u64,
77        bandwidth: Option<u64>,
78        buffer_size: usize,
79        parallel: usize,
80        reverse: bool,
81    },
82
83    /// Server acknowledgment of setup
84    SetupAck { port: u16, cookie: String },
85
86    /// Test start signal
87    Start { timestamp: u64 },
88
89    /// Interval results
90    Interval {
91        stream_id: usize,
92        start: f64,
93        end: f64,
94        bytes: u64,
95        bits_per_second: f64,
96    },
97
98    /// Final results
99    Result {
100        stream_id: usize,
101        bytes_sent: u64,
102        bytes_received: u64,
103        duration: f64,
104        bits_per_second: f64,
105        retransmits: Option<u64>,
106    },
107
108    /// Test completion signal
109    Done,
110
111    /// Error message
112    Error { message: String },
113}
114
115impl Message {
116    /// Creates a Setup message for test initialization.
117    ///
118    /// # Arguments
119    ///
120    /// * `protocol` - Protocol name ("TCP" or "UDP")
121    /// * `duration` - Test duration
122    /// * `bandwidth` - Target bandwidth for UDP (None for TCP)
123    /// * `buffer_size` - Buffer size in bytes
124    /// * `parallel` - Number of parallel streams
125    /// * `reverse` - Whether to use reverse mode
126    pub fn setup(
127        protocol: String,
128        duration: Duration,
129        bandwidth: Option<u64>,
130        buffer_size: usize,
131        parallel: usize,
132        reverse: bool,
133    ) -> Self {
134        Message::Setup {
135            version: PROTOCOL_VERSION,
136            protocol,
137            duration: duration.as_secs(),
138            bandwidth,
139            buffer_size,
140            parallel,
141            reverse,
142        }
143    }
144
145    /// Creates a SetupAck message.
146    ///
147    /// # Arguments
148    ///
149    /// * `port` - Server port number
150    /// * `cookie` - Session identifier string
151    pub fn setup_ack(port: u16, cookie: String) -> Self {
152        Message::SetupAck { port, cookie }
153    }
154
155    /// Creates a Start message to begin the test.
156    ///
157    /// # Arguments
158    ///
159    /// * `timestamp` - Unix timestamp when test starts
160    pub fn start(timestamp: u64) -> Self {
161        Message::Start { timestamp }
162    }
163
164    /// Creates an Interval message with periodic statistics.
165    ///
166    /// # Arguments
167    ///
168    /// * `stream_id` - Stream identifier
169    /// * `start` - Interval start time in seconds
170    /// * `end` - Interval end time in seconds
171    /// * `bytes` - Bytes transferred during interval
172    /// * `bits_per_second` - Throughput during interval
173    pub fn interval(
174        stream_id: usize,
175        start: f64,
176        end: f64,
177        bytes: u64,
178        bits_per_second: f64,
179    ) -> Self {
180        Message::Interval {
181            stream_id,
182            start,
183            end,
184            bytes,
185            bits_per_second,
186        }
187    }
188
189    /// Creates a Result message with final test statistics.
190    ///
191    /// # Arguments
192    ///
193    /// * `stream_id` - Stream identifier
194    /// * `bytes_sent` - Total bytes sent
195    /// * `bytes_received` - Total bytes received
196    /// * `duration` - Test duration in seconds
197    /// * `bits_per_second` - Average throughput
198    /// * `retransmits` - TCP retransmit count (None for UDP)
199    pub fn result(
200        stream_id: usize,
201        bytes_sent: u64,
202        bytes_received: u64,
203        duration: f64,
204        bits_per_second: f64,
205        retransmits: Option<u64>,
206    ) -> Self {
207        Message::Result {
208            stream_id,
209            bytes_sent,
210            bytes_received,
211            duration,
212            bits_per_second,
213            retransmits,
214        }
215    }
216
217    /// Creates a Done message to signal test completion.
218    pub fn done() -> Self {
219        Message::Done
220    }
221
222    /// Creates an Error message.
223    ///
224    /// # Arguments
225    ///
226    /// * `message` - Error description
227    pub fn error(message: String) -> Self {
228        Message::Error { message }
229    }
230}
231
232/// Serialize a message to JSON bytes
233/// Serializes a protocol message to JSON bytes.
234///
235/// The serialized format is a length-prefixed JSON message:
236/// - First 4 bytes: message length as big-endian u32
237/// - Remaining bytes: UTF-8 encoded JSON
238///
239/// # Arguments
240///
241/// * `msg` - The message to serialize
242///
243/// # Errors
244///
245/// Returns an error if JSON serialization fails.
246///
247/// # Examples
248///
249/// ```
250/// use rperf3::protocol::{Message, serialize_message};
251///
252/// let msg = Message::done();
253/// let bytes = serialize_message(&msg).expect("Serialization failed");
254/// assert!(bytes.len() >= 4); // At least length prefix
255/// ```
256pub fn serialize_message(msg: &Message) -> crate::Result<Vec<u8>> {
257    let json = serde_json::to_vec(msg)?;
258    let len = json.len() as u32;
259    let mut result = Vec::with_capacity(4 + json.len());
260    result.extend_from_slice(&len.to_be_bytes());
261    result.extend_from_slice(&json);
262    Ok(result)
263}
264
265/// Deserializes a protocol message from an async reader.
266///
267/// Reads a length-prefixed JSON message from the stream:
268/// - First 4 bytes: message length as big-endian u32
269/// - Next N bytes: UTF-8 encoded JSON message
270///
271/// # Arguments
272///
273/// * `reader` - An async reader to deserialize from
274///
275/// # Errors
276///
277/// Returns an error if:
278/// - Reading from the stream fails
279/// - JSON deserialization fails
280/// - Message format is invalid
281///
282/// # Examples
283///
284/// ```no_run
285/// use rperf3::protocol::deserialize_message;
286/// use tokio::net::TcpStream;
287///
288/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
289/// let mut stream = TcpStream::connect("127.0.0.1:5201").await?;
290/// let message = deserialize_message(&mut stream).await?;
291/// # Ok(())
292/// # }
293/// ```
294pub async fn deserialize_message<R: tokio::io::AsyncRead + Unpin>(
295    reader: &mut R,
296) -> crate::Result<Message> {
297    use tokio::io::AsyncReadExt;
298
299    let mut len_bytes = [0u8; 4];
300    reader.read_exact(&mut len_bytes).await?;
301    let len = u32::from_be_bytes(len_bytes) as usize;
302
303    let mut json_bytes = vec![0u8; len];
304    reader.read_exact(&mut json_bytes).await?;
305
306    let msg = serde_json::from_slice(&json_bytes)?;
307    Ok(msg)
308}