use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::Semaphore;
use http_body_util::combinators::BoxBody;
use hyper::body::{Bytes, Incoming};
use hyper::service::Service;
use hyper::{Request, Response};
use crate::handler;
use crate::protect::Protection;
use crate::request::LuaRequest;
use nitr_core::Error;
use nitr_core::Result;
use nitr_core::RuntimePool;
use tracing::Instrument as _;
pub struct Svc {
pool: Arc<std::sync::RwLock<Arc<RuntimePool>>>,
streams: Arc<Semaphore>,
protection: Arc<Protection>,
health: Option<Arc<crate::health::HealthState>>,
peer_addr: SocketAddr,
tls: bool,
}
impl Svc {
pub(crate) fn new(
pool: Arc<std::sync::RwLock<Arc<RuntimePool>>>,
streams: Arc<Semaphore>,
protection: Arc<Protection>,
health: Option<Arc<crate::health::HealthState>>,
peer_addr: SocketAddr,
tls: bool,
) -> Self {
Self {
pool,
streams,
protection,
health,
peer_addr,
tls,
}
}
}
impl Service<Request<Incoming>> for Svc {
type Response = Response<BoxBody<Bytes, Infallible>>;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&self, req: Request<Incoming>) -> Self::Future {
if let Some(health) = &self.health
&& let Some(resp) = health.answer(req.method(), req.uri().path())
{
return Box::pin(async move { Ok(resp) });
}
let pool = crate::server::current_pool(&self.pool);
let streams = self.streams.clone();
let protection = self.protection.clone();
let id = protection.request_id(&req);
let span = tracing::info_span!(
"request",
id = %id,
method = %req.method(),
path = %req.uri().path(),
status = tracing::field::Empty,
);
let mut req = LuaRequest::synthetic(
req.map(|body| {
use http_body_util::BodyExt as _;
body.map_err(|err| Box::new(err) as _).boxed()
}),
self.peer_addr,
id.into(),
);
req.tls = self.tls;
Box::pin(
async move { handler::handle(&pool, req, streams, protection).await }.instrument(span),
)
}
}