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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::time::Duration;

use display_more::DisplayOptionExt;
use futures_util::FutureExt;

use crate::LogIdOptionExt;
use crate::RaftLogReader;
use crate::RaftTypeConfig;
use crate::StorageError;
use crate::async_runtime::Mutex;
use crate::async_runtime::Select4;
use crate::async_runtime::watch::WatchReceiver;
use crate::base::BoxStream;
use crate::entry::RaftEntry;
use crate::entry::raft_entry_ext::RaftEntryExt;
use crate::errors::ReplicationClosed;
use crate::errors::StorageIOResult;
use crate::log_id_range::LogIdRange;
use crate::progress::inflight_id::InflightId;
use crate::raft::AppendEntriesRequest;
use crate::raft_state::IOId;
use crate::replication::backoff_consumer::BackoffConsumer;
use crate::replication::event_watcher::EventWatcher;
use crate::replication::inflight_append_queue::InflightAppendQueue;
use crate::replication::payload::Payload;
use crate::replication::replication_context::ReplicationContext;
use crate::storage::RaftLogStorage;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::EntryOf;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::MutexOf;
use crate::type_config::alias::WatchReceiverOf;

/// The state of the request stream of one stream session, which generates its AppendEntries
/// requests, see [`Self::into_request_stream()`].
///
/// The replication task creates it when a session starts and moves it into the session's request
/// stream. A transport may poll that stream after the session has ended, while the next session
/// runs, so each session has a state of its own. With the streams of other sessions it shares only
/// the log reader and the backoff iterator, each behind a lock of its own.
///
/// The fields come in three groups, in this order: the session, what the stream builds its
/// requests from, and what it reports to the task, which holds a handle to each report.
pub(crate) struct StreamState<C, LS>
where
    C: RaftTypeConfig,
    LS: RaftLogStorage<C>,
{
    /// Becomes `true` when the session ends, even if the transport keeps polling the stream.
    pub(crate) session_rx: WatchReceiverOf<C, bool>,

    /// Whether this stream has yielded a request. The first delay is checked before opening.
    pub(crate) has_yielded_request: bool,

    /// The inflight id of the plan this session runs, see [`Self::is_plan_current()`].
    pub(crate) inflight_id: Option<InflightId>,

    /// What this session has left to send: for `LogsSince`, the entries after `prev`; for a
    /// probe, the range `(prev_log_id, last_log_id]`.
    ///
    /// Set to `None` when all entries have been sent.
    pub(crate) payload: Option<Payload<C>>,

    /// The leader's vote, the target, the config, and the channels to and from RaftCore.
    pub(crate) replication_context: ReplicationContext<C>,

    /// RaftCore's plans, its log I/O and its commits, which tell the stream what to send.
    pub(crate) event_watcher: EventWatcher<C>,

    /// Handle that samples backoff delays and clears the current backoff on reset.
    /// `ReplicationCore` enables new backoff after RPC errors. The iterator is shared with the
    /// task's `BackoffState`, which outlives the session.
    pub(crate) backoff_consumer: BackoffConsumer<C>,

    /// The [`RaftLogStorage::LogReader`] interface, shared with the task and with the request
    /// streams of its other sessions.
    ///
    /// A stream holds this lock only while it reads, see [`Self::read_log_entries()`]. The task
    /// takes it to wait until no stream reads.
    pub(crate) log_reader: Arc<MutexOf<C, LS::LogReader>>,

    /// Tracks in-flight requests to infer conservative sending times for the leader clock.
    pub(crate) inflight_append_queue: Arc<StdMutex<InflightAppendQueue<C>>>,

    /// A fatal error found while generating the request stream, which the task reads once the
    /// stream has ended.
    pub(crate) fatal_error: Arc<MutexOf<C, Option<ReplicationClosed>>>,

    /// Synchronously pause after checking leadership to model descheduling within one poll.
    #[cfg(test)]
    pub(crate) after_leader_check: Option<Box<dyn FnOnce() + Send>>,
}

