Skip to main content

bedrock_agentcore/runtime/
ping.rs

1use 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/// The health that `GET /ping` reports to AgentCore Runtime.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum PingStatus {
16    /// The agent is idle. The service may end an idle session.
17    Healthy,
18    /// The agent is working in the background. The service keeps the session.
19    HealthyBusy,
20}
21
22impl PingStatus {
23    /// The text of the status in the ping reply.
24    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
38/// `None` means the automatic status.
39pub(crate) type PingHandler = Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>;
40
41/// What the last ping reported.
42#[derive(Clone, Copy)]
43struct Last {
44    status: PingStatus,
45    /// The Unix seconds of the last change of the status.
46    changed: u64,
47    /// Whether the status came from the custom handler.
48    custom: bool,
49}
50
51/// The status of the last ping and the time when it last changed.
52#[derive(Clone)]
53pub(crate) struct PingState {
54    handler: Option<PingHandler>,
55    tasks: AsyncTasks,
56    last: Arc<Mutex<Last>>,
57    // Whether the last call of the custom handler panicked.
58    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    /// The result of the custom handler. `None` when there is no handler, when it
69    /// leaves the status to the registry, and when it panics.
70    fn custom(&self) -> Option<PingStatus> {
71        // The custom handler is user code. It runs before the lock is taken.
72        let handler = self.handler.as_ref()?;
73        let outcome = catch_unwind(AssertUnwindSafe(|| handler()));
74        // The service pings a session every two seconds. One line is written when
75        // the handler starts to panic and one when it returns again.
76        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    /// The status now and the Unix time in seconds of its last change. The time
88    /// must not move while the status stays the same: the service reads it to find
89    /// out how long a session has been idle.
90    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                // The automatic status changed when the registry changed, which can be
104                // long before this ping. After a status of the custom handler the
105                // time is the time of this ping: the service saw that status at the
106                // ping before, which can be later than the change of the registry.
107                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            // Work that started and ended between two pings changed the status twice.
112            // No ping saw it, and the session was still not idle during that time.
113            last.changed = last.changed.max(tasks_changed.unwrap_or(0));
114            (previous, (last.status, last.changed))
115        };
116        // On AgentCore Runtime only the service can call /ping. This line tells a
117        // developer why a session was kept. It is written after the lock is released.
118        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}