openraft/runtime/mod.rs
1use openraft_macros::add_async_trait;
2
3use crate::engine::Command;
4use crate::RaftTypeConfig;
5use crate::StorageError;
6
7/// Defines behaviors of a runtime to support the protocol engine.
8///
9/// An Engine defines the consensus algorithm, i.e., what to do(`command`) when some `event`
10/// happens:
11///
12/// It receives events such as `write-log-entry` from a client,
13/// or `elect` from a timer, and outputs `command`, such as
14/// `append-entry-to-storage`, or `commit-entry-at-index-5` to a runtime to execute.
15///
16/// A `RaftRuntime` talks to `RaftStorage` and `RaftNetwork` to get things done.
17///
18/// The workflow of writing something through raft protocol with engine and runtime would be like
19/// this:
20///
21/// ```text
22/// Client Engine Runtime Storage Netwoork
23/// | | write x=1 | | |
24/// |-------------------------------------------------------->| | |
25/// | event:write | | | |
26/// | .------------------------------------------------| | |
27/// | '--------------->| | | |
28/// | | cmd:append-log-1 | | |
29/// | |--+--------------------------->| append | |
30/// | | | |----------->| |
31/// | | | |<-----------| |
32/// | | | cmd:replicate-log-1 | ok | |
33/// | | '--------------------------->| | |
34/// | | | | send |
35/// | | |------------------------>|
36/// | | | | send |
37/// | | |------------------------>|
38/// | | | | |
39/// | | |<------------------------|
40/// | event:ok | | ok | |
41/// | .------------------------------------------------| | |
42/// | '--------------->| | | |
43/// | | |<------------------------|
44/// | event:ok | | ok | |
45/// | .------------------------------------------------| | |
46/// | '--------------->| | | |
47/// | | cmd:commit-log-1 | | |
48/// | |------------------------------>| | |
49/// | | cmd:apply-log-1 | | |
50/// | |------------------------------>| | |
51/// | | | apply | |
52/// | | |----------->| |
53/// | | |<-----------| |
54/// | | | ok | |
55/// |<--------------------------------------------------------| | |
56/// | response | | | |
57/// ```
58///
59/// TODO: add this diagram to guides/
60#[add_async_trait]
61pub(crate) trait RaftRuntime<C: RaftTypeConfig> {
62 /// Run a command produced by the engine.
63 ///
64 /// If a command can not be run, i.e., waiting for some event, it will be returned
65 async fn run_command(&mut self, cmd: Command<C>) -> Result<Option<Command<C>>, StorageError<C::NodeId>>;
66}