bee_runtime/
worker.rs

1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4//! A module that deals with asynchronous workers in general.
5
6use std::any::{Any, TypeId};
7
8use async_trait::async_trait;
9
10use crate::node::Node;
11
12/// Errors that might occur during the lifetime of asynchronous workers.
13#[derive(Debug)]
14pub struct Error(pub Box<dyn std::error::Error + Send>);
15
16impl std::fmt::Display for Error {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        write!(f, "worker error: {:?}.", self.0)
19    }
20}
21
22impl std::error::Error for Error {
23    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
24        self.0.source()
25    }
26}
27
28/// A trait representing a node worker.
29///
30/// Node workers are conceptually similar to actors in the actor programming model, but differ slightly in a number of
31/// crucial ways.
32///
33/// - Workers may register and access shared state, known as 'resources'.
34/// - Workers have a topological ordering that determine when they should be started and stopped.
35#[async_trait]
36pub trait Worker<N: Node>: Any + Send + Sync + Sized {
37    /// The configuration state required to start this worker.
38    type Config;
39    /// An error that may be emitted during node startup and shutdown.
40    type Error: std::error::Error;
41
42    /// Generate a list of `TypeId`s representing the topological worker dependencies of this worker.
43    ///
44    /// Workers listed will be started before this worker and shut down after this worker.
45    // TODO Replace with associated constant when stabilized.
46    fn dependencies() -> &'static [TypeId] {
47        &[]
48    }
49
50    /// Attempt to instantiate this worker with the given node and worker configuration.
51    async fn start(node: &mut N, config: Self::Config) -> Result<Self, Self::Error>;
52
53    /// Attempt to stop an instance of this worker.
54    async fn stop(self, _node: &mut N) -> Result<(), Self::Error> {
55        Ok(())
56    }
57}