bedrock_agentcore/runtime/
ping.rs1use std::{
2 fmt,
3 panic::{AssertUnwindSafe, catch_unwind},
4 sync::{
5 Arc, Mutex, PoisonError,
6 atomic::{AtomicBool, Ordering},
7 },
8};
9
10use super::handler::panic_text;
11use crate::tasks::{AsyncTasks, unix_seconds};
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum PingStatus {
16 Healthy,
18 HealthyBusy,
20}
21
22impl PingStatus {
23 pub fn as_str(self) -> &'static str {
25 match self {
26 Self::Healthy => "Healthy",
27 Self::HealthyBusy => "HealthyBusy",
28 }
29 }
30}
31
32impl fmt::Display for PingStatus {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 f.write_str(self.as_str())
35 }
36}
37
38pub(crate) type PingHandler = Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>;
40
41#[derive(Clone, Copy)]
43struct Last {
44 status: PingStatus,
45 changed: u64,
47 custom: bool,
49}
50
51#[derive(Clone)]
53pub(crate) struct PingState {
54 handler: Option<PingHandler>,
55 tasks: AsyncTasks,
56 last: Arc<Mutex<Last>>,
57 panicking: Arc<AtomicBool>,
59}
60
61impl PingState {
62 pub(crate) fn new(handler: Option<PingHandler>, tasks: AsyncTasks) -> Self {
63 let last = Last { status: PingStatus::Healthy, changed: unix_seconds(), custom: false };
64 let last = Arc::new(Mutex::new(last));
65 Self { handler, tasks, last, panicking: Arc::default() }
66 }
67
68 fn custom(&self) -> Option<PingStatus> {
71 let handler = self.handler.as_ref()?;
73 let outcome = catch_unwind(AssertUnwindSafe(|| handler()));
74 match (&outcome, self.panicking.swap(outcome.is_err(), Ordering::Relaxed)) {
77 (Err(panic), false) => tracing::warn!(
78 panic = panic_text(panic.as_ref()),
79 "the custom ping handler panicked, using the automatic status until it returns a status"
80 ),
81 (Ok(_), true) => tracing::info!("the custom ping handler no longer panics"),
82 _ => {}
83 }
84 outcome.ok().flatten()
85 }
86
87 pub(crate) fn current(&self) -> (PingStatus, u64) {
91 let (status, tasks_changed) = match self.custom() {
92 Some(status) => (status, None),
93 None => {
94 let (active, changed) = self.tasks.activity();
95 (if active > 0 { PingStatus::HealthyBusy } else { PingStatus::Healthy }, Some(changed))
96 }
97 };
98
99 let (previous, current) = {
100 let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
101 let previous = last.status;
102 if previous != status {
103 last.changed = tasks_changed.filter(|_| !last.custom).unwrap_or_else(unix_seconds);
108 last.status = status;
109 }
110 last.custom = tasks_changed.is_none();
111 last.changed = last.changed.max(tasks_changed.unwrap_or(0));
114 (previous, (last.status, last.changed))
115 };
116 if previous != status {
119 let active_tasks = self.tasks.active_count();
120 tracing::info!(from = %previous, to = %status, active_tasks, "ping status changed");
121 }
122 current
123 }
124}