openraft 0.10.2

Advanced Raft consensus
Documentation
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::future::Future;

use anyerror::AnyError;
use futures_util::Stream;
use openraft_macros::add_async_trait;
use openraft_macros::since;

use crate::OptionalSend;
use crate::OptionalSync;
use crate::RaftTypeConfig;
use crate::base::BoxFuture;
use crate::base::BoxStream;
use crate::errors::RPCError;
use crate::errors::ReplicationClosed;
use crate::errors::StreamingError;
use crate::errors::Unreachable;
use crate::network::Backoff;
use crate::network::NetAppend;
use crate::network::RPCOption;
use crate::network::stream_append_sequential;
use crate::raft::AppendEntriesRequest;
use crate::raft::AppendResult;
use crate::raft::SnapshotResponse;
use crate::raft::VoteRequest;
use crate::raft::VoteResponse;
use crate::raft::message::TransferLeaderRequest;
use crate::raft::message::TransferLeaderResponse;
use crate::type_config::alias::SnapshotOf;
use crate::type_config::alias::VoteOf;

/// A trait defining the interface for a Raft network between cluster members.
///
/// **This is the recommended trait for most applications.** It provides a unified interface
/// for all network operations with sensible defaults. Simply implement the required methods
/// (`append_entries`, `vote`, `full_snapshot`) and the sub-traits ([`NetAppend`], [`NetVote`],
/// [`NetSnapshot`], etc.) will be automatically derived via blanket implementations.
///
/// # Design: unary RPCs with streaming compatibility
///
/// `RaftNetworkV2` is designed around **request-response (unary) RPCs** — `append_entries`,
/// `vote`, and `full_snapshot` each send one request and produce one response. When this
/// trait was introduced, it was not designed for stream-oriented AppendEntries.
///
/// It remains **compatible** with the stream-oriented API, however: if an application only
/// implements the unary `append_entries`, Openraft adapts it into a stream by calling it
/// sequentially via the default [`stream_append`](Self::stream_append) implementation
/// (see [`stream_append_sequential`]). This is
/// convenient but not optimal for throughput.
///
/// For true streaming performance while keeping the unified interface, an application can
/// **override the default [`stream_append`](Self::stream_append)** on `RaftNetworkV2` itself
/// with a custom implementation (e.g. native gRPC bidirectional streaming or pipelined
/// AppendEntries) — without giving up the convenience of `RaftNetworkV2` for the other RPCs.
///
/// # Implementing the sub-traits directly
///
/// A network type can implement the sub-traits directly instead of `RaftNetworkV2`. It must
/// implement all of the traits that [`RaftNetworkFactory::Network`] requires:
///
/// - [`NetStreamAppend`] — stream-oriented AppendEntries, used by log replication and heartbeats
/// - [`NetVote`] — RequestVote
/// - [`NetSnapshot`] — full snapshot transfer
/// - [`NetTransferLeader`] — TransferLeader notification
/// - [`NetBackoff`] — backoff strategy on `Unreachable`
///
/// The factory does not require [`NetAppend`], the unary AppendEntries interface. Openraft uses it
/// only in [`stream_append_sequential`], the helper that builds stream-oriented AppendEntries out
/// of unary calls, so implement [`NetAppend`] only to build [`NetStreamAppend`] with that helper.
/// The `raft-kv-memstore-grpc` example streams AppendEntries natively, so it implements only the
/// traits above, with no unary AppendEntries.
///
/// Either approach can provide native streaming: implement [`NetStreamAppend`] directly, or
/// override [`stream_append`](Self::stream_append) as described above, because the blanket
/// [`NetStreamAppend`] implementation forwards to the override. Throughput depends on how
/// `stream_append` sends the requests, not on which trait it is implemented on. Implementing the
/// sub-traits directly lets a network type leave out the unary
/// [`append_entries`](Self::append_entries) that `RaftNetworkV2` requires.
///
/// See the [network chapter of the guide](crate::docs::getting_started#4-implement-raftnetwork)
/// for details and discussion on this trait and how to implement it.
///
/// # RPC timeouts
///
/// Openraft passes [`RPCOption`] to every network method. Network implementations are responsible
/// for applying `RPCOption::soft_ttl()` with transport timeouts, deadlines, keepalives, or
/// reconnect policies.
///
/// Openraft may shut down an in-flight RPC once `RPCOption::hard_ttl()` has elapsed, so network
/// implementations should return timeout errors before the hard limit.
///
/// Votes, pre-votes, heartbeats and `transfer_leader` requests are the exception: Openraft keeps
/// each of them in flight until its call returns, because dropping an RPC in flight cancels it. Log
/// replication, which `hard_ttl()` does not limit, also keeps its requests in flight when it stops.
/// A transport over HTTP/2 resets the stream of a canceled RPC, and a server on the `h2` crate, as
/// tonic's is, closes the connection with `GOAWAY` once more than 20 reset streams, by default,
/// wait for it to accept them, as they do when a stalled server resumes.
///
/// - Openraft sends every vote and pre-vote that an election needs, even while earlier ones to the
///   same target are still in flight. The votes to a target that does not answer thus accumulate,
///   one per election round, until the network fails them.
/// - It sends the `transfer_leader` requests of every leadership transfer, even while those of an
///   earlier transfer are still in flight.
/// - It sends a heartbeat to a target only after the previous one has returned, and keeps it in
///   flight even after the heartbeats to the target stop, such as when the leader steps down. A
///   call that never returns thus stops the heartbeats to its target.
/// - When log replication to a target stops, such as when the leader steps down, it sends no new
///   request on its `stream_append()` call, and polls the call until its output stream ends. A call
///   that never ends thus keeps the network instance of that replication alive.
///
/// A network that needs to bound the RPCs in flight to a target implements that limit itself. To
/// detect a target that stopped answering, prefer transport keepalives, which fail all the RPCs of
/// a connection together, to a timeout per RPC, which resets each stream.
///
/// For `stream_append`, `hard_ttl()` is not a hard limit on the lifetime of the whole stream.
/// A streaming transport should instead use `soft_ttl()` for setup, per-response, or idle-timeout
/// policy and return an error when the connection stops making progress.
///
/// A single network instance is used to connect to a single target node. The network instance is
/// constructed by the [`RaftNetworkFactory`](`crate::network::RaftNetworkFactory`).
///
/// V2 network API removes the `install_snapshot()` method that sends snapshot in chunks
/// and introduces the `full_snapshot()` method that lets the application fully customize snapshot
/// transmit.
///
/// [Ensure connection to correct node][correct-node]
///
/// [`NetAppend`]: crate::network::NetAppend
/// [`NetVote`]: crate::network::NetVote
/// [`NetSnapshot`]: crate::network::NetSnapshot
/// [`NetStreamAppend`]: crate::network::NetStreamAppend
/// [`NetTransferLeader`]: crate::network::NetTransferLeader
/// [`NetBackoff`]: crate::network::NetBackoff
/// [`RaftNetworkFactory::Network`]: crate::network::RaftNetworkFactory::Network
/// [correct-node]: `crate::docs::cluster_control::dynamic_membership#ensure-connection-to-the-correct-node`
#[since(
    version = "0.10.2",
    change = "`transfer_leader` requests stay in flight past `RPCOption::hard_ttl()`"
)]
#[since(
    version = "0.10.2",
    change = "log replication that stops keeps its requests in flight until its stream ends"
)]
#[since(
    version = "0.10.2",
    change = "votes, pre-votes and heartbeats stay in flight past `RPCOption::hard_ttl()`"
)]
#[since(version = "0.10.0")]
#[add_async_trait]
pub trait RaftNetworkV2<C>: OptionalSend + OptionalSync + 'static
where C: RaftTypeConfig
{
    /// Snapshot data this network implementation can transmit.
    #[since(
        version = "0.10.0",
        change = "moved SnapshotData from RaftTypeConfig to RaftNetworkV2"
    )]
    type SnapshotData: OptionalSend + 'static;

    /// Send an AppendEntries RPC to the target.
    ///
    /// The remote follower should pass the request to [`Raft::append_entries()`] and send back
    /// its result:
    ///
    /// - `Ok(log_id)` acknowledges the entries up to `log_id`: the request's last log id, which is
    ///   `prev_log_id` for a request without entries. A transport that sent only a prefix of the
    ///   entries acknowledges the last log id it sent, which must lie in `[prev_log_id,
    ///   last_log_id]`.
    /// - [`AppendError::Conflict`] reports the `prev_log_id` of the rejected request, and may carry
    ///   the follower's conflict hint.
    /// - [`AppendError::HigherVote`] reports the follower's higher vote.
    ///
    /// Return an [`RPCError`] if no reply is received.
    ///
    /// [`AppendResult`] does not implement serde, so the transport sends it in its own wire
    /// format. A transport that does not carry hints can send [`StreamAppendResult`], a
    /// serializable format without the hint: both ends convert with `result.map_err(Into::into)`.
    /// The leader then receives no hint and finds the matching log by binary search.
    ///
    /// [`Raft::append_entries()`]: crate::raft::Raft::append_entries
    /// [`AppendError::Conflict`]: crate::raft::AppendError::Conflict
    /// [`AppendError::HigherVote`]: crate::raft::AppendError::HigherVote
    /// [`StreamAppendResult`]: crate::raft::StreamAppendResult
    #[since(version = "0.10.0", change = "returns AppendResult with an optional conflict hint")]
    async fn append_entries(
        &mut self,
        rpc: AppendEntriesRequest<C>,
        option: RPCOption,
    ) -> Result<AppendResult<C>, RPCError<C>>;

    /// Send a stream of AppendEntries RPCs to the target and return a stream of responses.
    ///
    /// This method forwards a stream of AppendEntries requests to the remote follower.
    /// The remote follower should call [`Raft::stream_append()`] to process the stream
    /// and send back a stream of responses.
    ///
    /// The default implementation processes requests sequentially in a request-response
    /// manner: it sends one request, waits for the response, then sends the next.
    /// This is simple but not optimal for performance. Each request goes through
    /// [`append_entries()`], so a conflict in this stream carries a hint only when that method
    /// returns one.
    ///
    /// Custom transports may merge, split, or pipeline requests under the ordering and response
    /// bounds documented by [`NetStreamAppend::stream_append`]. Responses need not map one-to-one
    /// to input requests.
    ///
    /// The output stream terminates when the input is exhausted or an error occurs.
    ///
    /// The caller may drop the returned future before it resolves, or the output stream before it
    /// ends, such as after the stream yields an error or a conflict, and then call
    /// `stream_append()` again on the same `self`. A dropped call must leave `self` safe for the
    /// next one: discard a connection that it left with a partial request or unread responses, and
    /// stop the work that it moved to another task, even while that work waits for room to send.
    /// The default implementation starts no task, and dropping its stream drops `input` and the
    /// [`append_entries()`] call in progress, so a dropped `append_entries()` call must leave
    /// `self` safe as well. The cancellation section of [`NetStreamAppend::stream_append`]
    /// describes the rules.
    ///
    /// # Note
    ///
    /// This method returns `BoxFuture` and `BoxStream` instead of `impl Future`/`impl Stream`
    /// to avoid a higher-ranked lifetime error that occurs when the return type
    /// captures the lifetime `'s` in an `impl Trait` position.
    ///
    /// [`Raft::stream_append()`]: crate::raft::Raft::stream_append
    /// [`NetStreamAppend::stream_append`]: crate::network::NetStreamAppend::stream_append
    /// [`append_entries()`]: Self::append_entries
    #[since(
        version = "0.10.0",
        change = "response stream yields AppendError with an optional conflict hint"
    )]
    #[since(version = "0.10.0")]
    fn stream_append<'s, S>(
        &'s mut self,
        input: S,
        option: RPCOption,
    ) -> BoxFuture<'s, Result<BoxStream<'s, Result<AppendResult<C>, RPCError<C>>>, RPCError<C>>>
    where
        S: Stream<Item = AppendEntriesRequest<C>> + OptionalSend + Unpin + 'static,
    {
        stream_append_sequential(self, input, option)
    }

    /// Send a RequestVote RPC to the target.
    async fn vote(&mut self, rpc: VoteRequest<C>, option: RPCOption) -> Result<VoteResponse<C>, RPCError<C>>;

    /// Send a Pre-Vote RPC to the target.
    ///
    /// The node receiving this message should pass it to [`Raft::pre_vote()`]. Pre-Vote asks the
    /// target whether it *would* grant a vote for `rpc.vote` (a hypothetical `term + 1`) without
    /// persisting any vote or changing its term. It is sent when
    /// [`Config::enable_pre_vote`](crate::Config::enable_pre_vote) is set, and by
    /// [`Trigger::elect(true)`].
    ///
    /// The default implementation synthesizes a **granting** response, so a network that has not
    /// implemented `pre_vote` makes Pre-Vote a no-op and elections proceed exactly as before (e.g.
    /// during a rolling upgrade). This is deliberately distinct from a transport failure: an
    /// implementor that cannot reach the target must return `Err` (typically
    /// [`Unreachable`]), which the caller does **not** count as a grant — otherwise a fully
    /// isolated node would synthesize a quorum of grants and inflate its term, defeating
    /// Pre-Vote.
    ///
    /// To test an implementation, send a pre-vote from a candidate whose log is behind to a
    /// leader: the target refuses it, while the default implementation grants it.
    ///
    /// [`Raft::pre_vote()`]: crate::raft::Raft::pre_vote
    /// [`Trigger::elect(true)`]: crate::raft::trigger::Trigger::elect
    #[since(version = "0.10.0", change = "added pre_vote RPC for the Pre-Vote feature")]
    async fn pre_vote(&mut self, rpc: VoteRequest<C>, _option: RPCOption) -> Result<VoteResponse<C>, RPCError<C>> {
        // Not implemented: grant unconditionally so Pre-Vote degrades to the normal election path.
        Ok(VoteResponse::new(rpc.vote, None, true))
    }

    /// Send a complete Snapshot to the target.
    ///
    /// This method is responsible for fragmenting the snapshot and sending it to the target node.
    /// Before returning from this method, the snapshot should be completely transmitted and
    /// installed on the target node or rejected because of `vote` being smaller than the
    /// remote one.
    ///
    /// There is no default implementation: `snapshot` holds the whole [`Self::SnapshotData`]
    /// handle, and the transport decides how to move it. The target calls
    /// [`Raft::install_full_snapshot()`] only after it holds the complete snapshot; see
    /// [sending a snapshot](crate::docs::upgrade_guide::upgrade_09_10#sending-a-snapshot).
    ///
    /// The `vote` is the leader vote used to check if the leader is still valid by a
    /// follower.
    /// When the follower finished receiving the snapshot, it calls
    /// [`Raft::install_full_snapshot()`] with this vote.
    ///
    /// Return `Ok` only with the response that [`Raft::install_full_snapshot()`] returned on the
    /// target, and never for a snapshot that the target only staged to install at a later
    /// restart: the leader takes `Ok` as proof that the target installed it. See
    /// [`NetSnapshot::full_snapshot`] for what the leader records for each outcome.
    ///
    /// `cancel` gets `Ready` when the caller decides to cancel this snapshot transmission. The
    /// caller may also drop the returned future at any `.await`, whether or not `cancel` is ready,
    /// and then call `full_snapshot()` again on the same `self`. A dropped call must leave `self`
    /// safe for the next one: discard a connection that the call left with a partial request or an
    /// unread reply, and stop the work that the call moved to another task. The cancellation
    /// section of [`NetSnapshot::full_snapshot`] describes how.
    ///
    /// [`Raft::install_full_snapshot()`]: crate::raft::Raft::install_full_snapshot
    /// [`NetSnapshot::full_snapshot`]: crate::network::NetSnapshot::full_snapshot
    async fn full_snapshot(
        &mut self,
        vote: VoteOf<C>,
        snapshot: SnapshotOf<C, Self::SnapshotData>,
        cancel: impl Future<Output = ReplicationClosed> + OptionalSend + 'static,
        option: RPCOption,
    ) -> Result<SnapshotResponse<C>, StreamingError<C>>;

    /// Send TransferLeader message to the target node.
    ///
    /// The node received this message should pass it to [`Raft::handle_transfer_leader()`].
    /// Return the [`TransferLeaderResponse`] that the target's call returned; the response type
    /// describes what `Ok(())` and each error report.
    ///
    /// This method provides a default implementation that just returns [`Unreachable`] error to
    /// ignore it. In case the application did not implement it, other nodes just wait for the
    /// Leader lease to timeout and then restart election.
    ///
    /// [`Raft::handle_transfer_leader()`]: crate::raft::Raft::handle_transfer_leader
    #[since(version = "0.10.0", change = "returns TransferLeaderResponse")]
    #[since(version = "0.10.0")]
    async fn transfer_leader(
        &mut self,
        _req: TransferLeaderRequest<C>,
        _option: RPCOption,
    ) -> Result<TransferLeaderResponse<C>, RPCError<C>> {
        Err(RPCError::Unreachable(Unreachable::new(&AnyError::error(
            "transfer_leader not implemented",
        ))))
    }

    /// Build a backoff instance if the target node is temporarily(or permanently) unreachable.
    ///
    /// When a [`Unreachable`](`crate::error::Unreachable`) error is returned from the `Network`
    /// methods, Openraft does not retry connecting to a node immediately. Instead, it sleeps
    /// for a while and retries. The duration of the sleep is determined by the backoff
    /// instance.
    ///
    /// The backoff returns the ith sleep interval before the ith retry. Make it infinite: after
    /// it ends, Openraft keeps retrying with a fixed delay, as [`Backoff`] describes. The
    /// returned instance will be dropped if a successful RPC is made.
    ///
    /// Return `None` (the default) to use the backoff configured in
    /// [`Config::backoff`](crate::Config::backoff). Only this `None` selects that policy: a
    /// returned backoff that runs out does not fall back to it.
    #[since(
        version = "0.10.0",
        change = "changed return type to Option<Backoff>; None delegates to Config::backoff"
    )]
    fn backoff(&self) -> Option<Backoff> {
        None
    }
}

