Skip to main content

ntex/http/
service.rs

1use crate::error::{Error, IntoFailure};
2use crate::io::{Filter, Io, types};
3use crate::service::{IntoServiceFactory, RequestState, pipeline::PipelineFactory};
4use crate::{Ctx, Service, ServiceFactory};
5
6use super::error::{DispatchError, H2Error, ResponseError};
7use super::{Request, Response, config::DispatcherConfig, h1, h2};
8
9/// An HTTP/1.1 and HTTP/2 transport service.
10///
11/// The protocol is selected from
12/// [`HttpProtocol`](crate::http::HttpProtocol) metadata attached to the I/O
13/// stream, normally by a TLS ALPN acceptor. Connections without HTTP/2
14/// metadata are handled as HTTP/1.
15///
16/// # Factory scope
17///
18/// The application and control service factories are instantiated once per
19/// accepted connection: [`ServiceFactory::create`] runs for every connection
20/// and the resulting services are dropped when it closes. Do not perform
21/// expensive initialization or keep state that must outlive a connection in
22/// these factories. Build such state once per worker instead, for example in
23/// the server factory closure that constructs this `HttpService` (or the
24/// `web::HttpServer` application closure), or in the worker state passed to
25/// `create`, and share it by cloning an `Rc` or `Arc` into the factory.
26#[derive(derive_more::Debug)]
27#[debug("HttpService")]
28pub struct HttpService<F, Req: RequestState<Io<F>>, Err> {
29    sf: super::HttpPipeline<Req::State, Err>,
30    /// Without a control service the default action is applied to every event.
31    h1_ctl: Option<super::Ctl1Pipeline<Req::State, F, Err>>,
32    h2_ctl: Option<super::Ctl2Pipeline<Req::State>>,
33    config: DispatcherConfig,
34}
35
36impl<F, Req, Err> HttpService<F, Req, Err>
37where
38    F: Filter + 'static,
39    Req: RequestState<Io<F>>,
40    Req::State: Clone,
41    Err: ResponseError + 'static,
42{
43    #[must_use]
44    /// Creates a service that supports HTTP/1.1 and HTTP/2.
45    ///
46    /// `sf` is instantiated for every accepted connection; see
47    /// [factory scope](Self#factory-scope).
48    pub fn new<H>(sf: impl IntoServiceFactory<H, Req::State, Request>) -> Self
49    where
50        H: ServiceFactory<Req::State, Request, Error = Err> + 'static,
51        H::Res: Into<Response>,
52        H::InitError: IntoFailure,
53    {
54        HttpService {
55            sf: PipelineFactory::new(
56                sf.into_factory()
57                    .map(Into::into)
58                    .map_init_err(|e| DispatchError::Control(e.fail())),
59            ),
60            h1_ctl: None,
61            h2_ctl: None,
62            config: DispatcherConfig::default(),
63        }
64    }
65
66    #[must_use]
67    /// Creates an HTTP/1-only service.
68    ///
69    /// `sf` is instantiated for every accepted connection; see
70    /// [factory scope](Self#factory-scope).
71    pub fn h1<H>(sf: impl IntoServiceFactory<H, Req::State, Request>) -> h1::H1Service<F, Req, Err>
72    where
73        H: ServiceFactory<Req::State, Request, Error = Err> + 'static,
74        H::Res: Into<Response>,
75        H::InitError: IntoFailure,
76    {
77        h1::H1Service::new(sf)
78    }
79
80    #[must_use]
81    /// Creates an HTTP/2-only service.
82    ///
83    /// `sf` is instantiated for every accepted connection; see
84    /// [factory scope](Self#factory-scope).
85    pub fn h2<H>(sf: impl IntoServiceFactory<H, Req::State, Request>) -> h2::H2Service<F, Req, Err>
86    where
87        H: ServiceFactory<Req::State, Request, Error = Err> + 'static,
88        H::Res: Into<Response>,
89        H::InitError: IntoFailure,
90    {
91        h2::H2Service::new(sf)
92    }
93}
94
95impl<F, Req, Err> HttpService<F, Req, Err>
96where
97    F: Filter,
98    Req: RequestState<Io<F>>,
99    Err: ResponseError + 'static,
100{
101    #[must_use]
102    /// Provides the HTTP/1 control service.
103    ///
104    /// The service receives the lifecycle events described by
105    /// [`h1::Control`]. Unless this method is called, the default action is
106    /// applied to each event without a service call. Like the application
107    /// factory, `ctl` is instantiated for every HTTP/1 connection.
108    pub fn h1_control<Ctl>(
109        self,
110        ctl: impl IntoServiceFactory<Ctl, Req::State, h1::Control<F, Err>>,
111    ) -> Self
112    where
113        Ctl: ServiceFactory<Req::State, h1::Control<F, Err>, Res = h1::ControlAck<F>> + 'static,
114        Ctl::Error: IntoFailure,
115        Ctl::InitError: IntoFailure,
116    {
117        HttpService {
118            sf: self.sf,
119            h1_ctl: Some(PipelineFactory::new(
120                ctl.into_factory()
121                    .map_err(|e| DispatchError::Service(e.fail()))
122                    .map_init_err(|e| DispatchError::Control(e.fail())),
123            )),
124            h2_ctl: self.h2_ctl,
125            config: self.config,
126        }
127    }
128
129    #[must_use]
130    /// Provides the HTTP/2 control service.
131    ///
132    /// Unless this method is called, the default action is applied to each
133    /// HTTP/2 control event without a service call. Like the application
134    /// factory, `ctl` is instantiated for every HTTP/2 connection.
135    pub fn h2_control<Ctl>(
136        self,
137        ctl: impl IntoServiceFactory<Ctl, Req::State, h2::Control<Error<H2Error>>>,
138    ) -> Self
139    where
140        Ctl:
141            ServiceFactory<Req::State, h2::Control<Error<H2Error>>, Res = h2::ControlAck> + 'static,
142        Ctl::Error: IntoFailure,
143        Ctl::InitError: IntoFailure,
144    {
145        HttpService {
146            sf: self.sf,
147            h1_ctl: self.h1_ctl,
148            h2_ctl: Some(PipelineFactory::new(
149                ctl.into_factory()
150                    .map_err(|e| DispatchError::Service(e.fail()))
151                    .map_init_err(|e| DispatchError::Control(e.fail())),
152            )),
153            config: self.config,
154        }
155    }
156}
157
158impl<St, F, Req, Err> Service<St, Req> for HttpService<F, Req, Err>
159where
160    F: Filter + 'static,
161    Req: RequestState<Io<F>>,
162    Req::State: Clone,
163    Err: ResponseError + 'static,
164{
165    type Res = ();
166    type Error = DispatchError;
167
168    async fn call(&self, req: Req, _: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
169        let (st, io) = req.unpack();
170
171        let svc = self.sf.create(st.clone()).await?;
172
173        let id = self.config.next_id();
174        let ioref = io.get_ref();
175        let (_guard, inflight) = self.config.insert_io(&ioref);
176
177        if io.query::<types::HttpProtocol>().get() == Some(types::HttpProtocol::Http2) {
178            log::trace!(
179                "{}: New http2 connection {id}, peer address {:?}, in-flight: {inflight}",
180                io.tag(),
181                io.query::<types::PeerAddr>().get(),
182            );
183            let ctl = match &self.h2_ctl {
184                Some(ctl) => Some(ctl.create(st).await?),
185                None => None,
186            };
187
188            h2::handle(id, io.into(), svc, ctl).await
189        } else {
190            log::trace!(
191                "{}: New http1 connection {id}, peer address {:?}, in-flight: {inflight}",
192                io.tag(),
193                io.query::<types::PeerAddr>().get(),
194            );
195            let ctl = match &self.h1_ctl {
196                Some(ctl) => Some(ctl.create(st).await?),
197                None => None,
198            };
199
200            h1::handle_io(id, io, svc, ctl, self.config.clone()).await
201        }
202    }
203
204    async fn ready(&self, _: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
205        Ok(())
206    }
207
208    async fn shutdown(&self, _: crate::Ctx<'_, Self, St>) {
209        // check inflight connections
210        let inflight = self.config.shutdown();
211        if inflight != 0 {
212            log::trace!("Shutting down service, in-flight connections: {inflight}");
213
214            self.config.wait_shutdown().await;
215            log::trace!("Shutting down is complected");
216        }
217    }
218}