Skip to main content

Monitor

Struct Monitor 

Source
pub struct Monitor { /* private fields */ }
Expand description

Registry and pull-driven observation point for monitored tasks.

Monitor is cheap to clone. Every clone shares the same retained task records, and its methods may be called from multiple threads. It does not own a background worker, timer, callback executor, or event queue; health is classified when the caller requests a status, report, or transition poll.

Implementations§

Source§

impl Monitor

Source

pub fn new() -> Self

Creates an empty monitor.

Examples found in repository?
examples/fixed_monitor.rs (line 6)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "fixed-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    heartbeat.beat()?;
13
14    for status in monitor.snapshot() {
15        println!(
16            "id={} name={} heartbeats={} health={:?}",
17            status.id.get(),
18            status.name,
19            status.heartbeat_count,
20            status.health,
21        );
22    }
23
24    Ok(())
25}
More examples
Hide additional examples
examples/learned_monitor.rs (line 6)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let timing = LearnedTiming::default()
8        .with_minimum_samples(5)
9        .with_minimum_grace(Duration::from_millis(25))
10        .with_adaptation(Adaptation::Slow)
11        .with_model(LearningModel::robust_window(5));
12    let heartbeat = monitor.register(TaskConfig::new("learned-worker", Timing::Learned(timing)))?;
13
14    heartbeat.beat()?;
15
16    let status = monitor
17        .status(heartbeat.id())
18        .expect("registered task remains retained");
19    println!("health={:?} timing={:?}", status.health, status.timing);
20
21    Ok(())
22}
examples/health_report.rs (line 6)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "api-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    let starting = monitor.summary(HealthPolicy::readiness());
13    println!(
14        "before first beat: verdict={:?}, starting={}",
15        starting.verdict, starting.counts.starting,
16    );
17
18    heartbeat.beat()?;
19
20    let report = monitor.report(HealthPolicy::liveness());
21    println!(
22        "after first beat: verdict={:?}, healthy={}",
23        report.summary.verdict, report.summary.counts.healthy,
24    );
25    for task in report.tasks.iter() {
26        println!("{}: {:?}", task.name, task.health);
27    }
28
29    Ok(())
30}
examples/worker_loop.rs (line 6)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(
8        TaskConfig::new("worker-loop", Timing::fixed(Duration::from_millis(250)))
9            .with_startup_grace(Duration::from_secs(1)),
10    )?;
11    let task_id = heartbeat.id();
12
13    let worker = thread::spawn(move || -> Result<(), StoppedError> {
14        for completed_step in 1..=3 {
15            thread::sleep(Duration::from_millis(50));
16            heartbeat.beat()?;
17            println!("worker completed step {completed_step}");
18        }
19
20        // Dropping the final heartbeat at the end of this closure marks the
21        // retained task record as stopped.
22        Ok(())
23    });
24
25    while !worker.is_finished() {
26        thread::sleep(Duration::from_millis(25));
27        if let Some(status) = monitor.status(task_id) {
28            println!("observer: {:?}", status.health);
29        }
30    }
31
32    worker.join().expect("worker thread panicked")?;
33
34    let stopped = monitor
35        .status(task_id)
36        .expect("stopped task remains retained until purged");
37    println!("after join: {:?}", stopped.health);
38
39    assert_eq!(monitor.purge_stopped(), 1);
40    assert!(monitor.status(task_id).is_none());
41
42    Ok(())
43}
Source

pub fn register(&self, config: TaskConfig) -> Result<Heartbeat, RegisterError>

Registers a task and returns its heartbeat handle.

Registration retains one task record until it is removed with Monitor::purge_stopped. Every task begins in HealthState::Starting. After the first beat, fixed timing can become HealthState::Healthy, while learned timing enters HealthState::Learning until its baseline is trained. No thread or timer is started.

§Errors

Returns RegisterError when the task name is empty, timing or learning configuration is invalid, or the monitor’s task identifier space is exhausted.

