use std::future::{Future, IntoFuture, poll_fn};
use std::io;
use std::pin::pin;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use http::header::CONNECTION;
use http::{HeaderValue, Method, Request, Response, StatusCode, Version};
use http_body::Body as HttpBody;
use hyper::body::Incoming;
use hyper::service::service_fn;
use hyper_util::rt::{TokioIo, TokioTimer};
use hyper_util::server::conn::auto::Builder;
use navree_kernel::{BoxError, BoxFuture};
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use tower::{Service, ServiceExt as _};
use crate::body::{Body, DEFAULT_BODY_LIMIT};
use crate::extract::rejection::ExtensionRejection;
use crate::extract::{FromRequestParts, ProxyTrust};
use crate::network::DEFAULT_IPV6_PREFIX;
use crate::{HttpOptions, ServerOptions};
mod body;
mod clock;
mod frames;
mod gate;
mod listener;
mod streams;
mod unread;
pub use body::{BodyReadLimit, BodyReadTimeout};
pub use listener::{Listener, poll_tcp_sent};
pub(crate) use unread::UnreadLimit;
use body::{Pace, PacedBody, ResponseBody};
use clock::{Clock, InFlight, Timer, Watched};
use gate::{Gate, Slot};
use streams::{Progress, Streams};
use unread::{Drain, Kept, Unread, waits_to_continue};
pub(crate) const MIN_HEADER_BYTES: usize = 8 * 1024;
const HYPER_STACK_HEADERS: usize = 100;
const LONGEST_LIMIT: Duration = Duration::from_secs(365 * 24 * 60 * 60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConnectInfo<T>(pub T);
impl<T: Clone + Send + Sync + 'static> FromRequestParts for ConnectInfo<T> {
type Rejection = ExtensionRejection;
async fn from_request_parts(parts: &mut http::request::Parts) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<Self>()
.cloned()
.ok_or(ExtensionRejection(std::any::type_name::<Self>()))
}
}
pub fn serve<L, S, B>(listener: L, service: S) -> Serve<L, S>
where
L: Listener,
S: Service<Request<Body>, Response = Response<B>> + Clone + Send + 'static,
{
Serve {
listener,
service,
options: ServerOptions::default(),
grace: Duration::from_secs(HttpOptions::default().shutdown_grace_secs),
proxies: ProxyTrust::none(),
ipv6_prefix: DEFAULT_IPV6_PREFIX,
body_limit: DEFAULT_BODY_LIMIT,
signal: None,
}
}
#[must_use = "a server does nothing until it is awaited"]
pub struct Serve<L, S> {
listener: L,
service: S,
options: ServerOptions,
grace: Duration,
proxies: ProxyTrust,
ipv6_prefix: u8,
body_limit: usize,
signal: Option<BoxFuture<'static, ()>>,
}
impl<L, S> Serve<L, S> {
pub fn options(mut self, options: &HttpOptions) -> Self {
self.options = options.server.clone();
self.grace = Duration::from_secs(options.shutdown_grace_secs);
self.proxies = ProxyTrust::new(options.trust_proxy, &options.trusted_proxies);
self.ipv6_prefix = options.rate_limit_ipv6_prefix;
self.body_limit = options.body_limit_bytes;
self
}
pub fn with_graceful_shutdown<F>(mut self, signal: F) -> Self
where
F: Future<Output = ()> + Send + 'static,
{
self.signal = Some(Box::pin(signal));
self
}
}
impl<L, S> std::fmt::Debug for Serve<L, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Serve")
.field("options", &self.options)
.field("grace", &self.grace)
.finish_non_exhaustive()
}
}
impl<L, S, B> IntoFuture for Serve<L, S>
where
L: Listener,
S: Service<Request<Body>, Response = Response<B>> + Clone + Send + 'static,
S::Future: Send + 'static,
S::Error: Into<BoxError>,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
type Output = io::Result<()>;
type IntoFuture = BoxFuture<'static, io::Result<()>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.run())
}
}
impl<L, S, B> Serve<L, S>
where
L: Listener,
S: Service<Request<Body>, Response = Response<B>> + Clone + Send + 'static,
S::Future: Send + 'static,
S::Error: Into<BoxError>,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
async fn run(self) -> io::Result<()> {
let Self {
mut listener,
service,
options,
grace,
proxies,
ipv6_prefix,
body_limit,
signal,
} = self;
let mut gate = Gate::new(&options, proxies, ipv6_prefix);
let limits = Arc::new(Limits::new(options, body_limit));
let mut signal = signal.unwrap_or_else(|| Box::pin(std::future::pending()));
let stopping = CancellationToken::new();
let mut connections = JoinSet::new();
loop {
let (stream, remote, slot) = tokio::select! {
biased;
() = &mut signal => break,
next = gate.next(&mut listener) => next,
};
let clock = Arc::new(Clock::new(limits.header_read, limits.idle));
gate.track(&clock, &slot);
connections.spawn(connection(
listener.handshake(stream),
remote,
slot,
clock,
service.clone(),
limits.clone(),
stopping.clone(),
));
while connections.try_join_next().is_some() {}
}
drop(gate);
drop(listener);
stopping.cancel();
let drained = tokio::time::timeout(grace, async {
while connections.join_next().await.is_some() {}
});
if drained.await.is_err() {
tracing::warn!(target: "navree::http", ?grace, "in-flight requests did not finish within the grace period; closing them");
connections.shutdown().await;
}
Ok(())
}
}
#[derive(Debug)]
struct Limits {
server: ServerOptions,
header_read: Option<Duration>,
idle: Option<Duration>,
body: Option<Pace>,
write_stall: Option<Duration>,
upgraded_idle: Option<Duration>,
body_limit: usize,
}
impl Limits {
fn new(server: ServerOptions, body_limit: usize) -> Self {
Self {
header_read: server.header_read_timeout_ms.map(limit),
idle: server.idle_timeout_ms.map(limit),
body: server
.body_read_timeout_ms
.map(|timeout| Pace::new(limit(timeout), server.body_min_bytes_per_sec)),
write_stall: server.write_stall_timeout_ms.map(limit),
upgraded_idle: server.upgraded_idle_timeout_ms.map(limit),
body_limit,
server,
}
}
}
fn limit(ms: u64) -> Duration {
Duration::from_millis(ms).min(LONGEST_LIMIT)
}
fn builder(options: &ServerOptions, executor: Streams) -> Builder<Streams> {
let mut builder = Builder::new(executor);
let header_bytes = options.max_header_bytes.max(MIN_HEADER_BYTES);
{
let mut http1 = builder.http1();
http1
.timer(TokioTimer::new())
.header_read_timeout(None)
.max_buf_size(header_bytes);
if options.max_headers != HYPER_STACK_HEADERS {
http1.max_headers(options.max_headers);
}
}
builder
.http2()
.timer(TokioTimer::new())
.keep_alive_interval(options.http2_keep_alive_interval_ms.map(limit))
.keep_alive_timeout(limit(options.http2_keep_alive_timeout_ms))
.max_concurrent_streams(options.http2_max_concurrent_streams)
.max_header_list_size(u32::try_from(header_bytes).unwrap_or(u32::MAX))
.enable_connect_protocol();
builder
}
async fn connection<H, I, A, S, B>(
handshake: H,
remote: A,
slot: Slot,
clock: Arc<Clock>,
service: S,
limits: Arc<Limits>,
stopping: CancellationToken,
) where
H: Future<Output = io::Result<I>> + Send,
I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
A: Clone + std::fmt::Debug + Send + Sync + 'static,
S: Service<Request<Body>, Response = Response<B>> + Clone + Send + 'static,
S::Future: Send + 'static,
S::Error: Into<BoxError>,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
let io = tokio::select! {
biased;
() = stopping.cancelled() => return,
io = within(limits.header_read, handshake) => io,
};
let io = match io {
Ok(io) => io,
Err(error) => {
tracing::debug!(target: "navree::http", peer = ?remote, %error, "handshake failed");
return;
}
};
clock.handshaken();
let unread = Arc::new(Unread::new(clock.clone(), limits.body_limit));
let mut drain = Drain::new(unread.clone());
let hyper_service = {
let clock = clock.clone();
let remote = remote.clone();
let pace = limits.body;
let max_headers = limits.server.max_headers;
service_fn(move |request: Request<Incoming>| {
let bodiless = HttpBody::is_end_stream(request.body());
let in_flight = clock.request(request.version(), bodiless);
let progress = (request.version() == Version::HTTP_2).then(Progress::announce);
let upgrades = request.method() == Method::CONNECT;
let refused = progress.is_some() && request.headers().len() > max_headers;
let unread = progress.is_none().then(|| {
unread.next_request();
unread.clone()
});
let served = (!refused).then(|| {
let request = prepare(request, &remote, pace, unread.as_ref());
service.clone().oneshot(request)
});
async move {
let Some(served) = served else {
let mut response = Response::new(None);
*response.status_mut() = StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE;
return Ok(finishing(response, in_flight, progress));
};
let mut response = served.await?;
if unread.is_some_and(|unread| unread.closes()) {
response
.headers_mut()
.insert(CONNECTION, HeaderValue::from_static("close"));
}
if upgraded(upgrades, response.status()) {
in_flight.upgraded();
}
Ok::<_, S::Error>(finishing(response.map(Some), in_flight, progress))
}
})
};
let io = TokioIo::new(Watched::new(
io,
clock.clone(),
slot,
limits.write_stall,
limits.upgraded_idle,
));
let builder = builder(
&limits.server,
Streams::new(clock.clone(), limits.write_stall),
);
let mut conn = pin!(builder.serve_connection_with_upgrades(io, hyper_service));
let mut timer: Timer = None;
let mut closing = false;
loop {
tokio::select! {
biased;
result = conn.as_mut() => {
if let Err(error) = result {
tracing::debug!(target: "navree::http", peer = ?remote, %error, "connection closed with an error");
}
return;
}
() = stopping.cancelled(), if !closing => {
closing = true;
drain.give_up();
conn.as_mut().graceful_shutdown();
clock.close_soon();
}
() = poll_fn(|cx| clock.poll_expired(&mut timer, cx)) => {
if closing || !clock.says_goodbye() {
tracing::debug!(target: "navree::http", peer = ?remote, "connection timed out");
return;
}
closing = true;
conn.as_mut().graceful_shutdown();
clock.say_goodbye();
}
() = poll_fn(|cx| drain.poll(cx)) => {}
}
}
}
async fn within<T>(
limit: Option<Duration>,
future: impl Future<Output = io::Result<T>>,
) -> io::Result<T> {
match limit {
Some(limit) => tokio::time::timeout(limit, future)
.await
.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())),
None => future.await,
}
}
fn prepare<A>(
request: Request<Incoming>,
remote: &A,
pace: Option<Pace>,
unread: Option<&Arc<Unread<Body>>>,
) -> Request<Body>
where
A: Clone + Send + Sync + 'static,
{
let (mut parts, incoming) = request.into_parts();
parts.extensions.insert(ConnectInfo(remote.clone()));
if HttpBody::is_end_stream(&incoming) {
return Request::from_parts(parts, Body::new(incoming));
}
let body = match pace {
Some(pace) => {
let limit = BodyReadLimit::default();
parts.extensions.insert(limit.clone());
Body::new(PacedBody::new(incoming, pace, limit))
}
None => Body::new(incoming),
};
let body = match unread {
Some(unread) => {
let limit = unread.limit();
parts.extensions.insert(limit.clone());
let waits = waits_to_continue(&parts);
Body::new(Kept::new(body, unread.clone(), limit, waits))
}
None => body,
};
Request::from_parts(parts, body)
}
fn upgraded(connect: bool, status: StatusCode) -> bool {
status == StatusCode::SWITCHING_PROTOCOLS || (connect && status.is_success())
}
fn finishing<B>(
response: Response<Option<B>>,
in_flight: InFlight,
progress: Option<Arc<Progress>>,
) -> Response<ResponseBody<B>> {
response.map(|body| ResponseBody::new(body, in_flight, progress))
}