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
impl Monitor
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates an empty monitor.
Examples found in repository?
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
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}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}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}Sourcepub fn register(&self, config: TaskConfig) -> Result<Heartbeat, RegisterError>
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?
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
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}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}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}Sourcepub fn status(&self, id: TaskId) -> Option<TaskStatus>
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?
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
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}Sourcepub fn snapshot(&self) -> Vec<TaskStatus>
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?
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}Sourcepub fn retrain(&self, id: TaskId) -> Result<(), RetrainError>
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.
Sourcepub fn purge_stopped(&self) -> usize
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?
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
impl Monitor
pub fn summary(&self, policy: HealthPolicy) -> HealthSummary
pub fn summary(&self, policy: HealthPolicy) -> HealthSummary
Returns a compact policy-driven aggregate health summary.
Examples found in repository?
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
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?
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
impl Monitor
Sourcepub fn transition_cursor(&self) -> TransitionCursor
pub fn transition_cursor(&self) -> TransitionCursor
Creates an independent transition cursor for this monitor.