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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use std::any::Any;
use std::future::Future;
use std::sync::Arc;

use futures::channel::mpsc;
use futures::channel::oneshot;
use futures::future::BoxFuture;
use futures::future::FutureExt;
use futures::sink::SinkExt;
use futures::TryFutureExt;

use crate::append::AppendArgs;
use crate::append::AppendError;
use crate::applicable::ApplicableTo;
use crate::error::ShutDown;
use crate::error::ShutDownOr;
use crate::invocation::CommitFor;
use crate::invocation::Invocation;
use crate::invocation::LogEntryOf;
use crate::invocation::SnapshotFor;
use crate::invocation::StateOf;
use crate::retry::RetryPolicy;

use super::commits::Commit;
use super::state_keeper::StateKeeperHandle;
use super::Admin;
use super::NodeStatus;

pub type BoxedRetryPolicy<I> = Box<
    dyn RetryPolicy<
            Invocation = I,
            Error = Box<dyn Any + Send>,
            StaticError = Box<dyn Any + Send>,
            Future = BoxFuture<'static, Result<(), Box<dyn Any + Send>>>,
        > + Send,
>;

pub type RequestAndResponseSender<I> =
    (NodeHandleRequest<I>, oneshot::Sender<NodeHandleResponse<I>>);

/// A remote handle for a paxakos [`Node`][crate::Node].
pub struct NodeHandle<I: Invocation> {
    sender: mpsc::Sender<RequestAndResponseSender<I>>,
    state_keeper: StateKeeperHandle<I>,
}

impl<I: Invocation> Clone for NodeHandle<I> {
    fn clone(&self) -> Self {
        Self {
            sender: self.sender.clone(),
            state_keeper: self.state_keeper.clone(),
        }
    }
}

macro_rules! dispatch_node_handle_req {
    ($self:ident, $name:ident) => {{
        let req = NodeHandleRequest::$name;

        let mut sender = $self.sender.clone();
        let (s, r) = oneshot::channel();

        async move {
            let send_res = sender.send((req, s)).await;

            match (send_res, r.await) {
                (Ok(_), Ok(NodeHandleResponse::$name(r))) => Some(r),
                (Err(_), _) | (_, Err(_)) => None,
                _ => unreachable!(),
            }
        }
    }};

    ($self:ident, $name:ident, $args:tt) => {{
        let req = NodeHandleRequest::$name $args;

        let mut sender = $self.sender.clone();
        let (s, r) = oneshot::channel();

        async move {
            let send_res = sender.send((req, s)).await;

            match (send_res, r.await) {
                (Ok(_), Ok(NodeHandleResponse::$name(r))) => Some(r),
                (Err(_), _) | (_, Err(_)) => None,
                _ => unreachable!(),
            }
        }
    }};
}

impl<I: Invocation> NodeHandle<I> {
    pub(crate) fn new(
        sender: mpsc::Sender<RequestAndResponseSender<I>>,
        state_keeper: StateKeeperHandle<I>,
    ) -> Self {
        Self {
            sender,
            state_keeper,
        }
    }

    /// Node's current status.
    pub fn status(&self) -> impl Future<Output = Result<NodeStatus, ShutDown>> {
        dispatch_node_handle_req!(self, Status).map(|r| r.ok_or(ShutDown))
    }

    /// Requests that snapshot of the node's current state be taken.
    pub fn prepare_snapshot(&self) -> impl Future<Output = Result<SnapshotFor<I>, ShutDown>> {
        self.state_keeper.prepare_snapshot()
    }

    /// Affirms that the given snapshot was written to persistent storage.
    ///
    /// Currently does nothing.
    pub fn affirm_snapshot(
        &self,
        snapshot: SnapshotFor<I>,
    ) -> impl Future<Output = Result<(), crate::error::AffirmSnapshotError>> {
        self.state_keeper.affirm_snapshot(snapshot)
    }

    /// Requests that the given snapshot be installed.
    ///
    /// See [`Node::install_snapshot`][crate::Node::install_snapshot].
    pub fn install_snapshot(
        &self,
        snapshot: SnapshotFor<I>,
    ) -> impl Future<Output = Result<(), crate::error::InstallSnapshotError>> {
        self.state_keeper.install_snapshot(snapshot)
    }

    /// Reads the node's current state.
    ///
    /// As the name implies the state may be stale, i.e. other node's may have
    /// advanced the shared state without this node being aware.
    pub fn read_stale<F, T>(
        &self,
        f: F,
    ) -> impl Future<Output = Result<T, crate::error::ReadStaleError>>
    where
        F: FnOnce(&StateOf<I>) -> T + Send + 'static,
        T: Send + 'static,
    {
        self.state_keeper.try_read_stale(f)
    }

    /// Appends `applicable` to the shared log.
    pub fn append<A, P, R>(
        &self,
        applicable: A,
        args: P,
    ) -> impl Future<Output = Result<CommitFor<I, A>, R::StaticError>>
    where
        A: ApplicableTo<StateOf<I>>,
        P: Into<AppendArgs<I, R>>,
        R: RetryPolicy<Invocation = I> + Send + 'static,
        R::Error: Send,
        R::StaticError: From<ShutDownOr<R::Error>>,
        R::Future: Send,
    {
        let args = args.into();
        let args = AppendArgs {
            round: args.round,
            importance: args.importance,
            retry_policy: Box::new(BoxingRetryPolicy::from(args.retry_policy))
                as BoxedRetryPolicy<I>,
        };

        dispatch_node_handle_req!(self, Append, {
            log_entry: applicable.into_log_entry(),
            args,
        })
        .map(|r| match r {
            Some(r) => r
                .map_err(|e| {
                    e.map(|e| *e.downcast::<R::Error>().expect("downcast error"))
                        .into()
                })
                .map(Commit::projected),
            None => Err(ShutDownOr::ShutDown.into()),
        })
    }
}

impl<I: Invocation> Admin for NodeHandle<I> {
    fn force_active(&self) -> futures::future::BoxFuture<'static, Result<bool, ShutDown>> {
        self.state_keeper.force_active().boxed()
    }
}

impl<I: Invocation> std::fmt::Debug for NodeHandle<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "paxakos::NodeHandle")
    }
}

pub enum NodeHandleRequest<I: Invocation> {
    Status,

    Append {
        log_entry: Arc<LogEntryOf<I>>,
        args: AppendArgs<I, BoxedRetryPolicy<I>>,
    },
}

#[derive(Debug)]
pub enum NodeHandleResponse<I: Invocation> {
    Status(NodeStatus),

    Append(Result<CommitFor<I>, ShutDownOr<Box<dyn Any + Send>>>),
}

pub struct BoxingRetryPolicy<R> {
    delegate: R,
}

impl<R> From<R> for BoxingRetryPolicy<R> {
    fn from(delegate: R) -> Self {
        BoxingRetryPolicy { delegate }
    }
}

impl<R> RetryPolicy for BoxingRetryPolicy<R>
where
    R: RetryPolicy + Send,
    R::Error: Send + 'static,
    R::Future: Send,
{
    type Invocation = <R as RetryPolicy>::Invocation;
    type Error = Box<dyn Any + Send>;
    type StaticError = Box<dyn Any + Send>;
    type Future = BoxFuture<'static, Result<(), Self::Error>>;

    fn eval(&mut self, error: AppendError<Self::Invocation>) -> Self::Future {
        self.delegate
            .eval(error)
            .map_err(|err| Box::new(err) as Self::Error)
            .boxed()
    }
}