Skip to main content

nitr_http/
service.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6use 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
26/// Service that handles incoming requests by checking a Lua runtime out of
27/// the pool for the duration of each request.
28pub struct Svc {
29    /// The swappable pool handle: read per request so reloads apply to
30    /// live keep-alive connections too.
31    pool: Arc<std::sync::RwLock<Arc<RuntimePool>>>,
32    /// Streaming-response slots (`max_streams`); a permit is held for each
33    /// live streaming body.
34    streams: Arc<Semaphore>,
35    /// Pre-Lua protection (rate limiting, size limits) and request ids.
36    protection: Arc<Protection>,
37    /// Health endpoints served on this (main) listener; `None` when they
38    /// are disabled or bound to their own address.
39    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        // Probes answer before anything request-shaped happens: no rate
71        // limiting, no pool checkout, no Lua. A liveness check that could
72        // queue behind a saturated pool would cause the restart it is
73        // meant to prevent.
74        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        // The per-request span: every tracing event below it (including
84        // Lua `log.*` calls) carries the request id, method, and path;
85        // `status` is recorded when the response is built, so the span's
86        // close line doubles as an access log.
87        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}