1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//! Defines the [`Executor`] trait and its [default implementation][StdThread].

use futures::FutureExt;

/// Shorthand to extract `Error` type out of `E`.
pub type ErrorOf<E> = <E as Executor>::Error;

/// The executor used to run the code which applies log entries to the `State`.
pub trait Executor: 'static {
    /// Type of error yielded when a task cannot be executed.
    type Error;

    /// Executes the given task.
    fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
        self,
        task: F,
    ) -> Result<(), Self::Error>;
}

impl<S: futures::task::Spawn + 'static> Executor for S {
    type Error = futures::task::SpawnError;

    fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
        self,
        task: F,
    ) -> Result<(), Self::Error> {
        self.spawn_obj(futures::task::FutureObj::from(task.boxed()))
    }
}

/// Executor which spawns a new thread for each task.
pub struct StdThread;

impl Default for StdThread {
    fn default() -> Self {
        Self
    }
}

impl Executor for StdThread {
    type Error = std::io::Error;

    fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
        self,
        task: F,
    ) -> Result<(), Self::Error> {
        let thread_buidler = std::thread::Builder::new();

        thread_buidler
            .spawn(|| {
                futures::executor::block_on(task);
            })
            .map(|_| ())
    }
}

/// Executor that delegates to `wasm_bindgen_futures::spawn_local`.
#[cfg(feature = "wasm-bindgen-futures")]
pub struct WasmExecutor;

#[cfg(feature = "wasm-bindgen-futures")]
impl Executor for WasmExecutor {
    type Error = ();

    fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
        self,
        task: F,
    ) -> Result<(), Self::Error> {
        wasm_bindgen_futures::spawn_local(task);

        Ok(())
    }
}