1// Copyright (C) 2024 Huawei Device Co., Ltd.
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6//     http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14//! ipc async impl
15
16mod ipc_ylong;
17
18use std::future::Future;
19use std::pin::Pin;
20
21pub use ipc_ylong::{Runtime, Ylong};
22use ylong_runtime::task::JoinHandle;
23
24use crate::errors::IpcResult;
25
26/// A type alias for a pinned, boxed future that lets you write shorter code
27/// without littering it with Pin and Send bounds.
28pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
29
30/// A thread pool for running ipc transactions.
31pub trait IpcAsyncPool {
32    /// This function should conceptually behave like this:
33    ///
34    /// ```text
35    /// let result = spawn(spawn, after_handle).await;
36    /// ```
37    fn spawn<'a, F1, F2, Fut, A, B>(
38        spawn_this: F1,
39        after_handle: F2,
40    ) -> BoxFuture<'a, IpcResult<B>>
41    where
42        F1: FnOnce() -> A,
43        F2: FnOnce(A) -> Fut,
44        Fut: Future<Output = IpcResult<B>>,
45        F1: Send + 'static,
46        F2: Send + 'a,
47        Fut: Send + 'a,
48        A: Send + 'static,
49        B: Send + 'a;
50}
51
52/// A runtime for executing an async ipc server.
53pub trait IpcAsyncRuntime {
54    /// Using the default task setting, spawns a task onto the global runtime.
55    fn spawn<T, R>(task: T) -> JoinHandle<R>
56    where
57        T: Future<Output = R>,
58        T: Send + 'static,
59        R: Send + 'static;
60
61    /// Using the default task setting, spawns a blocking task.
62    fn spawn_blocking<T, R>(task: T) -> JoinHandle<R>
63    where
64        T: FnOnce() -> R,
65        T: Send + 'static,
66        R: Send + 'static;
67
68    /// Block on the provided future, running it to completion and returning its
69    /// output.
70    fn block_on<F: Future>(future: F) -> F::Output;
71}
72