packages feed

raft-consensus-distributed-process-0.2.0.0: src/Control/Distributed/Process/Raft/Client.hs

{-# LANGUAGE ImportQualifiedPost #-}

module Control.Distributed.Process.Raft.Client
  ( -- * Interface
    withSession,
    ClientSession,

    -- ** Session information
    Raft.Client.sessionId,
    Raft.Client.lowestUnacknowledgedSequenceNum,
    Raft.Client.setLeader,

    -- ** Creating requests
    newRequest,

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

    -- * Other exports
    Microseconds,
  )
where

import Control.Concurrent.STM (atomically, newTQueueIO, readTQueue, writeTQueue)
import Control.Distributed.Process
  ( NodeId,
    Process,
    exit,
    getSelfNode,
    link,
    match,
    matchUnknown,
    nsendRemote,
    receiveWait,
    register,
    spawnLocal,
  )
import Control.Distributed.Process.Raft.Instances ()
import Control.Distributed.Process.Serializable (Serializable)
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO)
import Distributed.Consensus.Raft.Client
  ( ClientImplementation (..),
    ClientRequest,
    ClientSession,
    Microseconds,
    SessionError (..),
    newRequest,
  )
import Distributed.Consensus.Raft.Client qualified as Raft.Client

-- | Open a client session, and run an action with a handle to this session.
--
-- It is perfectly safe, and encouraged, to send separate requests in
-- separate threads. However, you should call 'withSession' only once.
--
-- See 'newRequest' to build a request, and 'sendRequest' to send it.
withSession ::
  (Serializable entry, Serializable result) =>
  -- | At least one node part of the cluster
  NodeId ->
  (ClientSession entry NodeId result Process -> Process b) ->
  Process b
withSession clusterMember f = do
  recvQueue <- liftIO newTQueueIO

  mailPid <-
    spawnLocal $
      forever $
        receiveWait
          [ match $ liftIO . atomically . writeTQueue recvQueue,
            matchUnknown $ pure ()
          ]

  link mailPid

  register clientMailboxProcessName mailPid

  thisNodeId <- getSelfNode

  Raft.Client.withSession thisNodeId clusterMember (impl recvQueue) f <* exit mailPid "Completed"
  where
    impl recvQueue =
      ClientImplementation
        { sendClientRequest = (`nsendRemote` serverMailboxProcessName),
          receiveClientResponse = liftIO $ atomically $ readTQueue recvQueue,
          generateClientSessionId = Raft.Client.randomSessionId
        }

clientMailboxProcessName :: String
clientMailboxProcessName = "raft-consensus-client-inbox"

serverMailboxProcessName :: String
serverMailboxProcessName = "raft-consensus-server-inbox"

-- | Send a client request to a Raft cluster, and wait for its result.
--
-- The user must take care to handle the possible 'SessionError's, and be
-- ready to retry with the same request.
--
-- Redirections are handled automatically, until the timeout expires.
--
-- 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
--   'Raft.Client.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.
sendRequest ::
  ClientSession entry NodeId result Process ->
  Microseconds ->
  ClientRequest entry NodeId ->
  Process
    (Either SessionError result)
sendRequest = Raft.Client.sendRequest