1use std::convert::Infallible;
7use std::future::Future;
8use std::net::SocketAddr;
9use std::pin::Pin;
10use std::sync::Arc;
11use tokio::sync::Semaphore;
12
13use http_body_util::combinators::BoxBody;
14use hyper::body::{Bytes, Incoming};
15use hyper::service::Service;
16use hyper::{Request, Response};
17
18use crate::handler;
19use crate::protect::Protection;
20use crate::request::LuaRequest;
21use nitr_core::Error;
22use nitr_core::Result;
23use nitr_core::RuntimePool;
24use tracing::Instrument as _;
25
26pub struct Svc {
29 pool: Arc<std::sync::RwLock<Arc<RuntimePool>>>,
32 streams: Arc<Semaphore>,
35 protection: Arc<Protection>,
37 health: Option<Arc<crate::health::HealthState>>,
40 peer_addr: SocketAddr,
41 tls: bool,
42}
43
44impl Svc {
45 pub(crate) fn new(
46 pool: Arc<std::sync::RwLock<Arc<RuntimePool>>>,
47 streams: Arc<Semaphore>,
48 protection: Arc<Protection>,
49 health: Option<Arc<crate::health::HealthState>>,
50 peer_addr: SocketAddr,
51 tls: bool,
52 ) -> Self {
53 Self {
54 pool,
55 streams,
56 protection,
57 health,
58 peer_addr,
59 tls,
60 }
61 }
62}
63
64impl Service<Request<Incoming>> for Svc {
65 type Response = Response<BoxBody<Bytes, Infallible>>;
66 type Error = Error;
67 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
68
69 fn call(&self, req: Request<Incoming>) -> Self::Future {
70 if let Some(health) = &self.health
75 && let Some(resp) = health.answer(req.method(), req.uri().path())
76 {
77 return Box::pin(async move { Ok(resp) });
78 }
79 let pool = crate::server::current_pool(&self.pool);
80 let streams = self.streams.clone();
81 let protection = self.protection.clone();
82 let id = protection.request_id(&req);
83 let span = tracing::info_span!(
88 "request",
89 id = %id,
90 method = %req.method(),
91 path = %req.uri().path(),
92 status = tracing::field::Empty,
93 );
94 let mut req = LuaRequest::synthetic(
95 req.map(|body| {
96 use http_body_util::BodyExt as _;
97 body.map_err(|err| Box::new(err) as _).boxed()
98 }),
99 self.peer_addr,
100 id.into(),
101 );
102 req.tls = self.tls;
103
104 Box::pin(
105 async move { handler::handle(&pool, req, streams, protection).await }.instrument(span),
106 )
107 }
108}