bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
//! Tracking of background work for health reporting.
//!
//! AgentCore Runtime asks the agent for its health through `GET /ping`. While the
//! agent answers `HealthyBusy`, the service does not end the session for being idle.
//! [`AsyncTasks`] records the work that should keep a session alive after the
//! invocation that started it has returned.
//!
//! Tracking does not run, cancel or wait for the work. It only counts it.
//! [`AsyncTasks::tracked`] ties the count to the work itself, so that it follows the
//! real lifetime of the work:
//!
//! ```
//! # use bedrock_agentcore::{RequestContext, context};
//! # async fn long_job() {}
//! # async fn handler(ctx: RequestContext) {
//! // The task is registered here, before it is scheduled.
//! let job = ctx.tasks().tracked("long job", long_job());
//! tokio::spawn(context::scope(ctx.clone(), job));
//! # }
//! ```
//!
//! [`AsyncTasks::track`] returns the [`TaskGuard`] for work that is not one future.
//! Bind the guard to a name inside the work: `let _guard = guard;`. The pattern
//! `let _ = guard;` does not move the guard into a `move` block, so the guard stays
//! in the handler and the work is not tracked.
//!
//! `context::scope` carries the request context into the task, not the tracing span.
//! To keep the request ID and session ID on the task's log lines, also attach the
//! span, for example with `tracing::Instrument::in_current_span`. The example
//! `examples/background.rs` shows both.
//!
//! A guard that stays in the handler is dropped when the handler returns, and the
//! agent reports idle while the work still runs. The same rule holds for blocking
//! work: move the guard into the closure given to `tokio::task::spawn_blocking`,
//! because a blocking closure that has started cannot be cancelled.

use std::{
    collections::HashMap,
    fmt,
    sync::{
        Arc, Mutex, MutexGuard, PoisonError,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

pub(crate) fn unix_seconds() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_secs())
}

/// Identifies one tracked task of an [`AsyncTasks`] registry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TaskId(u64);

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

/// The registry of background work of one app. Clones share the same registry.
#[derive(Clone, Default)]
pub struct AsyncTasks {
    inner: Arc<Inner>,
}

#[derive(Default)]
struct Inner {
    next_id: AtomicU64,
    active: Mutex<HashMap<TaskId, Entry>>,
    /// Unix seconds of the last change between no active task and some. Written
    /// while `active` is locked.
    changed: AtomicU64,
}

struct Entry {
    name: String,
    started: Instant,
}

impl AsyncTasks {
    /// An empty registry. The runtime server creates one for each app.
    pub fn new() -> Self {
        Self::default()
    }

    /// The lock is held only for map operations, never across user code. A panic
    /// cannot leave the map in a broken state, so a poisoned lock is still usable.
    fn active(&self) -> MutexGuard<'_, HashMap<TaskId, Entry>> {
        self.inner.active.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Registers a task. It stays active until [`complete`](Self::complete) is called
    /// with the returned ID. Prefer [`tracked`](Self::tracked) or
    /// [`track`](Self::track), which cannot be forgotten.
    #[must_use = "pass this ID to complete(), or the task stays active"]
    pub fn add(&self, name: impl Into<String>) -> TaskId {
        // The conversion is the caller's code. It runs before the lock is taken.
        let entry = Entry { name: name.into(), started: Instant::now() };
        let id = TaskId(self.inner.next_id.fetch_add(1, Ordering::Relaxed));
        let mut active = self.active();
        active.insert(id, entry);
        if active.len() == 1 {
            self.inner.changed.store(unix_seconds(), Ordering::Relaxed);
        }
        id
    }

    /// Marks a task as finished. Returns `false` when the task is not active, for
    /// example because it was completed before.
    pub fn complete(&self, id: TaskId) -> bool {
        let mut active = self.active();
        let removed = active.remove(&id).is_some();
        if removed && active.is_empty() {
            self.inner.changed.store(unix_seconds(), Ordering::Relaxed);
        }
        removed
    }

    /// The number of active tasks, and the Unix seconds of the last change between
    /// no active task and some. The time is 0 when no task was ever registered.
    #[cfg(feature = "runtime")]
    pub(crate) fn activity(&self) -> (usize, u64) {
        let active = self.active();
        (active.len(), self.inner.changed.load(Ordering::Relaxed))
    }

    /// Registers a task that stays active until the returned guard is dropped.
    pub fn track(&self, name: impl Into<String>) -> TaskGuard {
        TaskGuard { tasks: self.clone(), id: self.add(name) }
    }

    /// Registers a task now and returns `future` with the task tied to it. The task
    /// stays active until the returned future completes, panics or is dropped.
    pub fn tracked<N, F>(&self, name: N, future: F) -> impl Future<Output = F::Output> + use<N, F>
    where
        N: Into<String>,
        F: Future,
    {
        let guard = self.track(name);
        async move {
            let _guard = guard;
            future.await
        }
    }

    /// The number of active tasks.
    pub fn active_count(&self) -> usize {
        self.active().len()
    }

    /// The active tasks and how long each one has been running.
    pub fn info(&self) -> TaskInfo {
        let now = Instant::now();
        let mut running: Vec<RunningTask> = self
            .active()
            .iter()
            .map(|(id, entry)| RunningTask { id: *id, name: entry.name.clone(), duration: now - entry.started })
            .collect();
        running.sort_by_key(|task| task.id.0);
        TaskInfo { running }
    }
}

