packages feed

raft-consensus-0.2.0.0: src/Distributed/Consensus/Raft/Session.hs

{-# 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)