apalis_core/poller/
controller.rs

1use std::sync::{
2    atomic::{AtomicUsize, Ordering},
3    Arc,
4};
5
6use super::{PLUGGED, STOPPED, UNPLUGGED};
7
8/// The `Controller` struct represents a thread-safe state manager.
9/// It uses `AtomicUsize` for state to ensure safe concurrent access.
10/// Used to control polling
11#[derive(Debug, Clone)]
12pub struct Controller {
13    pub(super) state: Arc<AtomicUsize>,
14}
15
16impl Controller {
17    /// Constructs a new `Controller` instance with an initial state.
18    pub fn new() -> Self {
19        Controller {
20            state: Arc::new(AtomicUsize::new(PLUGGED)),
21        }
22    }
23
24    /// Sets the state of the controller to `PLUGGED`.
25    pub fn plug(&self) {
26        self.state.store(PLUGGED, Ordering::Relaxed);
27    }
28
29    /// Sets the state of the controller to `UNPLUGGED`.
30    pub fn unplug(&self) {
31        self.state.store(UNPLUGGED, Ordering::Relaxed);
32    }
33
34    /// Returns `true` if the current state is `PLUGGED`.
35    pub fn is_plugged(&self) -> bool {
36        self.state.load(Ordering::Relaxed) == PLUGGED
37    }
38
39    /// Sets the state of the controller to `Stopped`.
40    pub fn stop(&self) {
41        self.state.store(STOPPED, Ordering::Relaxed);
42    }
43
44    /// Returns `true` if the current state is `STOPPED`.
45    pub fn is_stopped(&self) -> bool {
46        self.state.load(Ordering::Relaxed) == STOPPED
47    }
48}
49
50impl Default for Controller {
51    fn default() -> Self {
52        Self::new()
53    }
54}