binder/binder_async.rs
1/*
2 * Copyright (C) 2021 The Android Open Source Project
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 */
16
17use std::future::Future;
18use std::pin::Pin;
19
20/// A type alias for a pinned, boxed future that lets you write shorter code without littering it
21/// with Pin and Send bounds.
22pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
23
24/// A thread pool for running binder transactions.
25pub trait BinderAsyncPool {
26 /// This function should conceptually behave like this:
27 ///
28 /// ```text
29 /// let result = spawn_thread(|| spawn_me()).await;
30 /// return after_spawn(result).await;
31 /// ```
32 ///
33 /// If the spawning fails for some reason, the method may also skip the `after_spawn` closure
34 /// and immediately return an error.
35 ///
36 /// The only difference between different implementations should be which
37 /// `spawn_thread` method is used. For Tokio, it would be `tokio::task::spawn_blocking`.
38 ///
39 /// This method has the design it has because the only way to define a trait that
40 /// allows the return type of the spawn to be chosen by the caller is to return a
41 /// boxed `Future` trait object, and including `after_spawn` in the trait function
42 /// allows the caller to avoid double-boxing if they want to do anything to the value
43 /// returned from the spawned thread.
44 fn spawn<'a, F1, F2, Fut, A, B, E>(
45 spawn_me: F1,
46 after_spawn: F2,
47 ) -> BoxFuture<'a, Result<B, E>>
48 where
49 F1: FnOnce() -> A,
50 F2: FnOnce(A) -> Fut,
51 Fut: Future<Output = Result<B, E>>,
52 F1: Send + 'static,
53 F2: Send + 'a,
54 Fut: Send + 'a,
55 A: Send + 'static,
56 B: Send + 'a,
57 E: From<crate::StatusCode>;
58}
59
60/// A runtime for executing an async binder server.
61pub trait BinderAsyncRuntime {
62 /// Block on the provided future, running it to completion and returning its output.
63 fn block_on<F: Future>(&self, future: F) -> F::Output;
64}