Skip to main content

rig_agentcore/
busy.rs

1//! The work an app has open, which decides whether `/ping` says `Healthy` or
2//! `HealthyBusy`.
3
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7/// The open work of one app, and when its status last changed.
8#[derive(Debug)]
9pub(crate) struct Busy {
10    state: Mutex<State>,
11}
12
13#[derive(Debug)]
14struct State {
15    open: usize,
16    /// Unix seconds of the last status change: the app's start, or the moment
17    /// the open count went from zero to one or back to zero.
18    since: u64,
19}
20
21impl Busy {
22    pub(crate) fn new() -> Arc<Self> {
23        Arc::new(Self {
24            state: Mutex::new(State {
25                open: 0,
26                since: now(),
27            }),
28        })
29    }
30
31    fn lock(&self) -> MutexGuard<'_, State> {
32        self.state.lock().unwrap_or_else(PoisonError::into_inner)
33    }
34
35    /// Count one more piece of open work, held until the guard drops.
36    pub(crate) fn open(this: &Arc<Self>) -> BusyGuard {
37        {
38            let mut state = this.lock();
39            if state.open == 0 {
40                state.since = now();
41            }
42            state.open += 1;
43        }
44        BusyGuard {
45            busy: Arc::clone(this),
46        }
47    }
48
49    /// Whether any work is open, and when the status last changed.
50    pub(crate) fn status(&self) -> (bool, u64) {
51        let state = self.lock();
52        (state.open > 0, state.since)
53    }
54}
55
56/// Keeps the app's `/ping` at `HealthyBusy` while it is alive. Get one from
57/// [`AgentCoreApp::track_task`](crate::AgentCoreApp::track_task). The work is
58/// released when the guard drops, which also happens when a task holding it is
59/// aborted or panics.
60#[must_use = "dropping the guard at once ends the busy status immediately"]
61#[derive(Debug)]
62pub struct BusyGuard {
63    busy: Arc<Busy>,
64}
65
66impl Drop for BusyGuard {
67    fn drop(&mut self) {
68        let mut state = self.busy.lock();
69        state.open = state.open.saturating_sub(1);
70        if state.open == 0 {
71            state.since = now();
72        }
73    }
74}
75
76fn now() -> u64 {
77    SystemTime::now()
78        .duration_since(UNIX_EPOCH)
79        .map_or(0, |elapsed| elapsed.as_secs())
80}