Skip to main content

gadk_platform/
exec.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use futures::future::BoxFuture;
17use tokio::task::JoinSet;
18
19/// Runs all tasks and returns after all complete.
20///
21/// Contract for implementations:
22/// - the future returned by [`run`](Self::run) must not complete before every task has
23///   completed;
24/// - dropping that future before it completes cancels the tasks that are still running
25///   (Rust cancellation): no task may outlive the call that started it.
26#[async_trait::async_trait]
27pub trait TaskRunner: Send + Sync {
28    /// Runs every task and returns once all of them have completed. Dropping the returned
29    /// future cancels the tasks still running.
30    async fn run(&self, tasks: Vec<BoxFuture<'static, ()>>);
31}
32
33/// Default runner: one tokio task per future, held in a [`JoinSet`] so that dropping the
34/// `run` future aborts them. A task panic aborts the remaining tasks, waits for them to
35/// stop, and is then re-raised on the caller.
36pub struct TokioTaskRunner;
37
38#[async_trait::async_trait]
39impl TaskRunner for TokioTaskRunner {
40    async fn run(&self, tasks: Vec<BoxFuture<'static, ()>>) {
41        let mut set = JoinSet::new();
42        for t in tasks {
43            set.spawn(t);
44        }
45        while let Some(res) = set.join_next().await {
46            if let Err(e) = res
47                && e.is_panic()
48            {
49                set.abort_all();
50                // Wait for the aborted siblings to stop before re-raising.
51                while set.join_next().await.is_some() {}
52                std::panic::resume_unwind(e.into_panic());
53            }
54        }
55    }
56}