// =============================================================================
// Blanket implementations: RaftNetworkV2 → Sub-traits
// =============================================================================
//
// These blanket impls allow existing RaftNetworkV2 implementations to
// automatically satisfy all sub-trait requirements by delegating to
// the corresponding RaftNetworkV2 methods.

use crate::network::NetBackoff;
use crate::network::NetSnapshot;
use crate::network::NetStreamAppend;
use crate::network::NetTransferLeader;
use crate::network::NetVote;

impl<C, T> NetAppend<C> for T
where
    C: RaftTypeConfig,
    T: RaftNetworkV2<C> + ?Sized,
{
    async fn append_entries(
        &mut self,
        rpc: AppendEntriesRequest<C>,
        option: RPCOption,
    ) -> Result<AppendResult<C>, RPCError<C>> {
        RaftNetworkV2::append_entries(self, rpc, option).await
    }
}

impl<C, T> NetBackoff<C> for T
where
    C: RaftTypeConfig,
    T: RaftNetworkV2<C> + ?Sized,
{
    fn backoff(&self) -> Option<Backoff> {
        RaftNetworkV2::backoff(self)
    }
}

impl<C, T> NetVote<C> for T
where
    C: RaftTypeConfig,
    T: RaftNetworkV2<C> + ?Sized,
{
    async fn vote(&mut self, rpc: VoteRequest<C>, option: RPCOption) -> Result<VoteResponse<C>, RPCError<C>> {
        RaftNetworkV2::vote(self, rpc, option).await
    }

    async fn pre_vote(&mut self, rpc: VoteRequest<C>, option: RPCOption) -> Result<VoteResponse<C>, RPCError<C>> {
        RaftNetworkV2::pre_vote(self, rpc, option).await
    }
}