impl<C, LS> StreamState<C, LS>
where
    C: RaftTypeConfig,
    LS: RaftLogStorage<C>,
{
    /// Turn this state into the session's stream of AppendEntries requests.
    pub(crate) fn into_request_stream(self) -> BoxStream<'static, AppendEntriesRequest<C>> {
        let strm = futures_util::stream::unfold(self, Self::next_append_request);
        Box::pin(strm)
    }

    /// Generates the next AppendEntries request and records it in the inflight queue.
    ///
    /// Used as the unfold function for the request stream.
    async fn next_append_request(mut self) -> Option<(AppendEntriesRequest<C>, Self)> {
        let res = self.next_request().await;

        let req = match res {
            Ok(Some(req)) => req,
            Ok(None) => return None,
            Err(err) => {
                let mut fatal_error = self.fatal_error.lock().await;
                *fatal_error = Some(err);
                return None;
            }
        };

        let range = req.log_id_range();
        {
            let mut inflight_queue = self.inflight_append_queue.lock().unwrap();
            inflight_queue.push(range.prev, range.last);
        }

        self.has_yielded_request = true;
        Some((req, self))
    }

    /// Generates the next AppendEntries request from the current log range.
    ///
    /// Returns `Ok(None)` when there are no more entries to send or this session has ended.
    /// After each call, the payload is advanced or cleared according to its completion rule.
    pub(crate) async fn next_request(&mut self) -> Result<Option<AppendEntriesRequest<C>>, ReplicationClosed> {
        // A cooperative runtime can defer the async cancellation poll even after retirement.
        if *self.session_rx.borrow_watched() {
            return Ok(None);
        }

        // The waits below end with the session. They take a clone of `session_rx`, because what
        // they wait for borrows all of `self`.
        let mut session_rx = self.session_rx.clone();

        // An empty range still sends one RPC and is then cleared by `update_sent()`.
        let Some(Some(log_id_range)) = C::cancellable_by(self.next_range(), session_rx.changed()).await else {
            return Ok(None);
        };

        tracing::debug!("{}: log_id_range: {}", func_name!(), log_id_range);

        // A storage read must finish before the task releases its logs: by confirming a clear, or
        // by reporting that its closed stream reads the log no more.
        let res = self.read_log_entries(log_id_range).await;
        let (entries, sending_range) = match res {
            Ok(Some(x)) => x,
            Ok(None) => return Ok(None),
            Err(sto_err) => {
                tracing::error!("{} replication to target={}", sto_err, self.replication_context.target);

                self.replication_context.notify_storage_error(sto_err).await;
                return Err(ReplicationClosed::new("storage error"));
            }
        };

        // Read the commit first: the core publishes a new leader's accepted IO before its commit,
        // so a later leader's commit makes the following check stop this stale stream.
        //
        // Marking the commit as seen keeps the pending `committed_rx.changed()` from forcing a
        // second, entry-less request that carries this same commit. A commit that advances
        // after this read stays unseen and gets a request of its own.
        let leader_commit = self.event_watcher.committed_rx.borrow_and_update().clone();
        let accepted_io: IOId<C> = self.event_watcher.io_accepted_rx.borrow_watched().clone();
        if self.replication_context.leader_changed(&accepted_io) {
            return Ok(None);
        }

        #[cfg(test)]
        if let Some(hook) = self.after_leader_check.take() {
            hook();
        }

        self.update_sent(sending_range.last.clone());

        let request: AppendEntriesRequest<C> = AppendEntriesRequest {
            vote: self.replication_context.leader_vote.clone().into_vote(),
            prev_log_id: sending_range.prev,
            leader_commit,
            entries,
        };

        if let Some(first) = request.entries.first() {
            debug_assert_eq!(
                request.prev_log_id.next_index(),
                first.index(),
                "expect AppendEntries prev_log_id({}) to be immediately before the first entry at index {}",
                request.prev_log_id.display(),
                first.index()
            );
        }

        let entry_count = request.entries.len() as u64;
        self.replication_context.replicate_batch.record(entry_count);

        tracing::debug!("next_request: AppendEntries: {}", request);

        let wait = async {
            if self.has_yielded_request {
                self.backoff_consumer.backoff_if_enabled().await?;
            }
            self.replication_context.wait_for_send_period().await
        };
        let Some(ready) = C::cancellable_by(wait, session_rx.changed()).await else {
            return Ok(None);
        };
        ready?;

        Ok(Some(request))
    }

    /// Wait for the range of the next request, or return `None` once there is none: the payload is
    /// done, the plan is no longer current, or RaftCore has closed the stream.
    ///
    /// A probe sends its own range. `LogsSince` sends the logs after `prev` up to the last one
    /// submitted. While there are none, it waits, and returns an empty range when a commit that no
    /// request has carried needs one.
    async fn next_range(&mut self) -> Option<LogIdRange<C>> {
        let payload = self.payload.as_ref()?;

        tracing::debug!("pipeline stream payload: {}", payload);

        let prev = match payload {
            Payload::Probe { log_id_range } => return Some(log_id_range.clone()),
            Payload::LogsSince { prev } => prev.clone(),
        };

        loop {
            // Checked before every request, not only while waiting: a stream with entries left to
            // send never waits. The session of a plan that RaftCore dropped or replaced must end,
            // because the task confirms a clear only between sessions, and a stream that RaftCore
            // closed must read nothing more, also when a transport keeps polling it.
            if !self.is_plan_current() {
                return None;
            }

            let current: IOId<C> = self.event_watcher.io_submitted_rx.borrow_watched().clone();
            let last_log_id = current.last_log_id().cloned();

            tracing::debug!(
                "building next entries range to replicate: current last_log_id: {}",
                last_log_id.display()
            );

            if last_log_id > prev {
                return Some(non_reversed_log_id_range(prev, last_log_id));
            }

            let data_change = self.event_watcher.replicate_rx.changed();
            let io_change = self.event_watcher.io_submitted_rx.changed();
            let committed_change = self.event_watcher.committed_rx.changed();
            let cancel = self.replication_context.cancel_rx.changed();

            let selected = C::select4(cancel, data_change, io_change, committed_change).await;
            match selected {
                Select4::Second(_) => {
                    tracing::debug!("replicate_rx changed");
                    // Continue: the loop checks whether this plan is still current.
                }
                Select4::Third(_) => {
                    tracing::debug!("io_submitted_rx changed");
                    // Continue
                }
                Select4::Fourth(_) => {
                    tracing::debug!("committed_rx changed");
                    // Only a commit that no request has carried is still unseen here, because
                    // `next_request()` marks every commit it sends. With no new logs to piggyback
                    // on, an entry-less request is the only way to deliver it.
                    return Some(non_reversed_log_id_range(prev, last_log_id));
                }
                Select4::First(cancel_res) => {
                    tracing::info!(
                        "Replication Stream is canceled, res: {:?}, when:(next_range:wait-for-changed)",
                        cancel_res
                    );
                    return None;
                }
            }
        }
    }

    /// Return `true` if this stream may read the log, and send what it has read: its session has
    /// not ended, and it still runs RaftCore's current plan.
    ///
    /// The stream checks it while it holds the lock of `log_reader`, before and after each read.
    /// Once a session has ended, the task takes that lock to wait until no stream reads, so no
    /// stream of that session reads after that.
    fn may_read(&mut self) -> bool {
        let ended = *self.session_rx.borrow_watched();
        if ended {
            tracing::info!(
                "the session of inflight_id: {} has ended; quit",
                self.inflight_id.display()
            );
            return false;
        }

        self.is_plan_current()
    }

    /// Return `true` if this stream still runs RaftCore's current log plan for the target.
    ///
    /// RaftCore publishes another plan, with a new inflight id, when it replaces this one, and a
    /// clear, a plan without payload, when it drops it, as when a heartbeat finds the follower's
    /// log reverted. When it removes the target or stops leading, it closes the stream, which then
    /// runs no plan at all.
    fn is_plan_current(&mut self) -> bool {
        // RaftCore sends nothing on `cancel_rx`: it resolves only once RaftCore drops the sender.
        let closed = self.replication_context.cancel_rx.changed().now_or_never().is_some();
        if closed {
            tracing::info!(
                "the stream of inflight_id: {} is closed; quit",
                self.inflight_id.display()
            );
            return false;
        }

        let current = self.event_watcher.replicate_rx.borrow_watched().as_ref().map(|replicate| replicate.inflight_id);
        if current == self.inflight_id {
            return true;
        }

        tracing::info!(
            "inflight_id: {} is no longer the current plan, which is {}; quit",
            self.inflight_id.display(),
            current.display()
        );
        false
    }

    /// Advances the payload past `sent_last`, the last log id of the request just generated.
    ///
    /// Clears the payload when its completion rule is satisfied.
    fn update_sent(&mut self, sent_last: Option<LogIdOf<C>>) {
        let Some(payload) = self.payload.take() else {
            return;
        };

        self.payload = payload.update_sent(sent_last);
    }

    /// Reads log entries from storage for the given range.
    ///
    /// Returns the entries and the actual range covered (may be smaller than requested
    /// due to `limited_get_log_entries`). Returns `None` if this stream may not read, or may not
    /// send what it has read, see [`Self::may_read()`].
    ///
    /// The stream holds the lock of `log_reader` only for the read, so a stream that waits, as for
    /// new logs or a backoff delay, holds back neither the task nor the stream of another session.
    async fn read_log_entries(
        &mut self,
        log_id_range: LogIdRange<C>,
    ) -> Result<Option<(Vec<EntryOf<C>>, LogIdRange<C>)>, StorageError<C>> {
        tracing::debug!("read_log_entries: log_id_range: {}", log_id_range);

        // Series of logs to send, and the last log id to send
        let rng = &log_id_range;

        // The log index start and end to send.
        let (start, end) = {
            let start = rng.prev.next_index();
            let end = rng.last.next_index();

            (start, end)
        };

        if start >= end {
            debug_assert_eq!(
                start, end,
                "read_log_entries received reversed range: start({}) > end({}), log_id_range: {}",
                start, end, log_id_range
            );
            // Heartbeat RPC, no logs to send, last log id is the same as prev_log_id
            let r = LogIdRange::new(rng.prev.clone(), rng.prev.clone());
            return Ok(Some((vec![], r)));
        }

        let max_entries = self.replication_context.config.max_payload_entries;
        let end = std::cmp::min(end, start + max_entries);

        // A stream whose session has ended does not take the lock again.
        let log_reader = self.log_reader.clone();
        let Some(mut log_reader) = C::cancellable_by(log_reader.lock(), self.session_rx.changed()).await else {
            return Ok(None);
        };
        if !self.may_read() {
            return Ok(None);
        }

        // limited_get_log_entries will return logs smaller than the range [start, end).
        let logs = log_reader.limited_get_log_entries(start, end).await.sto_read_logs()?;

        // RaftCore keeps the entries of a plan it dropped until this task confirms the clear,
        // and the entries a closed stream may read until the task reports that it reads the
        // log no more, both of which wait for this read. A read whose session ended, or whose
        // plan RaftCore dropped, replaced or closed meanwhile, is stale all the same, and it is
        // not sent: its entries may belong to a plan that the target no longer runs.
        if !self.may_read() {
            return Ok(None);
        }
        drop(log_reader);

        // Handle empty result gracefully: treat as heartbeat.
        // This violates the API contract but we don't panic.
        // We sleep briefly to avoid a tight loop since the log_id_range won't advance.
        if logs.is_empty() {
            let sleep_duration = Duration::from_millis(10);
            tracing::warn!(
                "limited_get_log_entries({}, {}) returned empty; \
                 this violates the API contract but is handled gracefully as a heartbeat. \
                 Sleeping {:?} to avoid tight loop.",
                start,
                end,
                sleep_duration
            );
            C::sleep(sleep_duration).await;
            let r = LogIdRange::new(rng.prev.clone(), rng.prev.clone());
            return Ok(Some((vec![], r)));
        }

        let first = logs.first().map(|ent| ent.ref_log_id()).unwrap();
        let last = logs.last().map(|ent| ent.log_id()).unwrap();

        debug_assert!(
            logs.len() <= (end - start) as usize,
            "expect logs ⊆ [{}..{}) but got {} entries, first: {}, last: {}",
            start,
            end,
            logs.len(),
            first,
            last
        );

        let r = LogIdRange::new(rng.prev.clone(), Some(last));
        Ok(Some((logs, r)))
    }
}

