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
//! Provides a primitive to create interruptible infinite loops
//!
//! This allows to create infinite loops in threads which allow to be interrupted via a CTRL-C handler in order to shut down the
//! application gracefully

use std::{
    sync::{Arc, Condvar, Mutex},
    time::Duration,
};

struct KeeperData {
    running: Mutex<bool>,
    waiting: Condvar,
}

/// Thread-safe public pointer to the KeeperData struct.
#[derive(Clone)]
pub struct Keeper(Arc<KeeperData>);

/// Public enumeration for the keeper wait condition.
#[derive(Debug)]
pub enum WaitResult {
    Finished,
    Interrupted,
}

impl Default for Keeper {
    fn default() -> Self {
        Self::new()
    }
}

impl Keeper {
    /// Returns a Keeper instance.
    ///
    /// # Example
    /// ```rust,no_run
    /// use celp_sdk::util::keeper::Keeper;
    ///
    /// let keeper = Keeper::new();
    /// ```
    pub fn new() -> Self {
        Self(Arc::new(KeeperData {
            running: true.into(),
            waiting: Condvar::new(),
        }))
    }

    /// Wait for a set amount of milliseconds.
    /// Thread is blocked for the given amount of milliseconds.
    ///
    /// # Arguments
    ///
    /// * `time_ms` - The time to wait in milliseconds.
    ///
    /// # Returns
    ///
    /// * WaitResult on success
    /// * A boxed Error on failure
    ///
    /// # Example
    /// ```rust,no_run
    /// use celp_sdk::util::keeper::Keeper;
    ///
    /// let keeper = Keeper::new();
    ///
    /// fn execute(keeper: &Keeper) -> Result<(), Box<dyn std::error::Error>> {
    ///     while let Ok(true) = keeper.run_loop() {
    ///         match keeper.wait(250) {
    ///             Ok(result) => {println!("result: {:?}", result)}
    ///             Err(e) => {eprintln!("error: {e:#?}")}
    ///         }
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn wait(&self, time_ms: u64) -> Result<WaitResult, Box<dyn std::error::Error + '_>> {
        let running = self
            // Thread-safe pointer to Keeper.
            .0
            // Conditional variable that blocks thread waiting on an event.
            .waiting
            // Guard the thread and wait a set amount of milliseconds.
            .wait_timeout(
                self.0
                    .running
                    .lock()
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + '_>)?,
                Duration::from_millis(time_ms),
            )
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + '_>)?;
        // Check if the timeout value was reached or not.
        let res = match running.1.timed_out() {
            true => WaitResult::Finished,
            false => WaitResult::Interrupted,
        };

        Ok(res)
    }

    /// Stop the thread.
    ///
    /// # Returns
    ///
    /// * An error if the loop can't be stopped
    ///
    /// # Example
    /// ```rust,no_run
    /// use celp_sdk::util::keeper::Keeper;
    ///
    /// let keeper = Keeper::new();
    ///
    /// fn some_handler(keeper: &Keeper) {
    ///     if let Err(e) = keeper.stop() {
    ///         eprintln!("error: {e:#?}");
    ///     }
    /// }
    /// ```
    pub fn stop(&self) -> Result<(), Box<dyn std::error::Error + '_>> {
        // Get the global running state mutex.
        let mut running = self
            .0
            .running
            .lock()
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + '_>)?;
        *running = false;
        // Wake up all blocked threads on this conditional variable.
        self.0.waiting.notify_all();
        // Return Ok in the case that the lock was successfully retrieved.
        Ok(())
    }

    /// Run infinite loop.
    ///
    /// # Returns
    ///
    /// * A bool on success
    /// * An error when the loop fails to run
    ///
    /// # Example
    /// ```rust,no_run
    /// use celp_sdk::util::keeper::Keeper;
    ///
    /// let keeper = Keeper::new();
    ///
    /// fn execute(keeper: &Keeper) -> Result<(), Box<dyn std::error::Error>> {
    ///     while let Ok(true) = keeper.run_loop() {
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn run_loop(&self) -> Result<bool, Box<dyn std::error::Error + '_>> {
        // Get the global running state mutex.
        let res = self
            .0
            .running
            .lock()
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + '_>)?;
        // Return value of mutex.
        Ok(res.to_owned())
    }
}