impl<C, T> NetSnapshot<C> for T
where
    C: RaftTypeConfig,
    T: RaftNetworkV2<C> + ?Sized,
{
    type SnapshotData = T::SnapshotData;

    async fn full_snapshot(
        &mut self,
        vote: VoteOf<C>,
        snapshot: SnapshotOf<C, Self::SnapshotData>,
        cancel: impl Future<Output = ReplicationClosed> + OptionalSend + 'static,
        option: RPCOption,
    ) -> Result<SnapshotResponse<C>, StreamingError<C>> {
        RaftNetworkV2::full_snapshot(self, vote, snapshot, cancel, option).await
    }
}

impl<C, T> NetTransferLeader<C> for T
where
    C: RaftTypeConfig,
    T: RaftNetworkV2<C> + ?Sized,
{
    async fn transfer_leader(
        &mut self,
        req: TransferLeaderRequest<C>,
        option: RPCOption,
    ) -> Result<TransferLeaderResponse<C>, RPCError<C>> {
        RaftNetworkV2::transfer_leader(self, req, option).await
    }
}

impl<C, T> NetStreamAppend<C> for T
where
    C: RaftTypeConfig,
    T: RaftNetworkV2<C> + ?Sized,
{
    fn stream_append<'s, S>(
        &'s mut self,
        input: S,
        option: RPCOption,
    ) -> BoxFuture<'s, Result<BoxStream<'s, Result<AppendResult<C>, RPCError<C>>>, RPCError<C>>>
    where
        S: Stream<Item = AppendEntriesRequest<C>> + OptionalSend + Unpin + 'static,
    {
        RaftNetworkV2::stream_append(self, input, option)
    }
}