mssf_core/runtime/executor.rs
1// ------------------------------------------------------------
2// Copyright (c) Microsoft Corporation. All rights reserved.
3// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
4// ------------------------------------------------------------
5
6use std::{future::Future, pin::Pin};
7
8// Executor is used by rs to post jobs to execute in the background
9// Sync is needed due to we use the executor across await boundary.
10pub trait Executor: Clone + Sync + Send + 'static {
11 // Required functions
12
13 /// spawns the task to run in background, and returns a join handle
14 /// where the future's result can be awaited.
15 /// If the future panics, the join handle should return an error code.
16 /// This is primarily used by mssf Bridge to execute user app async callbacks/notifications.
17 /// User app impl future may panic, and mssf propagates panic as an error in JoinHandle
18 /// to SF.
19 fn spawn<F>(&self, future: F)
20 where
21 F: Future + Send + 'static,
22 F::Output: Send;
23}
24
25/// Runtime independent sleep trait.
26pub trait Timer: Send + Sync + 'static {
27 /// Returns a future that is ready after duration.
28 fn sleep(&self, duration: std::time::Duration) -> Pin<Box<dyn EventFuture>>;
29}
30
31/// Runtime independent event future.
32pub trait EventFuture: Send + Future<Output = ()> {}
33
34impl<T> EventFuture for T where T: Future<Output = ()> + Send {}
35
36pub trait CancelToken: Send + Sync + 'static {
37 /// Get a future to wait for cancellation.
38 fn wait(&self) -> Pin<Box<dyn EventFuture>>;
39
40 /// Is the token cancelled
41 fn is_cancelled(&self) -> bool;
42
43 /// Cancel the token.
44 fn cancel(&self);
45
46 /// Clone the cancel token.
47 /// Because the dyn requirement, CancelToken cannot be cloned directly.
48 fn clone_box(&self) -> Box<dyn CancelToken>;
49}
50
51pub type BoxedCancelToken = Box<dyn CancelToken>;
52
53impl Clone for BoxedCancelToken {
54 fn clone(&self) -> Self {
55 self.clone_box()
56 }
57}