use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant};
pub const DEFAULT_PORT: u16 = 5201;
pub const DEFAULT_DURATION_SECS: u64 = 10;
pub const DEFAULT_BUFFER_SIZE: usize = 128 * 1024;
#[derive(Debug, Clone)]
pub struct BandwidthConfig {
pub duration: Duration,
pub buffer_size: usize,
pub parallel_streams: u8,
pub connect_timeout: Duration,
pub upload: bool,
}
impl Default for BandwidthConfig {
fn default() -> Self {
Self {
duration: Duration::from_secs(DEFAULT_DURATION_SECS),
buffer_size: DEFAULT_BUFFER_SIZE,
parallel_streams: 1,
connect_timeout: Duration::from_secs(10),
upload: false,
}
}
}
impl BandwidthConfig {
pub fn with_duration(mut self, duration: Duration) -> Self {
self.duration = duration;
self
}
pub fn with_buffer_size(mut self, size: usize) -> Self {
self.buffer_size = size;
self
}
pub fn with_parallel_streams(mut self, streams: u8) -> Self {
self.parallel_streams = streams.max(1);
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = timeout;
self
}
pub fn upload_mode(mut self) -> Self {
self.upload = true;
self
}
pub fn download_mode(mut self) -> Self {
self.upload = false;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BandwidthResult {
pub host: String,
pub port: u16,
pub upload: bool,
pub duration_secs: f64,
pub bytes_transferred: u64,
pub bandwidth_bps: f64,
pub bandwidth_mbps: f64,
pub bandwidth_mbytes_per_sec: f64,
pub transfer_count: u64,
pub connect_time_ms: f64,
pub success: bool,
pub error: Option<String>,
}
impl BandwidthResult {
fn failed(host: &str, port: u16, error: &str) -> Self {
Self {
host: host.to_string(),
port,
upload: false,
duration_secs: 0.0,
bytes_transferred: 0,
bandwidth_bps: 0.0,
bandwidth_mbps: 0.0,
bandwidth_mbytes_per_sec: 0.0,
transfer_count: 0,
connect_time_ms: 0.0,
success: false,
error: Some(error.to_string()),
}
}
}
pub fn bandwidth_test(host: &str, port: u16, config: &BandwidthConfig) -> Result<BandwidthResult> {
let addr = format!("{}:{}", host, port);
let socket_addr = addr
.to_socket_addrs()
.map_err(|e| IronError::Other(format!("Failed to resolve {}: {}", addr, e)))?
.next()
.ok_or_else(|| IronError::Other(format!("No addresses found for {}", addr)))?;
let connect_start = Instant::now();
let mut stream = TcpStream::connect_timeout(&socket_addr, config.connect_timeout)
.map_err(|e| IronError::Other(format!("Failed to connect to {}: {}", addr, e)))?;
let connect_time = connect_start.elapsed();
stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
stream.set_nodelay(true).ok();
let buffer = vec![0u8; config.buffer_size];
let mut total_bytes: u64 = 0;
let mut transfer_count: u64 = 0;
let test_start = Instant::now();
if config.upload {
while test_start.elapsed() < config.duration {
match stream.write(&buffer) {
Ok(n) => {
total_bytes += n as u64;
transfer_count += 1;
}
Err(e) => {
if e.kind() != std::io::ErrorKind::WouldBlock {
return Ok(BandwidthResult::failed(
host,
port,
&format!("Write error: {}", e),
));
}
}
}
}
} else {
let mut read_buffer = vec![0u8; config.buffer_size];
while test_start.elapsed() < config.duration {
match stream.read(&mut read_buffer) {
Ok(0) => break, Ok(n) => {
total_bytes += n as u64;
transfer_count += 1;
}
Err(e) => {
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut
{
continue;
}
break;
}
}
}
}
let duration = test_start.elapsed();
let duration_secs = duration.as_secs_f64();
let bits_transferred = total_bytes * 8;
let bandwidth_bps = if duration_secs > 0.0 {
bits_transferred as f64 / duration_secs
} else {
0.0
};
let bandwidth_mbps = bandwidth_bps / 1_000_000.0;
let bandwidth_mbytes = if duration_secs > 0.0 {
total_bytes as f64 / duration_secs / 1_000_000.0
} else {
0.0
};
Ok(BandwidthResult {
host: host.to_string(),
port,
upload: config.upload,
duration_secs,
bytes_transferred: total_bytes,
bandwidth_bps,
bandwidth_mbps,
bandwidth_mbytes_per_sec: bandwidth_mbytes,
transfer_count,
connect_time_ms: connect_time.as_secs_f64() * 1000.0,
success: total_bytes > 0,
error: None,
})
}
pub fn loopback_test(duration: Duration) -> Result<BandwidthResult> {
use std::net::TcpListener;
use std::thread;
let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| IronError::Other(e.to_string()))?;
let port = listener
.local_addr()
.map_err(|e| IronError::Other(format!("failed to get local address: {}", e)))?
.port();
let buffer_size = DEFAULT_BUFFER_SIZE;
let test_duration = duration;
let receiver = thread::spawn(move || {
let Ok((mut stream, _)) = listener.accept() else {
return 0u64;
};
stream
.set_read_timeout(Some(Duration::from_millis(100)))
.ok();
let mut buffer = vec![0u8; buffer_size];
let mut total_bytes: u64 = 0;
let start = Instant::now();
while start.elapsed() < test_duration + Duration::from_secs(1) {
match stream.read(&mut buffer) {
Ok(0) => break,
Ok(n) => total_bytes += n as u64,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => continue,
Err(_) => break,
}
}
total_bytes
});
thread::sleep(Duration::from_millis(50));
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port))
.map_err(|e| IronError::Other(e.to_string()))?;
stream.set_nodelay(true).ok();
let buffer = vec![0xABu8; buffer_size];
let mut total_sent: u64 = 0;
let start = Instant::now();
while start.elapsed() < test_duration {
match stream.write(&buffer) {
Ok(n) => total_sent += n as u64,
Err(_) => break,
}
}
drop(stream);
let total_received = receiver.join().unwrap_or(0);
let duration_secs = start.elapsed().as_secs_f64();
let bytes_transferred = total_sent.min(total_received);
let bits_transferred = bytes_transferred * 8;
let bandwidth_bps = if duration_secs > 0.0 {
bits_transferred as f64 / duration_secs
} else {
0.0
};
Ok(BandwidthResult {
host: "127.0.0.1".to_string(),
port,
upload: true,
duration_secs,
bytes_transferred,
bandwidth_bps,
bandwidth_mbps: bandwidth_bps / 1_000_000.0,
bandwidth_mbytes_per_sec: bytes_transferred as f64 / duration_secs / 1_000_000.0,
transfer_count: bytes_transferred / buffer_size as u64,
connect_time_ms: 0.0,
success: bytes_transferred > 0,
error: None,
})
}
pub fn memory_bandwidth_test(duration: Duration) -> MemoryBandwidthResult {
let buffer_size = 64 * 1024 * 1024; let src = vec![0xABu8; buffer_size];
let mut dst = vec![0u8; buffer_size];
let start = Instant::now();
let mut iterations = 0u64;
let mut checksum = 0u8;
while start.elapsed() < duration {
dst.copy_from_slice(&src);
checksum = checksum.wrapping_add(dst[iterations as usize % buffer_size]);
iterations += 1;
}
let _ = std::hint::black_box(checksum);
let duration_secs = start.elapsed().as_secs_f64();
let total_bytes = iterations * buffer_size as u64 * 2; let bandwidth_gbps = if duration_secs > 0.0 {
(total_bytes as f64 / duration_secs) / 1_000_000_000.0
} else {
0.0
};
MemoryBandwidthResult {
duration_secs,
total_bytes_copied: total_bytes,
iterations,
bandwidth_gbytes_per_sec: bandwidth_gbps,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryBandwidthResult {
pub duration_secs: f64,
pub total_bytes_copied: u64,
pub iterations: u64,
pub bandwidth_gbytes_per_sec: f64,
}
pub fn quick_bandwidth_estimate() -> Option<f64> {
let servers = [
("8.8.8.8", 53), ("1.1.1.1", 53), ("208.67.222.222", 53), ];
let config = BandwidthConfig::default().with_duration(Duration::from_secs(2));
for (host, port) in &servers {
if let Ok(result) = bandwidth_test(host, *port, &config) {
if result.success && result.bandwidth_mbps > 0.0 {
return Some(result.bandwidth_mbps);
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_loopback() {
let result = loopback_test(Duration::from_secs(1));
assert!(result.is_ok());
let result = result.unwrap();
assert!(result.bandwidth_mbps > 0.0);
println!("Loopback bandwidth: {:.2} Mbps", result.bandwidth_mbps);
}
#[test]
fn test_memory_bandwidth() {
let result = memory_bandwidth_test(Duration::from_secs(1));
assert!(result.bandwidth_gbytes_per_sec > 0.0);
println!(
"Memory bandwidth: {:.2} GB/s",
result.bandwidth_gbytes_per_sec
);
}
}