bedrock_agentcore/
tasks.rs1use 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#[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#[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 changed: AtomicU64,
74}
75
76struct Entry {
77 name: String,
78 started: Instant,
79}
80
81impl AsyncTasks {
82 pub fn new() -> Self {
84 Self::default()
85 }
86
87 fn active(&self) -> MutexGuard<'_, HashMap<TaskId, Entry>> {
90 self.inner.active.lock().unwrap_or_else(PoisonError::into_inner)
91 }
92
93 #[must_use = "pass this ID to complete(), or the task stays active"]
97 pub fn add(&self, name: impl Into<String>) -> TaskId {
98 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 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 #[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 pub fn track(&self, name: impl Into<String>) -> TaskGuard {
130 TaskGuard { tasks: self.clone(), id: self.add(name) }
131 }
132
133 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 pub fn active_count(&self) -> usize {
149 self.active().len()
150 }
151
152 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#[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 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#[derive(Clone, Debug)]
195pub struct TaskInfo {
196 running: Vec<RunningTask>,
197}
198
199impl TaskInfo {
200 pub fn active_count(&self) -> usize {
202 self.running.len()
203 }
204
205 pub fn running(&self) -> &[RunningTask] {
207 &self.running
208 }
209}
210
211#[derive(Clone, Debug)]
213pub struct RunningTask {
214 id: TaskId,
215 name: String,
216 duration: Duration,
217}
218
219impl RunningTask {
220 pub fn id(&self) -> TaskId {
222 self.id
223 }
224
225 pub fn name(&self) -> &str {
227 &self.name
228 }
229
230 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 assert!(tasks.complete(guard.id()));
261 drop(guard);
262 assert_eq!(tasks.info().active_count(), 0);
263 }
264
265 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 let finishes = tokio::spawn(tasks.tracked("finishes", async move {
303 let _ = gate.await;
304 }));
305 let cancelled = tokio::spawn(tasks.tracked("cancelled", std::future::pending::<()>()));
308 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}