impl fmt::Debug for AsyncTasks {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncTasks").field("active_count", &self.active_count()).finish()
    }
}

/// Keeps one task active in an [`AsyncTasks`] registry. Dropping the guard completes
/// the task. The guard cannot be cloned, so one task is completed once.
#[must_use = "the task is completed as soon as the guard is dropped"]
#[derive(Debug)]
pub struct TaskGuard {
    tasks: AsyncTasks,
    id: TaskId,
}

impl TaskGuard {
    /// The ID of the tracked task.
    pub fn id(&self) -> TaskId {
        self.id
    }
}

impl Drop for TaskGuard {
    fn drop(&mut self) {
        self.tasks.complete(self.id);
    }
}

/// A snapshot of the active tasks, from [`AsyncTasks::info`].
#[derive(Clone, Debug)]
pub struct TaskInfo {
    running: Vec<RunningTask>,
}

impl TaskInfo {
    /// The number of active tasks.
    pub fn active_count(&self) -> usize {
        self.running.len()
    }

    /// The active tasks in the order they were registered.
    pub fn running(&self) -> &[RunningTask] {
        &self.running
    }
}

/// One active task in a [`TaskInfo`].
#[derive(Clone, Debug)]
pub struct RunningTask {
    id: TaskId,
    name: String,
    duration: Duration,
}

impl RunningTask {
    /// The ID of the task.
    pub fn id(&self) -> TaskId {
        self.id
    }

    /// The name given when the task was registered.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// How long the task had been active when the snapshot was taken.
    pub fn duration(&self) -> Duration {
        self.duration
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn names(tasks: &AsyncTasks) -> Vec<String> {
        tasks.info().running().iter().map(|task| task.name().to_owned()).collect()
    }

    #[test]
    fn tasks_are_active_until_completed_once_or_their_guard_is_dropped() {
        let tasks = AsyncTasks::new();
        let first = tasks.add("first");
        let guard = tasks.track("second");
        let shared = tasks.clone();
        assert_ne!(first, guard.id());
        assert_eq!((shared.active_count(), names(&tasks)), (2, vec!["first".to_owned(), "second".to_owned()]));
        std::thread::sleep(Duration::from_millis(20));
        assert!(tasks.info().running().iter().all(|task| task.duration() >= Duration::from_millis(20)));

        assert!(tasks.complete(first));
        assert!(!tasks.complete(first), "a second completion finds nothing");
        assert_eq!(names(&tasks), ["second"]);

        // Completing by ID and then dropping the guard completes the task once.
        assert!(tasks.complete(guard.id()));
        drop(guard);
        assert_eq!(tasks.info().active_count(), 0);
    }

    /// A task name whose conversion reads the registry. The conversion fails at once,
    /// without a deadlock, if the registry calls it with its lock held.
    struct CountsTasks(AsyncTasks);

    impl From<CountsTasks> for String {
        fn from(name: CountsTasks) -> Self {
            let active = name.0.inner.active.try_lock().expect("the registry lock is held during the name conversion");
            format!("task number {}", active.len() + 1)
        }
    }

    #[test]
    fn name_conversion_runs_outside_the_registry_lock() {
        let tasks = AsyncTasks::new();
        let _first = tasks.track(CountsTasks(tasks.clone()));
        let _second = tasks.add(CountsTasks(tasks.clone()));
        assert_eq!(names(&tasks), ["task number 1", "task number 2"]);
    }

    #[test]
    fn guard_completes_its_task_when_the_owner_unwinds() {
        let tasks = AsyncTasks::new();
        let guard = tasks.track("panics");
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
            let _guard = guard;
            panic!("the work failed");
        }));
        assert!(unwound.is_err());
        assert_eq!(tasks.active_count(), 0);
    }

    #[tokio::test]
    async fn guard_follows_spawned_work_through_completion_cancellation_and_blocking() {
        let tasks = AsyncTasks::new();
        let (release, gate) = tokio::sync::oneshot::channel::<()>();

        // Finishes by itself. `tracked` registers the task before the work is scheduled.
        let finishes = tokio::spawn(tasks.tracked("finishes", async move {
            let _ = gate.await;
        }));
        // Is cancelled before its first poll: this runtime has one thread and the
        // test does not yield before the abort.
        let cancelled = tokio::spawn(tasks.tracked("cancelled", std::future::pending::<()>()));
        // Blocking work outlives the async task that started it.
        let guard = tasks.track("blocking");
        let (unblock, blocked) = std::sync::mpsc::channel::<()>();
        let blocking = tokio::task::spawn_blocking(move || {
            let _guard = guard;
            let _ = blocked.recv();
        });
        assert_eq!(tasks.active_count(), 3);

        cancelled.abort();
        assert!(cancelled.await.unwrap_err().is_cancelled());
        assert_eq!(names(&tasks), ["finishes", "blocking"]);

        release.send(()).unwrap();
        finishes.await.unwrap();
        assert_eq!(names(&tasks), ["blocking"]);

        unblock.send(()).unwrap();
        blocking.await.unwrap();
        assert_eq!(tasks.active_count(), 0);
    }
}