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
use std::future::Future;
use std::sync::Arc;

use crate::error::{AcceptError, CommitError, PrepareError};
use crate::node::{CoordNumOf, RoundNumOf, StateOf};
use crate::state::{LogEntryIdOf, LogEntryOf};
use crate::{CoordNum, Promise, RoundNum, State};

use super::state_keeper::StateKeeperHandle;

pub type RequestHandlerFor<N> = RequestHandler<StateOf<N>, RoundNumOf<N>, CoordNumOf<N>>;

/// Used by [`Communicator`][crate::communicator::Communicator]s to prepare
/// replies.
#[derive(Debug)]
pub struct RequestHandler<S: State, R: RoundNum, C: CoordNum>(StateKeeperHandle<S, R, C>);

impl<S: State, R: RoundNum, C: CoordNum> RequestHandler<S, R, C> {
    pub(crate) fn new(state_keeper: StateKeeperHandle<S, R, C>) -> Self {
        Self(state_keeper)
    }

    /// Asks this node to answer a `send_prepare` sent by another node.
    pub fn handle_prepare(
        &self,
        round_num: R,
        coord_num: C,
    ) -> impl Future<Output = Result<Promise<R, C, LogEntryOf<S>>, PrepareError<S, C>>> {
        let handle = self.0.clone();
        async move { handle.handle_prepare(round_num, coord_num).await }
    }

    /// Asks this node to answer a `send_proposal` sent by another node.
    pub fn handle_proposal<I: Into<Arc<LogEntryOf<S>>>>(
        &self,
        round_num: R,
        coord_num: C,
        entry: I,
    ) -> impl Future<Output = Result<(), AcceptError<S, C>>> {
        let handle = self.0.clone();
        async move { handle.handle_proposal(round_num, coord_num, entry).await }
    }

    /// Asks this node to commit the given log entry for the given round number.
    pub fn handle_commit<I: Into<Arc<LogEntryOf<S>>>>(
        &self,
        round_num: R,
        coord_num: C,
        entry: I,
    ) -> impl Future<Output = Result<(), CommitError<S>>> {
        self.0.handle_commit(round_num, coord_num, entry)
    }

    /// Asks this node to answer a `send_commit_by_id` sent by another node.
    pub fn handle_commit_by_id(
        &self,
        round_num: R,
        coord_num: C,
        entry_id: LogEntryIdOf<S>,
    ) -> impl Future<Output = Result<(), CommitError<S>>> {
        let handle = self.0.clone();
        async move {
            handle
                .handle_commit_by_id(round_num, coord_num, entry_id)
                .await
        }
    }
}