Skip to main content

nodedb_raft/node/rpc/
install_snapshot.rs

1// SPDX-License-Identifier: BUSL-1.1
2
3//! `InstallSnapshot` request handler.
4
5use tracing::info;
6
7use crate::message::{InstallSnapshotRequest, InstallSnapshotResponse};
8use crate::node::core::RaftNode;
9use crate::storage::LogStorage;
10
11impl<S: LogStorage> RaftNode<S> {
12    /// Handle incoming InstallSnapshot RPC (Raft paper Figure 13).
13    ///
14    /// Called on followers (and learners) that are too far behind for
15    /// log-based catch-up. The leader sends its snapshot; the receiver
16    /// replaces its log and state.
17    pub fn handle_install_snapshot(
18        &mut self,
19        req: &InstallSnapshotRequest,
20    ) -> InstallSnapshotResponse {
21        if req.term < self.hard_state.current_term {
22            return InstallSnapshotResponse {
23                term: self.hard_state.current_term,
24            };
25        }
26
27        if req.term > self.hard_state.current_term {
28            self.become_follower(req.term);
29        }
30
31        self.leader_id = req.leader_id;
32        self.reset_election_timeout();
33
34        if req.done && req.last_included_index > self.log.snapshot_index() {
35            info!(
36                node = self.config.node_id,
37                group = self.config.group_id,
38                snapshot_index = req.last_included_index,
39                snapshot_term = req.last_included_term,
40                "applying installed snapshot"
41            );
42
43            self.log
44                .apply_snapshot(req.last_included_index, req.last_included_term);
45
46            if self.volatile.commit_index < req.last_included_index {
47                self.volatile.commit_index = req.last_included_index;
48            }
49            if self.volatile.last_applied < req.last_included_index {
50                self.volatile.last_applied = req.last_included_index;
51            }
52        }
53
54        InstallSnapshotResponse {
55            term: self.hard_state.current_term,
56        }
57    }
58}