1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
use std::{
io::Write,
net::{SocketAddr, TcpStream},
time::{Duration, Instant},
};
#[derive(thiserror::Error, Debug)]
pub enum ClientError {
#[error("Failed to connect to Rerun server at {addr:?}: {err}")]
Connect {
addr: SocketAddr,
err: std::io::Error,
},
#[error("Failed to send to Rerun server at {addr:?}: {err}")]
Send {
addr: SocketAddr,
err: std::io::Error,
},
}
/// State of the [`TcpStream`]
///
/// Because the [`TcpClient`] lazily connects on [`TcpClient::send`], it needs a
/// very simple state machine to track the state of the connection.
/// [`TcpStreamState::Pending`] is the nominal state for any new TCP connection
/// when we successfully connect, we transition to [`TcpStreamState::Connected`].
enum TcpStreamState {
/// The [`TcpStream`] is yet to be connected.
///
/// Tracks the duration and connection attempts since the last time the client
/// was `Connected.`
///
/// Behavior: Try to connect on next [`TcpClient::connect`] or [`TcpClient::send`].
///
/// Transitions:
/// - Pending -> Connected on successful connection.
/// - Pending -> Pending on failed connection.
Pending {
start_time: Instant,
num_attempts: usize,
},
/// A healthy [`TcpStream`] ready to send packets
///
/// Behavior: Send packets on [`TcpClient::send`]
///
/// Transitions:
/// - Connected -> Pending on send error
Connected(TcpStream),
}
impl TcpStreamState {
fn reset() -> Self {
Self::Pending {
start_time: Instant::now(),
num_attempts: 0,
}
}
}
/// Connect to a rerun server and send log messages.
///
/// Blocking connection.
pub struct TcpClient {
addr: SocketAddr,
stream_state: TcpStreamState,
flush_timeout: Option<Duration>,
}
impl TcpClient {
pub fn new(addr: SocketAddr, flush_timeout: Option<Duration>) -> Self {
Self {
addr,
stream_state: TcpStreamState::reset(),
flush_timeout,
}
}
/// Returns `false` on failure. Does nothing if already connected.
///
/// [`Self::send`] will call this.
pub fn connect(&mut self) -> Result<(), ClientError> {
match self.stream_state {
TcpStreamState::Connected(_) => Ok(()),
TcpStreamState::Pending {
start_time,
num_attempts,
} => {
re_log::debug!("Connecting to {:?}…", self.addr);
let timeout = std::time::Duration::from_secs(5);
match TcpStream::connect_timeout(&self.addr, timeout) {
Ok(mut stream) => {
re_log::debug!("Connected to {:?}.", self.addr);
if let Err(err) = stream
.write(&crate::PROTOCOL_VERSION_1.to_le_bytes())
.and_then(|_| stream.write(crate::PROTOCOL_HEADER.as_bytes()))
{
self.stream_state = TcpStreamState::Pending {
start_time,
num_attempts: num_attempts + 1,
};
Err(ClientError::Send {
addr: self.addr,
err,
})
} else {
self.stream_state = TcpStreamState::Connected(stream);
Ok(())
}
}
Err(err) => {
self.stream_state = TcpStreamState::Pending {
start_time,
num_attempts: num_attempts + 1,
};
Err(ClientError::Connect {
addr: self.addr,
err,
})
}
}
}
}
}
/// Blocks until it is sent.
pub fn send(&mut self, packet: &[u8]) -> Result<(), ClientError> {
use std::io::Write as _;
self.connect()?;
if let TcpStreamState::Connected(stream) = &mut self.stream_state {
re_log::trace!("Sending a packet of size {}…", packet.len());
if let Err(err) = stream.write(&(packet.len() as u32).to_le_bytes()) {
self.stream_state = TcpStreamState::reset();
return Err(ClientError::Send {
addr: self.addr,
err,
});
}
if let Err(err) = stream.write(packet) {
self.stream_state = TcpStreamState::reset();
return Err(ClientError::Send {
addr: self.addr,
err,
});
}
Ok(())
} else {
unreachable!("self.connect should have ensured this");
}
}
/// Wait until all logged data have been sent.
pub fn flush(&mut self) {
re_log::trace!("Attempting to flush TCP stream…");
match &mut self.stream_state {
TcpStreamState::Pending { .. } => {
re_log::warn_once!(
"Tried to flush while TCP stream was still Pending. Data was possibly dropped."
);
}
TcpStreamState::Connected(stream) => {
if let Err(err) = stream.flush() {
re_log::warn!("Failed to flush TCP stream: {err}");
self.stream_state = TcpStreamState::reset();
} else {
re_log::trace!("TCP stream flushed.");
}
}
}
}
/// Check if the underlying [`TcpStream`] is in the [`TcpStreamState::Pending`] state
/// and has reached the flush timeout threshold.
///
/// Note that this only occurs after a failure to connect or a failure to send.
pub fn has_timed_out_for_flush(&self) -> bool {
match self.stream_state {
TcpStreamState::Pending {
start_time,
num_attempts,
} => {
// If a timeout wasn't provided, never timeout
self.flush_timeout.map_or(false, |timeout| {
Instant::now().duration_since(start_time) > timeout && num_attempts > 0
})
}
TcpStreamState::Connected(_) => false,
}
}
}