raft-consensus-0.1.0.0: src/Distributed/Consensus/Raft/Transformer.hs
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE TupleSections #-}
module Distributed.Consensus.Raft.Transformer
( module Distributed.Consensus.Raft.Transformer.Definition,
-- * Cluster nodes
self,
peers,
clusterNodes,
-- * Capabilities
dequeueEvent,
enqueueEvent,
sendRPC,
sendRPCConcurrently,
sendRPCResult,
sendClientResponse,
sendAdminResponse,
whenRole,
sendHeartbeat,
sendAppendEntriesTo,
setCommitIndex,
voteFor,
applyLogEntries,
applyCommittedEntries,
nextElectionTimeout,
updateTerm,
updateMatchIndex,
trace,
acceptClientRequests,
persistSnapshot,
applySnapshot,
isClusterMember,
leaderStepDown,
serveReadOnlyQueries,
currentSnapshot,
appendLogEntries,
restoreState,
pendingClusterMembershipChanges,
proposeClusterMembership,
-- ** Roles
becomeFollower,
becomeNonMember,
becomeLeader,
becomeCandidate,
-- ** Elections
checkElection,
-- ** Timers
resetHeartBeatTimer,
resetElectionTimer,
)
where
import Control.Concurrent.Class.MonadMVar (MonadMVar, takeMVar)
import Control.Concurrent.Class.MonadSTM (atomically, readTQueue, writeTQueue)
import Control.Monad (unless, void, when)
import Control.Monad.Class.MonadAsync (MonadAsync, async, mapConcurrently_, race)
import Control.Monad.Class.MonadFork (MonadFork)
import Control.Monad.Class.MonadSTM (MonadSTM)
import Control.Monad.Class.MonadThrow (MonadMask)
import Control.Monad.Class.MonadTimer (MonadDelay)
import Control.Monad.Trans.Class (lift)
import Data.Foldable (for_, traverse_)
import qualified Data.Foldable as Foldable
import Data.Function ((&))
import Data.Functor (($>), (<&>))
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as Map
import Data.Maybe (fromJust, isJust)
import Data.Sequence (ViewR (..))
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable (for)
import Distributed.Consensus.Raft.Domain
( ClusterConfiguration (..),
LogIndex,
Role (..),
Snapshot (..),
SnapshotMetadata (..),
StateMachineStep (..),
Term,
allNodes,
hasQuorum,
)
import Distributed.Consensus.Raft.Domain.Admin (AdminResponse)
import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId, ClientResponse, ClientResult (..))
import Distributed.Consensus.Raft.Implementation hiding (sendAdminResponse, sendClientResponse, sendRPC, sendRPCResult)
import qualified Distributed.Consensus.Raft.Implementation as Impl
import Distributed.Consensus.Raft.Log (Lookup (..), absoluteIndex, logEntries)
import qualified Distributed.Consensus.Raft.Log as Log
import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
import Distributed.Consensus.Raft.Timer (Microseconds, resetTimer)
import Distributed.Consensus.Raft.Transformer.Definition
import Lens.Micro.Platform
( assign,
at,
use,
view,
(%=),
(+=),
(.=),
(^.),
_1,
_3,
)
import System.Random (uniformR)
-- | Node identifier
self :: (Monad m) => RaftT entry node result state m node
self = view configuration <&> nodeId
-- | All nodes in the cluster, except self
peers :: (Monad m, Ord node) => RaftT entry node result state m (Set node)
peers = do
s <- self
use clusterConfiguration <&> Set.delete s . allNodes
-- | All nodes in the cluster; both 'self' and 'peers'.
clusterNodes :: (Monad m, Ord node) => RaftT entry node result state m (Set node)
clusterNodes = use clusterConfiguration <&> allNodes
-- | Returns @Nothing@ if the exit lock has been unlocked, in which case
-- the server should shut down
dequeueEvent :: (MonadMVar m, MonadAsync m) => RaftT entry node result state m (Maybe (Event entry node result state))
dequeueEvent = do
queue <- view eventQueue
lock <- view exitLock
lift (race (takeMVar lock) (atomically (readTQueue queue)))
>>= either (const (pure Nothing)) (pure . Just)
enqueueEvent :: (MonadSTM m) => Event entry node result state -> RaftT entry node result state m ()
enqueueEvent event = do
queue <- view eventQueue
lift $ atomically $ writeTQueue queue event
-- | Send a 'RPC' to another node.
--
-- To send a 'RPC' to multiple other nodes, concurrently, see 'sendRPCConcurrently'
sendRPC :: (Monad m) => node -> RPC entry node state -> RaftSendT entry node result state m ()
sendRPC node rpc = do
impl <- view implementation
lift $ impl.networking.sendRPC node rpc
-- | Send a 'RPC' concurrently to other nodes.
--
-- To send a 'RPC' to a single node, see 'sendRPC'
sendRPCConcurrently :: (MonadAsync m) => Set node -> RPC entry node state -> RaftSendT entry node result state m ()
sendRPCConcurrently nodes rpc = do
impl <- view implementation
lift $ mapConcurrently_ (flip impl.networking.sendRPC rpc) nodes
sendRPCResult :: (Monad m) => node -> RPCResult node result -> RaftSendT entry node result state m ()
sendRPCResult node rpc = do
impl <- view implementation
lift $ impl.networking.sendRPCResult node rpc
sendClientResponse :: (Monad m) => node -> ClientResponse node result -> RaftSendT entry node result state m ()
sendClientResponse node response = do
impl <- view implementation
lift $ impl.networking.sendClientResponse node response
sendAdminResponse :: (Monad m) => node -> AdminResponse node -> RaftSendT entry node result state m ()
sendAdminResponse admin response = do
impl <- view implementation
lift $ impl.networking.sendAdminResponse admin response
whenRole ::
(Monad m) =>
Role ->
RaftT entry node result state m () ->
RaftT entry node result state m ()
whenRole r action = do
ourRole <- use role
when (ourRole == r) action
-- | Send a heartbeat RPC concurrently to all other nodes.
--
-- This function also resets the heartbeat timer.
sendHeartbeat ::
( Ord node,
MonadDelay m,
MonadMVar m,
MonadFork m,
MonadMask m,
MonadAsync m
) =>
RaftT entry node result state m ()
sendHeartbeat =
whenRole Leader $ do
config <- view configuration
peers >>= traverse_ sendAppendEntriesTo
view heartBeatTimer >>= lift . resetTimer config.heartBeatTimeout
-- | For a given destination node, look up which of the entries
-- in our log should be replicated, and send an appropriate 'AppendEntries' RPC.
sendAppendEntriesTo :: (Ord node, MonadAsync m) => node -> RaftT entry node result state m ()
sendAppendEntriesTo destination = do
entries <- use commandLog
use (nextIndex . at destination)
>>= ( \case
Nothing -> pure $ Just (0, initialTerm)
Just destNextIndex ->
let previousLogIndex = pred destNextIndex
in case entries Log.!? previousLogIndex of
Found (!prevTerm, _, _) -> pure $ Just (previousLogIndex, prevTerm)
NotFound -> pure $ Just (0, initialTerm)
-- The follower's next index is "lost" in the snapshot;
-- we can't specify entries to append. A snapshot will have
-- to be installed
LogIndexInSnapshot (SnapshotMetadata lastSnapshotIndex lastSnapshotTerm)
| previousLogIndex == lastSnapshotIndex -> pure $ Just (lastSnapshotIndex, lastSnapshotTerm)
| otherwise -> pure Nothing
)
>>= \case
Just (previousLogIndex, previousLogTerm) -> do
let toBeReplicated = Seq.drop (fromIntegral $ Log.relativeIndex entries previousLogIndex) (logEntries entries)
-- We send 'AppendEntries' event if 'toBeReplicated'
-- is empty, as this serves as a heartbeat mechanism
( AppendEntries
<$> use term
<*> (view configuration <&> nodeId)
<*> pure previousLogIndex
<*> pure previousLogTerm
<*> pure (((,) <$> view _1 <*> view _3) <$> toBeReplicated)
<*> use commitIndex
<*> use readOnlySequenceNum
)
>>= runSend . sendRPC destination . AE
Nothing ->
( InstallSnapshot
<$> use term
<*> (view configuration <&> nodeId)
<*> currentSnapshot
)
>>= runSend . sendRPC destination . IS
applyEntry ::
( Ord node,
MonadMVar m,
MonadAsync m
) =>
Term -> LogIndex -> LogEntry entry node -> RaftT entry node result state m (Maybe (CommandResponse node result))
applyEntry entryTerm entryIndex (LogEntryCommand (Command reqId entry)) = do
sm <- view implementation <&> stateMachine
currState <- use internalState
result <-
case sm entry of
Read runRead -> pure $ runRead currState
Transition runWrite -> do
let (newState, result) = runWrite currState
trace (\ctx -> LogEntryApplied ctx entryTerm entryIndex entry)
internalState .= newState
pure result
pure $ Just (MkCommandResponse result reqId)
applyEntry _entryTerm _entryIndex LogEntryLeaderChange = pure Nothing
applyEntry _entryTerm _entryIndex (LogEntryMembershipChange clusterConf) = do
setClusterMembership clusterConf
case clusterConf of
Simple {} -> trace MembershipChangeCompleted $> Nothing
Joint {} -> pure Nothing
-- | Updates the commit index. Returns 'True' if some log entries can be applied,
-- and 'False' otherwise.
updateCommitIndex :: (Ord node, Monad m) => RaftT entry node result state m Bool
updateCommitIndex = do
commitIndex' <- use commitIndex
entries <- use commandLog
ourTerm <- use term
matchIndices <- use matchIndex
s <- self
clusterConf <- use clusterConfiguration
-- Fetch the indices, starting from the log index after the commit index, such that:
-- 1. the entry is associated with the current term
-- 2. a quorum of nodes have committed this index
--
-- All of this is done relative to the snapshot, hence why all of the
-- indices are relativized
let relativeMatchIndices = fmap (Log.relativeIndex entries) matchIndices
relativeCommitIndex = Log.relativeIndex entries commitIndex'
liveEntries = logEntries entries
relativeQuorumIndices =
Seq.zip
( Seq.fromFunction
(length liveEntries)
-- The initial commit index is 0, hence the first entry to be committed
-- should have index 1
succ
)
liveEntries
& Seq.drop (fromIntegral relativeCommitIndex)
& Seq.filter ((== ourTerm) . view _1 . snd)
& fmap fst
-- By definition of the Raft algorithm, only a contiguous subset of
-- indices can have been accepted with a quorum, hence the use of
-- takeWhileL
& Seq.takeWhileL
( \i ->
hasQuorum
clusterConf
-- Note that 'matchIndices' do not include the leader,
-- so we take the leader into account by inserting it
-- with the other match indices
( Set.insert s $
Map.keysSet
(Map.filter (>= fromIntegral i) relativeMatchIndices)
)
)
& fmap fromIntegral
case Seq.viewr relativeQuorumIndices of
Seq.EmptyR -> pure False
_ :> relativeLastIndex -> do
let lastIndex = absoluteIndex entries relativeLastIndex
setCommitIndex lastIndex
trace (`CommitIndexIncreasedTo` lastIndex)
pure True
setCommitIndex :: (Monad m) => LogIndex -> RaftT entry node result state m ()
setCommitIndex ix = do
impl <- view implementation
s <- self
commitIndex .= ix
lift $ impl.persistence.writeCommitIndex s ix
-- | Set the current vote, both in the internal state
-- but also in persisted state.
--
-- This function doesn't emit any RPCs
voteFor :: (Monad m) => Maybe node -> RaftT entry node result state m ()
voteFor mNode = do
impl <- view implementation
s <- self
t <- use term
lift $ impl.persistence.writeVotedFor s t mNode
votedFor .= mNode
traverse_ (\n -> trace (\ctx -> VotedFor ctx t n)) mNode
-- | Update the commit index, and apply log entries if there are
-- any log entries that /can/ be applied.
applyLogEntries :: (Ord node, MonadMVar m, MonadAsync m, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()
applyLogEntries = do
isTimeToCommit <- updateCommitIndex
when isTimeToCommit applyCommittedEntries
applyCommittedEntries :: (Ord node, MonadMVar m, MonadAsync m, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()
applyCommittedEntries = do
lastAppliedIndex <- use lastApplied
currentCommitIndex <- use commitIndex
when (lastAppliedIndex < currentCommitIndex) $ do
entries <- use commandLog
let unAppliedEntries =
entries
& (`Log.keepEntriesUpTo` currentCommitIndex)
& logEntries
& Seq.drop (fromIntegral (Log.relativeIndex entries lastAppliedIndex))
lastApplied .= currentCommitIndex
trace (`LastAppliedIndexIncreasedTo` currentCommitIndex)
confBefore <- use clusterConfiguration
results <-
mapM (\(t, ix, e) -> applyEntry t ix e) unAppliedEntries
-- Membership change commands don't return a result
<&> fmap fromJust . Seq.filter isJust
whenRole Leader $ do
leaderId <- self
let resultsByReqId =
results
& Foldable.toList
& map (\(MkCommandResponse result reqId) -> (reqId, NonEmpty.singleton result))
& Map.fromListWith (<>)
& Map.map NonEmpty.reverse -- Necessary because 'fromListWith' reverses order of applied commands
for_ (Map.toList resultsByReqId) $ \(reqId, responses) ->
use currentClientRequests
<&> Map.lookup reqId
>>= \case
Nothing -> pure () -- TODO: isn't this unexpected?
Just requester -> do
for_ responses $ \response -> do
runSend $ sendClientResponse requester (MkResponse reqId (Just leaderId) (Success response))
trace (`CommandResultResponded` MkCommandResponse (Success response) reqId)
currentClientRequests %= Map.delete reqId
view configuration <&> maxLogLength >>= \case
Nothing -> pure ()
Just maxLog -> do
entries' <- use commandLog
when
(Seq.length (logEntries entries') > maxLog)
(currentSnapshot >>= persistSnapshot)
-- If cluster configuration has changed, then the quorum
-- threshold may be different. Let's try to apply log entries
-- and unify the cluster membership
whenRole Leader $ do
reconfigured <- use clusterConfiguration <&> (/= confBefore)
when reconfigured applyLogEntries
unifyCluster
-- Since the last applied index could have been updated,
-- we might be able to serve some read-only requests
serveReadOnlyQueries
nextElectionTimeout :: (Monad m) => RaftT entry node result state m Microseconds
nextElectionTimeout = do
gen <- use randomGen
(lowerBound, upperBound) <- view configuration <&> electionTimeoutRange
let (timeout, nextGen) = uniformR (lowerBound, upperBound) gen
randomGen .= nextGen
pure timeout
trace :: (Monad m) => (EventContext node -> RaftTrace entry node result state) -> RaftT entry node result state m ()
trace makeTrace = do
eventCtx <- EventContext <$> use term <*> self
impl <- view implementation
lift $ tracer impl (makeTrace eventCtx)
-- | Update the internal term state, returning the previous and new 'Term's.
--
-- If the update function returns the current term, this function does nothing.
updateTerm :: (Monad m) => (Term -> Term) -> RaftT entry node result state m (Term, Term)
updateTerm update = do
currTerm <- use term
s <- self
let newTerm = update currTerm
when (newTerm > currTerm) $ do
impl <- view implementation
lift $ impl.persistence.writeTerm s newTerm
term .= newTerm
pure (currTerm, newTerm)
updateMatchIndex ::
(Ord node, Monad m) =>
node -> LogIndex -> RaftT entry node result state m ()
updateMatchIndex responder ackedIndex = do
prev <- use (matchIndex . at responder)
let newMatch = maybe ackedIndex (max ackedIndex) prev
matchIndex . at responder .= Just newMatch
nextIndex . at responder .= Just (succ newMatch)
-- | Set up a callback for a client request
acceptClientRequests ::
(MonadMVar m) =>
-- | Client node
NonEmpty (ClientRequest entry node) ->
RaftT entry node result state m (NonEmpty ClientRequestId)
acceptClientRequests requests = do
-- The term is part of the request ID. Our internal counter is volatile and
-- restarts from zero whenever we boot, so without the term an entry stamped
-- by an earlier leader could collide with one of ours, and we would answer
-- the client with the result of that older command. See 'RequestId'.
ourTerm <- use term
ci <- use commitIndex
sm <- view implementation <&> stateMachine
s <- self
for requests $ \(MkRequest clientReqId clientId entry) -> do
case sm entry of
-- Read-only requests don't go to the log, and so
-- we need to persist more information about them.
Read runRead -> do
readOnlySequenceNum += 1
rseq <- use readOnlySequenceNum
pendingReadRequests
%= Map.insert
clientReqId
( MkPendingRead
{ _pendingReadTerm = ourTerm,
_pendingReadLogIndex = ci,
_pendingReadClient = clientId,
_pendingReadLeaderAcknowledgedBy = Set.singleton s,
_pendingReadProjection = runRead,
_pendingReadSequenceNum = rseq
}
)
trace (\ctx -> ReadOnlyQueryQueued ctx ci entry)
Transition _ -> currentClientRequests %= Map.insert clientReqId clientId
pure clientReqId
currentSnapshot :: (Monad m) => RaftT entry node result state m (Snapshot node state)
currentSnapshot = do
lastAppliedIndex <- use lastApplied
entries <- use commandLog
ourTerm <- use term
-- The snapshot stands in for the log up to and including 'lastAppliedIndex',
-- so its term has to be the term of the entry /at/ that index, not the term we
-- happen to be in now. Those differ whenever we snapshot in a later term than
-- the entries we are compacting, and getting it wrong wedges a follower for
-- good: it installs the snapshot, the leader then sends 'AppendEntries' with
-- the real term for that index, the consistency check against the snapshot
-- metadata fails, the leader backs up into the snapshot and installs it
-- again, forever.
let lastAppliedTerm = case entries Log.!? lastAppliedIndex of
Found (entryTerm, _, _) -> entryTerm
-- Already compacted into our own snapshot, whose metadata knows the term.
LogIndexInSnapshot (SnapshotMetadata _ snapshotTerm) -> snapshotTerm
-- Cannot happen: 'lastApplied' never runs past the log.
NotFound -> ourTerm
Snapshot (SnapshotMetadata lastAppliedIndex lastAppliedTerm)
<$> use internalState
<*> use clusterConfiguration
-- | Serialize the snapshot in a separate thread.
--
-- An event will be emitted to run `applySnapshot`.
--
-- If a snapshot is currently being serialized, 'persistSnapshot' does nothing. This means
-- that if the node is currently snapshotting because its log is too long, and then
-- a leader sends 'InstallSnapshot', the leader's 'InstallSnapshot' may be ignored.
-- This isn't wrong, but will result in the leader potentially re-sending an 'InstallSnapshot'
-- RPC again soon.
persistSnapshot :: (MonadAsync m) => Snapshot node state -> RaftT entry node result state m ()
persistSnapshot snapshot = do
inprogress <- use snapshotInProgress
-- We guard persisting snapshot, since we could be appending to the log a lot,
-- in which case we might notice that the log is too long just as often,
-- resulting in a cascade of snapshotting.
if inprogress
then pure ()
else do
snapshotInProgress .= True
s <- self
impl <- view implementation
queue <- view eventQueue
void $ lift $ async $ do
impl.persistence.writeSnapshot s snapshot
atomically $
writeTQueue
queue
(EventSnapshotPersisted snapshot)
-- | Whether we are in the configuration we are currently using.
isClusterMember :: (Ord node, Monad m) => RaftT entry node result state m Bool
isClusterMember = do
s <- self
use clusterConfiguration <&> Set.member s . allNodes
-- | Check if any of the pending read only queries
-- can be served. If they can, serve them!
serveReadOnlyQueries :: (Ord node, MonadAsync m) => RaftT entry node result state m ()
serveReadOnlyQueries = whenRole Leader $ do
clusterConf <- use clusterConfiguration
appIx <- use lastApplied
ourTerm <- use term
leaderId <- self
entries <- use commandLog
let appliedInOurTerm = case entries Log.!? appIx of
Found (t, _, _) -> t == ourTerm
LogIndexInSnapshot (SnapshotMetadata _ t) -> t == ourTerm
NotFound -> False
canBeServed pendingRead =
-- TODO: what if it's an old term? How could this even be possible?
(pendingRead ^. pendingReadTerm == ourTerm)
&& appliedInOurTerm
&& (pendingRead ^. pendingReadLogIndex <= appIx)
&& hasQuorum clusterConf (pendingRead ^. pendingReadLeaderAcknowledgedBy)
(ready, notReady) <- use pendingReadRequests <&> Map.partition canBeServed
st <- use internalState
for_ (Map.toList ready) $ \(reqId, request) -> do
let result = request ^. pendingReadProjection $ st
runSend $
sendClientResponse
(request ^. pendingReadClient)
(MkResponse reqId (Just leaderId) (Success result))
trace (`CommandResultResponded` MkCommandResponse (Success result) reqId)
pendingReadRequests .= notReady
-- | Apply a snapshot to the internal state.
--
-- This can be used by any node on itself, or
-- as part of the 'InstallSnapshot' remote procedure call.
applySnapshot ::
(Monad m) =>
Snapshot node state ->
RaftT entry node result state m ()
applySnapshot snapshot = do
snapshotInProgress .= False
let snapshotIndex = snapshot.sMetadata.smLastIncludedIndex
alreadyApplied <- use lastApplied <&> (>= snapshotIndex)
-- Log.applySnapshot is a no-op if the incoming snapshot doesn't
-- advance the log
lastIndexBefore <- use commandLog <&> Log.lastLogIndex
commandLog %= Log.applySnapshot snapshot.sMetadata
-- A snapshot may change the last log index (either truncating
-- the log or fast-forwarding it), leading to the last log index
-- jumping around
lastIndexAfter <- use commandLog <&> Log.lastLogIndex
when (lastIndexAfter /= lastIndexBefore) $
trace (`LastLogIndexChangedTo` lastIndexAfter)
unless alreadyApplied $ do
internalState .= sData snapshot
clusterConfiguration .= sCluster snapshot
-- Commit index should never decrease
use commitIndex >>= \cix -> when (snapshotIndex > cix) (setCommitIndex snapshotIndex)
lastApplied %= max snapshot.sMetadata.smLastIncludedIndex
trace (`SnapshotApplied` sMetadata snapshot)
-- | Apply one or more entries to the log, from the leader's point of view
appendLogEntries ::
( Ord node,
MonadMVar m,
MonadAsync m,
MonadMask m,
MonadFork m,
MonadDelay m
) =>
NonEmpty (Term, LogEntry entry node) ->
RaftT entry node result state m ()
appendLogEntries entries = do
s <- self
impl <- view implementation
startingLogIndex <- use commandLog <&> Log.lastLogIndex
commandLog %= (`Log.extend` Seq.fromList (NonEmpty.toList entries))
let batchToWrite =
zipWith
(curry (\(ix, (t, entry)) -> (t, ix, entry)))
[succ startingLogIndex ..]
(NonEmpty.toList entries)
lift $ impl.persistence.writeLogEntry s batchToWrite
for_ batchToWrite $ \(t, ix, entry) ->
trace (\ctx -> LogEntryAppended ctx t ix entry)
-- It's important to emit this event because a new leader may have its
-- log index jump. Without having visibility into this jump,
-- it's hard to check that the commit index is always <= the last log index
use commandLog <&> Log.lastLogIndex >>= trace . flip LastLogIndexChangedTo
whenRole Leader $
peers >>= traverse_ sendAppendEntriesTo
-- In a single-node cluster, we would already have
-- quorum to update our commit index
applyLogEntries
restoreState ::
( MonadMVar m,
MonadAsync m,
Ord node,
MonadMask m,
MonadFork m,
MonadDelay m
) =>
RaftT entry node result state m ()
restoreState = do
impl <- view implementation
s <- self
(persistedTerm, persistedVote, mPersistedSnapshot, persistedCommit) <-
lift $ do
t <- impl.persistence.readTerm s
(t,,,)
<$> impl.persistence.readVotedFor s t
<*> impl.persistence.readSnapshot s
<*> impl.persistence.readCommitIndex s
term .= persistedTerm
votedFor .= persistedVote
let snapshotIndex = maybe 0 (smLastIncludedIndex . sMetadata) mPersistedSnapshot
entries <- lift $ Seq.fromList <$> impl.persistence.readLogEntriesFrom s (succ snapshotIndex)
let restoredLog = Log.buildLog entries (sMetadata <$> mPersistedSnapshot)
commandLog .= restoredLog
-- Not persisting the commit index on purpose here,
-- since we're restoring from persisted state
commitIndex .= min persistedCommit (Log.lastLogIndex restoredLog)
traverse_ applySnapshot mPersistedSnapshot
trace
( \ctx ->
StateRestored
ctx
persistedVote
restoredLog
)
restoredCommit <- use commitIndex
when (restoredCommit > 0) $ do
trace (`LastLogIndexChangedTo` Log.lastLogIndex restoredLog)
trace (`CommitIndexIncreasedTo` restoredCommit)
applyCommittedEntries
-- | Is a cluster membership change ongoing?
pendingClusterMembershipChanges :: (Monad m) => RaftT entry node result state m Bool
pendingClusterMembershipChanges =
(>) <$> use pendingConfigurationIndex <*> use lastApplied
-- | Set the cluster membership configuration, updating
-- the rest of the state as well.
setClusterMembership ::
( Ord node,
MonadMVar m,
MonadAsync m
) =>
ClusterConfiguration node -> RaftT entry node result state m ()
setClusterMembership clusterConf = do
clusterConfiguration .= clusterConf
trace (`MembershipChangeApplied` clusterConf)
whenRole Leader $ do
s <- self
ps <- peers
lastIx <- use commandLog <&> Log.lastLogIndex
-- Pre-emptively prepare state for new membership
nextIndex %= \m -> Map.fromSet (\p -> Map.findWithDefault (succ lastIx) p m) ps
matchIndex %= (`Map.restrictKeys` ps)
unless (s `Set.member` allNodes clusterConf) becomeNonMember
proposeClusterMembership ::
( MonadMVar m,
MonadAsync m,
Ord node,
MonadMask m,
MonadFork m,
MonadDelay m
) =>
ClusterConfiguration node -> RaftT entry node result state m ()
proposeClusterMembership clusterConf = do
use commandLog <&> succ . Log.lastLogIndex >>= assign pendingConfigurationIndex
ourTerm <- use term
appendLogEntries (NonEmpty.singleton (ourTerm, LogEntryMembershipChange clusterConf))
-- | If the cluster is currently in a joint configuration, unify the
-- membership to be in a simple configuration. Otherwise, do nothing.
unifyCluster :: (MonadMVar m, MonadAsync m, Ord node, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()
unifyCluster = do
pending <- pendingClusterMembershipChanges
use clusterConfiguration >>= \case
Joint _ after | not pending -> proposeClusterMembership (Simple after)
_ -> pure ()
becomeLeader ::
( Ord node,
MonadDelay m,
MonadMVar m,
MonadFork m,
MonadMask m,
MonadAsync m
) =>
RaftT entry node result state m ()
becomeLeader = do
role .= Leader
self <&> Just >>= assign currentLeader
yesVotes .= Set.empty
lastIx <- use commandLog <&> Log.lastLogIndex
peers <&> Map.fromSet (const (lastIx + 1)) >>= assign nextIndex
trace LeaderElected
-- In order to serve read-only queries, there needs to be at least
-- one entry committed in this term (see Raft paper, section 8)
ourTerm <- use term
appendLogEntries (NonEmpty.singleton (ourTerm, LogEntryLeaderChange))
-- cluster configuration could be ongoing, started under a different leader
use clusterConfiguration >>= \case
Simple _ -> pure ()
Joint _before after ->
appendLogEntries (NonEmpty.singleton (ourTerm, LogEntryMembershipChange (Simple after)))
sendHeartbeat -- Note that 'sendHeartbeat' will also reset the heartbeat timer
-- | Reply to clients that the leader is stepping down. This function does nothing
-- if the role isn't 'Leader'
leaderStepDown :: (MonadAsync m) => Maybe node -> RaftT entry node result state m ()
leaderStepDown mNewLeader = whenRole Leader $ do
clientReqs <- use currentClientRequests
for_ (Map.toList clientReqs) $ \(reqId, requester) -> do
runSend $ sendClientResponse requester (MkResponse reqId mNewLeader NotLeader)
trace (`CommandResultResponded` MkCommandResponse NotLeader reqId)
currentClientRequests .= mempty
readRequests <- use pendingReadRequests
for_ (Map.toList readRequests) $ \(reqId, request) -> do
runSend $
sendClientResponse
(request ^. pendingReadClient)
(MkResponse reqId mNewLeader NotLeader)
trace (`CommandResultResponded` MkCommandResponse NotLeader reqId)
pendingReadRequests .= mempty
becomeFollower ::
(MonadMVar m, MonadDelay m, MonadFork m, MonadMask m, MonadAsync m) =>
-- | Leader if known
Maybe node ->
RaftT entry node result state m ()
becomeFollower mLeaderNodeId = do
leaderStepDown mLeaderNodeId
resetHeartBeatTimer
resetElectionTimer
r <- use role
unless (r == Follower) $ do
trace BecameFollower
role .= Follower
currentLeader .= mLeaderNodeId
becomeCandidate ::
( Ord node,
MonadAsync m,
MonadMask m,
MonadFork m,
MonadMVar m,
MonadDelay m
) =>
RaftT entry node result state m ()
becomeCandidate = do
trace BecameCandidate
role .= Candidate
currentLeader .= Nothing
-- The following pieces of state are only useful to leaders
nextIndex .= mempty
matchIndex .= mempty
s <- self
term += 1
w <- view implementation <&> writeTerm . persistence
thisTerm <- use term
lift (w s thisTerm)
voteFor (Just s)
yesVotes .= Set.singleton s
resetElectionTimer
checkElection -- there might only be a single node in the cluster
r <- use role
when (r == Candidate) $ do
currentTerm <- use term
(lastLogTerm, lastLogIx) <- use commandLog <&> Log.lastLogInfo
let rpc = RequestVote currentTerm s lastLogIx lastLogTerm
peers >>= (runSend . (`sendRPCConcurrently` rpc))
checkElection ::
( Ord node,
MonadAsync m,
MonadMask m,
MonadFork m,
MonadMVar m,
MonadDelay m
) =>
RaftT entry node result state m ()
checkElection = do
q <- hasQuorum <$> use clusterConfiguration <*> use yesVotes
when q becomeLeader
becomeNonMember ::
(MonadMVar m, MonadAsync m) =>
RaftT entry node result state m ()
becomeNonMember = do
r <- use role
leaderStepDown Nothing
unless (r == NonMember) $ do
trace BecameNonMember
role .= NonMember
currentLeader .= Nothing
resetHeartBeatTimer ::
( MonadAsync m,
MonadMask m,
MonadFork m,
MonadMVar m,
MonadDelay m
) =>
RaftT entry node result state m ()
resetHeartBeatTimer = do
config <- view configuration
view heartBeatTimer >>= lift . resetTimer config.heartBeatTimeout
resetElectionTimer ::
( MonadAsync m,
MonadMask m,
MonadFork m,
MonadMVar m,
MonadDelay m
) =>
RaftT entry node result state m ()
resetElectionTimer = do
electionTimeout <- nextElectionTimeout
view electionTimer >>= lift . resetTimer electionTimeout