ntex_service/
fn_shutdown.rs1use std::{cell::Cell, convert::Infallible, fmt, marker::PhantomData};
2
3use crate::{Ctx, Service, ServiceFactory};
4
5pub struct FnShutdown<F, Err> {
7 f_shutdown: Cell<Option<F>>,
8 err: PhantomData<Err>,
9}
10
11impl<F, Err> FnShutdown<F, Err> {
12 pub fn new<St>(f: F) -> Self
14 where
15 F: AsyncFnOnce(&St),
16 {
17 Self {
18 f_shutdown: Cell::new(Some(f)),
19 err: PhantomData,
20 }
21 }
22}
23
24impl<F, Err> Clone for FnShutdown<F, Err>
25where
26 F: Clone,
27{
28 #[inline]
29 fn clone(&self) -> Self {
30 let f = self.f_shutdown.take();
31 self.f_shutdown.set(f.clone());
32 Self {
33 f_shutdown: Cell::new(f),
34 err: PhantomData,
35 }
36 }
37}
38
39impl<F, Err> fmt::Debug for FnShutdown<F, Err> {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.debug_struct("FnShutdown")
42 .field("fn", &std::any::type_name::<F>())
43 .finish()
44 }
45}
46
47impl<F, St, Req, Err> Service<St, Req> for FnShutdown<F, Err>
48where
49 F: AsyncFnOnce(&St),
50{
51 type Res = Req;
52 type Error = Err;
53
54 #[inline]
55 #[allow(clippy::manual_async_fn)]
56 fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
57 async move {
60 if let Some(f) = self.f_shutdown.take() {
61 (f)(ctx.st()).await;
62 }
63 }
64 }
65
66 #[inline]
67 fn call(&self, req: Req, _: Ctx<'_, Self, St>) -> impl Future<Output = Result<Req, Err>> {
68 std::future::ready(Ok(req))
69 }
70}
71
72impl<F, St, Req, Err> ServiceFactory<St, Req> for FnShutdown<F, Err>
73where
74 F: AsyncFnOnce(&St) + Clone,
75{
76 type Res = Req;
77 type Error = Err;
78
79 type Service = FnShutdown<F, Err>;
80 type InitError = Infallible;
81
82 #[inline]
83 async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError> {
84 if let Some(f) = self.f_shutdown.take() {
85 self.f_shutdown.set(Some(f.clone()));
86 Ok(FnShutdown {
87 f_shutdown: Cell::new(Some(f)),
88 err: PhantomData,
89 })
90 } else {
91 panic!("FnShutdown was used already");
92 }
93 }
94}
95
96#[cfg(test)]
97#[path = "../tests/unit/fn_shutdown.rs"]
98mod tests;