packages feed

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

{-# LANGUAGE OverloadedRecordDot #-}

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

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

    -- ** Creating requests
    newRequest,

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

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

    -- ** Messaging
    ClientRequest,
    Request (..),
    RequestPayload (..),
    ClientResponse,
    Response (..),
    ResponsePayload (..),

    -- * Other exports
    SessionId (..),
    SequenceNum,
    Microseconds,
    ClientRequestId (..),
  )
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.Client
  ( ClientRequest,
    ClientRequestId (..),
    ClientResponse,
    SequenceNum,
    SessionId (..),
  )
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 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
  { -- | 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.
    --
    -- See 'randomSessionId' for a good default implementation if
    -- the underlying monad @m@ supports IO.
    generateClientSessionId :: m SessionId
  }

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 'withSession' is like so:
--
-- @
-- 'withSession' self lastKnownLeader impl $ \\session -> do
--     req <- 'newRequest' session entry
--
--     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
-- @
--
-- 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,
    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 ->
  (ClientSession entry node result m -> m a) ->
  m a
withSession self leader impl f =
  Session.withSession self leader (clientToSessionImplementation impl) (f . ClientSession)

-- | 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
sessionId :: ClientSession entry node result m -> SessionId
sessionId (ClientSession session) = Session.sessionId session

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

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

-- | Create a request to apply an entry to the replicated state machine.
--
-- 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.
--
-- 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.
--
-- 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 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 '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 ->
  ClientRequest entry node ->
  m
    ( Either
        SessionError
        result
    )
sendRequest (ClientSession session) timeout =
  Session.sendRequest
    (\(ClientRequestId _ seqNum) -> seqNum)
    session
    timeout
    Nothing -- clients always send requests to the leader