Skip to main content

ntex_service/
fn_ready.rs

1use std::{convert::Infallible, fmt, marker::PhantomData};
2
3use crate::{Ctx, Service, ServiceFactory};
4
5/// A pass-through service with readiness controlled by an asynchronous function.
6///
7/// The callback receives only pipeline state, not a readiness scope. For scoped
8/// readiness and change notifications, implement [`Service`] directly.
9pub struct FnReadiness<F, Err> {
10    f: F,
11    err: PhantomData<Err>,
12}
13
14impl<F, Err> FnReadiness<F, Err> {
15    /// Creates a readiness service from an asynchronous function.
16    pub fn new<St>(f: F) -> Self
17    where
18        F: AsyncFn(&St) -> Result<(), Err>,
19    {
20        Self {
21            f,
22            err: PhantomData,
23        }
24    }
25}
26
27impl<F, Err> Clone for FnReadiness<F, Err>
28where
29    F: Clone,
30{
31    #[inline]
32    fn clone(&self) -> Self {
33        Self {
34            f: self.f.clone(),
35            err: PhantomData,
36        }
37    }
38}
39
40impl<F, Err> fmt::Debug for FnReadiness<F, Err> {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.debug_struct("FnReadiness")
43            .field("fn", &std::any::type_name::<F>())
44            .finish()
45    }
46}
47
48impl<F, Err, St, Req> ServiceFactory<St, Req> for FnReadiness<F, Err>
49where
50    F: AsyncFn(&St) -> Result<(), Err> + Clone,
51{
52    type Res = Req;
53    type Error = Err;
54
55    type Service = FnReadiness<F, Err>;
56    type InitError = Infallible;
57
58    #[inline]
59    async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError> {
60        Ok(self.clone())
61    }
62}
63
64impl<F, St, Req, Err> Service<St, Req> for FnReadiness<F, Err>
65where
66    F: AsyncFn(&St) -> Result<(), Err> + Clone,
67{
68    type Res = Req;
69    type Error = Err;
70
71    #[inline]
72    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Err>> {
73        (self.f)(ctx.st())
74    }
75
76    #[inline]
77    fn call(&self, req: Req, _: Ctx<'_, Self, St>) -> impl Future<Output = Result<Req, Err>> {
78        std::future::ready(Ok(req))
79    }
80}
81
82#[cfg(test)]
83#[path = "../tests/unit/fn_ready.rs"]
84mod tests;