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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
pub(crate) use tokio::runtime::Runtime as TokioRuntime;
use tokio::runtime::Builder as TokioRuntimeBuilder;
use core::future::Future;
use utils::*;
use crate::*;

/// A runtime for the Catalyzer framework.
/// 
/// You most likely won't need to use this directly,
/// as everything is handled by the `#[main]` macro.
#[derive(Debug)]
pub struct CatalyzerRuntime {
    tokio: TokioRuntime
}

/// A builder for the [`CatalyzerRuntime`](crate::internals::runtime::CatalyzerRuntime).
#[derive(Debug)]
pub struct CatalyzerRuntimeBuilder {
    tokio: Option<TokioRuntime>,
}

impl CatalyzerRuntime {
    fn default_preinit() -> Result<CatalyzerRuntime> {
        #[cfg(feature = "builtin-logger")]
        {
            let log_level = std::env::var("CATALYZER_LOG_LEVEL").unwrap_or("info".to_string());
            let log_level = log_level.parse().unwrap_or(log::LevelFilter::Info);
            let mut l = ::builtin_logger::SimpleLogger::new()
                .with_level(log_level);
            #[cfg(debug_assertions)]
            { l = l.with_colors(true); }
            #[cfg(not(debug_assertions))]
            { l = l.with_colors(false); }
            let _ = l.init();
        }
        use std::sync::atomic::{AtomicU8, Ordering};
        static ATOMIC_ID: AtomicU8 = AtomicU8::new(0);
        CatalyzerRuntime::builder()
            .setup_tokio(|b|
                b.enable_all()
                .thread_name_fn(|| {
                    let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
                    format!("Catalyzer Runtime Worker #{id}")
                })
            )?
            .build()
    }
    /// Creates a new builder for the runtime.
    #[inline]
    pub fn builder() -> CatalyzerRuntimeBuilder {
        CatalyzerRuntimeBuilder {
            tokio: None,
        }
    }
    /// Initializes the runtime with an optional custom initialization function.
    pub fn init(func: Option<fn() -> Result<Self>>) -> Self {
        match func.map_or_else(Self::default_preinit, |f| f()) {
            Err(e) => {
                log::error!("Failed to initialize runtime: {}", e);
                std::process::exit(1);
            }
            Ok(rt) => rt,
        }
    }
    /// Runs the given future on the runtime.
    /// 
    /// This function will also install signal handlers for Ctrl+C and SIGTERM.
    ///
    /// # Example
    /// 
    /// ```rust
    /// # use catalyzer::internals::runtime::CatalyzerRuntime;
    /// # use catalyzer::Result;
    /// fn main() {
    ///     async fn main() -> Result {
    ///         // Your code here
    ///         Ok(())
    ///     }
    ///     CatalyzerRuntime::init(None).run(main);
    /// }
    /// ```
    pub fn run<F, Fut>(self, f: F) where
        Fut: Future<Output = Result>,
        F: FnOnce() -> Fut,
    {
        let (sender, reciever) = tokio::sync::oneshot::channel::<()>();
        let mercy_handlers = async {
            tokio::select! {
                _ = signals::ctrl_c() => {
                    log::info!("Received Ctrl+C, shutting down...");
                },
                _ = signals::term() => {
                    log::info!("Received SIGTERM, shutting down...");
                },
            }
            tokio::select! {
                _ = signals::ctrl_c() => {},
                _ = signals::term() => {},
            }
            log::warn!("Received second signal, please mercy...");
            if let Err(_) = sender.send(()) {
                log::error!("Failed to emit mercy signal, shutting down...");
                std::process::exit(1);
            }
            tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
            log::error!("Mercy timeout reached, shutting down...");
            std::process::exit(1);
        };
        self.tokio.spawn(mercy_handlers);
        self.tokio.block_on(async move {
            tokio::select! {
                _ = f() => {
                    log::debug!("Webserver shutdown successfully!");
                },
                _ = reciever => {
                    log::trace!("Received mercy signal, shutting down...");
                },
            }
        });
        self.tokio.shutdown_timeout(tokio::time::Duration::from_secs(5));
        log::info!("Shutdown successful!");
    }
}

impl CatalyzerRuntimeBuilder {
    /// Allows you to set up the Tokio runtime.
    /// 
    /// This function is chainable.
    /// 
    /// # Example
    /// 
    /// ```rust
    /// # use catalyzer::internals::runtime::CatalyzerRuntimeBuilder;
    /// # use catalyzer::Result;
    /// # fn main() -> Result {
    /// CatalyzerRuntime::builder()
    ///     .setup_tokio(|b| b.enable_all())?
    ///     .build()
    /// # ;
    /// # }
    pub fn setup_tokio<F>(mut self, f: F) -> Result<Self> where
        F: FnOnce(&mut TokioRuntimeBuilder) -> &mut TokioRuntimeBuilder,
    {
        let mut builder = TokioRuntimeBuilder::new_multi_thread();
        f(&mut builder);
        builder.build()
            .map(|t| { self.tokio = Some(t); self})
            .map_auto()
    }
    /// Builds the [`CatalyzerRuntime`](crate::internals::runtime::CatalyzerRuntime).
    /// 
    /// This function consumes the builder, and returns a runtime.
    pub fn build(self) -> Result<CatalyzerRuntime> {
        let tokio = self.tokio.ok_or(CatalyzerError::RuntimeInitializationError)?;
        Ok(CatalyzerRuntime { tokio, })
    }
}

pub(crate) mod signals {
    use tokio::signal;
    pub(crate) async fn ctrl_c() {
        if let Err(_) = signal::ctrl_c().await {
            log::error!("Failed to install signal handler");
            std::process::exit(1);
        }
    }
    #[cfg(unix)]
    pub(crate) async fn term() {
        match signal::unix::signal(signal::unix::SignalKind::terminate()) {
            Ok(mut stream) => { stream.recv().await; },
            Err(e) => {
                log::error!("Failed to install signal handler: {}", e);
                std::process::exit(1);
            },
        }
    }
    #[cfg(not(unix))]
    pub(crate) async fn term() {
        core::future::pending::<()>().await;
    }
}