signal_handler/
callback.rs1use core::{
2 future::Future,
3 ops::{Deref, DerefMut},
4 pin::Pin,
5};
6use std::{collections::HashMap, sync::Arc, time::SystemTime};
7
8#[derive(Debug, Clone)]
10#[non_exhaustive]
11pub struct CallbackInfo {
12 pub time: SystemTime,
13}
14
15impl Default for CallbackInfo {
16 fn default() -> Self {
17 Self {
18 time: SystemTime::now(),
19 }
20 }
21}
22
23impl CallbackInfo {
24 pub fn new() -> Self {
25 Self::default()
26 }
27
28 pub fn time(&self) -> &SystemTime {
29 &self.time
30 }
31
32 pub fn time_now() -> SystemTime {
33 SystemTime::now()
34 }
35}
36
37#[derive(Clone)]
39pub enum Callback {
40 Sync(Arc<dyn Fn(CallbackInfo) + Send + Sync + 'static>),
41 #[allow(clippy::type_complexity)]
42 Async(
43 Arc<
44 dyn Fn(CallbackInfo) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>
45 + Send
46 + Sync
47 + 'static,
48 >,
49 ),
50}
51
52impl core::fmt::Debug for Callback {
53 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
54 match self {
55 Self::Sync(_) => write!(f, "Callback::Sync"),
56 Self::Async(_) => write!(f, "Callback::Async"),
57 }
58 }
59}
60
61impl Callback {
62 pub fn with_sync<F>(cb: F) -> Self
63 where
64 F: Fn(CallbackInfo) + Send + Sync + 'static,
65 {
66 Self::Sync(Arc::new(cb))
67 }
68
69 pub fn with_async<F>(cb: F) -> Self
70 where
71 F: Fn(CallbackInfo) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>
72 + Send
73 + Sync
74 + 'static,
75 {
76 Self::Async(Arc::new(cb))
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub enum CallbackType {
83 Initialized,
84 ReloadConfig,
85 WaitForStop,
86 PrintStats,
87}
88
89#[derive(Debug, Clone, Default)]
91pub struct Callbacks(HashMap<CallbackType, Callback>);
92
93impl Deref for Callbacks {
94 type Target = HashMap<CallbackType, Callback>;
95
96 fn deref(&self) -> &Self::Target {
97 &self.0
98 }
99}
100
101impl DerefMut for Callbacks {
102 fn deref_mut(&mut self) -> &mut Self::Target {
103 &mut self.0
104 }
105}
106
107impl Callbacks {
108 pub fn new() -> Self {
109 Self::default()
110 }
111
112 pub fn into_inner(self) -> HashMap<CallbackType, Callback> {
113 self.0
114 }
115
116 pub fn has_async(&self) -> bool {
117 self.iter().any(|(_, cb)| matches!(cb, Callback::Async(_)))
118 }
119}