use std::{
io::{Read, Write},
net::{SocketAddr, TcpStream},
time::{Duration, Instant},
};
use indicatrix_vault::db::sqlite::Database;
use crate::cli::ServeArgs;
pub struct DeadlineIo<'a, S> {
inner: &'a mut S,
deadline: Instant,
}
impl<'a, S> DeadlineIo<'a, S> {
pub(crate) const fn new(inner: &'a mut S, deadline: Instant) -> Self {
Self { inner, deadline }
}
fn check_deadline(&self) -> std::io::Result<()> {
if Instant::now() >= self.deadline {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"pre-HELLO handshake deadline exceeded",
));
}
Ok(())
}
}
impl<S: Read> Read for DeadlineIo<'_, S> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.check_deadline()?;
self.inner.read(buf)
}
}
impl<S: Write> Write for DeadlineIo<'_, S> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.inner.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
pub struct DeadlineSocket<'a> {
sock: &'a TcpStream,
deadline: Instant,
}
impl<'a> DeadlineSocket<'a> {
pub(crate) const fn new(sock: &'a TcpStream, deadline: Instant) -> Self {
Self { sock, deadline }
}
fn rearm(&self) -> std::io::Result<()> {
let remaining = self.deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"pre-HELLO handshake deadline exceeded",
));
}
self.sock.set_read_timeout(Some(remaining))
}
}
impl Read for DeadlineSocket<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.rearm()?;
let mut sock = self.sock;
sock.read(buf)
}
}
impl Write for DeadlineSocket<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut sock = self.sock;
sock.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
let mut sock = self.sock;
sock.flush()
}
}
pub(super) fn open_library_database(path: &std::path::Path) -> Result<Database, String> {
let path_str = path
.to_str()
.ok_or_else(|| format!("--db {}: path is not valid Unicode", path.display()))?;
Database::open_read_only(path_str).map_err(|e| {
format!(
"failed to open the design-library database read-only at {}: {e:#}",
path.display()
)
})
}
#[must_use]
pub(super) fn resolve_library_db_path(args: &ServeArgs) -> std::path::PathBuf {
args.db
.clone()
.unwrap_or_else(|| std::path::PathBuf::from(indicatrix_vault::db::sqlite::DEFAULT_DB_FILE))
}
const TCP_KEEPALIVE_IDLE: Duration = Duration::from_secs(30);
const TCP_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(10);
pub fn tune_accepted_socket(stream: &TcpStream, peer: Option<SocketAddr>) {
if let Err(e) = stream.set_nodelay(true) {
tracing::debug!("connection {peer:?}: failed to set TCP_NODELAY: {e}");
}
let sock_ref = socket2::SockRef::from(stream);
let keepalive = socket2::TcpKeepalive::new()
.with_time(TCP_KEEPALIVE_IDLE)
.with_interval(TCP_KEEPALIVE_INTERVAL);
if let Err(e) = sock_ref.set_tcp_keepalive(&keepalive) {
tracing::debug!("connection {peer:?}: failed to set TCP keepalive: {e}");
}
}
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(20);
pub fn apply_handshake_timeout(stream: &TcpStream, peer: Option<SocketAddr>) {
if let Err(e) = stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT)) {
tracing::debug!("connection {peer:?}: failed to set handshake read timeout: {e}");
}
if let Err(e) = stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT)) {
tracing::debug!("connection {peer:?}: failed to set handshake write timeout: {e}");
}
}
#[cfg(feature = "worker")]
pub fn payload_preference_for_choice(
choice: indicatrix_net::messages::adaptive::PayloadChoice,
peer: Option<SocketAddr>,
) -> Vec<indicatrix_net::messages::PayloadEncoding> {
match choice {
indicatrix_net::messages::adaptive::PayloadChoice::Fixed(encoding) => vec![encoding],
indicatrix_net::messages::adaptive::PayloadChoice::Auto => {
payload_preference_for(peer).to_vec()
}
}
}
#[cfg(feature = "worker")]
pub fn payload_preference_for(
peer: Option<SocketAddr>,
) -> &'static [indicatrix_net::messages::PayloadEncoding] {
if peer.is_some_and(|p| p.ip().is_loopback()) {
&indicatrix_net::messages::LOOPBACK_SERVER_PREFERENCE
} else {
&indicatrix_net::messages::DEFAULT_SERVER_PREFERENCE
}
}
#[cfg(test)]
mod tests {
use super::DeadlineIo;
use std::{
io::Read,
time::{Duration, Instant},
};
struct Trickle {
gap: Duration,
}
impl Read for Trickle {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
std::thread::sleep(self.gap);
buf[0] = 0;
Ok(1)
}
}
#[test]
fn deadline_io_drops_a_trickling_peer_once_the_total_budget_elapses() {
let mut trickle = Trickle {
gap: Duration::from_millis(100),
};
let deadline = Instant::now() + Duration::from_millis(300);
let mut guarded = DeadlineIo::new(&mut trickle, deadline);
let start = Instant::now();
let mut buf = [0u8; 16];
let err = guarded.read_exact(&mut buf).expect_err(
"a 16-byte read at one byte/100ms must never complete inside a 300ms budget",
);
let elapsed = start.elapsed();
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{err}");
assert!(
elapsed >= Duration::from_millis(250) && elapsed < Duration::from_millis(700),
"expected to be dropped at ~300ms, was dropped at {elapsed:?}"
);
}
#[test]
fn deadline_io_refuses_immediately_once_the_deadline_has_already_passed() {
let mut trickle = Trickle {
gap: Duration::from_millis(100),
};
let deadline = Instant::now()
.checked_sub(Duration::from_millis(1))
.expect("the process has been running for at least 1ms");
let mut guarded = DeadlineIo::new(&mut trickle, deadline);
let start = Instant::now();
let mut buf = [0u8; 1];
let err = guarded.read_exact(&mut buf).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{err}");
assert!(
start.elapsed() < Duration::from_millis(50),
"must fail without ever calling the inner reader"
);
}
}