packages feed

raft-consensus 0.1.1.0 → 0.2.0.0

raw patch · 22 files changed

+1228/−722 lines, 22 filesdep ~linearizablePVP ok

version bump matches the API change (PVP)

Dependency ranges changed: linearizable

API changes (from Hackage documentation)

- Distributed.Consensus.Raft: MkCommandResponse :: !result -> !ClientRequestId -> CommandResponse node result
- Distributed.Consensus.Raft: MkConfig :: !node -> !(Microseconds, Microseconds) -> !Microseconds -> !Word64 -> Maybe Int -> Config node
- Distributed.Consensus.Raft: MkRequest :: !id -> !node -> !payload -> Request id node payload
- Distributed.Consensus.Raft: MkResponse :: !id -> !Maybe node -> !payload -> Response id node payload
- Distributed.Consensus.Raft.Admin: AdminNotLeader :: !Maybe node -> AdminError node
- Distributed.Consensus.Raft.Admin: MkRequest :: !id -> !node -> !payload -> Request id node payload
- Distributed.Consensus.Raft.Admin: MkResponse :: !id -> !Maybe node -> !payload -> Response id node payload
- Distributed.Consensus.Raft.Admin: UnexpectedAdminResponse :: AdminError node
- Distributed.Consensus.Raft.Admin: [generateSessionId] :: AdminImplementation node (m :: Type -> Type) -> node -> m SessionId
- Distributed.Consensus.Raft.Admin: data AdminError node
- Distributed.Consensus.Raft.Admin: data RaftAdminT node (m :: Type -> Type) a
- Distributed.Consensus.Raft.Admin: instance Control.Monad.Trans.Class.MonadTrans (Distributed.Consensus.Raft.Admin.RaftAdminT node)
- Distributed.Consensus.Raft.Admin: instance GHC.Classes.Eq node => GHC.Classes.Eq (Distributed.Consensus.Raft.Admin.AdminError node)
- Distributed.Consensus.Raft.Admin: instance GHC.Internal.Base.Applicative m => GHC.Internal.Base.Applicative (Distributed.Consensus.Raft.Admin.RaftAdminT node m)
- Distributed.Consensus.Raft.Admin: instance GHC.Internal.Base.Functor m => GHC.Internal.Base.Functor (Distributed.Consensus.Raft.Admin.RaftAdminT node m)
- Distributed.Consensus.Raft.Admin: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Monad (Distributed.Consensus.Raft.Admin.RaftAdminT node m)
- Distributed.Consensus.Raft.Admin: instance GHC.Internal.Show.Show node => GHC.Internal.Show.Show (Distributed.Consensus.Raft.Admin.AdminError node)
- Distributed.Consensus.Raft.Admin: sendAdminCommand :: forall (m :: Type -> Type) node. MonadTimer m => Microseconds -> node -> AdminRequest node -> RaftAdminT node m (Either (AdminError node) (AdminCommandResult node))
- Distributed.Consensus.Raft.Admin: withAdminSession :: (MonadAsync m, MonadFork m, MonadMask m) => node -> AdminImplementation node m -> ((forall a. () => RaftAdminT node m a -> m a) -> m b) -> m b
- Distributed.Consensus.Raft.Client: MkClientRequestId :: SessionId -> SequenceNum -> ClientRequestId
- Distributed.Consensus.Raft.Client: MkRequest :: !id -> !node -> !payload -> Request id node payload
- Distributed.Consensus.Raft.Client: MkResponse :: !id -> !Maybe node -> !payload -> Response id node payload
- Distributed.Consensus.Raft.Client: Redirect :: node -> ClientError entry node
- Distributed.Consensus.Raft.Client: Success :: !result -> ClientResult result
- Distributed.Consensus.Raft.Client: [generateSessionId] :: ClientImplementation entry node result (m :: Type -> Type) -> node -> m SessionId
- Distributed.Consensus.Raft.Client: [receiveResponse] :: ClientImplementation entry node result (m :: Type -> Type) -> m (ClientResponse node result)
- Distributed.Consensus.Raft.Client: [sendRequest] :: ClientImplementation entry node result (m :: Type -> Type) -> node -> ClientRequest entry node -> m ()
- Distributed.Consensus.Raft.Client: clientSession :: forall (m :: Type -> Type) entry node result. Monad m => RaftClientT entry node result m SessionId
- Distributed.Consensus.Raft.Client: data ClientError entry node
- Distributed.Consensus.Raft.Client: data ClientResult result
- Distributed.Consensus.Raft.Client: data RaftClientT entry node result (m :: Type -> Type) a
- Distributed.Consensus.Raft.Client: instance Control.Monad.Trans.Class.MonadTrans (Distributed.Consensus.Raft.Client.RaftClientT entry node result)
- Distributed.Consensus.Raft.Client: instance GHC.Classes.Eq node => GHC.Classes.Eq (Distributed.Consensus.Raft.Client.ClientError entry node)
- Distributed.Consensus.Raft.Client: instance GHC.Classes.Ord node => GHC.Classes.Ord (Distributed.Consensus.Raft.Client.ClientError entry node)
- Distributed.Consensus.Raft.Client: instance GHC.Internal.Base.Applicative m => GHC.Internal.Base.Applicative (Distributed.Consensus.Raft.Client.RaftClientT entry node result m)
- Distributed.Consensus.Raft.Client: instance GHC.Internal.Base.Functor m => GHC.Internal.Base.Functor (Distributed.Consensus.Raft.Client.RaftClientT entry node result m)
- Distributed.Consensus.Raft.Client: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Monad (Distributed.Consensus.Raft.Client.RaftClientT entry node result m)
- Distributed.Consensus.Raft.Client: instance GHC.Internal.Show.Show node => GHC.Internal.Show.Show (Distributed.Consensus.Raft.Client.ClientError entry node)
- Distributed.Consensus.Raft.Client: sendClientRequest :: forall (m :: Type -> Type) node entry result. MonadTimer m => Microseconds -> node -> ClientRequest entry node -> RaftClientT entry node result m (Either (ClientError entry node) (node, result))
- Distributed.Consensus.Raft.Client: withClientSession :: (MonadAsync m, MonadFork m, MonadMask m) => node -> ClientImplementation entry node result m -> ((forall a. () => RaftClientT entry node result m a -> m a) -> m b) -> m b
+ Distributed.Consensus.Raft: AdminRequestId :: SessionId -> SequenceNum -> AdminRequestId
+ Distributed.Consensus.Raft: Candidate :: Role
+ Distributed.Consensus.Raft: ClientRequestId :: SessionId -> SequenceNum -> ClientRequestId
+ Distributed.Consensus.Raft: ClusterConfigurationIs :: ClusterConfiguration node -> AdminCommandResult node
+ Distributed.Consensus.Raft: ClusterMembershipNoKnownLeader :: node -> ClusterMembershipError node
+ Distributed.Consensus.Raft: CommandResponse :: result -> ClientRequestId -> CommandResponse node result
+ Distributed.Consensus.Raft: Config :: node -> (Microseconds, Microseconds) -> Microseconds -> Word64 -> Maybe Int -> Config node
+ Distributed.Consensus.Raft: ExpiredSession :: SessionId -> SessionError
+ Distributed.Consensus.Raft: Follower :: Role
+ Distributed.Consensus.Raft: GetClusterConfiguration :: AdminCommand node
+ Distributed.Consensus.Raft: Heartbeat :: RequestPayload request
+ Distributed.Consensus.Raft: HeartbeatEcho :: ResponsePayload response
+ Distributed.Consensus.Raft: JoinCluster :: node -> AdminCommand node
+ Distributed.Consensus.Raft: JoinInitiated :: AdminCommandResult node
+ Distributed.Consensus.Raft: Leader :: Role
+ Distributed.Consensus.Raft: LeaveCluster :: AdminCommand node
+ Distributed.Consensus.Raft: LeaveInitiated :: AdminCommandResult node
+ Distributed.Consensus.Raft: NonMember :: Role
+ Distributed.Consensus.Raft: NotLeader :: ResponsePayload response
+ Distributed.Consensus.Raft: RV :: RequestVote node -> RPC entry node state
+ Distributed.Consensus.Raft: RVR :: RequestVoteResult node -> RPCResult node result
+ Distributed.Consensus.Raft: Request :: id -> node -> SequenceNum -> RequestPayload payload -> Request id node payload
+ Distributed.Consensus.Raft: RequestPayload :: request -> RequestPayload request
+ Distributed.Consensus.Raft: Response :: id -> Maybe node -> ResponsePayload payload -> Response id node payload
+ Distributed.Consensus.Raft: ResponsePayload :: response -> ResponsePayload response
+ Distributed.Consensus.Raft: SessionExpired :: ResponsePayload response
+ Distributed.Consensus.Raft: SessionId :: Word64 -> Word64 -> SessionId
+ Distributed.Consensus.Raft: ShutDown :: AdminCommand node
+ Distributed.Consensus.Raft: ShutdownInitiated :: AdminCommandResult node
+ Distributed.Consensus.Raft: Timeout :: SessionError
+ Distributed.Consensus.Raft: UnexpectedResponse :: SessionError
+ Distributed.Consensus.Raft: [requestOldestOutstanding] :: Request id node payload -> SequenceNum
+ Distributed.Consensus.Raft: [rvCandidateLastLogEntryIndex] :: RequestVote node -> LogIndex
+ Distributed.Consensus.Raft: [rvCandidateLastLogEntryTerm] :: RequestVote node -> Term
+ Distributed.Consensus.Raft: [rvCandidateNode] :: RequestVote node -> node
+ Distributed.Consensus.Raft: [rvCandidateTerm] :: RequestVote node -> Term
+ Distributed.Consensus.Raft: [rvrVoteGranted] :: RequestVoteResult node -> Bool
+ Distributed.Consensus.Raft: [rvrVoterNode] :: RequestVoteResult node -> node
+ Distributed.Consensus.Raft: [rvrVoterTerm] :: RequestVoteResult node -> Term
+ Distributed.Consensus.Raft: data AdminCommand node
+ Distributed.Consensus.Raft: data AdminCommandResult node
+ Distributed.Consensus.Raft: data AdminRequestId
+ Distributed.Consensus.Raft: data ReadOnlySequenceNum
+ Distributed.Consensus.Raft: data RequestPayload request
+ Distributed.Consensus.Raft: data RequestVote node
+ Distributed.Consensus.Raft: data RequestVoteResult node
+ Distributed.Consensus.Raft: data ResponsePayload response
+ Distributed.Consensus.Raft: data SequenceNum
+ Distributed.Consensus.Raft: data SessionError
+ Distributed.Consensus.Raft: type AdminRequest node = Request AdminRequestId node AdminCommand node
+ Distributed.Consensus.Raft: type AdminResponse node = Response AdminRequestId node AdminCommandResult node
+ Distributed.Consensus.Raft: type ClientRequest entry node = Request ClientRequestId node entry
+ Distributed.Consensus.Raft: type ClientResponse node result = Response ClientRequestId node result
+ Distributed.Consensus.Raft.Admin: AdminRequestId :: SessionId -> SequenceNum -> AdminRequestId
+ Distributed.Consensus.Raft.Admin: ExpiredSession :: SessionId -> SessionError
+ Distributed.Consensus.Raft.Admin: Heartbeat :: RequestPayload request
+ Distributed.Consensus.Raft.Admin: HeartbeatEcho :: ResponsePayload response
+ Distributed.Consensus.Raft.Admin: Joint :: Set node -> Set node -> ClusterConfiguration node
+ Distributed.Consensus.Raft.Admin: NoKnownLeader :: SessionError
+ Distributed.Consensus.Raft.Admin: Request :: id -> node -> SequenceNum -> RequestPayload payload -> Request id node payload
+ Distributed.Consensus.Raft.Admin: RequestPayload :: request -> RequestPayload request
+ Distributed.Consensus.Raft.Admin: Response :: id -> Maybe node -> ResponsePayload payload -> Response id node payload
+ Distributed.Consensus.Raft.Admin: ResponsePayload :: response -> ResponsePayload response
+ Distributed.Consensus.Raft.Admin: SessionExpired :: ResponsePayload response
+ Distributed.Consensus.Raft.Admin: SessionId :: Word64 -> Word64 -> SessionId
+ Distributed.Consensus.Raft.Admin: Simple :: Set node -> ClusterConfiguration node
+ Distributed.Consensus.Raft.Admin: UnexpectedResponse :: SessionError
+ Distributed.Consensus.Raft.Admin: [generateAdminSessionId] :: AdminImplementation node (m :: Type -> Type) -> m SessionId
+ Distributed.Consensus.Raft.Admin: [requestOldestOutstanding] :: Request id node payload -> SequenceNum
+ Distributed.Consensus.Raft.Admin: data AdminRequestId
+ Distributed.Consensus.Raft.Admin: data AdminSession node (m :: Type -> Type)
+ Distributed.Consensus.Raft.Admin: data ClusterConfiguration node
+ Distributed.Consensus.Raft.Admin: data RequestPayload request
+ Distributed.Consensus.Raft.Admin: data ResponsePayload response
+ Distributed.Consensus.Raft.Admin: data SessionError
+ Distributed.Consensus.Raft.Admin: lowestUnacknowledgedSequenceNum :: forall (m :: Type -> Type) node. MonadSTM m => AdminSession node m -> STM m SequenceNum
+ Distributed.Consensus.Raft.Admin: randomSessionId :: MonadIO m => m SessionId
+ Distributed.Consensus.Raft.Admin: sendRequest :: (MonadTimer m, MonadMask m) => AdminSession node m -> Microseconds -> Maybe node -> AdminRequest node -> m (Either SessionError (AdminCommandResult node))
+ Distributed.Consensus.Raft.Admin: setLeader :: MonadSTM m => AdminSession node m -> node -> m ()
+ Distributed.Consensus.Raft.Admin: withSession :: (MonadAsync m, MonadFork m, MonadMask m, MonadTimer m) => node -> node -> AdminImplementation node m -> (AdminSession node m -> m b) -> m b
+ Distributed.Consensus.Raft.Client: ClientRequestId :: SessionId -> SequenceNum -> ClientRequestId
+ Distributed.Consensus.Raft.Client: ExpiredSession :: SessionId -> SessionError
+ Distributed.Consensus.Raft.Client: Heartbeat :: RequestPayload request
+ Distributed.Consensus.Raft.Client: HeartbeatEcho :: ResponsePayload response
+ Distributed.Consensus.Raft.Client: Request :: id -> node -> SequenceNum -> RequestPayload payload -> Request id node payload
+ Distributed.Consensus.Raft.Client: RequestPayload :: request -> RequestPayload request
+ Distributed.Consensus.Raft.Client: Response :: id -> Maybe node -> ResponsePayload payload -> Response id node payload
+ Distributed.Consensus.Raft.Client: ResponsePayload :: response -> ResponsePayload response
+ Distributed.Consensus.Raft.Client: SessionExpired :: ResponsePayload response
+ Distributed.Consensus.Raft.Client: SessionId :: Word64 -> Word64 -> SessionId
+ Distributed.Consensus.Raft.Client: UnexpectedResponse :: SessionError
+ Distributed.Consensus.Raft.Client: [generateClientSessionId] :: ClientImplementation entry node result (m :: Type -> Type) -> m SessionId
+ Distributed.Consensus.Raft.Client: [receiveClientResponse] :: ClientImplementation entry node result (m :: Type -> Type) -> m (ClientResponse node result)
+ Distributed.Consensus.Raft.Client: [requestOldestOutstanding] :: Request id node payload -> SequenceNum
+ Distributed.Consensus.Raft.Client: [sendClientRequest] :: ClientImplementation entry node result (m :: Type -> Type) -> node -> ClientRequest entry node -> m ()
+ Distributed.Consensus.Raft.Client: data ClientSession entry node result (m :: Type -> Type)
+ Distributed.Consensus.Raft.Client: data RequestPayload request
+ Distributed.Consensus.Raft.Client: data ResponsePayload response
+ Distributed.Consensus.Raft.Client: data SessionError
+ Distributed.Consensus.Raft.Client: lowestUnacknowledgedSequenceNum :: forall (m :: Type -> Type) entry node result. MonadSTM m => ClientSession entry node result m -> STM m SequenceNum
+ Distributed.Consensus.Raft.Client: randomSessionId :: MonadIO m => m SessionId
+ Distributed.Consensus.Raft.Client: sendRequest :: (MonadTimer m, MonadMask m) => ClientSession entry node result m -> Microseconds -> ClientRequest entry node -> m (Either SessionError result)
+ Distributed.Consensus.Raft.Client: setLeader :: MonadSTM m => ClientSession entry node result m -> node -> m ()
+ Distributed.Consensus.Raft.Client: withSession :: (MonadAsync m, MonadFork m, MonadMask m, MonadTimer m) => node -> node -> ClientImplementation entry node result m -> (ClientSession entry node result m -> m a) -> m a
- Distributed.Consensus.Raft: AppendEntries :: !Term -> !node -> !LogIndex -> !Term -> !Seq (Term, LogEntry entry node) -> !LogIndex -> !ReadOnlySequenceNum -> AppendEntries entry node
+ Distributed.Consensus.Raft: AppendEntries :: Term -> node -> LogIndex -> Term -> Seq (Term, LogEntry entry node) -> LogIndex -> ReadOnlySequenceNum -> AppendEntries entry node
- Distributed.Consensus.Raft: AppendEntriesResult :: !Term -> !node -> !Bool -> !LogIndex -> !LogIndex -> !ReadOnlySequenceNum -> AppendEntriesResult node result
+ Distributed.Consensus.Raft: AppendEntriesResult :: Term -> node -> Bool -> LogIndex -> LogIndex -> ReadOnlySequenceNum -> AppendEntriesResult node result
- Distributed.Consensus.Raft: Command :: !ClientRequestId -> !entry -> Command entry
+ Distributed.Consensus.Raft: Command :: ClientRequestId -> entry -> Command entry
- Distributed.Consensus.Raft: CommandReceived :: EventContext node -> !ClientRequestId -> entry -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: CommandReceived :: EventContext node -> ClientRequestId -> entry -> RaftTrace entry node result state
- Distributed.Consensus.Raft: CommandResultResponded :: EventContext node -> CommandResponse node (ClientResult result) -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: CommandResultResponded :: EventContext node -> CommandResponse node result -> RaftTrace entry node result state
- Distributed.Consensus.Raft: CommitIndexIncreasedTo :: EventContext node -> !LogIndex -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: CommitIndexIncreasedTo :: EventContext node -> LogIndex -> RaftTrace entry node result state
- Distributed.Consensus.Raft: EventContext :: !Term -> !node -> EventContext node
+ Distributed.Consensus.Raft: EventContext :: Term -> node -> EventContext node
- Distributed.Consensus.Raft: EventLogPersisted :: !Term -> !LogIndex -> Event entry node result state
+ Distributed.Consensus.Raft: EventLogPersisted :: Term -> LogIndex -> Event entry node result state
- Distributed.Consensus.Raft: InstallSnapshot :: !Term -> !node -> !Snapshot node state -> InstallSnapshot node state
+ Distributed.Consensus.Raft: InstallSnapshot :: Term -> node -> Snapshot node state -> InstallSnapshot node state
- Distributed.Consensus.Raft: InstallSnapshotResult :: !Term -> !node -> !SnapshotMetadata -> InstallSnapshotResult node
+ Distributed.Consensus.Raft: InstallSnapshotResult :: Term -> node -> SnapshotMetadata -> InstallSnapshotResult node
- Distributed.Consensus.Raft: LastAppliedIndexIncreasedTo :: EventContext node -> !LogIndex -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: LastAppliedIndexIncreasedTo :: EventContext node -> LogIndex -> RaftTrace entry node result state
- Distributed.Consensus.Raft: LastLogIndexChangedTo :: EventContext node -> !LogIndex -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: LastLogIndexChangedTo :: EventContext node -> LogIndex -> RaftTrace entry node result state
- Distributed.Consensus.Raft: LogEntryAppended :: EventContext node -> !Term -> !LogIndex -> LogEntry entry node -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: LogEntryAppended :: EventContext node -> Term -> LogIndex -> LogEntry entry node -> RaftTrace entry node result state
- Distributed.Consensus.Raft: LogEntryApplied :: EventContext node -> !Term -> !LogIndex -> entry -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: LogEntryApplied :: EventContext node -> Term -> LogIndex -> entry -> RaftTrace entry node result state
- Distributed.Consensus.Raft: NoKnownLeader :: node -> ClusterMembershipError node
+ Distributed.Consensus.Raft: NoKnownLeader :: SessionError
- Distributed.Consensus.Raft: ReadOnlyQueryQueued :: EventContext node -> !LogIndex -> entry -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: ReadOnlyQueryQueued :: EventContext node -> LogIndex -> entry -> RaftTrace entry node result state
- Distributed.Consensus.Raft: RequestVote :: Term -> node -> LogIndex -> Term -> RPC entry node state
+ Distributed.Consensus.Raft: RequestVote :: Term -> node -> LogIndex -> Term -> RequestVote node
- Distributed.Consensus.Raft: RequestVoteResult :: node -> Term -> Bool -> RPCResult node result
+ Distributed.Consensus.Raft: RequestVoteResult :: node -> Term -> Bool -> RequestVoteResult node
- Distributed.Consensus.Raft: Snapshot :: !SnapshotMetadata -> !state -> !ClusterConfiguration node -> Snapshot node state
+ Distributed.Consensus.Raft: Snapshot :: SnapshotMetadata -> state -> ClusterConfiguration node -> Snapshot node state
- Distributed.Consensus.Raft: SnapshotApplied :: EventContext node -> !SnapshotMetadata -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: SnapshotApplied :: EventContext node -> SnapshotMetadata -> RaftTrace entry node result state
- Distributed.Consensus.Raft: SnapshotMetadata :: !LogIndex -> !Term -> SnapshotMetadata
+ Distributed.Consensus.Raft: SnapshotMetadata :: LogIndex -> Term -> SnapshotMetadata
- Distributed.Consensus.Raft: VoteRequestedBy :: EventContext node -> !Term -> node -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: VoteRequestedBy :: EventContext node -> Term -> node -> RaftTrace entry node result state
- Distributed.Consensus.Raft: VotedFor :: EventContext node -> !Term -> node -> RaftTrace entry node result state
+ Distributed.Consensus.Raft: VotedFor :: EventContext node -> Term -> node -> RaftTrace entry node result state
- Distributed.Consensus.Raft: [aeCommitIndex] :: AppendEntries entry node -> !LogIndex
+ Distributed.Consensus.Raft: [aeCommitIndex] :: AppendEntries entry node -> LogIndex
- Distributed.Consensus.Raft: [aeEntries] :: AppendEntries entry node -> !Seq (Term, LogEntry entry node)
+ Distributed.Consensus.Raft: [aeEntries] :: AppendEntries entry node -> Seq (Term, LogEntry entry node)
- Distributed.Consensus.Raft: [aeLeaderNode] :: AppendEntries entry node -> !node
+ Distributed.Consensus.Raft: [aeLeaderNode] :: AppendEntries entry node -> node
- Distributed.Consensus.Raft: [aeLeaderTerm] :: AppendEntries entry node -> !Term
+ Distributed.Consensus.Raft: [aeLeaderTerm] :: AppendEntries entry node -> Term
- Distributed.Consensus.Raft: [aePreviousLogIndex] :: AppendEntries entry node -> !LogIndex
+ Distributed.Consensus.Raft: [aePreviousLogIndex] :: AppendEntries entry node -> LogIndex
- Distributed.Consensus.Raft: [aePreviousLogTerm] :: AppendEntries entry node -> !Term
+ Distributed.Consensus.Raft: [aePreviousLogTerm] :: AppendEntries entry node -> Term
- Distributed.Consensus.Raft: [aeReadOnlySeqNum] :: AppendEntries entry node -> !ReadOnlySequenceNum
+ Distributed.Consensus.Raft: [aeReadOnlySeqNum] :: AppendEntries entry node -> ReadOnlySequenceNum
- Distributed.Consensus.Raft: [aerCurrentTerm] :: AppendEntriesResult node result -> !Term
+ Distributed.Consensus.Raft: [aerCurrentTerm] :: AppendEntriesResult node result -> Term
- Distributed.Consensus.Raft: [aerMatch] :: AppendEntriesResult node result -> !Bool
+ Distributed.Consensus.Raft: [aerMatch] :: AppendEntriesResult node result -> Bool
- Distributed.Consensus.Raft: [aerNewEntryLogIndex] :: AppendEntriesResult node result -> !LogIndex
+ Distributed.Consensus.Raft: [aerNewEntryLogIndex] :: AppendEntriesResult node result -> LogIndex
- Distributed.Consensus.Raft: [aerNode] :: AppendEntriesResult node result -> !node
+ Distributed.Consensus.Raft: [aerNode] :: AppendEntriesResult node result -> node
- Distributed.Consensus.Raft: [aerPrevLogIndex] :: AppendEntriesResult node result -> !LogIndex
+ Distributed.Consensus.Raft: [aerPrevLogIndex] :: AppendEntriesResult node result -> LogIndex
- Distributed.Consensus.Raft: [aerReadOnlySeqNum] :: AppendEntriesResult node result -> !ReadOnlySequenceNum
+ Distributed.Consensus.Raft: [aerReadOnlySeqNum] :: AppendEntriesResult node result -> ReadOnlySequenceNum
- Distributed.Consensus.Raft: [electionTimeoutRange] :: Config node -> !(Microseconds, Microseconds)
+ Distributed.Consensus.Raft: [electionTimeoutRange] :: Config node -> (Microseconds, Microseconds)
- Distributed.Consensus.Raft: [heartBeatTimeout] :: Config node -> !Microseconds
+ Distributed.Consensus.Raft: [heartBeatTimeout] :: Config node -> Microseconds
- Distributed.Consensus.Raft: [isLeaderNode] :: InstallSnapshot node state -> !node
+ Distributed.Consensus.Raft: [isLeaderNode] :: InstallSnapshot node state -> node
- Distributed.Consensus.Raft: [isLeaderTerm] :: InstallSnapshot node state -> !Term
+ Distributed.Consensus.Raft: [isLeaderTerm] :: InstallSnapshot node state -> Term
- Distributed.Consensus.Raft: [isSnapshot] :: InstallSnapshot node state -> !Snapshot node state
+ Distributed.Consensus.Raft: [isSnapshot] :: InstallSnapshot node state -> Snapshot node state
- Distributed.Consensus.Raft: [isrNode] :: InstallSnapshotResult node -> !node
+ Distributed.Consensus.Raft: [isrNode] :: InstallSnapshotResult node -> node
- Distributed.Consensus.Raft: [isrSnapshotMetadata] :: InstallSnapshotResult node -> !SnapshotMetadata
+ Distributed.Consensus.Raft: [isrSnapshotMetadata] :: InstallSnapshotResult node -> SnapshotMetadata
- Distributed.Consensus.Raft: [isrTerm] :: InstallSnapshotResult node -> !Term
+ Distributed.Consensus.Raft: [isrTerm] :: InstallSnapshotResult node -> Term
- Distributed.Consensus.Raft: [nodeId] :: Config node -> !node
+ Distributed.Consensus.Raft: [nodeId] :: Config node -> node
- Distributed.Consensus.Raft: [randomSeed] :: Config node -> !Word64
+ Distributed.Consensus.Raft: [randomSeed] :: Config node -> Word64
- Distributed.Consensus.Raft: [requestId] :: Request id node payload -> !id
+ Distributed.Consensus.Raft: [requestId] :: Request id node payload -> id
- Distributed.Consensus.Raft: [requestOriginator] :: Request id node payload -> !node
+ Distributed.Consensus.Raft: [requestOriginator] :: Request id node payload -> node
- Distributed.Consensus.Raft: [requestPayload] :: Request id node payload -> !payload
+ Distributed.Consensus.Raft: [requestPayload] :: Request id node payload -> RequestPayload payload
- Distributed.Consensus.Raft: [responseClusterLeader] :: Response id node payload -> !Maybe node
+ Distributed.Consensus.Raft: [responseClusterLeader] :: Response id node payload -> Maybe node
- Distributed.Consensus.Raft: [responsePayload] :: Response id node payload -> !payload
+ Distributed.Consensus.Raft: [responsePayload] :: Response id node payload -> ResponsePayload payload
- Distributed.Consensus.Raft: [responseRequestId] :: Response id node payload -> !id
+ Distributed.Consensus.Raft: [responseRequestId] :: Response id node payload -> id
- Distributed.Consensus.Raft: [sCluster] :: Snapshot node state -> !ClusterConfiguration node
+ Distributed.Consensus.Raft: [sCluster] :: Snapshot node state -> ClusterConfiguration node
- Distributed.Consensus.Raft: [sData] :: Snapshot node state -> !state
+ Distributed.Consensus.Raft: [sData] :: Snapshot node state -> state
- Distributed.Consensus.Raft: [sMetadata] :: Snapshot node state -> !SnapshotMetadata
+ Distributed.Consensus.Raft: [sMetadata] :: Snapshot node state -> SnapshotMetadata
- Distributed.Consensus.Raft: [smLastIncludedIndex] :: SnapshotMetadata -> !LogIndex
+ Distributed.Consensus.Raft: [smLastIncludedIndex] :: SnapshotMetadata -> LogIndex
- Distributed.Consensus.Raft: [smLastIncludedTerm] :: SnapshotMetadata -> !Term
+ Distributed.Consensus.Raft: [smLastIncludedTerm] :: SnapshotMetadata -> Term
- Distributed.Consensus.Raft.Admin: AdminImplementation :: (node -> AdminRequest node -> m ()) -> m (AdminResponse node) -> (node -> m SessionId) -> AdminImplementation node (m :: Type -> Type)
+ Distributed.Consensus.Raft.Admin: AdminImplementation :: (node -> AdminRequest node -> m ()) -> m (AdminResponse node) -> m SessionId -> AdminImplementation node (m :: Type -> Type)
- Distributed.Consensus.Raft.Admin: ClusterConfigurationIs :: !ClusterConfiguration node -> AdminCommandResult node
+ Distributed.Consensus.Raft.Admin: ClusterConfigurationIs :: ClusterConfiguration node -> AdminCommandResult node
- Distributed.Consensus.Raft.Admin: NotLeader :: !Maybe node -> AdminCommandResult node
+ Distributed.Consensus.Raft.Admin: NotLeader :: ResponsePayload response
- Distributed.Consensus.Raft.Admin: Timeout :: AdminError node
+ Distributed.Consensus.Raft.Admin: Timeout :: SessionError
- Distributed.Consensus.Raft.Admin: [requestId] :: Request id node payload -> !id
+ Distributed.Consensus.Raft.Admin: [requestId] :: Request id node payload -> id
- Distributed.Consensus.Raft.Admin: [requestOriginator] :: Request id node payload -> !node
+ Distributed.Consensus.Raft.Admin: [requestOriginator] :: Request id node payload -> node
- Distributed.Consensus.Raft.Admin: [requestPayload] :: Request id node payload -> !payload
+ Distributed.Consensus.Raft.Admin: [requestPayload] :: Request id node payload -> RequestPayload payload
- Distributed.Consensus.Raft.Admin: [responseClusterLeader] :: Response id node payload -> !Maybe node
+ Distributed.Consensus.Raft.Admin: [responseClusterLeader] :: Response id node payload -> Maybe node
- Distributed.Consensus.Raft.Admin: [responsePayload] :: Response id node payload -> !payload
+ Distributed.Consensus.Raft.Admin: [responsePayload] :: Response id node payload -> ResponsePayload payload
- Distributed.Consensus.Raft.Admin: [responseRequestId] :: Response id node payload -> !id
+ Distributed.Consensus.Raft.Admin: [responseRequestId] :: Response id node payload -> id
- Distributed.Consensus.Raft.Admin: getClusterConfiguration :: forall (m :: Type -> Type) node. MonadSTM m => RaftAdminT node m (AdminRequest node)
+ Distributed.Consensus.Raft.Admin: getClusterConfiguration :: MonadSTM m => AdminSession node m -> m (AdminRequest node)
- Distributed.Consensus.Raft.Admin: joinCluster :: forall (m :: Type -> Type) node. MonadSTM m => node -> RaftAdminT node m (AdminRequest node)
+ Distributed.Consensus.Raft.Admin: joinCluster :: MonadSTM m => AdminSession node m -> node -> m (AdminRequest node)
- Distributed.Consensus.Raft.Admin: leaveCluster :: forall (m :: Type -> Type) node. MonadSTM m => RaftAdminT node m (AdminRequest node)
+ Distributed.Consensus.Raft.Admin: leaveCluster :: MonadSTM m => AdminSession node m -> m (AdminRequest node)
- Distributed.Consensus.Raft.Admin: sessionId :: Word64 -> Word64 -> SessionId
+ Distributed.Consensus.Raft.Admin: sessionId :: forall node (m :: Type -> Type). AdminSession node m -> SessionId
- Distributed.Consensus.Raft.Admin: shutDown :: forall (m :: Type -> Type) node. MonadSTM m => RaftAdminT node m (AdminRequest node)
+ Distributed.Consensus.Raft.Admin: shutDown :: MonadSTM m => AdminSession node m -> m (AdminRequest node)
- Distributed.Consensus.Raft.Client: ClientImplementation :: (node -> ClientRequest entry node -> m ()) -> m (ClientResponse node result) -> (node -> m SessionId) -> ClientImplementation entry node result (m :: Type -> Type)
+ Distributed.Consensus.Raft.Client: ClientImplementation :: (node -> ClientRequest entry node -> m ()) -> m (ClientResponse node result) -> m SessionId -> ClientImplementation entry node result (m :: Type -> Type)
- Distributed.Consensus.Raft.Client: NoKnownLeader :: ClientError entry node
+ Distributed.Consensus.Raft.Client: NoKnownLeader :: SessionError
- Distributed.Consensus.Raft.Client: NotLeader :: ClientResult result
+ Distributed.Consensus.Raft.Client: NotLeader :: ResponsePayload response
- Distributed.Consensus.Raft.Client: Timeout :: ClientError entry node
+ Distributed.Consensus.Raft.Client: Timeout :: SessionError
- Distributed.Consensus.Raft.Client: [requestId] :: Request id node payload -> !id
+ Distributed.Consensus.Raft.Client: [requestId] :: Request id node payload -> id
- Distributed.Consensus.Raft.Client: [requestOriginator] :: Request id node payload -> !node
+ Distributed.Consensus.Raft.Client: [requestOriginator] :: Request id node payload -> node
- Distributed.Consensus.Raft.Client: [requestPayload] :: Request id node payload -> !payload
+ Distributed.Consensus.Raft.Client: [requestPayload] :: Request id node payload -> RequestPayload payload
- Distributed.Consensus.Raft.Client: [responseClusterLeader] :: Response id node payload -> !Maybe node
+ Distributed.Consensus.Raft.Client: [responseClusterLeader] :: Response id node payload -> Maybe node
- Distributed.Consensus.Raft.Client: [responsePayload] :: Response id node payload -> !payload
+ Distributed.Consensus.Raft.Client: [responsePayload] :: Response id node payload -> ResponsePayload payload
- Distributed.Consensus.Raft.Client: [responseRequestId] :: Response id node payload -> !id
+ Distributed.Consensus.Raft.Client: [responseRequestId] :: Response id node payload -> id
- Distributed.Consensus.Raft.Client: newRequest :: forall (m :: Type -> Type) entry node result. MonadSTM m => entry -> RaftClientT entry node result m (ClientRequest entry node)
+ Distributed.Consensus.Raft.Client: newRequest :: MonadSTM m => ClientSession entry node result m -> entry -> m (ClientRequest entry node)
- Distributed.Consensus.Raft.Client: sessionId :: Word64 -> Word64 -> SessionId
+ Distributed.Consensus.Raft.Client: sessionId :: forall entry node result (m :: Type -> Type). ClientSession entry node result m -> SessionId
- Distributed.Consensus.Raft.Client: type ClientResponse node result = Response ClientRequestId node ClientResult result
+ Distributed.Consensus.Raft.Client: type ClientResponse node result = Response ClientRequestId node result

