packages feed

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

{-# LANGUAGE OverloadedRecordDot #-}

-- |
-- Module:      $module
-- Copyright:   (c) Laurent P. René de Cotret
-- License:     BSD 3-Clause
--
-- Manage a Raft cluster as an administrator.
--
-- === How to use this module
--
-- The key piece of information to use this module effectively is that
-- interactions are done in /sessions/. An admin starts a session
-- 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 'sendRequest'.
module Distributed.Consensus.Raft.Admin
  ( -- * Interface
    withSession,
    AdminSession,

    -- ** Session information
    sessionId,
    lowestUnacknowledgedSequenceNum,
    setLeader,

    -- ** Creating commands
    leaveCluster,
    joinCluster,
    getClusterConfiguration,
    shutDown,

    -- ** Sending commands
    sendRequest,
    SessionError (..),

    -- ** Configuration
    AdminImplementation (..),
    randomSessionId,

    -- ** Messaging
    AdminRequest,
    Request (..),
    RequestPayload (..),
    AdminResponse,
    Response (..),
    ResponsePayload (..),

    -- * Other exports
    SessionId (..),
    SequenceNum,
    Microseconds,
    ClusterConfiguration (..),
    AdminRequestId (..),
    AdminCommand (..),
    AdminCommandResult (..),
  )
where

import Control.Concurrent.Class.MonadSTM
  ( MonadSTM,
    STM,
  )
import Control.Monad.Class.MonadAsync (MonadAsync)
import Control.Monad.Class.MonadFork (MonadFork)
import Control.Monad.Class.MonadThrow (MonadMask)
import Control.Monad.Class.MonadTimer (MonadTimer)
import Distributed.Consensus.Raft.Domain (ClusterConfiguration (..), SequenceNum, SessionId (..))
import Distributed.Consensus.Raft.Domain.Admin
  ( AdminCommand (..),
    AdminCommandResult (..),
    AdminRequest,
    AdminRequestId (..),
    AdminResponse,
  )
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)

-- | 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, from any node. This should block until
    -- a response is available.
    receiveAdminResponse :: m (AdminResponse node),
    -- | Generate a globally-unique session ID.
    --
    -- See 'randomSessionId' for a good default implementation if
    -- the underlying monad @m@ supports IO.
    generateAdminSessionId :: m SessionId
  }

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 'AdminSession' from several threads concurrently.
--
-- The typical way you would use 'withSession' is like so:
--
-- @
-- 'withSession' self lastKnownLeader impl $ \\session -> do
--     req <- 'shutDown' session
--
--     let go = do
--             result <- 'sendRequest' session 1_000_000 (Just nodeToShutDown) req
--             case result of
--                 Left _ -> go
--                 Right r -> pure r
--
--     go
-- @
withSession ::
  ( MonadAsync m,
    MonadFork 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 ->
  (AdminSession node m -> m b) ->
  m b
withSession self leader impl f = do
  Session.withSession self leader (adminToSessionImplementation impl) (f . AdminSession)

-- | Handle to an open admin session. See 'withSession'.
newtype AdminSession node m = AdminSession (Session AdminRequestId node (AdminCommand node) (AdminCommandResult node) m)

-- | 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

-- | Returns the smallest unacknowledged 'SequenceNum' for outstanding requests.
lowestUnacknowledgedSequenceNum :: (MonadSTM m) => AdminSession node m -> STM m SequenceNum
lowestUnacknowledgedSequenceNum (AdminSession session) = Session.lowestUnacknowledgedSequenceNum session

-- | 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

-- | 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 ->
  m (AdminRequest node)
newRequest (AdminSession session) command =
  Session.newRequest session (RequestPayload command)

-- | Command that a node join a Raft cluster.
--
-- This has no effect if the node is already a member of the
-- cluster.
joinCluster ::
  (MonadSTM m) =>
  AdminSession node m ->
  -- | Leader of the cluster to join
  node ->
  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) => 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) => AdminSession node m -> m (AdminRequest node)
getClusterConfiguration session = newRequest session GetClusterConfiguration

-- | Request that a node shuts down.
shutDown :: (MonadSTM m) => AdminSession node m -> m (AdminRequest node)
shutDown session = newRequest session ShutDown

-- | 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 to command. If @Nothing@, the command is sent to
  -- the leader of the cluster
  Maybe node ->
  AdminRequest node ->
  m
    ( Either
        SessionError
        (AdminCommandResult node)
    )
sendRequest (AdminSession session) =
  Session.sendRequest
    (\(AdminRequestId _ seqNum) -> seqNum)
    session