Skip to main content

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::{fmt::Debug, 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    /// Register a callback to be invoked when this token is cancelled.
47    /// If this token is already cancelled, the callback is invoked immediately.
48    ///
49    /// # Panics (debug builds only)
50    /// Panics if a callback has already been registered.
51    fn on_cancel(&self, callback: Box<dyn FnOnce() + Send + Sync>);
52
53    /// Clone the cancel token.
54    /// Because the dyn requirement, CancelToken cannot be cloned directly.
55    fn clone_box(&self) -> Box<dyn CancelToken>;
56}
57
58pub type BoxedCancelToken = Box<dyn CancelToken>;
59
60impl Clone for BoxedCancelToken {
61    fn clone(&self) -> Self {
62        self.clone_box()
63    }
64}
65
66impl Debug for dyn CancelToken {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("CancelToken")
69            .field("cancelled", &self.is_cancelled())
70            .finish()
71    }
72}