Skip to main content

ntex_service/
boxed.rs

1//! Type-erased services and service factories.
2//!
3//! Use [`service()`] or [`BoxService::new`] to hide a service's concrete type
4//! while keeping its state, request, response, and error types explicit.
5//! This lets different implementations share a return type or collection.
6//! [`factory()`] and [`BoxServiceFactory`] do the same for factories; each
7//! created service is returned as a [`BoxService`].
8//!
9//! These wrappers use reference-counted, local handles. Cloning shares the
10//! underlying service or factory rather than cloning its implementation.
11//! Binding, readiness, calls, and shutdown are forwarded to the wrapped
12//! service. Type erasure preserves existing readiness caches but does not add
13//! one to a raw service; use [`crate::Pipeline`] or [`crate::ready()`] when a
14//! readiness cache is needed.
15//!
16//! The wrapped service's `ready`, `call`, and `shutdown` futures are stored in
17//! an [`InlineFuture`] slot of `WORDS` machine words. Futures that fit don't
18//! allocate, larger futures are boxed. The default `WORDS = 0` boxes every
19//! future larger than a pointer. Use [`BoxService::new_inline`] or
20//! [`BoxServiceFactory::new_inline`] to pick a larger slot.
21//!
22//! # Example
23//!
24//! ```
25//! use ntex_service::{boxed, fn_service};
26//!
27//! fn handler(double: bool) -> boxed::BoxService<(), u32, u32, ()> {
28//!     if double {
29//!         boxed::service(fn_service(async |req: u32| Ok::<_, ()>(req * 2)))
30//!     } else {
31//!         boxed::service(fn_service(async |req: u32| Ok::<_, ()>(req)))
32//!     }
33//! }
34//! ```
35//!
36//! # Framework guide
37//!
38//! - [Service Model](https://docs.ntex.rs/1-service.html)
39//! - [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
40
41use std::{fmt, rc::Rc};
42
43use crate::{BindCtx, Ctx, inline::InlineFuture};
44use crate::{Service, ServiceFactory, util::BoxFuture};
45
46// ============================ Service =============================
47
48/// Boxed service.
49///
50/// Type erasure preserves the wrapped service's readiness identity. Clones
51/// share that service and any bound readiness; boxing a raw service does not
52/// give it a cache.
53///
54/// The wrapped service's futures are stored inline when they fit into `WORDS`
55/// machine words and boxed otherwise, see [`InlineFuture`]. Boxed services
56/// with different `WORDS` are different types.
57pub struct BoxService<St, Req, Res, Err, const WORDS: usize = 0> {
58    inner: Rc<dyn ServiceObj<St, Req, WORDS, Res = Res, Error = Err>>,
59}
60
61/// Creates a boxed service.
62pub fn service<S, St, Req, Res, Err>(service: S) -> BoxService<St, Req, Res, Err>
63where
64    S: Service<St, Req, Res = Res, Error = Err> + 'static,
65{
66    BoxService::new(service)
67}
68
69impl<St, Req, Res, Err> BoxService<St, Req, Res, Err> {
70    /// Creates a boxed service with the default slot (`WORDS = 0`).
71    pub fn new<S>(service: S) -> Self
72    where
73        S: Service<St, Req, Res = Res, Error = Err> + 'static,
74    {
75        Self::new_inline(service)
76    }
77}
78
79impl<St, Req, Res, Err, const WORDS: usize> BoxService<St, Req, Res, Err, WORDS> {
80    /// Creates a boxed service that stores futures of up to `WORDS` machine
81    /// words inline.
82    ///
83    /// `WORDS` is usually inferred from the annotated type:
84    ///
85    /// ```
86    /// use ntex_service::{boxed::BoxService, fn_service};
87    ///
88    /// let svc: BoxService<(), u32, u32, (), 4> =
89    ///     BoxService::new_inline(fn_service(async |req: u32| Ok::<_, ()>(req)));
90    /// ```
91    pub fn new_inline<S>(service: S) -> Self
92    where
93        S: Service<St, Req, Res = Res, Error = Err> + 'static,
94    {
95        BoxService {
96            inner: Rc::new(service),
97        }
98    }
99}
100
101impl<St, Req, Res, Err, const WORDS: usize> Clone for BoxService<St, Req, Res, Err, WORDS> {
102    fn clone(&self) -> Self {
103        Self {
104            inner: self.inner.clone(),
105        }
106    }
107}
108
109impl<St, Req, Res, Err, const WORDS: usize> fmt::Debug for BoxService<St, Req, Res, Err, WORDS> {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        f.debug_struct("BoxService").finish()
112    }
113}
114
115impl<St, Req, Res, Err, const WORDS: usize> Service<St, Req>
116    for BoxService<St, Req, Res, Err, WORDS>
117{
118    type Res = Res;
119    type Error = Err;
120
121    fn bind(&self, ctx: BindCtx<'_>) {
122        self.inner.bind(ctx);
123    }
124
125    #[inline]
126    #[allow(clippy::manual_async_fn)]
127    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
128        // An `async fn` would store `ctx` twice. The block is still needed
129        // because the inner future borrows both `self` and `ctx` under one lifetime.
130        async move { self.inner.ready(ctx.cast()).await }
131    }
132
133    #[inline]
134    #[allow(clippy::manual_async_fn)]
135    fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<Res, Err>> {
136        // See `ready`.
137        async move { self.inner.call(req, ctx.cast()).await }
138    }
139
140    #[inline]
141    #[allow(clippy::manual_async_fn)]
142    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
143        // See `ready`.
144        async move { self.inner.shutdown(ctx.cast()).await }
145    }
146}
147
148trait ServiceObj<St, Req, const WORDS: usize> {
149    type Res;
150    type Error;
151
152    fn bind(&self, ctx: BindCtx<'_>);
153
154    fn ready<'a>(
155        &'a self,
156        ctx: Ctx<'a, (), St>,
157    ) -> InlineFuture<'a, Result<(), Self::Error>, WORDS>
158    where
159        Req: 'a;
160
161    fn call<'a>(
162        &'a self,
163        r: Req,
164        ctx: Ctx<'a, (), St>,
165    ) -> InlineFuture<'a, Result<Self::Res, Self::Error>, WORDS>
166    where
167        Req: 'a;
168
169    fn shutdown<'a>(&'a self, ctx: Ctx<'a, (), St>) -> InlineFuture<'a, (), WORDS>
170    where
171        St: 'a,
172        Req: 'a;
173}
174
175impl<S, St, Req, const WORDS: usize> ServiceObj<St, Req, WORDS> for S
176where
177    S: Service<St, Req>,
178{
179    type Res = S::Res;
180    type Error = S::Error;
181
182    fn bind(&self, ctx: BindCtx<'_>) {
183        Service::bind(self, ctx);
184    }
185
186    #[inline]
187    fn ready<'a>(&'a self, ctx: Ctx<'a, (), St>) -> InlineFuture<'a, Result<(), Self::Error>, WORDS>
188    where
189        Req: 'a,
190    {
191        InlineFuture::new_with(|| Service::ready(self, ctx.cast()))
192    }
193
194    #[inline]
195    fn call<'a>(
196        &'a self,
197        req: Req,
198        ctx: Ctx<'a, (), St>,
199    ) -> InlineFuture<'a, Result<S::Res, S::Error>, WORDS>
200    where
201        Req: 'a,
202    {
203        InlineFuture::new_with(|| Service::call(self, req, ctx.cast()))
204    }
205
206    #[inline]
207    fn shutdown<'a>(&'a self, ctx: Ctx<'a, (), St>) -> InlineFuture<'a, (), WORDS>
208    where
209        St: 'a,
210        Req: 'a,
211    {
212        InlineFuture::new_with(|| Service::shutdown(self, ctx.cast()))
213    }
214}
215
216// ============================ ServiceFactory =============================
217
218/// Boxed service factory.
219///
220/// Created services are [`BoxService`]s with the same `WORDS` slot size.
221pub struct BoxServiceFactory<St, Req, Res, Err, InitErr, const WORDS: usize = 0> {
222    inner: Rc<dyn ServiceFactoryObj<St, Req, WORDS, Res = Res, Error = Err, InitErr = InitErr>>,
223}
224
225/// Creates a boxed service factory.
226pub fn factory<Sf, St, Req>(
227    factory: Sf,
228) -> BoxServiceFactory<St, Req, Sf::Res, Sf::Error, Sf::InitError>
229where
230    Sf: ServiceFactory<St, Req> + 'static,
231    St: 'static,
232    Req: 'static,
233{
234    BoxServiceFactory::new(factory)
235}
236
237impl<St, Req, Res, Err, InitErr> BoxServiceFactory<St, Req, Res, Err, InitErr>
238where
239    St: 'static,
240    Req: 'static,
241{
242    /// Creates a boxed service factory with the default slot (`WORDS = 0`).
243    pub fn new<Sf>(factory: Sf) -> Self
244    where
245        Sf: ServiceFactory<St, Req, Res = Res, Error = Err, InitError = InitErr> + 'static,
246    {
247        Self::new_inline(factory)
248    }
249}
250
251impl<St, Req, Res, Err, InitErr, const WORDS: usize>
252    BoxServiceFactory<St, Req, Res, Err, InitErr, WORDS>
253where
254    St: 'static,
255    Req: 'static,
256{
257    /// Creates a boxed service factory whose services store futures of up to
258    /// `WORDS` machine words inline, see [`BoxService::new_inline`].
259    pub fn new_inline<Sf>(factory: Sf) -> Self
260    where
261        Sf: ServiceFactory<St, Req, Res = Res, Error = Err, InitError = InitErr> + 'static,
262    {
263        Self {
264            inner: Rc::new(factory),
265        }
266    }
267}
268
269impl<St, Req, Res, Err, InitErr, const WORDS: usize> ServiceFactory<St, Req>
270    for BoxServiceFactory<St, Req, Res, Err, InitErr, WORDS>
271where
272    Req: 'static,
273{
274    type Res = Res;
275    type Error = Err;
276
277    type Service = BoxService<St, Req, Res, Err, WORDS>;
278    type InitError = InitErr;
279
280    #[inline]
281    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
282        self.inner.create(st).await
283    }
284}
285
286impl<St, Req, Res, Err, InitErr, const WORDS: usize> Clone
287    for BoxServiceFactory<St, Req, Res, Err, InitErr, WORDS>
288{
289    fn clone(&self) -> Self {
290        Self {
291            inner: self.inner.clone(),
292        }
293    }
294}
295
296impl<St, Req, Res, Err, InitErr, const WORDS: usize> fmt::Debug
297    for BoxServiceFactory<St, Req, Res, Err, InitErr, WORDS>
298{
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.debug_struct("BoxServiceFactory").finish()
301    }
302}
303
304trait ServiceFactoryObj<St, Req, const WORDS: usize> {
305    type Res;
306    type Error;
307    type InitErr;
308
309    fn create<'a>(
310        &'a self,
311        st: &'a St,
312    ) -> BoxFuture<'a, Result<BoxService<St, Req, Self::Res, Self::Error, WORDS>, Self::InitErr>>
313    where
314        Req: 'a;
315}
316
317impl<Sf, St, Req, const WORDS: usize> ServiceFactoryObj<St, Req, WORDS> for Sf
318where
319    St: 'static,
320    Req: 'static,
321    Sf: ServiceFactory<St, Req> + 'static,
322{
323    type Res = Sf::Res;
324    type Error = Sf::Error;
325    type InitErr = Sf::InitError;
326
327    #[inline]
328    fn create<'a>(
329        &'a self,
330        st: &'a St,
331    ) -> BoxFuture<'a, Result<BoxService<St, Req, Self::Res, Self::Error, WORDS>, Self::InitErr>>
332    where
333        Req: 'a,
334    {
335        let fut = ServiceFactory::create(self, st);
336        Box::pin(async move { fut.await.map(BoxService::new_inline) })
337    }
338}