bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use std::{
    fmt,
    panic::{AssertUnwindSafe, catch_unwind},
    sync::{
        Arc, Mutex, PoisonError,
        atomic::{AtomicBool, Ordering},
    },
};

use super::handler::panic_text;
use crate::tasks::{AsyncTasks, unix_seconds};

/// The health that `GET /ping` reports to AgentCore Runtime.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PingStatus {
    /// The agent is idle. The service may end an idle session.
    Healthy,
    /// The agent is working in the background. The service keeps the session.
    HealthyBusy,
}

impl PingStatus {
    /// The text of the status in the ping reply.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Healthy => "Healthy",
            Self::HealthyBusy => "HealthyBusy",
        }
    }
}

impl fmt::Display for PingStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// `None` means the automatic status.
pub(crate) type PingHandler = Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>;

/// What the last ping reported.
#[derive(Clone, Copy)]
struct Last {
    status: PingStatus,
    /// The Unix seconds of the last change of the status.
    changed: u64,
    /// Whether the status came from the custom handler.
    custom: bool,
}

/// The status of the last ping and the time when it last changed.
#[derive(Clone)]
pub(crate) struct PingState {
    handler: Option<PingHandler>,
    tasks: AsyncTasks,
    last: Arc<Mutex<Last>>,
    // Whether the last call of the custom handler panicked.
    panicking: Arc<AtomicBool>,
}

impl PingState {
    pub(crate) fn new(handler: Option<PingHandler>, tasks: AsyncTasks) -> Self {
        let last = Last { status: PingStatus::Healthy, changed: unix_seconds(), custom: false };
        let last = Arc::new(Mutex::new(last));
        Self { handler, tasks, last, panicking: Arc::default() }
    }

    /// The result of the custom handler. `None` when there is no handler, when it
    /// leaves the status to the registry, and when it panics.
    fn custom(&self) -> Option<PingStatus> {
        // The custom handler is user code. It runs before the lock is taken.
        let handler = self.handler.as_ref()?;
        let outcome = catch_unwind(AssertUnwindSafe(|| handler()));
        // The service pings a session every two seconds. One line is written when
        // the handler starts to panic and one when it returns again.
        match (&outcome, self.panicking.swap(outcome.is_err(), Ordering::Relaxed)) {
            (Err(panic), false) => tracing::warn!(
                panic = panic_text(panic.as_ref()),
                "the custom ping handler panicked, using the automatic status until it returns a status"
            ),
            (Ok(_), true) => tracing::info!("the custom ping handler no longer panics"),
            _ => {}
        }
        outcome.ok().flatten()
    }

    /// The status now and the Unix time in seconds of its last change. The time
    /// must not move while the status stays the same: the service reads it to find
    /// out how long a session has been idle.
    pub(crate) fn current(&self) -> (PingStatus, u64) {
        let (status, tasks_changed) = match self.custom() {
            Some(status) => (status, None),
            None => {
                let (active, changed) = self.tasks.activity();
                (if active > 0 { PingStatus::HealthyBusy } else { PingStatus::Healthy }, Some(changed))
            }
        };

        let (previous, current) = {
            let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
            let previous = last.status;
            if previous != status {
                // The automatic status changed when the registry changed, which can be
                // long before this ping. After a status of the custom handler the
                // time is the time of this ping: the service saw that status at the
                // ping before, which can be later than the change of the registry.
                last.changed = tasks_changed.filter(|_| !last.custom).unwrap_or_else(unix_seconds);
                last.status = status;
            }
            last.custom = tasks_changed.is_none();
            // Work that started and ended between two pings changed the status twice.
            // No ping saw it, and the session was still not idle during that time.
            last.changed = last.changed.max(tasks_changed.unwrap_or(0));
            (previous, (last.status, last.changed))
        };
        // On AgentCore Runtime only the service can call /ping. This line tells a
        // developer why a session was kept. It is written after the lock is released.
        if previous != status {
            let active_tasks = self.tasks.active_count();
            tracing::info!(from = %previous, to = %status, active_tasks, "ping status changed");
        }
        current
    }
}