use super::accept_backoff::AcceptBackoff;
use super::conn_protocol::handle_conn;
use crate::rpc::RpcContext;
use core::time::Duration;
use shep_core::transport::Listener;
use tokio::sync::watch;
pub const CONN_QUEUE: usize = 64;
pub const HANDSHAKE_TIMEOUT_MS: u64 = 5_000;
#[derive(Debug)]
pub struct RpcServer {
listener: Listener,
ctx: RpcContext,
}
impl RpcServer {
#[must_use]
pub fn new(listener: Listener, ctx: RpcContext) -> Self {
Self { listener, ctx }
}
pub async fn serve(self, mut shutdown: watch::Receiver<bool>) {
let Self { mut listener, ctx } = self;
let mut backoff = AcceptBackoff::new();
if *shutdown.borrow() {
return;
}
loop {
tokio::select! {
accepted = listener.accept() => {
match accepted {
Ok(stream) => {
backoff.on_success();
let ctx = ctx.clone();
tokio::spawn(async move {
if let Err(err) = handle_conn(stream, ctx).await {
tracing::debug!(%err, "connection ended");
}
});
}
Err(err) => {
let wait = backoff.on_error(&err);
tracing::warn!(
%err,
retry_in_ms = wait.map_or(0, |d| d.as_millis() as u64),
"accept failed; continuing"
);
if wait_out_backoff(wait, &mut shutdown).await {
break;
}
}
}
}
changed = shutdown.changed() => {
if changed.is_err() || *shutdown.borrow() {
break;
}
}
}
}
}
}
async fn wait_out_backoff(delay: Option<Duration>, shutdown: &mut watch::Receiver<bool>) -> bool {
let Some(delay) = delay else {
return false;
};
tokio::select! {
() = tokio::time::sleep(delay) => false,
changed = shutdown.changed() => changed.is_err() || *shutdown.borrow(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn a_shutdown_during_a_backoff_wait_stops_the_loop() {
let (tx, mut rx) = watch::channel(false);
let flip = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(10)).await;
tx.send(true).expect("the receiver is alive");
});
let stopped = tokio::time::timeout(
Duration::from_millis(100),
wait_out_backoff(Some(Duration::from_secs(30)), &mut rx),
)
.await
.expect("the shutdown must end the wait, not the 30 s delay elapsing");
assert!(stopped, "a stop signal mid-backoff must end the wait");
flip.await.expect("the flip task must finish");
}
#[tokio::test(start_paused = true)]
async fn a_backoff_wait_ends_on_its_own_clock() {
let (_tx, mut rx) = watch::channel(false);
let stopped = tokio::time::timeout(
Duration::from_secs(1),
wait_out_backoff(Some(Duration::from_millis(5)), &mut rx),
)
.await
.expect("a 5 ms wait must elapse with no signal");
assert!(!stopped, "a wait that elapsed is not a shutdown");
}
#[tokio::test(start_paused = true)]
async fn no_wait_means_no_wait() {
let (_tx, mut rx) = watch::channel(false);
let stopped =
tokio::time::timeout(Duration::from_millis(100), wait_out_backoff(None, &mut rx))
.await
.expect("an at-once verdict must return without touching the clock");
assert!(!stopped, "an at-once verdict must not read as a shutdown");
}
}