fn non_reversed_log_id_range<C>(prev: Option<LogIdOf<C>>, last: Option<LogIdOf<C>>) -> LogIdRange<C>
where C: RaftTypeConfig {
    // `prev` is delivered through ReplicationCore's replication command channel, while `last` is
    // observed through the io_submitted watch channel. The watch channel may not have caught up yet.
    let last = std::cmp::max(last, prev.clone());
    LogIdRange::new(prev, last)
}

#[cfg(test)]
mod stream_state_test;

#[cfg(test)]
mod tests {
    use super::non_reversed_log_id_range;
    use crate::engine::testing::UTConfig;
    use crate::engine::testing::log_id;

    #[test]
    fn test_non_reversed_log_id_range() {
        let prev = Some(log_id(1, 1, 10));
        let stale_last = Some(log_id(1, 1, 9));

        let got = non_reversed_log_id_range::<UTConfig>(prev, stale_last);

        assert_eq!(got.prev, prev);
        assert_eq!(got.last, got.prev);
    }

    #[test]
    fn test_non_reversed_log_id_range_keeps_larger_last() {
        let prev = Some(log_id(1, 1, 10));
        let last = Some(log_id(1, 1, 12));

        let got = non_reversed_log_id_range::<UTConfig>(prev, last);

        assert_eq!(got.prev, prev);
        assert_eq!(got.last, last);
    }
}