Examples found in repository?
examples/fixed_monitor.rs (lines 7-10)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "fixed-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    heartbeat.beat()?;
13
14    for status in monitor.snapshot() {
15        println!(
16            "id={} name={} heartbeats={} health={:?}",
17            status.id.get(),
18            status.name,
19            status.heartbeat_count,
20            status.health,
21        );
22    }
23
24    Ok(())
25}
More examples
Hide additional examples
examples/learned_monitor.rs (line 12)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let timing = LearnedTiming::default()
8        .with_minimum_samples(5)
9        .with_minimum_grace(Duration::from_millis(25))
10        .with_adaptation(Adaptation::Slow)
11        .with_model(LearningModel::robust_window(5));
12    let heartbeat = monitor.register(TaskConfig::new("learned-worker", Timing::Learned(timing)))?;
13
14    heartbeat.beat()?;
15
16    let status = monitor
17        .status(heartbeat.id())
18        .expect("registered task remains retained");
19    println!("health={:?} timing={:?}", status.health, status.timing);
20
21    Ok(())
22}
examples/health_report.rs (lines 7-10)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "api-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    let starting = monitor.summary(HealthPolicy::readiness());
13    println!(
14        "before first beat: verdict={:?}, starting={}",
15        starting.verdict, starting.counts.starting,
16    );
17
18    heartbeat.beat()?;
19
20    let report = monitor.report(HealthPolicy::liveness());
21    println!(
22        "after first beat: verdict={:?}, healthy={}",
23        report.summary.verdict, report.summary.counts.healthy,
24    );
25    for task in report.tasks.iter() {
26        println!("{}: {:?}", task.name, task.health);
27    }
28
29    Ok(())
30}
examples/worker_loop.rs (lines 7-10)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(
8        TaskConfig::new("worker-loop", Timing::fixed(Duration::from_millis(250)))
9            .with_startup_grace(Duration::from_secs(1)),
10    )?;
11    let task_id = heartbeat.id();
12
13    let worker = thread::spawn(move || -> Result<(), StoppedError> {
14        for completed_step in 1..=3 {
15            thread::sleep(Duration::from_millis(50));
16            heartbeat.beat()?;
17            println!("worker completed step {completed_step}");
18        }
19
20        // Dropping the final heartbeat at the end of this closure marks the
21        // retained task record as stopped.
22        Ok(())
23    });
24
25    while !worker.is_finished() {
26        thread::sleep(Duration::from_millis(25));
27        if let Some(status) = monitor.status(task_id) {
28            println!("observer: {:?}", status.health);
29        }
30    }
31
32    worker.join().expect("worker thread panicked")?;
33
34    let stopped = monitor
35        .status(task_id)
36        .expect("stopped task remains retained until purged");
37    println!("after join: {:?}", stopped.health);
38
39    assert_eq!(monitor.purge_stopped(), 1);
40    assert!(monitor.status(task_id).is_none());
41
42    Ok(())
43}
Source

pub fn status(&self, id: TaskId) -> Option<TaskStatus>

Returns a compact status snapshot for one retained task.

Returns None when the identifier is unknown or its stopped record has already been purged.

Examples found in repository?
examples/learned_monitor.rs (line 17)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let timing = LearnedTiming::default()
8        .with_minimum_samples(5)
9        .with_minimum_grace(Duration::from_millis(25))
10        .with_adaptation(Adaptation::Slow)
11        .with_model(LearningModel::robust_window(5));
12    let heartbeat = monitor.register(TaskConfig::new("learned-worker", Timing::Learned(timing)))?;
13
14    heartbeat.beat()?;
15
16    let status = monitor
17        .status(heartbeat.id())
18        .expect("registered task remains retained");
19    println!("health={:?} timing={:?}", status.health, status.timing);
20
21    Ok(())
22}
More examples
Hide additional examples
examples/worker_loop.rs (line 27)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(
8        TaskConfig::new("worker-loop", Timing::fixed(Duration::from_millis(250)))
9            .with_startup_grace(Duration::from_secs(1)),
10    )?;
11    let task_id = heartbeat.id();
12
13    let worker = thread::spawn(move || -> Result<(), StoppedError> {
14        for completed_step in 1..=3 {
15            thread::sleep(Duration::from_millis(50));
16            heartbeat.beat()?;
17            println!("worker completed step {completed_step}");
18        }
19
20        // Dropping the final heartbeat at the end of this closure marks the
21        // retained task record as stopped.
22        Ok(())
23    });
24
25    while !worker.is_finished() {
26        thread::sleep(Duration::from_millis(25));
27        if let Some(status) = monitor.status(task_id) {
28            println!("observer: {:?}", status.health);
29        }
30    }
31
32    worker.join().expect("worker thread panicked")?;
33
34    let stopped = monitor
35        .status(task_id)
36        .expect("stopped task remains retained until purged");
37    println!("after join: {:?}", stopped.health);
38
39    assert_eq!(monitor.purge_stopped(), 1);
40    assert!(monitor.status(task_id).is_none());
41
42    Ok(())
43}
Source

pub fn snapshot(&self) -> Vec<TaskStatus>

Returns compact status snapshots for all retained tasks.

The returned vector is a point-in-time observation and has no guaranteed ordering. Use a TransitionCursor when only meaningful state changes are needed.

