kompact/runtime/
mod.rs

1use super::*;
2
3use std::{
4    error,
5    fmt,
6    sync::{
7        atomic::{AtomicUsize, Ordering},
8        Arc,
9        Once,
10    },
11};
12
13use crate::config::ConfigError;
14
15mod config;
16mod lifecycle;
17mod scheduler;
18mod system;
19
20pub use config::*;
21pub use scheduler::*;
22pub use system::*;
23
24static GLOBAL_RUNTIME_COUNT: AtomicUsize = AtomicUsize::new(0);
25
26fn default_runtime_label() -> String {
27    let runtime_count = GLOBAL_RUNTIME_COUNT.fetch_add(1, Ordering::SeqCst) + 1;
28    format!("kompact-runtime-{}", runtime_count)
29}
30
31static mut DEFAULT_ROOT_LOGGER: Option<KompactLogger> = None;
32static DEFAULT_ROOT_LOGGER_INIT: Once = Once::new();
33
34fn default_logger() -> &'static KompactLogger {
35    unsafe {
36        DEFAULT_ROOT_LOGGER_INIT.call_once(|| {
37            let decorator = slog_term::TermDecorator::new().stdout().build();
38            let drain = slog_term::FullFormat::new(decorator).build().fuse();
39            let drain = slog_async::Async::new(drain).chan_size(1024).build().fuse();
40            DEFAULT_ROOT_LOGGER = Some(slog::Logger::root_typed(
41                Arc::new(drain),
42                o!(
43                "location" => slog::PushFnValue(|r: &slog::Record<'_>, ser: slog::PushFnValueSerializer<'_>| {
44                    ser.emit(format_args!("{}:{}", r.file(), r.line()))
45                })
46                        ),
47            ));
48        });
49        match DEFAULT_ROOT_LOGGER {
50            Some(ref l) => l,
51            None => panic!("Can't re-initialise global logger after it has been dropped!"),
52        }
53    }
54}
55
56/// Removes the global default logger
57///
58/// This causes the remaining messages to be flushed to the output.
59///
60/// This can't be undone (as in, calling `default_logger()` afterwards again will panic),
61/// so make sure you use this only right before exiting the programme.
62pub fn drop_default_logger() {
63    unsafe {
64        // Overwriting the current value will implicitly drop it.
65        DEFAULT_ROOT_LOGGER = None;
66    }
67}
68
69type SchedulerBuilder = dyn Fn(usize) -> Box<dyn Scheduler>;
70
71type ScBuilder = dyn Fn(&KompactSystem, KPromise<()>, KPromise<()>) -> Box<dyn SystemComponents>;
72
73type TimerBuilder = dyn Fn() -> Box<dyn TimerComponent>;
74
75/// A Kompact system error
76#[derive(Debug)]
77pub enum KompactError {
78    /// A mutex in the system has been poisoned
79    Poisoned,
80    /// An error occurred loading the HOCON config
81    ConfigLoadingError(hocon::Error),
82    /// An error occurred reading values from the loaded config
83    ConfigError(ConfigError),
84    /// Something else occurred
85    Other(Box<dyn error::Error>),
86}
87
88impl KompactError {
89    /// Wrap an arbitrary [Error](std::error::Error) into a `KompactError`
90    pub fn from_other<E>(e: E) -> Self
91    where
92        E: error::Error + 'static,
93    {
94        KompactError::Other(Box::new(e))
95    }
96}
97
98impl PartialEq for KompactError {
99    fn eq(&self, other: &Self) -> bool {
100        match (self, other) {
101            (KompactError::Poisoned, KompactError::Poisoned) => true,
102            (KompactError::ConfigLoadingError(she), KompactError::ConfigLoadingError(ohe)) => {
103                she == ohe
104            }
105            (KompactError::ConfigError(se), KompactError::ConfigError(oe)) => se == oe,
106            _ => false,
107        }
108    }
109}
110
111impl From<hocon::Error> for KompactError {
112    fn from(e: hocon::Error) -> Self {
113        KompactError::ConfigLoadingError(e)
114    }
115}
116
117impl From<ConfigError> for KompactError {
118    fn from(e: ConfigError) -> Self {
119        KompactError::ConfigError(e)
120    }
121}
122
123impl fmt::Display for KompactError {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        match self {
126            KompactError::Poisoned => write!(f, "A mutex in the KompactSystem has been poisoned"),
127            KompactError::ConfigLoadingError(he) => {
128                write!(f, "An issue occurred loading configuration: {}", he)
129            }
130            KompactError::ConfigError(e) => {
131                write!(f, "An issue occurred reading configuration: {}", e)
132            }
133            KompactError::Other(o) => write!(f, "An unknown issue occurred: {}", o),
134        }
135    }
136}
137
138impl error::Error for KompactError {
139    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
140        match self {
141            KompactError::Poisoned => None,
142            KompactError::ConfigLoadingError(ref e) => Some(e),
143            KompactError::ConfigError(ref e) => Some(e),
144            KompactError::Other(ref o) => Some(o.as_ref()),
145        }
146    }
147}