Files

CHANGELOG.md view
@@ -1,5 +1,15 @@ # Revision history for raft-consensus +## 0.2.0.0 -- Unreleased++### Breaking changes++* Uniform data modeling for all remote procedure-calls. In particular, vote requests and results now have+  their own record types (`RequestVote` and `RequestVoteResult`).+* Client and admin interfaces are now session-based: use `withSession` and `sendRequest`.+* Data constructors no longer have a `Mk` prefix.+* `SessionId` and the types needed to serialize requests and responses are now exported.+ ## 0.1.1.0 -- 2026-11-30  * Improved that latency of service read-only requests. In version 0.1.0.0, a read-only request
bench/Main.hs view
@@ -14,9 +14,8 @@ import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.STM (TQueue, atomically, flushTQueue, newTQueueIO, readTQueue, retry, writeTQueue) import Control.DeepSeq (NFData)-import Control.Monad (forever, unless)+import Control.Monad (forever, unless, (>=>)) import Data.Functor ((<&>))-import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.List.NonEmpty (NonEmpty, nonEmpty)@@ -25,19 +24,29 @@ import Data.Set (Set) import qualified Data.Set as Set import Data.Word (Word64)-import Distributed.Consensus.Raft (Config (..), Implementation (..), Microseconds, Networking (..), Persistence (..), RPC, RPCResult, StateMachineStep (..), ephemeralPersistence, runRaftServer)+import Distributed.Consensus.Raft+  ( Config (..),+    Implementation (..),+    Microseconds,+    Networking (..),+    Persistence (..),+    RPC,+    RPCResult,+    StateMachineStep (..),+    ephemeralPersistence,+    runRaftServer,+  ) import qualified Distributed.Consensus.Raft as Raft import Distributed.Consensus.Raft.Admin (AdminRequest, AdminResponse) import Distributed.Consensus.Raft.Client-  ( ClientError (..),-    ClientImplementation (..),+  ( ClientImplementation (..),     ClientRequest,     ClientResponse,+    SessionError (..),     newRequest,     sendClientRequest,-    sessionId,-    withClientSession,   )+import qualified Distributed.Consensus.Raft.Client as Client import GHC.Generics (Generic) import Test.Tasty (TestTree, localOption, withResource) import Test.Tasty.Bench (TimeMode (WallTime), bench, bgroup, defaultMain, nfIO)@@ -135,15 +144,13 @@   serversTid <- async (runServers harness)   link serversTid -  firstLeaderRef <- newIORef 0-  (firstTid, firstClient) <- startClient harness firstLeaderRef (clientNodeId 0)+  (firstTid, firstClient) <- startClient harness (clientNodeId 0)   -- Blocking here until the leader is known   _ <- firstClient (Get 'a') -  leader <- readIORef firstLeaderRef   others <-     traverse-      (\i -> newIORef leader >>= \ref -> startClient harness ref (clientNodeId i))+      (startClient harness . clientNodeId)       [1 .. maxClients - 1]    pure $@@ -161,8 +168,8 @@           mempty           server.sSpec -    startClient :: Harness -> IORef Node -> Node -> IO (Async (), Command -> IO Result)-    startClient harness leaderRef self = do+    startClient :: Harness -> Node -> IO (Async (), Command -> IO Result)+    startClient harness self = do       runnerVar <- newEmptyMVar       tid <- async $         withClient harness self $ \runClientRequest -> do@@ -174,10 +181,8 @@       (tid,) <$> takeMVar runnerVar       where         request run command = do-          leader <- readIORef leaderRef-          run leader command >>= \case-            Right (actualLeader, result) -> writeIORef leaderRef actualLeader >> pure result-            Left (Redirect actualLeader) -> writeIORef leaderRef actualLeader >> request run command+          run command >>= \case+            Right result -> pure result             Left _ -> threadDelay 1_000 >> request run command  stopCluster :: Cluster -> IO ()@@ -205,7 +210,7 @@   deriving (Eq, Show)  data Server-  = MkServer+  = Server   { sConfig :: Config Node,     sSpec :: Implementation Command Node Result State IO   }@@ -223,9 +228,9 @@   Node ->   Server mkServer storage network fabric hbto etolb etoub seed node =-  MkServer+  Server     { sConfig =-        MkConfig+        Config           { nodeId = node,             electionTimeoutRange = (etolb, etoub),             heartBeatTimeout = hbto,@@ -242,14 +247,14 @@     }  data Harness-  = MkHarness+  = Harness   { clusterServers :: IntMap Server,     -- | Open a client session and run an action with it. One session serves-    -- the whole benchmark: see 'withClientSession'.+    -- the whole benchmark.     withClient ::       forall b.       Node ->-      ((Node -> Command -> IO (Either (ClientError Command Node) (Node, Result))) -> IO b) ->+      ((Command -> IO (Either SessionError Result)) -> IO b) ->       IO b   } @@ -277,13 +282,16 @@         mkServer' = mkServer storage network networkFabric hb etlb etup      pure $-      MkHarness+      Harness         { clusterServers =             IntMap.fromList $               map (\(serverSeed, n) -> (n, mkServer' serverSeed (fromIntegral n))) serverNodesWithSeeds,           withClient = \clientNode useClient ->-            withClientSession clientNode (clientSpec networkFabric clientNode) $ \runSession ->-              useClient (\leader comm -> runSession (newRequest comm >>= sendClientRequest maxBound leader))+            Client.withSession clientNode 0 (clientSpec networkFabric clientNode) $ \session ->+              useClient+                ( newRequest session+                    >=> Client.sendRequest session maxBound+                )         }     where       adminNode = -1@@ -293,14 +301,14 @@        clientSpec fabric clientNode =         ClientImplementation-          { sendRequest =+          { sendClientRequest =               -- No latency because that's not due to the cluster               send 0 fabric.requestsMailbox,-            receiveResponse =+            receiveClientResponse =               receive fabric.responsesMailbox clientNode,             -- We should generate a random session ID in normal circumstances,             -- but for a benchmark this doesn't matter-            generateSessionId = pure . sessionId 0 . fromIntegral+            generateClientSessionId = Client.randomSessionId           }  send :: Int -> IntMap (TQueue a) -> Node -> a -> IO ()@@ -378,7 +386,7 @@         }  data NetworkFabric-  = MkNetworkFabric+  = NetworkFabric   { rpcMailbox :: Mailbox (RPC Command Node State),     rpcResultsMailbox :: Mailbox (RPCResult Node Result),     requestsMailbox :: Mailbox (ClientRequest Command Node),@@ -389,7 +397,7 @@  newNetworkFabric :: Set Node -> IO NetworkFabric newNetworkFabric nodes =-  MkNetworkFabric+  NetworkFabric     <$> newMailbox     <*> newMailbox     <*> newMailbox
raft-consensus.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.4 name:               raft-consensus-version:            0.1.1.0+version:            0.2.0.0 synopsis:           Haskell implementation of the Raft consensus protocol -- description: homepage:           https://github.com/LaurentRDC/distributed-consensus@@ -46,6 +46,7 @@                       Distributed.Consensus.Raft.Implementation                       Distributed.Consensus.Raft.Log                       Distributed.Consensus.Raft.Messaging+                      Distributed.Consensus.Raft.Session                       Distributed.Consensus.Raft.Transformer                       Distributed.Consensus.Raft.Transformer.Definition                       Distributed.Consensus.Raft.Timer@@ -74,6 +75,7 @@                       Test.Distributed.Consensus.Raft.Client                       Test.Distributed.Consensus.Raft.Options                       Test.Distributed.Consensus.Raft.Properties+                      Test.Distributed.Consensus.Raft.Session                       Test.Distributed.Consensus.Raft.Scenario                       Test.StateMachine     ghc-options:      -rtsopts -threaded -with-rtsopts=-N@@ -82,7 +84,7 @@                     , raft-consensus                     , io-classes                     , io-sim ^>=1.11-                    , linearizable ^>=0.1+                    , linearizable ^>=0.2                     , pretty-simple ^>=4.1                     , random                     , tagged ^>=0.8
src/Distributed/Consensus/Raft.hs view
@@ -55,9 +55,13 @@ --    A separate package @raft-consensus-wal@ is provided in case you wish to use --    a write-ahead log from the @wal@ package. ----- Once this is done, you are ready to start individual nodes of your cluster using 'runRaftServer'--- or 'withRaftServer'.+-- These pieces are bundled in an 'Implementation'. Once this is done, you are ready to start individual+-- nodes of your cluster using 'runRaftServer' or 'withRaftServer'. --+-- If you wish to implement your own networking and/or persistence, you will need to+-- implement your own serialization and deserialization. To help with this, check out other+-- supporting packages such as @raft-consensus-serialise-instances@.+-- -- === How does one interact with a @raft-consensus@-based cluster? -- -- There are two ways to interact with a cluster:@@ -88,25 +92,20 @@      -- * Protocol implementation     Implementation (..),-    Networking (..),-    Persistence (..),-    StateMachineStep (..),-    runStateMachineStep, -    -- ** Helpers+    -- ** Tracing     nullTracer,++    -- ** Networking+    Networking (..),++    -- ** Persistance+    Persistence (..),     ephemeralPersistence, -    -- ** Domain types-    LogEntry (..),-    Term,-    Role,-    ClientRequestId,-    ClusterConfiguration (..),-    LogIndex,-    Snapshot (..),-    SnapshotMetadata (..),-    SessionId,+    -- ** State machine modeling+    StateMachineStep (..),+    runStateMachineStep,      -- ** Remote procedure calls     RPC (..),@@ -115,16 +114,43 @@     CommandResponse (..),     AppendEntries (..),     AppendEntriesResult (..),+    RequestVote (..),+    RequestVoteResult (..),     InstallSnapshot (..),     InstallSnapshotResult (..),     ClusterMembershipRequest (..),     ClusterMembershipResult (..),     ClusterMembershipError (..), +    -- ** Domain types+    LogEntry (..),+    Term,+    Role (..),+    ClientRequestId (..),+    ClusterConfiguration (..),+    LogIndex,+    ReadOnlySequenceNum,+    Snapshot (..),+    SnapshotMetadata (..),+    SessionId (..),+    SequenceNum,+     -- ** Messaging     Request (..),+    RequestPayload (..),     Response (..),+    ResponsePayload (..),+    SessionError (..),+    ClientRequest,+    ClientResponse, +    -- ** Administration+    AdminRequest,+    AdminResponse,+    AdminRequestId (..),+    AdminCommand (..),+    AdminCommandResult (..),+     -- ** Event tracing     Event (..),     EventContext (..),@@ -139,18 +165,27 @@ import Control.Monad.Class.MonadThrow (MonadMask) import Control.Monad.Class.MonadTimer (MonadDelay) import Distributed.Consensus.Raft.Algorithm (server)-import Distributed.Consensus.Raft.Client (ClientRequestId) import Distributed.Consensus.Raft.Domain   ( ClusterConfiguration (..),     LogIndex,-    Role,-    SessionId,+    ReadOnlySequenceNum,+    Role (..),+    SequenceNum,+    SessionId (..),     Snapshot (..),     SnapshotMetadata (..),     StateMachineStep (..),     Term,     runStateMachineStep,   )+import Distributed.Consensus.Raft.Domain.Admin+  ( AdminCommand (..),+    AdminCommandResult (..),+    AdminRequest,+    AdminRequestId (..),+    AdminResponse,+  )+import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId (..), ClientResponse) import Distributed.Consensus.Raft.Implementation   ( AppendEntries (..),     AppendEntriesResult (..),@@ -170,14 +205,14 @@     RPC (..),     RPCResult (..),     RaftTrace (..),+    RequestVote (..),+    RequestVoteResult (..),     ephemeralPersistence,     nullTracer,   ) import Distributed.Consensus.Raft.Log (Log)-import Distributed.Consensus.Raft.Messaging-  ( Request (..),-    Response (..),-  )+import Distributed.Consensus.Raft.Messaging (Request (..), RequestPayload (..), Response (..), ResponsePayload (..))+import Distributed.Consensus.Raft.Session (SessionError (..)) import Distributed.Consensus.Raft.Timer (Microseconds (..)) import Distributed.Consensus.Raft.Transformer   ( ClusterState (..),
src/Distributed/Consensus/Raft/Admin.hs view
@@ -1,11 +1,4 @@-{-# LANGUAGE BangPatterns #-}-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE DerivingStrategies #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedRecordDot #-}-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE TemplateHaskell #-}  -- | -- Module:      $module@@ -18,22 +11,27 @@ -- -- The key piece of information to use this module effectively is that -- interactions are done in /sessions/. An admin starts a session--- by calling 'withAdminSession', and all requests will have to originate--- from within.+-- by calling 'withSession', and all requests originate from the+-- resulting 'AdminSession' handle. --+-- This module is intended to be imported qualified; its exports+-- clash with the exports of "Distributed.Consensus.Raft.Client".+-- -- Try to keep sessions open as long as possible -- ideally for the length -- of an admin's lifetime. -- -- Administrators create requests using 'leaveCluster', 'joinCluster', or other builders.--- Requests are then sent using 'sendAdminCommand'. Interacting with a cluster may--- require retrying or redirecting requests; reuse requests as much as possible.--- To keep the implementation flexible, retrying and redirecting is something--- you need to do yourself.+-- Requests are then sent using 'sendRequest'. module Distributed.Consensus.Raft.Admin   ( -- * Interface-    withAdminSession,-    RaftAdminT,+    withSession,+    AdminSession, +    -- ** Session information+    sessionId,+    lowestUnacknowledgedSequenceNum,+    setLeader,+     -- ** Creating commands     leaveCluster,     joinCluster,@@ -41,21 +39,27 @@     shutDown,      -- ** Sending commands-    sendAdminCommand,-    AdminError (..),+    sendRequest,+    SessionError (..),      -- ** Configuration     AdminImplementation (..),+    randomSessionId, -    -- * Other exports-    SessionId,-    sessionId,-    SequenceNum,-    Microseconds,+    -- ** Messaging     AdminRequest,     Request (..),+    RequestPayload (..),     AdminResponse,     Response (..),+    ResponsePayload (..),++    -- * Other exports+    SessionId (..),+    SequenceNum,+    Microseconds,+    ClusterConfiguration (..),+    AdminRequestId (..),     AdminCommand (..),     AdminCommandResult (..),   )@@ -63,150 +67,134 @@  import Control.Concurrent.Class.MonadSTM   ( MonadSTM,-    TMVar,-    TVar,-    atomically,-    check,-    newEmptyTMVar,-    newTVarIO,-    orElse,-    readTMVar,-    readTVar,-    tryPutTMVar,-    writeTVar,+    STM,   )-import Control.Monad (void)-import Control.Monad.Class.MonadAsync (MonadAsync, link, withAsync)+import Control.Monad.Class.MonadAsync (MonadAsync) import Control.Monad.Class.MonadFork (MonadFork) import Control.Monad.Class.MonadThrow (MonadMask)-import Control.Monad.Class.MonadTimer (MonadTimer, registerDelay)-import Control.Monad.Trans.Class (MonadTrans (lift))-import Control.Monad.Trans.Reader (ReaderT (runReaderT))-import qualified Control.Monad.Trans.Reader as Reader-import Data.Map (Map)-import qualified Data.Map.Strict as Map-import Distributed.Consensus.Raft.Domain (SequenceNum, SessionId, sessionId)+import Control.Monad.Class.MonadTimer (MonadTimer)+import Distributed.Consensus.Raft.Domain (ClusterConfiguration (..), SequenceNum, SessionId (..)) import Distributed.Consensus.Raft.Domain.Admin   ( AdminCommand (..),     AdminCommandResult (..),     AdminRequest,-    AdminRequestId (MkAdminRequestId),+    AdminRequestId (..),     AdminResponse,   )-import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))+import Distributed.Consensus.Raft.Session+  ( Request (..),+    RequestPayload (..),+    Response (..),+    ResponsePayload (..),+    Session,+    SessionError (..),+    SessionImplementation (..),+    randomSessionId,+  )+import qualified Distributed.Consensus.Raft.Session as Session import Distributed.Consensus.Raft.Timer (Microseconds)-import Lens.Micro.Platform (makeLenses) --- | Admin monad transformer to issue administrative commands to a Raft cluster.------ The only way to execute an action of type 'RaftAdminT' is with--- 'withAdminSession'.-newtype RaftAdminT node m a-  = MkRaftAdminT (ReaderT (RaftAdminEnv node m) m a)-  deriving (Functor, Applicative, Monad)--instance MonadTrans (RaftAdminT node) where-  lift = MkRaftAdminT . lift--asks :: (Monad m) => (RaftAdminEnv node m -> a) -> RaftAdminT node m a-asks = MkRaftAdminT . Reader.asks- -- | Implementation of communication between an administrator and a cluster. --+-- Besides the requests you create with the builders in this module, a session+-- sends requests with a 'Heartbeat' payload to the leader periodically.+-- -- See the @raft-consensus-distributed-process@ package for an example -- implementation for the Cloud Haskell ecosystem. data AdminImplementation node m = AdminImplementation   { -- | Send an admin request to a node.     sendAdminRequest :: node -> AdminRequest node -> m (),-    -- | Receive the next admin response.+    -- | Receive the next admin response, from any node. This should block until+    -- a response is available.     receiveAdminResponse :: m (AdminResponse node),     -- | Generate a globally-unique session ID.-    generateSessionId :: node -> m SessionId+    --+    -- See 'randomSessionId' for a good default implementation if+    -- the underlying monad @m@ supports IO.+    generateAdminSessionId :: m SessionId   } --- | Open an admin session, and run an action with a runner for that session.+adminToSessionImplementation ::+  AdminImplementation node m ->+  SessionImplementation+    AdminRequestId+    node+    (AdminCommand node)+    (AdminCommandResult node)+    m+adminToSessionImplementation adminImpl =+  SessionImplementation+    { implSendRequest = adminImpl.sendAdminRequest,+      implReceiveResponse = adminImpl.receiveAdminResponse,+      implGenerateSessionId = adminImpl.generateAdminSessionId,+      implMakeRequestId = AdminRequestId+    }++-- | Open an admin session, and run an action with a handle to that session. ----- It is safe to use the runner from several threads concurrently.+-- It is safe to use the 'AdminSession' from several threads concurrently. ----- The typical way you would use 'withAdminSession' is like so:+-- The typical way you would use 'withSession' is like so: -- -- @--- 'withAdminSession' nodeId $ \\run -> do---     req <- run 'shutDown'+-- 'withSession' self lastKnownLeader impl $ \\session -> do+--     req <- 'shutDown' session -----     let go serverNode =---             run ('sendAdminCommand' 1000000 serverNode req) >>= \case---                Left _ -> go serverNode -- infinite retries---                Right resp -> pure resp+--     let go = do+--             result <- 'sendRequest' session 1_000_000 (Just nodeToShutDown) req+--             case result of+--                 Left _ -> go+--                 Right r -> pure r -----     go lastKnownLeader+--     go -- @------ In practice, 'withAdminSession' is usually run in its own thread,--- and requests are sent over to that thread using e.g. a 'TQueue'.-withAdminSession ::+withSession ::   ( MonadAsync m,     MonadFork m,-    MonadMask m+    MonadMask m,+    MonadTimer m   ) =>   -- | self identification   node ->+  -- | Initial guess for the cluster leader. This is corrected automatically+  -- from the responses of the cluster.+  node ->   AdminImplementation node m ->-  ((forall a. RaftAdminT node m a -> m a) -> m b) ->+  (AdminSession node m -> m b) ->   m b-withAdminSession self impl withSession = do-  nRId <- newTVarIO 0-  mbox <- newTVarIO mempty-  sessId <- generateSessionId impl self-  let recvLoop = do-        receiveAdminResponse impl >>= \resp -> do-          let adminReqId = responseRequestId resp-          atomically $ do-            box <- readTVar mbox-            case Map.lookup adminReqId box of-              Nothing -> pure ()-              -- Using 'tryPutTMVar' here in case of duplicate responses-              Just var -> void $ tryPutTMVar var (responsePayload resp)-          recvLoop+withSession self leader impl f = do+  Session.withSession self leader (adminToSessionImplementation impl) (f . AdminSession) -  withAsync recvLoop $ \thread -> do-    link thread-    withSession-      ( \(MkRaftAdminT f) ->-          runReaderT-            f-            (MkRaftAdminEnv self sessId impl nRId mbox)-      )+-- | Handle to an open admin session. See 'withSession'.+newtype AdminSession node m = AdminSession (Session AdminRequestId node (AdminCommand node) (AdminCommandResult node) m) -data RaftAdminEnv node m-  = MkRaftAdminEnv-  { node :: !node,-    currentSessionId :: !SessionId,-    implementation :: AdminImplementation node m,-    nextRequestId :: TVar m SequenceNum,-    mailbox :: TVar m (Map AdminRequestId (TMVar m (AdminCommandResult node)))-  }+-- | Read the current session ID. This helper can be useful if you need+-- to pin information to the current client+sessionId :: AdminSession node m -> SessionId+sessionId (AdminSession session) = Session.sessionId session -makeLenses ''AdminImplementation+-- | Returns the smallest unacknowledged 'SequenceNum' for outstanding requests.+lowestUnacknowledgedSequenceNum :: (MonadSTM m) => AdminSession node m -> STM m SequenceNum+lowestUnacknowledgedSequenceNum (AdminSession session) = Session.lowestUnacknowledgedSequenceNum session -data AdminError node-  = AdminNotLeader !(Maybe node)-  | Timeout-  | UnexpectedAdminResponse-  deriving (Eq, Show)+-- | Force-set a leader to this session.+--+-- This should only be used in case no leader is known by any of the+-- cluster nodes, for example to try another node after 'sendRequest'+-- returned 'NoKnownLeader'.+setLeader :: (MonadSTM m) => AdminSession node m -> node -> m ()+setLeader (AdminSession session) = Session.setLeader session -newCommand ::+-- | Create a request to run an administrative command.+--+-- Creating a request does not send anything; use 'sendRequest'.+newRequest ::   (MonadSTM m) =>+  AdminSession node m ->   AdminCommand node ->-  RaftAdminT node m (AdminRequest node)-newCommand entry = do-  (seqNumVar, sessId, self) <- asks ((,,) <$> nextRequestId <*> currentSessionId <*> node)-  reqId <- lift $ atomically $ do-    nextSeqNum <- readTVar seqNumVar-    writeTVar seqNumVar (succ nextSeqNum)-    pure $ MkAdminRequestId sessId nextSeqNum--  pure $ MkRequest reqId self entry+  m (AdminRequest node)+newRequest (AdminSession session) command =+  Session.newRequest session (RequestPayload command)  -- | Command that a node join a Raft cluster. --@@ -214,77 +202,55 @@ -- cluster. joinCluster ::   (MonadSTM m) =>+  AdminSession node m ->   -- | Leader of the cluster to join   node ->-  RaftAdminT node m (AdminRequest node)-joinCluster = newCommand . JoinCluster+  m (AdminRequest node)+joinCluster session = newRequest session . JoinCluster  -- | Command that a node leave the Raft cluster. -- -- Note that this node will not shut down unless the 'shutDown' -- command is also sent to it.-leaveCluster :: (MonadSTM m) => RaftAdminT node m (AdminRequest node)-leaveCluster = newCommand LeaveCluster+leaveCluster :: (MonadSTM m) => AdminSession node m -> m (AdminRequest node)+leaveCluster session = newRequest session LeaveCluster  -- | Ask a node for the cluster configuration it has committed. -- -- This is the only way for an admin to tell whether a 'joinCluster' or -- 'leaveCluster' has actually taken effect.-getClusterConfiguration :: (MonadSTM m) => RaftAdminT node m (AdminRequest node)-getClusterConfiguration = newCommand GetClusterConfiguration+getClusterConfiguration :: (MonadSTM m) => AdminSession node m -> m (AdminRequest node)+getClusterConfiguration session = newRequest session GetClusterConfiguration  -- | Request that a node shuts down.-shutDown :: (MonadSTM m) => RaftAdminT node m (AdminRequest node)-shutDown = newCommand ShutDown+shutDown :: (MonadSTM m) => AdminSession node m -> m (AdminRequest node)+shutDown session = newRequest session ShutDown -sendAdminCommand ::-  (MonadTimer m) =>+-- | Send an admin request to a Raft cluster, and wait for its result.+--+-- If a node replies that it is not the leader and names the leader, the request+-- is sent to that leader instead, until the timeout expires.+--+-- The timeout covers the whole call, redirections included. Because+-- 'Microseconds' is a 32-bit integer, timeouts are limited to about 35 minutes.+--+-- Note that 'JoinInitiated' and 'LeaveInitiated' only mean that the change+-- was started; use 'getClusterConfiguration' to see whether it took effect.+sendRequest ::+  (MonadTimer m, MonadMask m) =>+  AdminSession node m ->+  -- | Maximum time to wait for a response.   Microseconds ->-  node ->+  -- | Node to command. If @Nothing@, the command is sent to+  -- the leader of the cluster+  Maybe node ->   AdminRequest node ->-  RaftAdminT-    node-    m+  m     ( Either-        (AdminError node)+        SessionError         (AdminCommandResult node)     )-sendAdminCommand timeout contact req@(MkRequest reqId _ command) = do-  send <- asks (sendAdminRequest . implementation)-  mbox <- asks mailbox-  lift $ do-    resultVar <- atomically $ do-      mbox' <- readTVar mbox-      resultVar <- newEmptyTMVar-      writeTVar mbox (Map.insert reqId resultVar mbox')--      pure resultVar--    expired <- registerDelay (fromIntegral timeout)-    send contact req--    -- TODO: clean up mailbox entry for req ID-    --       regardless of success (possibly using 'bracket')-    atomically-      ( ( do-            resp <- readTMVar resultVar-            mbox' <- readTVar mbox-            writeTVar mbox (Map.delete reqId mbox')-            pure (expectedResponse command (Just resp))-        )-          `orElse` ( do-                       readTVar expired >>= check-                       readTVar mbox >>= writeTVar mbox . Map.delete reqId-                       pure (expectedResponse command Nothing)-                   )-      )---- TODO: is there a better way to associate valid responses based on the request?-expectedResponse :: AdminCommand node -> Maybe (AdminCommandResult node) -> Either (AdminError node) (AdminCommandResult node)-expectedResponse _ Nothing = Left Timeout-expectedResponse _ (Just (NotLeader leader)) = Left (AdminNotLeader leader)-expectedResponse (JoinCluster {}) (Just JoinInitiated) = Right JoinInitiated-expectedResponse (LeaveCluster {}) (Just LeaveInitiated) = Right LeaveInitiated-expectedResponse GetClusterConfiguration (Just resp@(ClusterConfigurationIs {})) = Right resp-expectedResponse ShutDown (Just ShutdownInitiated) = Right ShutdownInitiated-expectedResponse _ _ = Left UnexpectedAdminResponse+sendRequest (AdminSession session) =+  Session.sendRequest+    (\(AdminRequestId _ seqNum) -> seqNum)+    session
src/Distributed/Consensus/Raft/Algorithm.hs view
@@ -30,7 +30,6 @@ import qualified Distributed.Consensus.Raft.Admin as Admin import Distributed.Consensus.Raft.Domain   ( ClusterConfiguration (..),-    LogIndex,     Role (..),     Snapshot (..),     SnapshotMetadata (..),@@ -38,7 +37,7 @@     Term,   ) import Distributed.Consensus.Raft.Domain.Admin (AdminCommand (..), AdminRequest)-import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientResult (..))+import Distributed.Consensus.Raft.Domain.Client (ClientRequest) import Distributed.Consensus.Raft.Implementation   ( AppendEntries (..),     AppendEntriesResult (..),@@ -55,11 +54,13 @@     RPC (..),     RPCResult (..),     RaftTrace (..),+    RequestVote (..),+    RequestVoteResult (..),   ) import qualified Distributed.Consensus.Raft.Implementation as Impl import Distributed.Consensus.Raft.Log (Lookup (..), lastLogIndex, (!?)) import qualified Distributed.Consensus.Raft.Log as Log-import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))+import Distributed.Consensus.Raft.Messaging (Request (..), RequestPayload (..), Response (..), ResponsePayload (..)) import Distributed.Consensus.Raft.Transformer   ( Config (..),     PersistenceBatch (..),@@ -199,7 +200,7 @@       labelThisThread "persistence"       let write = impl.persistence.writeLogEntry node       forever $ do-        MkPersistenceBatch t lastLogIx entries <-+        PersistenceBatch t lastLogIx entries <-           atomically             -- I don't know how much this is expected to happen, but in case             -- multiple writes are queued up, we batch them into a group commit@@ -238,13 +239,11 @@    queued <- lift (atomically go)   handleClientRequest (NonEmpty.appendList requests (concatMap NonEmpty.toList queued))-handleEvent (EventRPC (RequestVote candidateTerm candidateNode candidateLastLogEntry candidateLastLogEntryTerm)) =-  handleRequestVote candidateTerm candidateNode candidateLastLogEntry candidateLastLogEntryTerm+handleEvent (EventRPC (RV requestVote)) = handleRequestVote requestVote handleEvent (EventRPC (AE appendEntries)) = handleAppendEntries appendEntries handleEvent (EventRPC (IS installSnapshot)) = handleInstallSnapshot installSnapshot handleEvent (EventRPC (CM clusterMembershipRequest)) = handleClusterMembershipRequest clusterMembershipRequest-handleEvent (EventRPCResult (RequestVoteResult voter voterTerm votedForUs)) =-  handleRequestVoteResult voter voterTerm votedForUs+handleEvent (EventRPCResult (RVR requestVoteResult)) = handleRequestVoteResult requestVoteResult handleEvent (EventRPCResult (AER appendEntriesResult)) = handleAppendEntriesResult appendEntriesResult handleEvent (EventRPCResult (ISR installSnapshotResult)) = handleInstallSnapshotResult installSnapshotResult handleEvent (EventRPCResult (CMR clusterMembershipResult)) = handleClusterMembershipResult clusterMembershipResult@@ -267,19 +266,19 @@   use role >>= \case     NonMember ->       runSend $ do-        for_ requests $ \(MkRequest reqId clientId _) ->-          Transformer.sendClientResponse clientId (MkResponse reqId mLeaderId NotLeader)+        for_ requests $ \(Request reqId clientId _ _) ->+          Transformer.sendClientResponse clientId (Response reqId mLeaderId NotLeader)     Candidate ->       runSend $-        for_ requests $ \(MkRequest reqId clientId _) ->-          Transformer.sendClientResponse clientId (MkResponse reqId mLeaderId NotLeader)+        for_ requests $ \(Request reqId clientId _ _) ->+          Transformer.sendClientResponse clientId (Response reqId mLeaderId NotLeader)     Follower ->       runSend $-        for_ requests $ \(MkRequest reqId clientId _) ->-          Transformer.sendClientResponse clientId (MkResponse reqId mLeaderId NotLeader)+        for_ requests $ \(Request reqId clientId _ _) ->+          Transformer.sendClientResponse clientId (Response reqId mLeaderId NotLeader)     Leader -> do-      reqIds <- acceptClientRequests requests-      let commands = NonEmpty.zipWith Command reqIds (requestPayload <$> requests)+      commands <- acceptClientRequests requests+       -- TODO: trace in separate thread?       for_ commands $ \(Command rid entry) ->         trace (\ctx -> CommandReceived ctx rid entry)@@ -297,7 +296,7 @@       ourTerm <- use term       traverse_         (appendLogEntries . fmap (\c -> (ourTerm, LogEntryCommand c)))-        (NonEmpty.nonEmpty $ NonEmpty.filter isNotReadOnly commands)+        (NonEmpty.nonEmpty $ filter isNotReadOnly commands)        broadcastForPendingReads @@ -504,18 +503,25 @@     MonadFork m,     MonadDelay m   ) =>-  Term ->-  node ->-  LogIndex ->-  Term ->+  RequestVote node ->   RaftT entry node result state m ()-handleRequestVote candidateTerm candidateNode candidateLastLogIndex candidateLastLogIndexTerm = do+handleRequestVote (RequestVote candidateTerm candidateNode candidateLastLogIndex candidateLastLogIndexTerm) = do   termOrdering <- handleTermNumber candidateTerm   ourTerm <- use term   s <- self   trace (\ctx -> VoteRequestedBy ctx candidateTerm candidateNode)   case termOrdering of-    LT -> runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm False)+    LT ->+      runSend $+        Transformer.sendRPCResult+          candidateNode+          ( RVR $+              RequestVoteResult+                { rvrVoterNode = s,+                  rvrVoterTerm = ourTerm,+                  rvrVoteGranted = False+                }+          )     _ -> do       when (termOrdering == GT) $ leaderStepDown Nothing       mAlreadyVoted <- use votedFor@@ -530,18 +536,54 @@               grantVote ourTerm               trace (\ctx -> VotedFor ctx candidateTerm candidateNode)             else do-              runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm False)+              runSend $+                Transformer.sendRPCResult+                  candidateNode+                  ( RVR $+                      RequestVoteResult+                        { rvrVoterNode = s,+                          rvrVoterTerm = ourTerm,+                          rvrVoteGranted = False+                        }+                  )         -- We already voted for this candidate         Just someCandidate           | someCandidate == candidateNode ->-              runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm True)+              runSend $+                Transformer.sendRPCResult+                  candidateNode+                  ( RVR $+                      RequestVoteResult+                        { rvrVoterNode = s,+                          rvrVoterTerm = ourTerm,+                          rvrVoteGranted = True+                        }+                  )         -- We already voted, for another candidate         Just _ ->-          runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm False)+          runSend $+            Transformer.sendRPCResult+              candidateNode+              ( RVR $+                  RequestVoteResult+                    { rvrVoterNode = s,+                      rvrVoterTerm = ourTerm,+                      rvrVoteGranted = False+                    }+              )   where     grantVote ourTerm = do       s <- self-      runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm True)+      runSend $+        Transformer.sendRPCResult+          candidateNode+          ( RVR $+              RequestVoteResult+                { rvrVoterNode = s,+                  rvrVoterTerm = ourTerm,+                  rvrVoteGranted = True+                }+          )       r <- use role       when (r == Follower) resetElectionTimer @@ -553,8 +595,8 @@     MonadMVar m,     MonadDelay m   ) =>-  node -> Term -> Bool -> RaftT entry node result state m ()-handleRequestVoteResult voter voterTerm votedForUs = do+  RequestVoteResult node -> RaftT entry node result state m ()+handleRequestVoteResult (RequestVoteResult voter voterTerm votedForUs) = do   handleTermNumber voterTerm >>= \case     LT -> pure () -- Vote request for an old term     _ -> do@@ -622,13 +664,13 @@         ClusterMembershipJoinRequest r -> (r, ClusterMembershipJoinResult)         ClusterMembershipLeaveRequest r -> (r, ClusterMembershipLeaveResult)   use role >>= \case-    NonMember -> self >>= \s -> runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (NoKnownLeader s))))-    Candidate -> self >>= \s -> runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (NoKnownLeader s))))+    NonMember -> self >>= \s -> runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (ClusterMembershipNoKnownLeader s))))+    Candidate -> self >>= \s -> runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (ClusterMembershipNoKnownLeader s))))     Follower ->       use currentLeader >>= \case         Nothing -> do           s <- self-          runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (NoKnownLeader s))))+          runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (ClusterMembershipNoKnownLeader s))))         Just leader -> runSend $ Transformer.sendRPC leader (CM request) -- forward to leader     Leader -> do       s <- self@@ -689,21 +731,30 @@   ClusterMembershipLeaveResult (Left _) -> pure ()  handleAdminRequest :: (MonadMVar m, MonadAsync m) => AdminRequest node -> RaftT entry node result state m ()-handleAdminRequest req@(MkRequest reqId adminId command) = do+-- TODO: handle lowestOutstandingSeqNum+handleAdminRequest (Request reqId adminId _lowestOutstandingSeqNum Heartbeat) =+  use currentLeader >>= \mLeader ->+    runSend (Transformer.sendAdminResponse adminId (Response reqId mLeader HeartbeatEcho))+handleAdminRequest req@(Request reqId adminId _lowestOutstandingSeqNum (RequestPayload command)) = do   trace (`AdminRequestReceived` req)   mLeaderId <- use currentLeader   case command of     ShutDown -> do       view exitLock >>= lift . (`putMVar` ())-      runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId Admin.ShutdownInitiated)+      runSend $ Transformer.sendAdminResponse adminId (Response reqId mLeaderId (ResponsePayload Admin.ShutdownInitiated))     GetClusterConfiguration ->       use role >>= \case-        Leader -> use clusterConfiguration >>= \conf -> runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId (Admin.ClusterConfigurationIs conf))-        _ -> runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId (Admin.NotLeader mLeaderId))+        Leader ->+          use clusterConfiguration >>= \conf ->+            runSend $+              Transformer.sendAdminResponse+                adminId+                (Response reqId mLeaderId (ResponsePayload $ Admin.ClusterConfigurationIs conf))+        _ -> runSend $ Transformer.sendAdminResponse adminId (Response reqId mLeaderId NotLeader)     (JoinCluster target) -> do       self >>= runSend . Transformer.sendRPC target . CM . ClusterMembershipJoinRequest-      runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId Admin.JoinInitiated)+      runSend $ Transformer.sendAdminResponse adminId (Response reqId mLeaderId (ResponsePayload Admin.JoinInitiated))     LeaveCluster -> do       s <- self       enqueueEvent (EventRPC (CM (ClusterMembershipLeaveRequest s)))-      runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId Admin.LeaveInitiated)+      runSend $ Transformer.sendAdminResponse adminId (Response reqId mLeaderId (ResponsePayload Admin.LeaveInitiated))
src/Distributed/Consensus/Raft/Client.hs view
@@ -1,10 +1,4 @@-{-# LANGUAGE DerivingStrategies #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE OverloadedRecordDot #-}  -- | -- Module:      $module@@ -17,285 +11,228 @@ -- -- The key piece of information to use this module effectively is that -- interactions are done in /sessions/. A client starts a session--- by calling 'withClientSession', and all requests will have to originate--- from within.+-- by calling 'withSession', and all requests originate from the+-- resulting 'ClientSession' handle. --+-- This module is intended to be imported qualified; its exports+-- clash with the exports of "Distributed.Consensus.Raft.Admin".+-- -- Try to keep sessions open as long as possible -- ideally for the length -- of a client's lifetime. -- -- Clients create requests using 'newRequest', and send those requests--- to a cluster via 'sendClientRequest'. Interacting with a cluster may--- require retrying or redirecting requests; reuse requests as much as possible.--- To keep the implementation flexible, retrying and redirecting is something--- you need to do yourself.+-- to a cluster via 'sendRequest'. module Distributed.Consensus.Raft.Client   ( -- * Interface-    withClientSession,-    RaftClientT,+    withSession,+    ClientSession, +    -- ** Session information+    sessionId,+    lowestUnacknowledgedSequenceNum,+    setLeader,+     -- ** Creating requests     newRequest,      -- ** Sending requests-    sendClientRequest,-    ClientError (..),+    sendRequest,+    SessionError (..),      -- ** Configuration     ClientImplementation (..),+    randomSessionId, -    -- ** Session information-    clientSession,+    -- ** Messaging+    ClientRequest,+    Request (..),+    RequestPayload (..),+    ClientResponse,+    Response (..),+    ResponsePayload (..),      -- * Other exports-    SessionId,-    sessionId,+    SessionId (..),     SequenceNum,     Microseconds,     ClientRequestId (..),-    ClientRequest,-    Request (..),-    ClientResponse,-    Response (..),-    ClientResult (..),   ) where  import Control.Concurrent.Class.MonadSTM   ( MonadSTM,-    TMVar,-    TVar,-    atomically,-    check,-    newEmptyTMVar,-    newTVarIO,-    orElse,-    readTMVar,-    readTVar,-    tryPutTMVar,-    writeTVar,+    STM,   )-import Control.Monad (void)-import Control.Monad.Class.MonadAsync (MonadAsync, link, withAsync)+import Control.Monad.Class.MonadAsync (MonadAsync) import Control.Monad.Class.MonadFork (MonadFork) import Control.Monad.Class.MonadThrow (MonadMask)-import Control.Monad.Class.MonadTimer (MonadTimer, registerDelay)-import Control.Monad.Trans.Class (MonadTrans, lift)-import Control.Monad.Trans.Reader (ReaderT (runReaderT), asks)-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as Map-import Data.Semigroup (Max (..))+import Control.Monad.Class.MonadTimer (MonadTimer) import Distributed.Consensus.Raft.Domain.Client   ( ClientRequest,     ClientRequestId (..),     ClientResponse,-    ClientResult (..),     SequenceNum,-    SessionId,-    sessionId,+    SessionId (..),   )-import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))+import Distributed.Consensus.Raft.Session+  ( Request (..),+    RequestPayload (..),+    Response (..),+    ResponsePayload (..),+    Session,+    SessionError (..),+    SessionImplementation (..),+    randomSessionId,+  )+import qualified Distributed.Consensus.Raft.Session as Session import Distributed.Consensus.Raft.Timer (Microseconds)-import Lens.Micro.Platform (makeLenses) --- | Client monad transformer to make requests to a Raft cluster.------ The only way to execute an action of type 'RaftClientT' is with--- 'withClientSession'.-newtype RaftClientT entry node result m a-  = MkRaftClientT (ReaderT (RaftClientEnv entry node result m) m a)-  deriving (Functor, Applicative, Monad)--instance MonadTrans (RaftClientT entry node result) where-  lift = MkRaftClientT . lift- -- | Implementation of communication between a client and a cluster. --+-- Besides the requests you create with 'newRequest', a session sends requests+-- with a 'Heartbeat' payload to the leader periodically+-- -- See the @raft-consensus-distributed-process@ package for an example -- implementation for the Cloud Haskell ecosystem. data ClientImplementation entry node result m = ClientImplementation-  { sendRequest :: node -> ClientRequest entry node -> m (),-    receiveResponse :: m (ClientResponse node result),+  { -- | Send a request to a node.+    sendClientRequest :: node -> ClientRequest entry node -> m (),+    -- | Receive the next response, from any node. This should block until+    -- a response is available.+    receiveClientResponse :: m (ClientResponse node result),     -- | Generate a globally-unique session ID.-    generateSessionId :: node -> m SessionId+    --+    -- See 'randomSessionId' for a good default implementation if+    -- the underlying monad @m@ supports IO.+    generateClientSessionId :: m SessionId   } --- | Open a client session, and run an action with a runner for that session.------ It is safe to use the runner from several threads concurrently.+clientToSessionImplementation ::+  ClientImplementation entry node result m ->+  SessionImplementation+    ClientRequestId+    node+    entry+    result+    m+clientToSessionImplementation clientImpl =+  SessionImplementation+    { implSendRequest = clientImpl.sendClientRequest,+      implReceiveResponse = clientImpl.receiveClientResponse,+      implGenerateSessionId = clientImpl.generateClientSessionId,+      implMakeRequestId = ClientRequestId+    }++-- | Open a client session, and run an action with with a handle+-- to this session (of type 'ClientSession'). ----- The typical way you would use 'withClientSession' is like so:+-- The typical way you would use 'withSession' is like so: -- -- @--- 'withClientSession' nodeId $ \\run -> do---     req <- run ('newRequest' someRequest)+-- 'withSession' self lastKnownLeader impl $ \\session -> do+--     req <- 'newRequest' session entry -----     let go serverNode =---             run ('sendClientRequest' 1000000 serverNode req) >>= \case---                Left ('Redirect' otherServerNode) -> go otherServerNode---                Left _ -> go serverNode -- infinite retries---                Right resp -> pure resp+--     let go = do+--             result <- 'sendRequest' session 1_000_000 req+--             case result of+--                 Left 'Timeout' -> go -- retry+--                 Left 'NoKnownLeader' -> go -- retry+--                 Left 'UnexpectedResponse' -> error "protocol mismatch"+--                 Right r -> pure r -----     go lastKnownLeader+--     go -- @ ----- In practice, 'withClientSession' is usually run in its own thread,--- and requests are sent over to that client thread using e.g. a 'TQueue'.-withClientSession ::+-- It is perfectly fine to either share the 'ClientSession' across threads,+-- or send requests from their own threads.+withSession ::   ( MonadAsync m,     MonadFork m,-    MonadMask m+    MonadMask m,+    MonadTimer m   ) =>   -- | self identification   node ->+  -- | Initial guess for the cluster leader. This is corrected automatically+  -- from the responses of the cluster.+  node ->+  -- | Client implementation details   ClientImplementation entry node result m ->-  ((forall a. RaftClientT entry node result m a -> m a) -> m b) ->-  m b-withClientSession self impl withSession = do-  nRId <- newTVarIO 0-  lAck <- newTVarIO Nothing-  mbox <- newTVarIO mempty-  sessId <- generateSessionId impl self-  let env =-        MkRaftClientEnv-          { node = self,-            currentSessionId = sessId,-            nextRequestId = nRId,-            latestAcknowledgement = lAck,-            implementation = impl,-            mailbox = mbox-          }-      recvLoop = do-        receiveResponse impl >>= \resp -> do-          let reqId = responseRequestId resp-          atomically $ do-            box <- readTVar mbox-            case Map.lookup reqId box of-              Nothing -> pure ()-              -- Using 'tryPutTMVar' here in case a response is duplicated-              Just var -> void $ tryPutTMVar var resp-          recvLoop--  withAsync recvLoop $ \thread -> do-    link thread-    withSession (\(MkRaftClientT f) -> runReaderT f env)--data RaftClientEnv entry node result m-  = MkRaftClientEnv-  { node :: !node,-    currentSessionId :: !SessionId,-    nextRequestId :: !(TVar m SequenceNum),-    latestAcknowledgement :: !(TVar m (Maybe (Max SequenceNum))),-    implementation :: ClientImplementation entry node result m,-    mailbox :: TVar m (Map ClientRequestId (TMVar m (ClientResponse node result)))-  }--makeLenses ''ClientImplementation+  (ClientSession entry node result m -> m a) ->+  m a+withSession self leader impl f =+  Session.withSession self leader (clientToSessionImplementation impl) (f . ClientSession) --- | Possible client errors-data ClientError entry node-  = -- | The client should make the request to another node-    Redirect node-  | Timeout-  | NoKnownLeader-  deriving (Eq, Show, Ord)+-- | Handle to an open client session. See 'withSession'.+newtype ClientSession entry node result m+  = ClientSession (Session ClientRequestId node entry result m)  -- | Read the current session ID. This helper can be useful if you need -- to pin information to the current client-clientSession :: (Monad m) => RaftClientT entry node result m SessionId-clientSession = MkRaftClientT $ asks currentSessionId+sessionId :: ClientSession entry node result m -> SessionId+sessionId (ClientSession session) = Session.sessionId session -newRequest :: (MonadSTM m) => entry -> RaftClientT entry node result m (ClientRequest entry node)-newRequest entry = do-  (seqNumVar, sessId, self) <- MkRaftClientT $ asks ((,,) <$> nextRequestId <*> currentSessionId <*> node)-  reqId <- lift $ atomically $ do-    nextSeqNum <- readTVar seqNumVar-    writeTVar seqNumVar (succ nextSeqNum)-    pure $ MkClientRequestId sessId nextSeqNum+-- | Returns the smallest unacknowledged 'SequenceNum' for outstanding requests.+lowestUnacknowledgedSequenceNum :: (MonadSTM m) => ClientSession entry node result m -> STM m SequenceNum+lowestUnacknowledgedSequenceNum (ClientSession session) = Session.lowestUnacknowledgedSequenceNum session -  pure $ MkRequest reqId self entry+-- | Force-set a leader to this session.+--+-- This should only be used in case no leader is known by any of the+-- cluster nodes, for example to try another node after 'sendRequest'+-- returned 'NoKnownLeader'.+setLeader :: (MonadSTM m) => ClientSession entry node result m -> node -> m ()+setLeader (ClientSession session) = Session.setLeader session --- | Send a request to a Raft cluster.+-- | Create a request to apply an entry to the replicated state machine. ----- The user must take care to handle the possible 'ClientError's, and be--- ready to retry.+-- Creating a request does not send anything; use 'sendRequest'. Each call creates+-- a distinct request, even for equal entries. See also the notes on retrying+-- in the module documentation.+newRequest ::+  (MonadSTM m) =>+  ClientSession entry node result m ->+  entry ->+  m (ClientRequest entry node)+newRequest (ClientSession session) payload =+  Session.newRequest session (RequestPayload payload)++-- | Send a client request to a Raft cluster, and wait for its result. ----- First, it is quite likely that the server will redirect requests--- via @'Redirect' otherServer@. 'request' does not follow that redirect,--- as you may want to control delays and retries.+-- The request is sent to the leader the session currently knows about. If+-- a node replies that it is not the leader and names the leader, the request is+-- sent to that leader instead, until the timeout expires. ----- Second, there is an unlikely, but real, possibility that the server+-- The user must take care to handle the possible 'SessionError's, and be+-- ready to retry with the same request.+--+-- There is an unlikely, but real, possibility that the server -- replies with 'NoKnownLeader'. In this case, you should try two things: -- -- * Retry the request, which may resolve itself--- * If retrying doesn't work, you should try to send the request to another server.+-- * If retrying doesn't work, you should try another server using 'setLeader'. --   It may be beneficial to keep a memory of all servers ever contacted for this --   particular purpose. -- -- It is perfectly safe, and encouraged, to send separate requests in--- separate threads. However, you should call 'withClientSession' only once.-sendClientRequest ::-  (MonadTimer m) =>+-- separate threads. However, you should call 'withSession' only once.+--+-- The timeout covers the whole call, redirections included. Because+-- 'Microseconds' is a 32-bit integer, timeouts are limited to about 35 minutes.+sendRequest ::+  (MonadTimer m, MonadMask m) =>+  ClientSession entry node result m ->   -- | Maximum time to wait for a response.   Microseconds ->-  node ->   ClientRequest entry node ->-  RaftClientT-    entry-    node-    result-    m+  m     ( Either-        (ClientError entry node)-        (node, result)-    )-sendClientRequest timeout lastKnownLeader req@(MkRequest reqId _ _) = do-  send <- MkRaftClientT $ asks (sendRequest . implementation)-  mbox <- MkRaftClientT $ asks mailbox-  ackVar <- MkRaftClientT $ asks latestAcknowledgement-  lift-    ( do-        resultVar <- atomically $ do-          mbox' <- readTVar mbox-          resultVar <- newEmptyTMVar-          -- TODO: bracket to deregister in case of an exception-          writeTVar mbox (Map.insert reqId resultVar mbox')--          pure resultVar--        expired <- registerDelay (fromIntegral timeout)-        send lastKnownLeader req--        -- TODO: clean up mailbox entry for req ID-        --       regardless of success (possibly using 'bracket')-        atomically-          ( ( do-                resp <- readTMVar resultVar-                mbox' <- readTVar mbox-                lAck <- readTVar ackVar-                writeTVar mbox (Map.delete reqId mbox')--                let MkClientRequestId _ respSeqNum = responseRequestId resp-                    watermark = Max respSeqNum-                writeTVar-                  ackVar-                  ( maybe-                      (Just watermark)-                      (Just . mappend watermark)-                      lAck-                  )--                pure (Just resp)-            )-              `orElse` ( do-                           readTVar expired >>= check-                           readTVar mbox >>= writeTVar mbox . Map.delete reqId-                           pure Nothing-                       )-          )+        SessionError+        result     )-    >>= \case-      Nothing -> pure $ Left Timeout-      Just (MkResponse _ (Just actualLeaderId) NotLeader) -> pure $ Left $ Redirect actualLeaderId-      Just (MkResponse _ (Just leader) (Success result)) -> pure $ Right (leader, result)-      -- TODO: what if leader is @Nothing@ but response is `Success`??-      Just (MkResponse _ Nothing _) -> pure $ Left NoKnownLeader+sendRequest (ClientSession session) timeout =+  Session.sendRequest+    (\(ClientRequestId _ seqNum) -> seqNum)+    session+    timeout+    Nothing -- clients always send requests to the leader
src/Distributed/Consensus/Raft/Domain.hs view
@@ -11,8 +11,7 @@     LogIndex,      -- * Sessions and sequences-    SessionId,-    sessionId,+    SessionId (..),     SequenceNum,      -- ** Read-only sequences@@ -40,6 +39,7 @@   deriving stock (Generic, Eq, Ord, Show, Read)   deriving newtype (Real, Binary, Enum, Num, Integral) +-- | The role of a node in the cluster. data Role   = Leader   | Follower@@ -66,24 +66,21 @@  -- | Uniquely identifies a session between a cluster and a client or admin, globally. This -- value should be generated at random.-data SessionId = MkSessionId Word64 Word64+data SessionId = SessionId Word64 Word64   deriving (Eq, Show, Ord, Generic)  instance Binary SessionId  instance Uniform SessionId -sessionId :: Word64 -> Word64 -> SessionId-sessionId = MkSessionId- -- | Incrementing sequence number for every client or admin request -- in the same session.-newtype SequenceNum = MkSequenceNum Word64+newtype SequenceNum = SequenceNum Word64   deriving stock (Eq, Ord)   deriving newtype (Show, Real, Num, Enum, Bounded, Integral, Binary)  -- | Incrementing counter for each round of approval for a read-only query.-newtype ReadOnlySequenceNum = MkReadOnlySequenceNum Word64+newtype ReadOnlySequenceNum = ReadOnlySequenceNum Word64   deriving stock (Eq, Ord)   deriving newtype (Show, Real, Num, Enum, Bounded, Integral, Binary) @@ -112,14 +109,15 @@   hasQuorum (Simple members1) votes     && hasQuorum (Simple members2) votes --- | 'LogIndex' is an absolute position within the 'Log'.+-- | 'LogIndex' is an absolute position within the log. ----- Note that the 'Log' may not have the elements associated with a given+-- Note that the log may not have the elements associated with a given -- 'LogIndex' due to compaction. newtype LogIndex = LogIndex Word64   deriving stock (Generic, Eq, Ord, Show)   deriving newtype (Real, Enum, Num, Binary, Integral) +-- | Metadata associated with a 'Snapshot'. data SnapshotMetadata = SnapshotMetadata   { smLastIncludedIndex :: !LogIndex,     smLastIncludedTerm :: !Term@@ -128,6 +126,8 @@  instance Binary SnapshotMetadata +-- | The state of the state machine, and the cluster configuration, as of the+-- last log entry described by 'sMetadata'. data Snapshot node state = Snapshot   { sMetadata :: !SnapshotMetadata,     sData :: !state,@@ -138,7 +138,7 @@ instance (Binary node, Binary state) => Binary (Snapshot node state)  -- | A state machine entry results in a step which can either read the state ('Read')--- or mutate the state ('Write').+-- or mutate the state ('Transition'). -- -- The distinction is important because reading from the state can be optimized -- differently than a mutation.@@ -149,10 +149,16 @@ --    Increment -> Transition $ \st -> (succ st, succ st) --    Decrement -> Transition $ \st -> (pred st, pred st) -- :}+--+-- Use 'runStateMachineStep' to execute. data StateMachineStep result state-  = Read (state -> result)-  | Transition (state -> (state, result))+  = -- | A read-only query over the state.+    -- Such queries can be served much faster than 'Transition's+    Read (state -> result)+  | -- | Transition the state to a new state, yielding a @result@.+    Transition (state -> (state, result)) +-- | Run a step on a state, yielding the new state and the result of the step. runStateMachineStep :: StateMachineStep result state -> state -> (state, result) runStateMachineStep (Read runRead) st = (st, runRead st) runStateMachineStep (Transition runTrans) st = runTrans st
src/Distributed/Consensus/Raft/Domain/Admin.hs view
@@ -28,23 +28,24 @@ instance (Binary node) => Binary (AdminCommand node)  data AdminRequestId-  = MkAdminRequestId+  = AdminRequestId       SessionId       SequenceNum   deriving stock (Generic, Eq, Ord, Show)  instance Binary AdminRequestId -type AdminRequest node = Request AdminRequestId node (AdminCommand node)+type AdminRequest node =+  Request+    AdminRequestId+    node+    (AdminCommand node)  data AdminCommandResult node   = JoinInitiated   | LeaveInitiated   | ShutdownInitiated   | ClusterConfigurationIs !(ClusterConfiguration node)-  | -- | The contacted node isn't the leader. The 'Maybe' contains the-    -- | node believed to be the current leader, if known.-    NotLeader !(Maybe node)   deriving (Eq, Show, Generic)  instance (Binary node) => Binary (AdminCommandResult node)
src/Distributed/Consensus/Raft/Domain/Client.hs view
@@ -2,38 +2,33 @@ {-# LANGUAGE DerivingStrategies #-}  module Distributed.Consensus.Raft.Domain.Client-  ( SessionId,-    sessionId,+  ( SessionId (..),     SequenceNum,     ClientRequestId (..),     ClientRequest,     ClientResponse,-    ClientResult (..),   ) where  import Data.Binary (Binary)-import Distributed.Consensus.Raft.Domain (SequenceNum, SessionId, sessionId)+import Distributed.Consensus.Raft.Domain (SequenceNum, SessionId (..)) import Distributed.Consensus.Raft.Messaging (Request (..), Response (..)) import GHC.Generics (Generic)  -- | Client-sourced request ID. This allows to correlate multiple client -- side-responses. data ClientRequestId-  = MkClientRequestId+  = ClientRequestId       SessionId       SequenceNum   deriving stock (Generic, Eq, Ord, Show)  instance Binary ClientRequestId -type ClientRequest entry node = Request ClientRequestId node entry--data ClientResult result-  = Success !result-  | NotLeader-  deriving (Eq, Show, Generic)--instance (Binary result) => Binary (ClientResult result)+type ClientRequest entry node =+  Request+    ClientRequestId+    node+    entry -type ClientResponse node result = Response ClientRequestId node (ClientResult result)+type ClientResponse node result = Response ClientRequestId node result
src/Distributed/Consensus/Raft/Implementation.hs view
@@ -23,6 +23,8 @@     ClusterMembershipRequest (..),     ClusterMembershipResult (..),     ClusterMembershipError (..),+    RequestVote (..),+    RequestVoteResult (..),     AdminRequest,     Event (..),     RPC (..),@@ -37,7 +39,7 @@ import Data.Sequence (Seq) import Distributed.Consensus.Raft.Domain (ClusterConfiguration (..), LogIndex, ReadOnlySequenceNum, Snapshot, SnapshotMetadata, StateMachineStep, Term) import Distributed.Consensus.Raft.Domain.Admin (AdminRequest, AdminResponse)-import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId, ClientResponse, ClientResult)+import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId, ClientResponse) import Distributed.Consensus.Raft.Log (Log) import GHC.Generics (Generic) @@ -46,7 +48,7 @@ -- There are four categories of things that need an implementation: -- -- * Persistence: how are values persisted durably?--- * State mechine: given an @entry@, how does the @state@ evolve?+-- * State machine: given an @entry@, how does the @state@ evolve? -- * Networking: how are nodes communicating? -- * Tracing: how is debugging information traced? data Implementation entry node result state m = Implementation@@ -67,6 +69,9 @@ -- -- See @raft-consensus-distributed-process@ for an implementation that fits -- in the Cloud Haskell ecosystem.+--+-- If you want to implement your own 'Networking', you might want to use serialization+-- instances provided in other helper packages, such as @raft-consensus-serialise-instances@. data Networking entry node result state m = Networking   { -- | Send a remote procedure call to another Raft node.     --@@ -94,11 +99,11 @@     sendAdminResponse :: node -> AdminResponse node -> m (),     -- | Receive a remote procedure call.     ---    -- At the type implies, this call should /block/ until a message is ready.+    -- As the type implies, this call should /block/ until a message is ready.     receiveRPC :: m (RPC entry node state),     -- | Receive the result of a remote procedure call.     ---    -- At the type implies, this call should /block/ until a message is ready.+    -- As the type implies, this call should /block/ until a message is ready.     receiveRPCResult :: m (RPCResult node result),     -- | Receive client requests.     --@@ -108,7 +113,7 @@     receiveClientRequests :: m (NonEmpty (ClientRequest entry node)),     -- | Receive a request from an administrator.     ---    -- At the type implies, this call should /block/ until a message is ready.+    -- As the type implies, this call should /block/ until a message is ready.     receiveAdminRequest :: m (AdminRequest node)   } @@ -116,10 +121,11 @@ -- -- This is broken out into its own type so that it can be provided cleanly by -- third-party packages. For example, see the @raft-consensus-wal@ package.+--+-- If you want to implement your own 'Persistence', you might want to use serialization+-- instances provided in other helper packages, such as @raft-consensus-serialise-instances@. data Persistence entry node state m = Persistence   { -- | Read log entries, starting from and including, a given 'LogIndex'-    ---    -- Implementations should     readLogEntriesFrom :: node -> LogIndex -> m [(Term, LogIndex, LogEntry entry node)],     -- | Write log entries durably.     --@@ -132,7 +138,7 @@     -- allows to persist data in a shared location for multiple nodes     -- (e.g. in a remote database)     writeLogEntry :: node -> [(Term, LogIndex, LogEntry entry node)] -> m (),-    -- Truncate log entries starting, and including, the provided log index.+    -- | Truncate log entries starting, and including, the provided log index.     --     -- Note that not all storage technologies support truncation. For example,     -- write-ahead logs cannot implement truncation. However, the goal is that@@ -179,7 +185,7 @@ -- of its state, it may vote again leading to multiple leaders in a single -- cluster, which would be catastrophic. ----- An alternative would be for a node's identity (the 'node' type variable)+-- An alternative would be for a node's identity (the @node@ type variable) -- to never be re-used. In this case, it would be perfectly fine to restart -- with an empty state. ephemeralPersistence :: (Applicative m) => Persistence entry node state m@@ -209,7 +215,7 @@  -- | A 'LogEntry' is anything which gets persisted -- in the replicated log. This includes client commands,--- byt also leadership changes (which are no-op entries)+-- but also leadership changes (which are no-op entries) -- and cluster membership changes. data LogEntry entry node   = LogEntryCommand (Command entry)@@ -220,7 +226,7 @@ instance (Binary node, Binary entry) => Binary (LogEntry entry node)  data CommandResponse node result-  = MkCommandResponse+  = CommandResponse       !result       !ClientRequestId   deriving (Eq, Show, Ord, Generic)@@ -279,7 +285,7 @@  data ClusterMembershipError node   = -- | carries the node that replied, not the leader-    NoKnownLeader node+    ClusterMembershipNoKnownLeader node   | OngoingClusterMembershipChange node   deriving (Eq, Show, Ord, Generic) @@ -292,20 +298,33 @@  instance (Binary node) => Binary (ClusterMembershipResult node) +data RequestVote node+  = RequestVote+  { rvCandidateTerm :: !Term,+    rvCandidateNode :: !node,+    rvCandidateLastLogEntryIndex :: !LogIndex,+    rvCandidateLastLogEntryTerm :: !Term+  }+  deriving (Eq, Ord, Show, Generic)++instance (Binary node) => Binary (RequestVote node)++data RequestVoteResult node+  = RequestVoteResult+  { rvrVoterNode :: !node,+    rvrVoterTerm :: !Term,+    rvrVoteGranted :: !Bool+  }+  deriving (Eq, Ord, Show, Generic)++instance (Binary node) => Binary (RequestVoteResult node)+ data RPC entry node state   = AE (AppendEntries entry node)   | IS (InstallSnapshot node state)   | CM (ClusterMembershipRequest node)-  | RequestVote-      -- | Candidate term-      Term-      -- | Identification of the candidate requesting vote-      node-      -- | Index of candidate's last log entry-      LogIndex-      -- | Term of candidate's last log entry-      Term-  deriving (Eq, Ord, Show, Generic) -- For easy derivation of de/serialization+  | RV (RequestVote node)+  deriving (Eq, Ord, Show, Generic)  instance (Binary node, Binary entry, Binary state) => Binary (RPC entry node state) @@ -313,14 +332,8 @@   = AER (AppendEntriesResult node result)   | ISR (InstallSnapshotResult node)   | CMR (ClusterMembershipResult node)-  | RequestVoteResult-      -- | Voter node-      node-      -- | Current term, for leader to update itself-      Term-      -- | Whether vote was granted-      Bool-  deriving (Eq, Ord, Show, Generic) -- For easy derivation of de/serialization+  | RVR (RequestVoteResult node)+  deriving (Eq, Ord, Show, Generic)  instance (Binary node, Binary result) => Binary (RPCResult node result) @@ -359,7 +372,7 @@     --    to another node, this event is not emitted     -- All Commands should have the same request ID     CommandReceived (EventContext node) !ClientRequestId entry-  | CommandResultResponded (EventContext node) (CommandResponse node (ClientResult result))+  | CommandResultResponded (EventContext node) (CommandResponse node result)   | -- TODO: better traching of new joining/leaving cluster     MembershipChangeInitiated (EventContext node)   | MembershipChangeCompleted (EventContext node)
src/Distributed/Consensus/Raft/Log.hs view
@@ -37,7 +37,7 @@ import Distributed.Consensus.Raft.Domain (LogIndex, SnapshotMetadata (..), Term) import GHC.Generics (Generic) --- | 'RelativeIndex' is a relative position within the 'Log'. It is+-- | 'RelativeLogIndex' is a relative position within the 'Log'. It is -- specified with respect to the snapshot. newtype RelativeLogIndex = RelativeLogIndex LogIndex   deriving stock (Generic, Eq, Ord, Show)
src/Distributed/Consensus/Raft/Messaging.hs view
@@ -2,32 +2,60 @@  module Distributed.Consensus.Raft.Messaging   ( Request (..),+    RequestPayload (..),+    request,     Response (..),+    ResponsePayload (..),   ) where  import Data.Binary (Binary)+import Distributed.Consensus.Raft.Domain (SequenceNum) import GHC.Generics (Generic) +data RequestPayload request+  = Heartbeat+  | RequestPayload !request+  deriving (Eq, Show, Generic)++request :: RequestPayload request -> Maybe request+request (RequestPayload req) = Just req+request _ = Nothing++instance (Binary request) => Binary (RequestPayload request)+ -- | Request incoming to the Raft cluster. -- -- This is an envelope that collects things that any request -- needs to be processed end-to-end. data Request id node payload-  = MkRequest-  { requestId :: !id,+  = Request+  { -- | Identifies the request, and its response.+    requestId :: !id,+    -- | The node to send the response to.     requestOriginator :: !node,-    requestPayload :: !payload+    -- | Lowest sequence number for a request whose response has been received.+    requestOldestOutstanding :: !SequenceNum,+    requestPayload :: !(RequestPayload payload)   }   deriving (Eq, Show, Generic)  instance (Binary id, Binary node, Binary payload) => Binary (Request id node payload) +data ResponsePayload response+  = HeartbeatEcho+  | NotLeader+  | SessionExpired+  | ResponsePayload !response+  deriving (Eq, Show, Generic)++instance (Binary response) => Binary (ResponsePayload response)+ data Response id node payload-  = MkResponse+  = Response   { responseRequestId :: !id,     responseClusterLeader :: !(Maybe node),-    responsePayload :: !payload+    responsePayload :: !(ResponsePayload payload)   }   deriving (Eq, Show, Generic) 
+ src/Distributed/Consensus/Raft/Session.hs view
@@ -0,0 +1,308 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE TupleSections #-}++-- |+-- Module:      $module+-- Copyright:   (c) Laurent P. René de Cotret+-- License:     BSD 3-Clause+--+-- Interface to interact with a Raft cluster via a session. This module+-- provides building blocks to represent both client and admin sessions.+--+-- You are not supposed to use this module directly!+module Distributed.Consensus.Raft.Session+  ( -- * Interface+    withSession,+    Session,++    -- ** Session information+    sessionId,+    lowestUnacknowledgedSequenceNum,+    setLeader,++    -- ** Creating requests+    newRequest,++    -- ** Sending requests+    sendRequest,+    SessionError (..),++    -- ** Configuration+    SessionImplementation (..),+    randomSessionId,++    -- ** Messaging+    Request (..),+    RequestPayload (..),+    Response (..),+    ResponsePayload (..),++    -- * Re-exports+    SessionId,+    SequenceNum,+    Microseconds,+  )+where++import Control.Concurrent.Class.MonadSTM+  ( MonadSTM,+    STM,+    TMVar,+    TVar,+    atomically,+    check,+    modifyTVar',+    newEmptyTMVar,+    newTVarIO,+    orElse,+    readTMVar,+    readTVar,+    readTVarIO,+    stateTVar,+    tryPutTMVar,+    writeTVar,+  )+import Control.Monad (forever, unless, void)+import Control.Monad.Class.MonadAsync (MonadAsync, link, withAsync)+import Control.Monad.Class.MonadFork (MonadFork)+import Control.Monad.Class.MonadThrow (MonadMask, bracket)+import Control.Monad.Class.MonadTimer (MonadTimer, registerDelay, threadDelay)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.Foldable (traverse_)+import Data.Functor ((<&>))+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (isNothing)+import Data.Set (Set)+import qualified Data.Set as Set+import Distributed.Consensus.Raft.Domain (SequenceNum, SessionId)+import Distributed.Consensus.Raft.Messaging (Request (..), RequestPayload (..), Response (..), ResponsePayload (..))+import qualified Distributed.Consensus.Raft.Messaging as Messaging+import Distributed.Consensus.Raft.Timer (Microseconds)+import System.Random.Stateful (globalStdGen, uniformM)++-- | Implementation of communication between a session and a cluster.+data SessionImplementation id node request response m = SessionImplementation+  { implSendRequest :: node -> Request id node request -> m (),+    implReceiveResponse :: m (Response id node response),+    -- | Generate a globally-unique session ID.+    implGenerateSessionId :: m SessionId,+    implMakeRequestId :: SessionId -> SequenceNum -> id+  }++-- | Generate a random 'SessionId'+randomSessionId :: (MonadIO m) => m SessionId+randomSessionId = liftIO $ uniformM globalStdGen++-- | Open a session, and run an action with a handle+-- to this session (of type 'Session').+--+-- It is perfectly fine to either share the 'Session' across threads,+-- or send requests from their own threads.+withSession ::+  ( MonadAsync m,+    MonadFork m,+    MonadMask m,+    Ord id,+    MonadTimer m+  ) =>+  -- | self identification+  node ->+  -- | Potential cluster leader+  node ->+  -- | Implementation details+  SessionImplementation id node request response m ->+  (Session id node request response m -> m a) ->+  m a+withSession self mLeader impl f = do+  session <-+    Session self+      <$> newTVarIO mLeader+      <*> implGenerateSessionId impl+      <*> newTVarIO 0+      <*> newTVarIO mempty+      <*> pure impl+      <*> newTVarIO mempty++  let recvLoop = forever $ do+        implReceiveResponse impl >>= \resp -> do+          atomically $ do+            readTVar (mailbox session)+              -- Using 'tryPutTMVar' here in case a response is duplicated+              >>= traverse_ (void . (`tryPutTMVar` resp))+                . Map.lookup (responseRequestId resp)++  -- This is the simplest heartbeat loop possible+  -- TODO: there must be an elegant way to have a timer+  --       such that a heartbeat is only sent in case no other requests+  --       have been sent+  let heartbeatLoop = forever $ do+        threadDelay 30_000_000+        void $ heartbeat session 30_000_000++  withAsync heartbeatLoop $ \heartbeatTid -> do+    link heartbeatTid+    withAsync recvLoop $ \thread -> do+      link thread+      f session++data Session id node request response m+  = Session+  { node :: !node,+    leader :: !(TVar m node),+    -- TODO: keep track of all nodes ever contacted, in case+    --       the leader goes down and we need to contact another node+    sessionId :: !SessionId,+    nextSequenceNum :: !(TVar m SequenceNum),+    outstanding :: !(TVar m (Set SequenceNum)),+    implementation :: SessionImplementation id node request response m,+    mailbox :: TVar m (Map id (TMVar m (Response id node response)))+  }++-- | Force-set a leader to this session.+--+-- This should only be used in case no leader is known by any of the+-- cluster nodes.+setLeader :: (MonadSTM m) => Session id node request response m -> node -> m ()+setLeader session newLeader =+  atomically (writeTVar (leader session) newLeader)++-- | Returns the smallest unacknowledged 'SequenceNum' for outstanding requests.+lowestUnacknowledgedSequenceNum :: (MonadSTM m) => Session id node request response m -> STM m SequenceNum+lowestUnacknowledgedSequenceNum session =+  readTVar (outstanding session)+    <&> Set.lookupMin+    >>= maybe (readTVar (nextSequenceNum session)) pure++newRequest ::+  (MonadSTM m) =>+  Session id node request response m ->+  RequestPayload request ->+  m (Request id node request)+newRequest session payload = do+  (seqNum, oldestOutstanding) <- atomically $ do+    nextSeqNum <- stateTVar (nextSequenceNum session) (\n -> (n, succ n))+    -- We only track the sequence number of non-control messages,+    -- for which retries are problematic.+    unless isControlMessage $ modifyTVar' (outstanding session) (Set.insert nextSeqNum)+    (nextSeqNum,) <$> lowestUnacknowledgedSequenceNum session++  pure $+    Request+      { requestId = session.implementation.implMakeRequestId (sessionId session) seqNum,+        requestOriginator = node session,+        requestOldestOutstanding = oldestOutstanding,+        requestPayload = payload+      }+  where+    isControlMessage = isNothing (Messaging.request payload)++data SessionError+  = -- | No response within the time limit.+    Timeout+  | -- | The node contacted is not the leader, and does not know who is.+    NoKnownLeader+  | -- | This session is expired; either its ID has been re-used,+    -- or no heartbeat was received by the cluster for too long.+    --+    -- Once a 'SessionExpired' has been received, all future+    -- requests will receive the same answer. The current session+    -- should be closed, and a new one should be opened.+    ExpiredSession SessionId+  | -- | The cluster responded with a kind of response which does not+    -- answer this kind of request. This should never happen, and+    -- is grounds for an exception.+    UnexpectedResponse+  deriving (Eq, Show, Ord)++-- | Send a request to a Raft cluster.+--+-- This function follows redirects; if the leader has changed since+-- the last request, 'sendRequest' will detect this and follow+-- the redirect, until the timeout expires. Once a result is received,+-- the request is no longer outstanding.+--+-- It is perfectly safe, and encouraged, to send separate requests in+-- separate threads.+sendRequest ::+  (MonadTimer m, MonadMask m, Ord id) =>+  (id -> SequenceNum) ->+  Session id node request response m ->+  -- | Maximum time to wait for a response.+  Microseconds ->+  -- | Destination. If @Nothing@, the request will+  -- be sent to the leader. Otherwise, send to the node directly.+  Maybe node ->+  Request id node request ->+  m (Either SessionError response)+sendRequest getSeqNum session timeout mContact req@(Request reqId _ _ _) =+  exchange session timeout mContact req >>= \case+    Right (_, ResponsePayload resp) -> Right resp <$ atomically acknowledge+    Right _ -> pure $ Left UnexpectedResponse+    Left err -> pure $ Left err+  where+    seqNum = getSeqNum reqId++    acknowledge = modifyTVar' session.outstanding (Set.delete seqNum)++heartbeat ::+  (MonadTimer m, MonadMask m, Ord id) =>+  Session id node request response m ->+  Microseconds ->+  m (Either SessionError ())+heartbeat session timeout =+  newRequest session Heartbeat+    >>= exchange session timeout Nothing+    <&> \case+      Right (_, HeartbeatEcho) -> Right ()+      Right _ -> Left UnexpectedResponse+      Left err -> Left err++exchange ::+  (MonadTimer m, MonadMask m, Ord id) =>+  Session id node request response m ->+  -- | Maximum time to wait for a response.+  Microseconds ->+  -- | Destination. If @Nothing@, the request will+  -- be sent to the leader. Otherwise, send to the node directly.+  Maybe node ->+  Request id node request ->+  m (Either SessionError (Maybe node, ResponsePayload response))+exchange session timeout mContact req@(Request reqId _ _ _) = do+  expired <- registerDelay (fromIntegral timeout)++  let attempt contact =+        bracket+          register+          deregister+          ( \resultVar -> do+              target <- maybe (readTVarIO (leader session)) pure contact+              session.implementation.implSendRequest target req+              atomically $+                (Just <$> readTMVar resultVar)+                  `orElse` (Nothing <$ (readTVar expired >>= check))+          )+          >>= traverse updateLeader+          >>= \case+            Nothing -> pure $ Left Timeout+            Just (Response _ (Just _) NotLeader) ->+              readTVarIO expired >>= \case+                True -> pure $ Left Timeout+                False -> attempt Nothing -- leader will have been updated by 'updateLeader'+            Just (Response _ Nothing NotLeader) -> pure $ Left NoKnownLeader+            Just (Response _ _ SessionExpired) -> pure $ Left $ ExpiredSession (sessionId session)+            Just (Response _ mLeader payload) -> pure $ Right (mLeader, payload)++  attempt mContact+  where+    updateLeader resp@(Response _ mClusterLeader _) =+      resp <$ traverse_ (atomically . writeTVar (leader session)) mClusterLeader++    register = atomically $ do+      resultVar <- newEmptyTMVar+      modifyTVar' (mailbox session) (Map.insert reqId resultVar)+      pure resultVar++    deregister _ = atomically $ modifyTVar' session.mailbox (Map.delete reqId)
src/Distributed/Consensus/Raft/Timer.hs view
@@ -31,7 +31,7 @@ -- -- If the action throws an exception, the exception will be thrown -- in the thread that created the timer with 'newTimer'.-data Timer m = MkTimer+data Timer m = Timer   { _action :: m (),     -- Normally we would use an IORef (Maybe _) here,     -- but 'io-classes' doesn't support IORef@@ -40,7 +40,10 @@  -- | Duration of time in microseconds. ----- The canonical way to build a 'Microsecond' value is to+-- The underlying type is a 32-bit integer, so the longest duration that+-- can be represented is a little under 36 minutes.+--+-- The canonical way to build a 'Microseconds' value is to -- either use a literal integer, or via 'fromIntegral': -- -- >>> 1000000 :: Microseconds@@ -54,17 +57,17 @@ instance UniformRange Microseconds -- via Generic  newTimer :: (MonadMVar m) => m () -> m (Timer m)-newTimer a = MkTimer a <$> newEmptyMVar+newTimer a = Timer a <$> newEmptyMVar  resetTimer ::   (MonadAsync m, MonadMask m, MonadFork m, MonadMVar m, MonadDelay m) =>   Microseconds -> Timer m -> m ()-resetTimer (Microseconds delay) timer@(MkTimer a h) = do+resetTimer (Microseconds delay) timer@(Timer a h) = do   cancelTimer timer   thread <- async (threadDelay (fromIntegral delay) >> a)   link thread -- can't be too careful   putMVar h thread  cancelTimer :: (MonadMVar m, MonadAsync m) => Timer m -> m ()-cancelTimer (MkTimer _ h) =+cancelTimer (Timer _ h) =   tryTakeMVar h >>= traverse_ cancel
src/Distributed/Consensus/Raft/Transformer.hs view
@@ -75,12 +75,11 @@ import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map.Strict as Map-import Data.Maybe (fromJust, fromMaybe, isJust)+import Data.Maybe (catMaybes, fromJust, fromMaybe, 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,@@ -93,12 +92,12 @@     hasQuorum,   ) import Distributed.Consensus.Raft.Domain.Admin (AdminResponse)-import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId, ClientResponse, ClientResult (..))+import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientResponse) 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.Messaging (Request (..), RequestPayload (..), Response (..), ResponsePayload (..)) import Distributed.Consensus.Raft.Timer (Microseconds, resetTimer) import Distributed.Consensus.Raft.Transformer.Definition import Lens.Micro.Platform@@ -292,7 +291,7 @@          pure result -  pure $ Just (MkCommandResponse result reqId)+  pure $ Just (CommandResponse result reqId) applyEntry _entryTerm _entryIndex LogEntryLeaderChange = pure Nothing applyEntry _entryTerm _entryIndex (LogEntryMembershipChange clusterConf) = do   setClusterMembership clusterConf@@ -416,7 +415,7 @@       let resultsByReqId =             results               & Foldable.toList-              & map (\(MkCommandResponse result reqId) -> (reqId, NonEmpty.singleton result))+              & map (\(CommandResponse 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) ->@@ -426,8 +425,16 @@             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)+                runSend $+                  sendClientResponse+                    requester+                    ( Response+                        { responseRequestId = reqId,+                          responseClusterLeader = Just leaderId,+                          responsePayload = ResponsePayload response+                        }+                    )+                trace (`CommandResultResponded` CommandResponse response reqId)               currentClientRequests %= Map.delete reqId      view configuration <&> maxLogLength >>= \case@@ -496,11 +503,14 @@       )  -- | Set up a callback for a client request+--+-- Non-command requests (e.g. heartbeats) are handled here,+-- such that the length of the output may not match the length of the input acceptClientRequests ::-  (MonadMVar m) =>+  (MonadMVar m, MonadAsync m) =>   -- | Client node   NonEmpty (ClientRequest entry node) ->-  RaftT entry node result state m (NonEmpty ClientRequestId)+  RaftT entry node result state m [Command entry] 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@@ -510,28 +520,44 @@   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+  -- TODO: handle lowestOutstandingSeqNum, clearing session state related to+  --       older requests+  forMaybeM requests $ \(Request clientReqId clientId _lowestOutstandingSeqNum payload) -> do+    case payload of+      -- TODO: handle session control messages+      Heartbeat ->+        -- TODO: update session state+        runSend+          ( sendClientResponse+              clientId+              (Response clientReqId (Just s) HeartbeatEcho)+          )+          $> Nothing+      RequestPayload entry -> do+        -- TODO: update session state+        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+                ( PendingRead+                    { _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 $ Just $ Command clientReqId entry+  where+    forMaybeM xs f = fmap catMaybes (mapM f (NonEmpty.toList xs))  currentSnapshot :: (Monad m) => RaftT entry node result state m (Snapshot node state) currentSnapshot = do@@ -626,9 +652,14 @@     runSend $       sendClientResponse         (request ^. pendingReadClient)-        (MkResponse reqId (Just leaderId) (Success result))+        ( Response+            { responseRequestId = reqId,+              responseClusterLeader = Just leaderId,+              responsePayload = ResponsePayload result+            }+        ) -    trace (`CommandResultResponded` MkCommandResponse (Success result) reqId)+    trace (`CommandResultResponded` CommandResponse result reqId)    pendingReadRequests .= notReady @@ -689,7 +720,7 @@   lift $     atomically $       writeTQueue writeQueue $-        MkPersistenceBatch+        PersistenceBatch           ourTerm           ( startingLogIndex               + fromIntegral@@ -845,8 +876,7 @@    clientReqs <- use currentClientRequests   for_ (Map.toList clientReqs) $ \(reqId, requester) -> do-    runSend $ sendClientResponse requester (MkResponse reqId mNewLeader NotLeader)-    trace (`CommandResultResponded` MkCommandResponse NotLeader reqId)+    runSend $ sendClientResponse requester (Response reqId mNewLeader NotLeader)    currentClientRequests .= mempty @@ -855,8 +885,7 @@     runSend $       sendClientResponse         (request ^. pendingReadClient)-        (MkResponse reqId mNewLeader NotLeader)-    trace (`CommandResultResponded` MkCommandResponse NotLeader reqId)+        (Response reqId mNewLeader NotLeader)    pendingReadRequests .= mempty @@ -910,7 +939,14 @@   when (r == Candidate) $ do     currentTerm <- use term     (lastLogTerm, lastLogIx) <- use commandLog <&> Log.lastLogInfo-    let rpc = RequestVote currentTerm s lastLogIx lastLogTerm+    let rpc =+          RV $+            RequestVote+              { rvCandidateTerm = currentTerm,+                rvCandidateNode = s,+                rvCandidateLastLogEntryIndex = lastLogIx,+                rvCandidateLastLogEntryTerm = lastLogTerm+              }     peers >>= (runSend . (`sendRPCConcurrently` rpc))  checkElection ::
src/Distributed/Consensus/Raft/Transformer/Definition.hs view
@@ -123,6 +123,7 @@   RaftT entry node result state m () runSend act = ask >>= lift . void . async . runReaderT act +-- | How a server starts up with respect to a cluster. data ClusterState node   = -- | Lone node, not in a cluster. This 'ClusterState' is useful if you want     -- to start up a Raft server and have it join an existing cluster.@@ -132,19 +133,19 @@     InCluster (Set node)  data FollowerState-  = MkFollowerState+  = FollowerState   { _nextIndex :: !LogIndex,     _matchIndex :: !LogIndex,-    -- | Whether the follower has acked at least an 'AppendEntries' in this term.+    -- | Whether the follower has acked at least an @AppendEntries@ in this term.     -- If this is the case, then we can assume that the follower is live and-    -- advance 'nextIndex' optimistically.+    -- advance @nextIndex@ optimistically.     _replicating :: !Bool   }  newFollowerState :: LogIndex -> FollowerState-newFollowerState next = MkFollowerState next 0 False+newFollowerState next = FollowerState next 0 False -data RaftState entry node result state = MkRaftState+data RaftState entry node result state = RaftState   { _role :: !Role,     _term :: !Term,     _clusterConfiguration :: !(ClusterConfiguration node),@@ -172,7 +173,7 @@     -- when a heartbeat counts to acknowledge a read-only request (or was already     -- in-flight, for example)     _readOnlySequenceNum :: !ReadOnlySequenceNum,-    -- | Value of '_readOnlySequenceNum' when an 'AppendEntries' RPC or heartbeat was last+    -- | Value of '_readOnlySequenceNum' when an @AppendEntries@ RPC or heartbeat was last     -- broadcast.     _readOnlySeqBroadcast :: !ReadOnlySequenceNum,     -- | 'True' if a snapshot is currently being written to storage, which is done asynchronously.@@ -182,7 +183,7 @@  -- | A pending read-only request isn't part of the -- log, so we need a little bit of extra metadata-data PendingRead node result state = MkPendingRead+data PendingRead node result state = PendingRead   { _pendingReadTerm :: !Term,     _pendingReadLogIndex :: !LogIndex,     _pendingReadClient :: !node,@@ -208,7 +209,7 @@   state ->   RaftState entry node result state initialRaftState initRole seed clusterConf initialState =-  MkRaftState+  RaftState     { _role = initRole,       _term = initialTerm,       _clusterConfiguration = Simple clusterConf,@@ -235,15 +236,15 @@ -- including metadata necessary to update the state -- once the write has completed data PersistenceBatch entry node-  = MkPersistenceBatch+  = PersistenceBatch   { pbTerm :: !Term,     pbEdgeLogIndex :: !LogIndex,     pbEntries :: ![(Term, LogIndex, LogEntry entry node)]   }  instance Semigroup (PersistenceBatch entry node) where-  (MkPersistenceBatch _ _ e1) <> MkPersistenceBatch t2 l2 e2 =-    MkPersistenceBatch t2 l2 (e1 <> e2)+  (PersistenceBatch _ _ e1) <> PersistenceBatch t2 l2 e2 =+    PersistenceBatch t2 l2 (e1 <> e2)  runRaftT ::   ( Ord node,@@ -268,7 +269,7 @@   fst     <$> evalRWST       f-      ( MkRaftEnv+      ( RaftEnv           { _configuration = config,             _implementation = impl,             _eventQueue = queue,@@ -281,7 +282,7 @@       (initialRaftState initRole (randomSeed config) members internalState)  data RaftEnv entry node result state m-  = MkRaftEnv+  = RaftEnv   { _configuration :: !(Config node),     _implementation :: !(Implementation entry node result state m),     _eventQueue :: TQueue m (Event entry node result state),@@ -303,7 +304,7 @@ simpleConfig node = do   seed <- randomIO   pure $-    MkConfig+    Config       { nodeId = node,         electionTimeoutRange = (1_000_000, 2_000_000),         heartBeatTimeout = 100_000,@@ -316,7 +317,7 @@ -- You should use 'simpleConfig' if you don't have strong opinions -- on the configuration values. data Config node-  = MkConfig+  = Config   { -- | Identification for the node     nodeId :: !node,     -- | Inclusive range of election timeouts. The actual election timeout will be
tests/Test/Distributed/Consensus/Raft.hs view
@@ -52,6 +52,7 @@     RPC,     RPCResult,     RaftTrace (..),+    SessionError (..),     Snapshot,     Term,     runRaftServer,@@ -59,29 +60,21 @@ import qualified Distributed.Consensus.Raft as Raft import Distributed.Consensus.Raft.Admin   ( AdminCommandResult (ClusterConfigurationIs),-    AdminError (AdminNotLeader),-    AdminImplementation-      ( AdminImplementation,-        receiveAdminResponse,-        sendAdminRequest-      ),+    AdminImplementation (..),     AdminRequest,     AdminResponse,+    AdminSession,     Microseconds,-    RaftAdminT,-    sessionId,-    withAdminSession,+    SessionId (..),   ) import qualified Distributed.Consensus.Raft.Admin as Admin import Distributed.Consensus.Raft.Client-  ( ClientError (..),-    ClientImplementation (..),+  ( ClientImplementation (..),     ClientRequest,     ClientResponse,-    RaftClientT,+    ClientSession,     newRequest,     sendClientRequest,-    withClientSession,   ) import qualified Distributed.Consensus.Raft.Client as Client import System.Random (RandomGen, mkStdGen64, randomR, uniformR)@@ -89,6 +82,7 @@ import Test.Distributed.Consensus.Raft.Options (PrintTrace (..), setNumRacyTests, withExplorationOptions, withPrintTraceOption) import Test.Distributed.Consensus.Raft.Properties (FaultInjection (..), allProperties) import Test.Distributed.Consensus.Raft.Scenario (checkScenario)+import qualified Test.Distributed.Consensus.Raft.Session as Session import Test.StateMachine (Command, Node (Node), Result, State, step) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck@@ -112,7 +106,7 @@   testGroup     "Raft"     [ testGroup-        "Property tests"+        "Deterministic simulation tests"         [ testGroup             "No fault injection"             [ testClusterWithoutRaces NoFaultInjection,@@ -123,6 +117,10 @@             [ testClusterWithoutRaces FaultInjection,               testClusterWithRaces FaultInjection             ]+        ],+      testGroup+        "Session tests"+        [ Session.tests         ]     ] @@ -196,9 +194,9 @@         race_           (threadDelay (fromIntegral scenarioTimeUpperBound) >> fail "Possible infinite loop detected")           ( do-              withAdminSession harness.hAdminNode harness.hAdminSpec $ \runAdminAction ->+              Admin.withSession harness.hAdminNode 0 harness.hAdminSpec $ \adminSession ->                 -- Run servers until the clients are done interacting-                withAsync (runServers harness runAdminAction) $ \_ -> do+                withAsync (runServers harness adminSession) $ \_ -> do                   withAsync (runClients harness scenarioInputs) $ \clients -> do                     wait clients                     -- We give an opportunity to all lone servers to leave the cluster@@ -207,7 +205,9 @@                           let tryShutDown :: Int -> IOSim s ()                               tryShutDown 0 = pure ()                               tryShutDown attemptsLeft =-                                runAdminAction (Admin.shutDown >>= Admin.sendAdminCommand scenarioInputs.electionTimeoutUpperBound node <&> void)+                                Admin.shutDown adminSession+                                  >>= Admin.sendRequest adminSession scenarioInputs.electionTimeoutUpperBound (Just node)+                                  <&> void                                   >>= either (const (tryShutDown (attemptsLeft - 1))) pure                            in tryShutDown 3 @@ -220,9 +220,9 @@      runServers ::       Harness s ->-      (forall a. RaftAdminT Node (IOSim s) a -> IOSim s a) ->+      AdminSession Node (IOSim s) ->       IOSim s ()-    runServers harness runAdminAction = do+    runServers harness adminSession = do       -- This is the point where we can mark this thread "racy"       -- (by default, it is not).       --@@ -257,12 +257,12 @@                       requestTimeout = 3 * server.sConfig.heartBeatTimeout                    threadDelay (fromIntegral waitToJoin)-                  untilJoined runAdminAction contact requestTimeout betweenAttempts node $-                    Admin.joinCluster contact >>= Admin.sendAdminCommand maxBound node+                  untilJoined adminSession contact requestTimeout betweenAttempts node $+                    Admin.joinCluster adminSession contact >>= Admin.sendRequest adminSession maxBound (Just node)                    threadDelay (fromIntegral waitToLeave)-                  untilLeft runAdminAction contact requestTimeout betweenAttempts node $-                    Admin.leaveCluster >>= Admin.sendAdminCommand maxBound node+                  untilLeft adminSession contact requestTimeout betweenAttempts node $+                    Admin.leaveCluster adminSession >>= Admin.sendRequest adminSession maxBound (Just node)                    putMVar isDone ()               )@@ -275,7 +275,7 @@       IOSim s ()     runClients harness scenarioInputs =       forConcurrently_ (IntMap.toList harness.hClients) $ \(clientNode, clientImplementation) ->-        withClientSession (fromIntegral clientNode) clientImplementation $ \runClientAction ->+        Client.withSession (fromIntegral clientNode) 0 clientImplementation $ \runClientAction ->           runClient             (fromIntegral clientNode)             runClientAction@@ -291,14 +291,14 @@          runClient ::           Node ->-          (forall a. RaftClientT Command Node Result (IOSim s) a -> IOSim s a) ->+          ClientSession Command Node Result (IOSim s) ->           -- \| Single request timeout           Microseconds ->           -- \| Timeout for retries           Microseconds ->           [Command] ->           IOSim s ()-        runClient clientNode runRequest maxTime retryBudget = go (Set.singleton (0 :: Node))+        runClient clientNode session maxTime retryBudget = go (Set.singleton (0 :: Node))           where             -- \| Given a node, and a set of known nodes, deterministically pick another             -- node from the set.@@ -307,34 +307,25 @@              go _ [] = pure ()             go knownNodes (command : rest) = do-              req <- runRequest (newRequest command)+              req <- newRequest session command               start <- getMonotonicTimeNSec               attempt req knownNodes retryBudget 0 >>= \case                 Just result -> do                   end <- getMonotonicTimeNSec-                  traceM (MkRaftClientTrace clientNode (Linearizable.MkEvent start end (command, Just result)))+                  traceM (RaftClientTrace clientNode (Linearizable.Event start end (command, Just result)))                 Nothing ->-                  traceM (MkRaftClientTrace clientNode (Linearizable.MkEvent start maxBound (command, Nothing @Result)))+                  traceM (RaftClientTrace clientNode (Linearizable.Event start maxBound (command, Nothing @Result)))               go knownNodes rest               where                 attempt payload nodeSet remaining target = do                   threadDelay (fromIntegral clientRetryTick)-                  runRequest (sendClientRequest maxTime target payload)+                  Client.sendRequest session maxTime payload                     >>= \case                       Left Timeout ->                         giveUp $                           "no response at all within "                             <> show (toInteger maxTime)                             <> " microseconds"-                      -- Command needs to be retried but on another target-                      (Left err@(Redirect otherNode))-                        | remaining <= clientRetryTick ->-                            giveUp $-                              "retried for "-                                <> show (toInteger retryBudget)-                                <> " microseconds, last response was "-                                <> show err-                        | otherwise -> attempt payload (Set.insert otherNode nodeSet) (remaining - clientRetryTick) otherNode                       (Left err@NoKnownLeader)                         | remaining <= clientRetryTick ->                             giveUp $@@ -344,8 +335,10 @@                                 <> show err                         | otherwise -> case nextCandidate target nodeSet of                             Nothing -> giveUp "No known nodes to query"-                            Just candidate -> attempt payload nodeSet (remaining - clientRetryTick) candidate-                      (Right (_, result)) -> pure (Just result)+                            Just candidate -> Client.setLeader session candidate >> attempt payload nodeSet (remaining - clientRetryTick) candidate+                      Left (ExpiredSession _) -> fail "Expired session"+                      Left UnexpectedResponse -> fail "Unexpected response"+                      (Right result) -> pure (Just result)                   where                     giveUp why =                       case faultInjection of@@ -437,7 +430,7 @@ instance Exception TestFault  data Server s-  = MkServer+  = Server   { sConfig :: Config Node,     sSpec :: Implementation Command Node Result State (IOSim s),     sFaultInjector :: TVar (IOSim s) (Maybe (ThreadId (IOSim s))) -> IOSim s ()@@ -490,8 +483,7 @@  untilJoined,   untilLeft ::-    -- | Run an admin action-    (forall a. RaftAdminT Node (IOSim s) a -> IOSim s a) ->+    AdminSession Node (IOSim s) ->     -- | Leader if you know it, or initial contact     Node ->     -- | How long to wait for one admin request to be answered.@@ -500,8 +492,7 @@     Microseconds ->     -- | The node whose membership should change     Node ->-    -- | The command that requests the change-    RaftAdminT Node (IOSim s) r ->+    IOSim s r ->     IOSim s () untilJoined = untilMembership Joining untilLeft = untilMembership Leaving@@ -510,7 +501,7 @@   forall s r.   MembershipDirection ->   -- | Run an admin action-  (forall a. RaftAdminT Node (IOSim s) a -> IOSim s a) ->+  AdminSession Node (IOSim s) ->   -- | Leader if you know it, or initial contact   Node ->   -- | How long to wait for one admin request to be answered.@@ -519,17 +510,12 @@   Microseconds ->   -- | The node whose membership should change   Node ->-  -- | The command that requests the change-  RaftAdminT Node (IOSim s) r ->+  IOSim s r ->   IOSim s ()-untilMembership direction runAdminAction initialContact requestTimeout betweenAttempts node command = do+untilMembership direction adminSession initialContact requestTimeout betweenAttempts node command = do   go 4 initialContact   where-    -- An admin action blocks until it gets a response, and the node being-    -- asked may well be down, so every attempt needs a bound.-    attempt :: forall a. RaftAdminT Node (IOSim s) a -> IOSim s (Maybe a)-    attempt = timeout (fromIntegral requestTimeout) . runAdminAction-+    attempt = timeout (fromIntegral requestTimeout)     isDone = case direction of       Joining -> Set.member node       Leaving -> Set.notMember node@@ -538,24 +524,20 @@     go attemptsLeft contact       | attemptsLeft <= 0 = pure ()       | otherwise =-          attempt (Admin.getClusterConfiguration >>= Admin.sendAdminCommand maxBound contact) >>= \case-            -- Settled: the configuration says what we wanted it to say.-            Just (Right (ClusterConfigurationIs (Simple cluster)))-              | isDone cluster -> pure ()-            -- A settled configuration that is not the one we want. This is the-            -- only state in which asking for the change is the right move.-            Just (Right (ClusterConfigurationIs (Simple _))) -> attempt command >> waitAndRetry contact-            -- Only the leader answers a configuration read, so follow the-            -- redirect. This still costs an attempt, so a pair of nodes that-            -- disagree about who leads cannot keep us here forever.-            Just (Left (AdminNotLeader (Just leader)))-              | leader /= contact -> go (attemptsLeft - 1) leader-            -- Either a change is already in flight (a 'Joint' configuration) or-            -- nobody could tell us. Do not ask again on an unknown state: that-            -- is how a request gets issued after the change has already landed,-            -- and such a request has nothing left to happen for it. Wait and-            -- re-read instead.-            _ -> waitAndRetry contact+          attempt+            ( Admin.getClusterConfiguration adminSession+                -- using a 'maxBound' timeout here because timing out is managed+                -- one level up (in 'attempt').+                -- TODO: refactor this whole thing to rely on the 'sendRequest'+                --       timeout+                >>= Admin.sendRequest adminSession maxBound (Just contact)+            )+            >>= \case+              -- Settled: the configuration says what we wanted it to say.+              Just (Right (ClusterConfigurationIs (Simple cluster)))+                | isDone cluster -> pure ()+              Just (Right (ClusterConfigurationIs (Simple _))) -> attempt command >> waitAndRetry contact+              _ -> waitAndRetry contact       where         waitAndRetry c = do           threadDelay (fromIntegral betweenAttempts)@@ -566,7 +548,7 @@ type TopologyConstraints s = TVar (IOSim s) (Map Node (Set Node))  data NetworkFabric s-  = MkNetworkFabric+  = NetworkFabric   { rpcMailbox :: Mailbox s (RPC Command Node State),     rpcResultsMailbox :: Mailbox s (RPCResult Node Result),     requestsMailbox :: Mailbox s (ClientRequest Command Node),@@ -584,7 +566,7 @@   }  data Environment s-  = MkResources+  = Resources   { networkFabric :: NetworkFabric s,     logPersistence :: IntMap (TVar (IOSim s) (Map LogIndex (Term, LogEntry Command Node))),     votePersistence :: IntMap (TVar (IOSim s) (Map Term Node)),@@ -595,8 +577,8 @@  newEnvironment :: Set Node -> IOSim s (Environment s) newEnvironment nodes =-  MkResources-    <$> ( MkNetworkFabric+  Resources+    <$> ( NetworkFabric             <$> newMailbox             <*> newMailbox             <*> newMailbox@@ -620,9 +602,9 @@  mkServer :: (forall a. (Show a) => a -> a) -> Environment s -> Microseconds -> Microseconds -> Microseconds -> Double -> Word64 -> Node -> Server s mkServer debug resources hbto etolb etoub faultProb seed node =-  MkServer+  Server     { sConfig =-        MkConfig+        Config           { nodeId = node,             electionTimeoutRange = (etolb, etoub),             heartBeatTimeout = hbto,@@ -681,7 +663,7 @@       go nextGen  data Harness s-  = MkHarness+  = Harness   { clusterServers :: IntMap (Server s),     loneServers :: IntMap (Server s, MVar (IOSim s) (), Microseconds, Microseconds),     hClients :: IntMap (ClientImplementation Command Node Result (IOSim s)),@@ -707,7 +689,7 @@      withAsync (networkPartitioner (networkFabric resources)) $ \_ ->       withHarness-        MkHarness+        Harness           { clusterServers =               IntMap.fromList $                 map (\(faultProb, serverSeed, n) -> (n, mkServer' faultProb serverSeed (fromIntegral n))) serverNodesWithMeta,@@ -755,20 +737,20 @@        clientSpec network clientNode =         ClientImplementation-          { sendRequest = send network.requestsMailbox network.topologyConstraints clientNode,-            receiveResponse =+          { sendClientRequest = send network.requestsMailbox network.topologyConstraints clientNode,+            receiveClientResponse =               receive network.responsesMailbox clientNode,-            Client.generateSessionId = \node -> do+            generateClientSessionId = do               -- That's the simplest way I know how to introduce randomness in IOSim               now <- getMonotonicTimeNSec-              pure $ sessionId now $ fromIntegral node+              pure $ SessionId now $ fromIntegral clientNode           }        adminSpec network =         AdminImplementation           { sendAdminRequest = send network.adminMailbox network.topologyConstraints adminNode,             receiveAdminResponse = receive network.adminResponsesMailbox adminNode,-            Admin.generateSessionId = pure . sessionId maxBound . fromIntegral+            generateAdminSessionId = pure $ SessionId maxBound (fromIntegral adminNode)           }        networkPartitioner network = go (mkStdGen64 pSeed)
tests/Test/Distributed/Consensus/Raft/Client.hs view
@@ -42,7 +42,7 @@     checkLinearizabilityOnKey key =       let history =             [ (effectiveNode, event)-            | (ix, MkRaftClientTrace (Node node) event) <- zip [0 :: Int ..] clientEvents,+            | (ix, RaftClientTrace (Node node) event) <- zip [0 :: Int ..] clientEvents,               commandKey (fst $ operation event) == key,               -- There's a problem with requests that never get a response.               -- I consider that they may apply at any time after the request@@ -76,7 +76,7 @@     --       To do this, 'RaftClientTrace' would have to be extended to represent 'Maybe result'     model :: Model State (Command, Maybe Result)     model =-      MkModel+      Model         { initialState = mempty :: State,           apply = \(command, observedResult) state ->             let (newState, expectedResult) = runStateMachineStep (Test.StateMachine.step command) state@@ -99,7 +99,7 @@     )  data RaftClientTrace entry node result-  = MkRaftClientTrace+  = RaftClientTrace   { rctNode :: node,     rctEvent :: Linearizable.Event Word64 (entry, Maybe result)   }
tests/Test/Distributed/Consensus/Raft/Properties.hs view
@@ -194,7 +194,7 @@   where     go = void $ whenever commandReceived $ \(_, reqId, _) ->       let thisCommandResponded =-            commandResponded >>= \(_, MkCommandResponse _result' reqId') ->+            commandResponded >>= \(_, CommandResponse _result' reqId') ->               predicate $ \_ -> unless (reqId == reqId') Nothing        in eventually thisCommandResponded <?> "Never received a response for " <> Text.show reqId @@ -262,7 +262,7 @@         <> " to leave a cluster did not result in new cluster membership"  data NodeIndexes-  = MkNodeIndexes+  = NodeIndexes       -- | Last applied index       !LogIndex       -- | Commit index@@ -279,7 +279,7 @@     checkState node acc =       case Map.lookup node acc of         Nothing -> assert "Incomplete state" False-        Just (MkNodeIndexes lastApplied committed lastIndex) -> do+        Just (NodeIndexes lastApplied committed lastIndex) -> do           assert "last_applied_index <= commit_index violated" (lastApplied <= committed)           assert "commit_index <= last_index violated" (committed <= lastIndex)     go acc =@@ -290,8 +290,8 @@               let newAcc =                     Map.alter                       ( \case-                          Nothing -> Just (MkNodeIndexes lastApplied 0 0)-                          Just (MkNodeIndexes _ y z) -> Just (MkNodeIndexes lastApplied y z)+                          Nothing -> Just (NodeIndexes lastApplied 0 0)+                          Just (NodeIndexes _ y z) -> Just (NodeIndexes lastApplied y z)                       )                       node                       acc@@ -301,8 +301,8 @@               let newAcc =                     Map.alter                       ( \case-                          Nothing -> Just (MkNodeIndexes 0 commitIndex 0)-                          Just (MkNodeIndexes x _ z) -> Just (MkNodeIndexes x commitIndex z)+                          Nothing -> Just (NodeIndexes 0 commitIndex 0)+                          Just (NodeIndexes x _ z) -> Just (NodeIndexes x commitIndex z)                       )                       node                       acc@@ -312,8 +312,8 @@               let newAcc =                     Map.alter                       ( \case-                          Nothing -> Just (MkNodeIndexes 0 0 lastLogIndex)-                          Just (MkNodeIndexes x y _) -> Just (MkNodeIndexes x y lastLogIndex)+                          Nothing -> Just (NodeIndexes 0 0 lastLogIndex)+                          Just (NodeIndexes x y _) -> Just (NodeIndexes x y lastLogIndex)                       )                       node                       acc@@ -438,7 +438,7 @@             _ -> go lastIx leaders         ) -data NodeLog = MkNodeLog !LogIndex !(Map LogIndex Term)+data NodeLog = NodeLog !LogIndex !(Map LogIndex Term)  data Committed   = NothingCommitted@@ -454,11 +454,11 @@             LogEntryAppended (EventContext _ n) t ix _ ->               go (Map.alter (Just . appendEntry ix t . fromMaybe emptyNodeLog) n logs) committed             LastLogIndexChangedTo (EventContext _ n) ix ->-              go (Map.adjust (\(MkNodeLog _ runs) -> MkNodeLog ix runs) n logs) committed+              go (Map.adjust (\(NodeLog _ runs) -> NodeLog ix runs) n logs) committed             SnapshotApplied (EventContext _ n) (SnapshotMetadata ix t) -> do-              let update l@(MkNodeLog lastIx runs)+              let update l@(NodeLog lastIx runs)                     | termAt ix l == Just t = l-                    | otherwise = MkNodeLog (max ix lastIx) (Map.insert ix t (Map.dropWhileAntitone (<= ix) runs))+                    | otherwise = NodeLog (max ix lastIx) (Map.insert ix t (Map.dropWhileAntitone (<= ix) runs))                in go (Map.alter (Just . update . fromMaybe emptyNodeLog) n logs) committed             CommitIndexIncreasedTo (EventContext _ n) c               | Just t <- Map.lookup n logs >>= termAt c -> case committed of@@ -472,7 +472,7 @@                 NothingCommitted -> pure ()                 Committed c t -> do                   let nodeLog = Map.findWithDefault emptyNodeLog n logs-                      MkNodeLog lastIx _ = nodeLog+                      NodeLog lastIx _ = nodeLog                    assert ("Incongruent last index for leader of term " <> Text.show term) (lastIx >= c) @@ -483,12 +483,12 @@             _ -> go logs committed         )       where-        emptyNodeLog = MkNodeLog 0 mempty+        emptyNodeLog = NodeLog 0 mempty -        appendEntry !ix !t (MkNodeLog _ runs) =+        appendEntry !ix !t (NodeLog _ runs) =           let kept = Map.takeWhileAntitone (< ix) runs-           in MkNodeLog ix $ case Map.lookupMax kept of+           in NodeLog ix $ case Map.lookupMax kept of                 Just (_, t') | t' == t -> kept                 _ -> Map.insert ix t kept -        termAt ix (MkNodeLog _ runs) = snd <$> Map.lookupLE ix runs+        termAt ix (NodeLog _ runs) = snd <$> Map.lookupLE ix runs
tests/Test/Distributed/Consensus/Raft/Scenario.hs view
@@ -47,8 +47,7 @@     Request (..),     Term,   )-import Distributed.Consensus.Raft.Admin (AdminCommand (..))-import Distributed.Consensus.Raft.Client (ClientResult)+import Distributed.Consensus.Raft.Admin (AdminCommand (..), RequestPayload (..)) import Test.Tasty.QuickCheck (Property, counterexample)  type Scenario entry node result state =@@ -106,19 +105,19 @@   (CommandReceived ctx reqId entry) -> Just (ctx, reqId, entry)   _ -> Nothing -commandResponded :: Predicate (RaftTrace entry node result state) (EventContext node, CommandResponse node (ClientResult result))+commandResponded :: Predicate (RaftTrace entry node result state) (EventContext node, CommandResponse node result) commandResponded = predicate $ \case   (CommandResultResponded ctx response) -> Just (ctx, response)   _ -> Nothing  joinClusterCommandReceived :: Predicate (RaftTrace entry node result state) (EventContext node) joinClusterCommandReceived = predicate $ \case-  (AdminRequestReceived ctx (MkRequest _ _ (JoinCluster _))) -> Just ctx+  (AdminRequestReceived ctx (Request _ _ _ (RequestPayload (JoinCluster _)))) -> Just ctx   _ -> Nothing  leaveClusterCommandReceived :: Predicate (RaftTrace entry node result state) (EventContext node) leaveClusterCommandReceived = predicate $ \case-  (AdminRequestReceived ctx (MkRequest _ _ LeaveCluster)) -> Just ctx+  (AdminRequestReceived ctx (Request _ _ _ (RequestPayload LeaveCluster))) -> Just ctx   _ -> Nothing  joinedCluster :: Predicate (RaftTrace entry node result state) (EventContext node)
+ tests/Test/Distributed/Consensus/Raft/Session.hs view
@@ -0,0 +1,125 @@+{-# LANGUAGE ExplicitForAll #-}+{-# LANGUAGE NoScopedTypeVariables #-}++module Test.Distributed.Consensus.Raft.Session (tests) where++import Control.Concurrent.Class.MonadSTM (atomically, newTQueueIO, readTQueue, writeTQueue)+import Control.Monad (replicateM, void)+import Control.Monad.IOSim (runSimOrThrow)+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Traversable (for)+import Distributed.Consensus.Raft (ClusterConfiguration (Simple), ResponsePayload (..))+import Distributed.Consensus.Raft.Admin (AdminImplementation (..))+import qualified Distributed.Consensus.Raft.Admin as Admin+import Distributed.Consensus.Raft.Client+  ( ClientImplementation (..),+    Request (..),+    Response (..),+    SessionId (..),+    lowestUnacknowledgedSequenceNum,+    newRequest,+    sendClientRequest,+  )+import qualified Distributed.Consensus.Raft.Client as Client+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.QuickCheck+  ( Property,+    chooseInt,+    counterexample,+    forAll,+    shuffle,+    testProperty,+    (===),+  )++tests :: TestTree+tests =+  testGroup+    "Session handling"+    [ testProperty "Oldest client outstanding request sequence number is valid" testPropClientOutstanding,+      testProperty "Oldest admin outstanding request sequence number is valid" testPropAdminOutstanding+    ]++testPropClientOutstanding :: Property+testPropClientOutstanding =+  forAll (chooseInt (1, 20) >>= \n -> shuffle [0 .. n - 1]) $ \order ->+    let n = length order++        expected :: [Int]+        expected =+          [ lowest (Set.fromList [0 .. n - 1] `Set.difference` Set.fromList answered)+          | answered <- inits' order+          ]+          where+            lowest remaining = fromMaybe n (Set.lookupMin remaining)+            inits' xs =+              [ take k xs+              | k <- [0 .. length xs]+              ]++        observed :: [Int]+        observed = fmap fromIntegral $ runSimOrThrow $ do+          inbox <- newTQueueIO+          let impl =+                ClientImplementation+                  { sendClientRequest = \leader (Request reqId _ _ _) ->+                      atomically $+                        writeTQueue inbox (Response reqId (Just leader) (ResponsePayload ())),+                    receiveClientResponse = atomically (readTQueue inbox),+                    generateClientSessionId = pure (SessionId 0 0)+                  }+          Client.withSession (0 :: Int) 0 impl $ \session -> do+            requests <- replicateM n (newRequest session ())+            before <- atomically $ lowestUnacknowledgedSequenceNum session+            afterEach <- for order $ \ix -> do+              void $+                Client.sendRequest+                  session+                  maxBound+                  (requests !! ix)+              atomically $ lowestUnacknowledgedSequenceNum session+            pure (before : afterEach)+     in counterexample ("Response order: " <> show order) (observed === expected)++testPropAdminOutstanding :: Property+testPropAdminOutstanding =+  forAll (chooseInt (1, 20) >>= \n -> shuffle [0 .. n - 1]) $ \order ->+    let n = length order++        expected :: [Int]+        expected =+          [ lowest (Set.fromList [0 .. n - 1] `Set.difference` Set.fromList answered)+          | answered <- inits' order+          ]+          where+            lowest remaining = fromMaybe n (Set.lookupMin remaining)+            inits' xs =+              [ take k xs+              | k <- [0 .. length xs]+              ]++        observed :: [Int]+        observed = fmap fromIntegral $ runSimOrThrow $ do+          inbox <- newTQueueIO+          let impl =+                AdminImplementation+                  { sendAdminRequest = \leader (Request reqId _ _ _) ->+                      atomically $+                        writeTQueue inbox (Response reqId (Just leader) (ResponsePayload $ Admin.ClusterConfigurationIs (Simple mempty))),+                    receiveAdminResponse = atomically (readTQueue inbox),+                    generateAdminSessionId = pure (SessionId 0 0)+                  }+          Admin.withSession (0 :: Int) 0 impl $ \session -> do+            requests <- replicateM n (Admin.getClusterConfiguration session)+            before <- atomically $ Admin.lowestUnacknowledgedSequenceNum session+            afterEach <- for order $ \ix -> do+              void $+                Admin.sendRequest+                  session+                  maxBound+                  Nothing+                  (requests !! ix)+              atomically $ Admin.lowestUnacknowledgedSequenceNum session+            pure (before : afterEach)+     in counterexample ("Response order: " <> show order) (observed === expected)