Examples found in repository?
examples/fixed_monitor.rs (line 14)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "fixed-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    heartbeat.beat()?;
13
14    for status in monitor.snapshot() {
15        println!(
16            "id={} name={} heartbeats={} health={:?}",
17            status.id.get(),
18            status.name,
19            status.heartbeat_count,
20            status.health,
21        );
22    }
23
24    Ok(())
25}
Source

pub fn len(&self) -> usize

Returns the number of retained task records.

Source

pub fn is_empty(&self) -> bool

Returns whether no task records are retained.

Source

pub fn retrain(&self, id: TaskId) -> Result<(), RetrainError>

Discards a learned baseline and returns the task to its learning phase.

The next interval is intentionally ignored so the time between the reset request and the next heartbeat cannot contaminate the new model. The task identifier and every existing heartbeat handle remain unchanged.

§Errors

Returns RetrainError::UnknownTask for an unknown or purged task, RetrainError::Stopped for a retained stopped task, and RetrainError::FixedTiming when the task does not use learned timing.

Source

pub fn purge_stopped(&self) -> usize

Removes all stopped records and returns the number removed.

Purging does not revive or reset any heartbeat handle. Existing handles for a stopped task remain stopped, and transition cursors forget a purged task on their next poll.

Examples found in repository?
examples/worker_loop.rs (line 39)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(
8        TaskConfig::new("worker-loop", Timing::fixed(Duration::from_millis(250)))
9            .with_startup_grace(Duration::from_secs(1)),
10    )?;
11    let task_id = heartbeat.id();
12
13    let worker = thread::spawn(move || -> Result<(), StoppedError> {
14        for completed_step in 1..=3 {
15            thread::sleep(Duration::from_millis(50));
16            heartbeat.beat()?;
17            println!("worker completed step {completed_step}");
18        }
19
20        // Dropping the final heartbeat at the end of this closure marks the
21        // retained task record as stopped.
22        Ok(())
23    });
24
25    while !worker.is_finished() {
26        thread::sleep(Duration::from_millis(25));
27        if let Some(status) = monitor.status(task_id) {
28            println!("observer: {:?}", status.health);
29        }
30    }
31
32    worker.join().expect("worker thread panicked")?;
33
34    let stopped = monitor
35        .status(task_id)
36        .expect("stopped task remains retained until purged");
37    println!("after join: {:?}", stopped.health);
38
39    assert_eq!(monitor.purge_stopped(), 1);
40    assert!(monitor.status(task_id).is_none());
41
42    Ok(())
43}
§

impl Monitor

pub fn summary(&self, policy: HealthPolicy) -> HealthSummary

Returns a compact policy-driven aggregate health summary.

Examples found in repository?
examples/health_report.rs (line 12)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "api-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    let starting = monitor.summary(HealthPolicy::readiness());
13    println!(
14        "before first beat: verdict={:?}, starting={}",
15        starting.verdict, starting.counts.starting,
16    );
17
18    heartbeat.beat()?;
19
20    let report = monitor.report(HealthPolicy::liveness());
21    println!(
22        "after first beat: verdict={:?}, healthy={}",
23        report.summary.verdict, report.summary.counts.healthy,
24    );
25    for task in report.tasks.iter() {
26        println!("{}: {:?}", task.name, task.health);
27    }
28
29    Ok(())
30}

pub fn report(&self, policy: HealthPolicy) -> HealthReport

Returns an aggregate health summary and the task snapshots behind it.

Task snapshots are ordered by task ID and are captured against the same monotonic observation tick used for the aggregate summary.

Examples found in repository?
examples/health_report.rs (line 20)
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(TaskConfig::new(
8        "api-worker",
9        Timing::fixed(Duration::from_secs(1)),
10    ))?;
11
12    let starting = monitor.summary(HealthPolicy::readiness());
13    println!(
14        "before first beat: verdict={:?}, starting={}",
15        starting.verdict, starting.counts.starting,
16    );
17
18    heartbeat.beat()?;
19
20    let report = monitor.report(HealthPolicy::liveness());
21    println!(
22        "after first beat: verdict={:?}, healthy={}",
23        report.summary.verdict, report.summary.counts.healthy,
24    );
25    for task in report.tasks.iter() {
26        println!("{}: {:?}", task.name, task.health);
27    }
28
29    Ok(())
30}
Source§

impl Monitor

Source

pub fn transition_cursor(&self) -> TransitionCursor

Creates an independent transition cursor for this monitor.

Trait Implementations§

Source§

impl Clone for Monitor

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for Monitor

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.