use std::future::Future;
use std::sync::Arc;
use futures::FutureExt;
use tokio::task::JoinHandle;
use tracing::Instrument;
use crate::context::InvocationContext;
use crate::fiber;
#[derive(Debug, Default)]
pub struct Teardowns {
tasks: parking_lot::Mutex<Vec<JoinHandle<()>>>,
}
impl Teardowns {
pub fn new() -> Self {
Self::default()
}
pub fn register(&self, task: JoinHandle<()>) {
let mut tasks = self.tasks.lock();
tasks.retain_mut(|h| {
if !h.is_finished() {
return true;
}
if let Some(Err(e)) = h.now_or_never()
&& e.is_panic()
{
tracing::warn!("adk: a teardown task panicked");
}
false
});
tasks.push(task);
}
pub async fn wait(&self) {
loop {
let next = self.tasks.lock().pop();
let Some(task) = next else { return };
if let Err(e) = task.await
&& e.is_panic()
{
tracing::warn!("adk: a teardown task panicked");
}
}
}
pub fn is_empty(&self) -> bool {
self.tasks.lock().is_empty()
}
}
impl InvocationContext {
pub fn teardowns(&self) -> Option<Arc<Teardowns>> {
self.inner().shared.teardowns.clone()
}
pub fn register_teardown(&self, task: JoinHandle<()>) {
if let Some(t) = self.teardowns() {
t.register(task);
}
}
pub fn spawn_teardown<F>(&self, work: F)
where
F: Future<Output = ()> + Send + 'static,
{
let Ok(handle) = tokio::runtime::Handle::try_current() else {
return;
};
let task = handle.spawn(fiber::current().scope(work).in_current_span());
self.register_teardown(task);
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::context::{ContextDelta, InvocationContext};
use super::Teardowns;
#[tokio::test]
async fn register_drops_finished_tasks() {
let reg = Teardowns::new();
let done = tokio::spawn(async {});
while !done.is_finished() {
tokio::task::yield_now().await;
}
reg.register(done);
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
reg.register(tokio::spawn(async move {
let _ = rx.await;
}));
assert_eq!(reg.tasks.lock().len(), 1, "the finished task was pruned");
let _ = tx.send(());
reg.wait().await;
assert!(reg.is_empty());
}
#[tokio::test]
async fn wait_awaits_tasks_registered_while_waiting() {
let reg = Arc::new(Teardowns::new());
let ctx = InvocationContext::builder()
.teardowns(reg.clone())
.build_invocation();
let done = Arc::new(AtomicUsize::new(0));
let (inner_ctx, d) = (ctx.clone(), done.clone());
ctx.spawn_teardown(async move {
tokio::task::yield_now().await;
let d2 = d.clone();
inner_ctx.spawn_teardown(async move {
tokio::task::yield_now().await;
d2.fetch_add(1, Ordering::SeqCst);
});
d.fetch_add(1, Ordering::SeqCst);
});
reg.wait().await;
assert_eq!(done.load(Ordering::SeqCst), 2);
assert!(reg.is_empty());
}
#[tokio::test]
async fn every_derived_context_shares_the_registry() {
let reg = Arc::new(Teardowns::new());
let ctx = InvocationContext::builder()
.teardowns(reg.clone())
.build_invocation();
let derived = ctx.with_delta(ContextDelta {
fresh_invocation: true,
..Default::default()
});
assert!(Arc::ptr_eq(&derived.teardowns().unwrap(), ®));
let (scoped, _guard) = ctx.clone().into_context().with_agent_cancel();
assert!(Arc::ptr_eq(&scoped.teardowns().unwrap(), ®));
}
#[tokio::test]
async fn without_a_registry_the_work_is_detached_and_still_runs() {
let ctx = InvocationContext::builder().build_invocation();
assert!(ctx.teardowns().is_none());
let (tx, rx) = tokio::sync::oneshot::channel();
ctx.spawn_teardown(async move {
let _ = tx.send(());
});
rx.await.unwrap();
}
}