scuffle_bootstrap/
service.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use std::pin::Pin;
use std::sync::Arc;
use std::task::{ready, Context, Poll};

#[cfg(any(test, doctest))]
#[doc(hidden)]
pub use scuffle_signal::SignalSvc;

/// A service that can be run.
///
/// This trait is used to define a service that can be run in parallel to other
/// services.
///
/// # See Also
///
/// - [`Global`](crate::Global)
/// - [`GlobalWithoutConfig`](crate::GlobalWithoutConfig)
/// - [`main`](crate::main)
pub trait Service<Global>: Send + Sync + 'static + Sized {
    /// Returns the name of the service, if any.
    fn name(&self) -> Option<&'static str> {
        None
    }

    /// Initialize the service and return `Ok(true)` if the service should be
    /// run.
    fn enabled(&self, global: &Arc<Global>) -> impl std::future::Future<Output = anyhow::Result<bool>> + Send {
        let _ = global;
        std::future::ready(Ok(true))
    }

    /// Run the service.
    /// This function should return a future that is pending as long as the
    /// service is running. When the service finishes without any errors,
    /// the future should resolve to `Ok(())`. As a best practice, the
    /// service should stop as soon as the provided context is done.
    ///
    /// Note: Adding the
    /// [`scuffle_signal::SignalSvc`](../../scuffle_signal/struct.SignalSvc.html)
    /// service to the list of services when calling [`main`](crate::main) will
    /// cancel the context as soon as a shutdown signal is received.
    ///
    /// # See Also
    ///
    /// - [`Context`](scuffle_context::Context)
    /// - [`scuffle_signal::SignalSvc`](../../scuffle_signal/struct.SignalSvc.html)
    fn run(
        self,
        global: Arc<Global>,
        ctx: scuffle_context::Context,
    ) -> impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static {
        let _ = global;
        async move {
            ctx.done().await;
            Ok(())
        }
    }
}

impl<G, F, Fut> Service<G> for F
where
    F: FnOnce(Arc<G>, scuffle_context::Context) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
{
    fn run(
        self,
        global: Arc<G>,
        ctx: scuffle_context::Context,
    ) -> impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static {
        self(global, ctx)
    }
}

pin_project_lite::pin_project! {
    #[must_use = "futures do nothing unless polled"]
    pub struct NamedFuture<T> {
        name: &'static str,
        #[pin]
        fut: T,
    }
}

impl<T> NamedFuture<T> {
    pub fn new(name: &'static str, fut: T) -> Self {
        Self { name, fut }
    }
}

impl<T> std::future::Future for NamedFuture<T>
where
    T: std::future::Future,
{
    type Output = (&'static str, T::Output);

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let res = ready!(this.fut.poll(cx));
        Poll::Ready((this.name, res))
    }
}

#[cfg(test)]
#[cfg_attr(all(test, coverage_nightly), coverage(off))]
mod tests {
    use std::sync::Arc;

    use scuffle_future_ext::FutureExt;

    use super::{NamedFuture, Service};

    struct DefaultService;

    impl Service<()> for DefaultService {}

    #[tokio::test]
    async fn defaukt_service() {
        let svc = DefaultService;
        let global = Arc::new(());
        let (ctx, handler) = scuffle_context::Context::new();

        assert_eq!(svc.name(), None);
        assert!(svc.enabled(&global).await.unwrap());

        handler.cancel();

        assert!(matches!(svc.run(global, ctx).await, Ok(())));

        assert!(handler
            .shutdown()
            .with_timeout(tokio::time::Duration::from_millis(200))
            .await
            .is_ok());
    }

    #[tokio::test]
    async fn future_service() {
        let (ctx, handler) = scuffle_context::Context::new();
        let global = Arc::new(());

        let fut_fn = |_global: Arc<()>, _ctx: scuffle_context::Context| async { anyhow::Result::<()>::Ok(()) };
        assert!(fut_fn.run(global, ctx).await.is_ok());

        handler.cancel();
        assert!(handler
            .shutdown()
            .with_timeout(tokio::time::Duration::from_millis(200))
            .await
            .is_ok());
    }

    #[tokio::test]
    async fn named_future() {
        let named_fut = NamedFuture::new("test", async { 42 });
        assert_eq!(named_fut.await, ("test", 42));
    }
}