ayun_core/traits/
service.rs

1use crate::{support::app, traits::ApplicationTrait, Result};
2use async_trait::async_trait;
3
4#[async_trait]
5pub trait ServiceTrait: 'static {
6    type Item;
7
8    fn new() -> Self;
9
10    fn register(self, item: Self::Item) -> Self;
11
12    fn init<A: ApplicationTrait>() -> Self;
13
14    fn run(self) -> Result<()>;
15
16    async fn shutdown() {
17        let ctrl_c = async {
18            tokio::signal::ctrl_c()
19                .await
20                .expect("failed to install Ctrl+C handler");
21        };
22
23        #[cfg(unix)]
24        let terminate = async {
25            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
26                .expect("fail to install the terminate signal handler")
27                .recv()
28                .await;
29        };
30
31        #[cfg(not(unix))]
32        let terminate = std::future::pending::<()>();
33
34        tokio::select! {
35            _ = ctrl_c => {},
36            _ = terminate => {},
37        }
38
39        tracing::warn!("signal received, starting graceful shutdown");
40
41        app()
42            .cleanup()
43            .unwrap_or_else(|err| tracing::error!(err = ?err, "failed to clean container"))
44    }
45}