Skip to main content

beatwise/monitor/
registry.rs

1const RUNNING: u8 = 0;
2const STOPPED: u8 = 1;
3
4const STOP_EXPLICIT: u8 = 1;
5const STOP_LAST_HANDLE_DROPPED: u8 = 2;
6
7const NO_TICK: u64 = 0;
8
9enum TimingState {
10    Fixed(FixedTiming),
11    Learned {
12        config: LearnedTiming,
13        state: Mutex<LearningState>,
14    },
15}
16
17struct TaskEntry {
18    id: TaskId,
19    name: Arc<str>,
20    created_tick: u64,
21    startup_grace: Duration,
22    timing: TimingState,
23
24    last_tick: AtomicU64,
25    stopped_tick: AtomicU64,
26    heartbeat_count: AtomicU64,
27    active_handles: AtomicUsize,
28    lifecycle: AtomicU8,
29    stop_reason: AtomicU8,
30}
31
32struct Inner {
33    epoch: Instant,
34    next_id: AtomicU64,
35    tasks: RwLock<HashMap<TaskId, Arc<TaskEntry>>>,
36}
37
38impl Inner {
39    fn now_tick(&self) -> u64 {
40        let elapsed_micros = self.epoch.elapsed().as_micros();
41        let bounded = elapsed_micros.min(u128::from(u64::MAX - 1)) as u64;
42        bounded + 1
43    }
44
45    fn read_tasks(&self) -> RwLockReadGuard<'_, HashMap<TaskId, Arc<TaskEntry>>> {
46        self.tasks
47            .read()
48            .unwrap_or_else(std::sync::PoisonError::into_inner)
49    }
50
51    fn write_tasks(&self) -> RwLockWriteGuard<'_, HashMap<TaskId, Arc<TaskEntry>>> {
52        self.tasks
53            .write()
54            .unwrap_or_else(std::sync::PoisonError::into_inner)
55    }
56}
57
58/// Registry and pull-driven observation point for monitored tasks.
59///
60/// `Monitor` is cheap to clone. Every clone shares the same retained task
61/// records, and its methods may be called from multiple threads. It does not own
62/// a background worker, timer, callback executor, or event queue; health is
63/// classified when the caller requests a status, report, or transition poll.
64#[derive(Clone)]
65pub struct Monitor {
66    inner: Arc<Inner>,
67}
68
69impl Default for Monitor {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl Monitor {
76    /// Creates an empty monitor.
77    #[must_use]
78    pub fn new() -> Self {
79        Self {
80            inner: Arc::new(Inner {
81                epoch: Instant::now(),
82                next_id: AtomicU64::new(1),
83                tasks: RwLock::new(HashMap::new()),
84            }),
85        }
86    }
87
88    /// Registers a task and returns its heartbeat handle.
89    ///
90    /// Registration retains one task record until it is removed with
91    /// [`Monitor::purge_stopped`]. Every task begins in
92    /// [`HealthState::Starting`]. After the first beat, fixed timing can become
93    /// [`HealthState::Healthy`], while learned timing enters
94    /// [`HealthState::Learning`] until its baseline is trained. No thread or
95    /// timer is started.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`RegisterError`] when the task name is empty, timing or learning
100    /// configuration is invalid, or the monitor's task identifier space is
101    /// exhausted.
102    pub fn register(&self, config: TaskConfig) -> Result<Heartbeat, RegisterError> {
103        config.validate()?;
104
105        let raw_id = self
106            .inner
107            .next_id
108            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
109                current.checked_add(1)
110            })
111            .map_err(|_| RegisterError::IdSpaceExhausted)?;
112
113        let id = TaskId(raw_id);
114        let created_tick = self.inner.now_tick();
115        let startup_grace = config.effective_startup_grace();
116        let timing = match config.timing {
117            Timing::Fixed(fixed) => TimingState::Fixed(fixed),
118            Timing::Learned(learned) => TimingState::Learned {
119                config: learned,
120                state: Mutex::new(LearningState::new(learned.model)),
121            },
122        };
123
124        let entry = Arc::new(TaskEntry {
125            id,
126            name: config.name,
127            created_tick,
128            startup_grace,
129            timing,
130            last_tick: AtomicU64::new(NO_TICK),
131            stopped_tick: AtomicU64::new(NO_TICK),
132            heartbeat_count: AtomicU64::new(0),
133            active_handles: AtomicUsize::new(1),
134            lifecycle: AtomicU8::new(RUNNING),
135            stop_reason: AtomicU8::new(0),
136        });
137
138        self.inner.write_tasks().insert(id, Arc::clone(&entry));
139
140        Ok(Heartbeat {
141            inner: Arc::clone(&self.inner),
142            entry,
143        })
144    }
145
146    /// Returns a compact status snapshot for one retained task.
147    ///
148    /// Returns `None` when the identifier is unknown or its stopped record has
149    /// already been purged.
150    #[must_use]
151    pub fn status(&self, id: TaskId) -> Option<TaskStatus> {
152        self.status_at(id, self.inner.now_tick())
153    }
154
155    /// Returns compact status snapshots for all retained tasks.
156    ///
157    /// The returned vector is a point-in-time observation and has no guaranteed
158    /// ordering. Use a [`TransitionCursor`] when only meaningful state changes
159    /// are needed.
160    #[must_use]
161    pub fn snapshot(&self) -> Vec<TaskStatus> {
162        let now = self.inner.now_tick();
163        self.inner
164            .read_tasks()
165            .values()
166            .map(|entry| status_for(entry, now))
167            .collect()
168    }
169
170    /// Returns the number of retained task records.
171    #[must_use]
172    pub fn len(&self) -> usize {
173        self.inner.read_tasks().len()
174    }
175
176    /// Returns whether no task records are retained.
177    #[must_use]
178    pub fn is_empty(&self) -> bool {
179        self.len() == 0
180    }
181
182    /// Discards a learned baseline and returns the task to its learning phase.
183    ///
184    /// The next interval is intentionally ignored so the time between the reset
185    /// request and the next heartbeat cannot contaminate the new model. The task
186    /// identifier and every existing heartbeat handle remain unchanged.
187    ///
188    /// # Errors
189    ///
190    /// Returns [`RetrainError::UnknownTask`] for an unknown or purged task,
191    /// [`RetrainError::Stopped`] for a retained stopped task, and
192    /// [`RetrainError::FixedTiming`] when the task does not use learned timing.
193    pub fn retrain(&self, id: TaskId) -> Result<(), RetrainError> {
194        let entry = self
195            .inner
196            .read_tasks()
197            .get(&id)
198            .cloned()
199            .ok_or(RetrainError::UnknownTask)?;
200
201        if entry.lifecycle.load(Ordering::Acquire) != RUNNING {
202            return Err(RetrainError::Stopped);
203        }
204
205        match &entry.timing {
206            TimingState::Fixed(_) => Err(RetrainError::FixedTiming),
207            TimingState::Learned { config, state } => {
208                let skip_next_interval = entry.last_tick.load(Ordering::Acquire) != NO_TICK;
209                lock_learning(state).reset_for_retraining(config.model, skip_next_interval);
210                Ok(())
211            }
212        }
213    }
214
215    /// Removes all stopped records and returns the number removed.
216    ///
217    /// Purging does not revive or reset any heartbeat handle. Existing handles
218    /// for a stopped task remain stopped, and transition cursors forget a purged
219    /// task on their next poll.
220    pub fn purge_stopped(&self) -> usize {
221        let mut tasks = self.inner.write_tasks();
222        let previous_len = tasks.len();
223        tasks.retain(|_, entry| entry.lifecycle.load(Ordering::Acquire) != STOPPED);
224        previous_len - tasks.len()
225    }
226
227    fn status_at(&self, id: TaskId, now: u64) -> Option<TaskStatus> {
228        let tasks = self.inner.read_tasks();
229        tasks.get(&id).map(|entry| status_for(entry, now))
230    }
231}