Skip to main content

bedrock_agentcore/
tasks.rs

1//! Tracking of background work for health reporting.
2//!
3//! AgentCore Runtime asks the agent for its health through `GET /ping`. While the
4//! agent answers `HealthyBusy`, the service does not end the session for being idle.
5//! [`AsyncTasks`] records the work that should keep a session alive after the
6//! invocation that started it has returned.
7//!
8//! Tracking does not run, cancel or wait for the work. It only counts it.
9//! [`AsyncTasks::tracked`] ties the count to the work itself, so that it follows the
10//! real lifetime of the work:
11//!
12//! ```
13//! # use bedrock_agentcore::{RequestContext, context};
14//! # async fn long_job() {}
15//! # async fn handler(ctx: RequestContext) {
16//! // The task is registered here, before it is scheduled.
17//! let job = ctx.tasks().tracked("long job", long_job());
18//! tokio::spawn(context::scope(ctx.clone(), job));
19//! # }
20//! ```
21//!
22//! [`AsyncTasks::track`] returns the [`TaskGuard`] for work that is not one future.
23//! Bind the guard to a name inside the work: `let _guard = guard;`. The pattern
24//! `let _ = guard;` does not move the guard into a `move` block, so the guard stays
25//! in the handler and the work is not tracked.
26//!
27//! `context::scope` carries the request context into the task, not the tracing span.
28//! To keep the request ID and session ID on the task's log lines, also attach the
29//! span, for example with `tracing::Instrument::in_current_span`. The example
30//! `examples/background.rs` shows both.
31//!
32//! A guard that stays in the handler is dropped when the handler returns, and the
33//! agent reports idle while the work still runs. The same rule holds for blocking
34//! work: move the guard into the closure given to `tokio::task::spawn_blocking`,
35//! because a blocking closure that has started cannot be cancelled.
36
37use std::{
38    collections::HashMap,
39    fmt,
40    sync::{
41        Arc, Mutex, MutexGuard, PoisonError,
42        atomic::{AtomicU64, Ordering},
43    },
44    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
45};
46
47pub(crate) fn unix_seconds() -> u64 {
48    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_secs())
49}
50
51/// Identifies one tracked task of an [`AsyncTasks`] registry.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub struct TaskId(u64);
54
55impl fmt::Display for TaskId {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        self.0.fmt(f)
58    }
59}
60
61/// The registry of background work of one app. Clones share the same registry.
62#[derive(Clone, Default)]
63pub struct AsyncTasks {
64    inner: Arc<Inner>,
65}
66
67#[derive(Default)]
68struct Inner {
69    next_id: AtomicU64,
70    active: Mutex<HashMap<TaskId, Entry>>,
71    /// Unix seconds of the last change between no active task and some. Written
72    /// while `active` is locked.
73    changed: AtomicU64,
74}
75
76struct Entry {
77    name: String,
78    started: Instant,
79}
80
81impl AsyncTasks {
82    /// An empty registry. The runtime server creates one for each app.
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// The lock is held only for map operations, never across user code. A panic
88    /// cannot leave the map in a broken state, so a poisoned lock is still usable.
89    fn active(&self) -> MutexGuard<'_, HashMap<TaskId, Entry>> {
90        self.inner.active.lock().unwrap_or_else(PoisonError::into_inner)
91    }
92
93    /// Registers a task. It stays active until [`complete`](Self::complete) is called
94    /// with the returned ID. Prefer [`tracked`](Self::tracked) or
95    /// [`track`](Self::track), which cannot be forgotten.
96    #[must_use = "pass this ID to complete(), or the task stays active"]
97    pub fn add(&self, name: impl Into<String>) -> TaskId {
98        // The conversion is the caller's code. It runs before the lock is taken.
99        let entry = Entry { name: name.into(), started: Instant::now() };
100        let id = TaskId(self.inner.next_id.fetch_add(1, Ordering::Relaxed));
101        let mut active = self.active();
102        active.insert(id, entry);
103        if active.len() == 1 {
104            self.inner.changed.store(unix_seconds(), Ordering::Relaxed);
105        }
106        id
107    }
108
109    /// Marks a task as finished. Returns `false` when the task is not active, for
110    /// example because it was completed before.
111    pub fn complete(&self, id: TaskId) -> bool {
112        let mut active = self.active();
113        let removed = active.remove(&id).is_some();
114        if removed && active.is_empty() {
115            self.inner.changed.store(unix_seconds(), Ordering::Relaxed);
116        }
117        removed
118    }
119
120    /// The number of active tasks, and the Unix seconds of the last change between
121    /// no active task and some. The time is 0 when no task was ever registered.
122    #[cfg(feature = "runtime")]
123    pub(crate) fn activity(&self) -> (usize, u64) {
124        let active = self.active();
125        (active.len(), self.inner.changed.load(Ordering::Relaxed))
126    }
127
128    /// Registers a task that stays active until the returned guard is dropped.
129    pub fn track(&self, name: impl Into<String>) -> TaskGuard {
130        TaskGuard { tasks: self.clone(), id: self.add(name) }
131    }
132
133    /// Registers a task now and returns `future` with the task tied to it. The task
134    /// stays active until the returned future completes, panics or is dropped.
135    pub fn tracked<N, F>(&self, name: N, future: F) -> impl Future<Output = F::Output> + use<N, F>
136    where
137        N: Into<String>,
138        F: Future,
139    {
140        let guard = self.track(name);
141        async move {
142            let _guard = guard;
143            future.await
144        }
145    }
146
147    /// The number of active tasks.
148    pub fn active_count(&self) -> usize {
149        self.active().len()
150    }
151
152    /// The active tasks and how long each one has been running.
153    pub fn info(&self) -> TaskInfo {
154        let now = Instant::now();
155        let mut running: Vec<RunningTask> = self
156            .active()
157            .iter()
158            .map(|(id, entry)| RunningTask { id: *id, name: entry.name.clone(), duration: now - entry.started })
159            .collect();
160        running.sort_by_key(|task| task.id.0);
161        TaskInfo { running }
162    }
163}
164
165impl fmt::Debug for AsyncTasks {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("AsyncTasks").field("active_count", &self.active_count()).finish()
168    }
169}
170
171/// Keeps one task active in an [`AsyncTasks`] registry. Dropping the guard completes
172/// the task. The guard cannot be cloned, so one task is completed once.
173#[must_use = "the task is completed as soon as the guard is dropped"]
174#[derive(Debug)]
175pub struct TaskGuard {
176    tasks: AsyncTasks,
177    id: TaskId,
178}
179
180impl TaskGuard {
181    /// The ID of the tracked task.
182    pub fn id(&self) -> TaskId {
183        self.id
184    }
185}
186
187impl Drop for TaskGuard {
188    fn drop(&mut self) {
189        self.tasks.complete(self.id);
190    }
191}
192
193/// A snapshot of the active tasks, from [`AsyncTasks::info`].
194#[derive(Clone, Debug)]
195pub struct TaskInfo {
196    running: Vec<RunningTask>,
197}
198
199impl TaskInfo {
200    /// The number of active tasks.
201    pub fn active_count(&self) -> usize {
202        self.running.len()
203    }
204
205    /// The active tasks in the order they were registered.
206    pub fn running(&self) -> &[RunningTask] {
207        &self.running
208    }
209}
210
211/// One active task in a [`TaskInfo`].
212#[derive(Clone, Debug)]
213pub struct RunningTask {
214    id: TaskId,
215    name: String,
216    duration: Duration,
217}
218
219impl RunningTask {
220    /// The ID of the task.
221    pub fn id(&self) -> TaskId {
222        self.id
223    }
224
225    /// The name given when the task was registered.
226    pub fn name(&self) -> &str {
227        &self.name
228    }
229
230    /// How long the task had been active when the snapshot was taken.
231    pub fn duration(&self) -> Duration {
232        self.duration
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    fn names(tasks: &AsyncTasks) -> Vec<String> {
241        tasks.info().running().iter().map(|task| task.name().to_owned()).collect()
242    }
243
244    #[test]
245    fn tasks_are_active_until_completed_once_or_their_guard_is_dropped() {
246        let tasks = AsyncTasks::new();
247        let first = tasks.add("first");
248        let guard = tasks.track("second");
249        let shared = tasks.clone();
250        assert_ne!(first, guard.id());
251        assert_eq!((shared.active_count(), names(&tasks)), (2, vec!["first".to_owned(), "second".to_owned()]));
252        std::thread::sleep(Duration::from_millis(20));
253        assert!(tasks.info().running().iter().all(|task| task.duration() >= Duration::from_millis(20)));
254
255        assert!(tasks.complete(first));
256        assert!(!tasks.complete(first), "a second completion finds nothing");
257        assert_eq!(names(&tasks), ["second"]);
258
259        // Completing by ID and then dropping the guard completes the task once.
260        assert!(tasks.complete(guard.id()));
261        drop(guard);
262        assert_eq!(tasks.info().active_count(), 0);
263    }
264
265    /// A task name whose conversion reads the registry. The conversion fails at once,
266    /// without a deadlock, if the registry calls it with its lock held.
267    struct CountsTasks(AsyncTasks);
268
269    impl From<CountsTasks> for String {
270        fn from(name: CountsTasks) -> Self {
271            let active = name.0.inner.active.try_lock().expect("the registry lock is held during the name conversion");
272            format!("task number {}", active.len() + 1)
273        }
274    }
275
276    #[test]
277    fn name_conversion_runs_outside_the_registry_lock() {
278        let tasks = AsyncTasks::new();
279        let _first = tasks.track(CountsTasks(tasks.clone()));
280        let _second = tasks.add(CountsTasks(tasks.clone()));
281        assert_eq!(names(&tasks), ["task number 1", "task number 2"]);
282    }
283
284    #[test]
285    fn guard_completes_its_task_when_the_owner_unwinds() {
286        let tasks = AsyncTasks::new();
287        let guard = tasks.track("panics");
288        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
289            let _guard = guard;
290            panic!("the work failed");
291        }));
292        assert!(unwound.is_err());
293        assert_eq!(tasks.active_count(), 0);
294    }
295
296    #[tokio::test]
297    async fn guard_follows_spawned_work_through_completion_cancellation_and_blocking() {
298        let tasks = AsyncTasks::new();
299        let (release, gate) = tokio::sync::oneshot::channel::<()>();
300
301        // Finishes by itself. `tracked` registers the task before the work is scheduled.
302        let finishes = tokio::spawn(tasks.tracked("finishes", async move {
303            let _ = gate.await;
304        }));
305        // Is cancelled before its first poll: this runtime has one thread and the
306        // test does not yield before the abort.
307        let cancelled = tokio::spawn(tasks.tracked("cancelled", std::future::pending::<()>()));
308        // Blocking work outlives the async task that started it.
309        let guard = tasks.track("blocking");
310        let (unblock, blocked) = std::sync::mpsc::channel::<()>();
311        let blocking = tokio::task::spawn_blocking(move || {
312            let _guard = guard;
313            let _ = blocked.recv();
314        });
315        assert_eq!(tasks.active_count(), 3);
316
317        cancelled.abort();
318        assert!(cancelled.await.unwrap_err().is_cancelled());
319        assert_eq!(names(&tasks), ["finishes", "blocking"]);
320
321        release.send(()).unwrap();
322        finishes.await.unwrap();
323        assert_eq!(names(&tasks), ["blocking"]);
324
325        unblock.send(()).unwrap();
326        blocking.await.unwrap();
327        assert_eq!(tasks.active_count(), 0);
328    }
329}