+ @Override
+ protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
+ RaftActorBehavior returnBehavior = super.handleAppendEntriesReply(sender, appendEntriesReply);
+ tryToCompleteLeadershipTransfer(appendEntriesReply.getFollowerId());
+ return returnBehavior;
+ }
+
+ /**
+ * Attempts to transfer leadership to a follower as per the raft paper (§3.10) as follows:
+ * <ul>
+ * <li>Start a timer (Stopwatch).</li>
+ * <li>Send an initial AppendEntries heartbeat to all followers.</li>
+ * <li>On AppendEntriesReply, check if the follower's new match Index matches the leader's last index</li>
+ * <li>If it matches,
+ * <ul>
+ * <li>Send an additional AppendEntries to ensure the follower has applied all its log entries to its state.</li>
+ * <li>Send an ElectionTimeout to the follower to immediately start an election.</li>
+ * <li>Notify {@link RaftActorLeadershipTransferCohort#transferComplete}.</li>
+ * </ul></li>
+ * <li>Otherwise if the election time out period elapses, notify
+ * {@link RaftActorLeadershipTransferCohort#abortTransfer}.</li>
+ * </ul>
+ *
+ * @param leadershipTransferCohort the cohort participating in the leadership transfer
+ */
+ public void transferLeadership(@NonNull RaftActorLeadershipTransferCohort leadershipTransferCohort) {
+ log.debug("{}: Attempting to transfer leadership", logName());
+
+ leadershipTransferContext = new LeadershipTransferContext(leadershipTransferCohort);
+
+ // Send an immediate heart beat to the followers.
+ sendAppendEntries(0, false);
+ }
+
+ private void tryToCompleteLeadershipTransfer(String followerId) {
+ if (leadershipTransferContext == null) {
+ return;
+ }
+
+ final Optional<String> requestedFollowerIdOptional
+ = leadershipTransferContext.transferCohort.getRequestedFollowerId();
+ if (requestedFollowerIdOptional.isPresent() && !requestedFollowerIdOptional.get().equals(followerId)) {
+ // we want to transfer leadership to specific follower