packages feed

raft-consensus-distributed-process 0.1.1.0 → 0.2.0.0

raw patch · 5 files changed

+213/−108 lines, 5 filesdep −randomdep ~raft-consensusPVP ok

version bump matches the API change (PVP)

Dependencies removed: random

Dependency ranges changed: raft-consensus

API changes (from Hackage documentation)

Files

CHANGELOG.md view
@@ -1,10 +1,17 @@ # Revision history for raft-consensus-distributed-process -## 0.1.1.0 -- 2026-11-30+## 0.2.0.0 +### Breaking changes++* Support for `raft-consensus-0.2.0.0`.+* Client and admin interfaces are now session-based: use `withSession` and `sendRequest`++## 0.1.1.0+ * Snapshots are now automatically chunked, preventing a large snapshot from being truncated in transit,   and allowing other messages to be interleaved on certain types of connections (#19). -## 0.1.0.0 -- 2026-11-26+## 0.1.0.0  * First version. Released on an unsuspecting world.
raft-consensus-distributed-process.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.4 name:               raft-consensus-distributed-process-version:            0.1.1.0+version:            0.2.0.0 synopsis:           Cloud Haskell facilities to the Raft consensus protocol -- description: license:            BSD-3-Clause@@ -41,7 +41,7 @@                     , containers >=0.7 && <0.9                     , distributed-process ^>=0.7                     , raft-consensus-distributed-process:io-classes-instances-                    , raft-consensus ^>=0.1+                    , raft-consensus ^>=0.2                     , stm ^>=2.5     default-language: GHC2021 @@ -68,8 +68,7 @@     build-depends:    base >= 4.18 && <4.23                     , distributed-process ^>=0.7                     , raft-consensus-distributed-process:io-classes-instances-                    , raft-consensus ^>=0.1-                    , random ^>=1.3+                    , raft-consensus ^>=0.2                     , stm ^>=2.5     default-language: GHC2021 @@ -81,8 +80,7 @@     build-depends:    base >= 4.18 && <4.23                     , distributed-process ^>=0.7                     , raft-consensus-distributed-process:io-classes-instances-                    , raft-consensus ^>=0.1-                    , random ^>=1.3+                    , raft-consensus ^>=0.2                     , stm ^>=2.5     default-language: GHC2021 
src/Control/Distributed/Process/Raft/Admin.hs view
@@ -1,34 +1,69 @@+{-# LANGUAGE ImportQualifiedPost #-}+ module Control.Distributed.Process.Raft.Admin-  ( withRaftAdmin,+  ( -- * Interface+    withSession,+    AdminSession, -    -- * Re-exports-    AdminError (..),-    Microseconds,-    sendAdminCommand,-    joinCluster,+    -- ** Session information+    Raft.Admin.sessionId,+    Raft.Admin.lowestUnacknowledgedSequenceNum,+    Raft.Admin.setLeader,++    -- ** Creating commands     leaveCluster,+    joinCluster,     getClusterConfiguration,     shutDown,++    -- ** Sending commands+    sendRequest,+    SessionError (..),++    -- * Other exports+    Microseconds,+    Raft.Admin.AdminCommand (..),+    AdminCommandResult (..),   ) 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+  ( NodeId,+    Process,+    exit,+    getSelfNode,+    link,+    match,+    matchUnknown,+    nsendRemote,+    receiveWait,+    register,+    spawnLocal,+  ) import Control.Distributed.Process.Raft.Instances () import Control.Monad (forever) import Control.Monad.IO.Class (liftIO)-import Distributed.Consensus.Raft.Admin (AdminCommandResult, AdminError, AdminImplementation (..), AdminRequest, Microseconds, RaftAdminT, sessionId, withAdminSession)+import Distributed.Consensus.Raft.Admin+  ( AdminCommandResult,+    AdminImplementation (..),+    AdminRequest,+    AdminSession,+    Microseconds,+    SessionError (..),+  ) import Distributed.Consensus.Raft.Admin qualified as Raft.Admin-import System.Random (randomIO) --- | Send an admin request to a Raft cluster.+-- | Open an admin session, and run an action with a handle to this session. -- -- It is perfectly safe, and encouraged, to send separate requests in--- separate threads.-withRaftAdmin ::-  ((forall a. RaftAdminT NodeId Process a -> Process a) -> Process b) ->+-- separate threads. However, you should call 'withSession' only once.+withSession ::+  -- | Some member of the Raft cluster+  NodeId ->+  (AdminSession NodeId Process -> Process b) ->   Process b-withRaftAdmin f = do+withSession clusterMember f = do   recvQueue <- liftIO newTQueueIO    mailPid <-@@ -45,16 +80,13 @@    thisNodeId <- getSelfNode -  withAdminSession thisNodeId (impl recvQueue) f <* exit mailPid "Completed"+  Raft.Admin.withSession thisNodeId clusterMember (impl recvQueue) f <* exit mailPid "Completed"   where     impl recvQueue =       AdminImplementation         { sendAdminRequest = (`nsendRemote` adminMailboxProcessName),           receiveAdminResponse = liftIO $ atomically $ readTQueue recvQueue,-          generateSessionId =-            const $-              liftIO $-                sessionId <$> randomIO <*> randomIO+          generateAdminSessionId = Raft.Admin.randomSessionId         }  -- | This value needs to be kept in sync with 'Control.Distributed.Process.Raft'.@@ -62,33 +94,55 @@ adminMailboxProcessName :: String adminMailboxProcessName = "raft-consensus-admin-mailbox" -sendAdminCommand ::+-- | Send an admin request to a Raft cluster, and wait for its result.+--+-- See 'Raft.Admin.sendRequest' for details.+sendRequest ::+  AdminSession NodeId Process ->+  -- | Maximum time to wait for a response.   Microseconds ->-  NodeId ->+  -- | Node to command. If @Nothing@, the command is sent to+  -- the leader of the cluster+  Maybe NodeId ->   AdminRequest NodeId ->-  RaftAdminT-    NodeId-    Process+  Process     ( Either-        (AdminError NodeId)+        SessionError         (AdminCommandResult NodeId)     )-sendAdminCommand = Raft.Admin.sendAdminCommand+sendRequest = Raft.Admin.sendRequest +-- | Command that a node join a Raft cluster.+--+-- This has no effect if the node is already a member of the+-- cluster. joinCluster ::-  -- \| Node to join+  AdminSession NodeId Process ->+  -- | Node to join   NodeId ->-  RaftAdminT NodeId Process (AdminRequest NodeId)+  Process (AdminRequest NodeId) joinCluster = Raft.Admin.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 ::-  RaftAdminT NodeId Process (AdminRequest NodeId)+  AdminSession NodeId Process ->+  Process (AdminRequest NodeId) leaveCluster = Raft.Admin.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 ::-  RaftAdminT NodeId Process (AdminRequest NodeId)+  AdminSession NodeId Process ->+  Process (AdminRequest NodeId) getClusterConfiguration = Raft.Admin.getClusterConfiguration +-- | Request that a node shuts down. shutDown ::-  RaftAdminT NodeId Process (AdminRequest NodeId)+  AdminSession NodeId Process ->+  Process (AdminRequest NodeId) shutDown = Raft.Admin.shutDown
src/Control/Distributed/Process/Raft/Client.hs view
@@ -1,12 +1,24 @@ {-# LANGUAGE ImportQualifiedPost #-}  module Control.Distributed.Process.Raft.Client-  ( withRaftClient,-    sendClientRequest,-    Microseconds,-    ClientError (..),+  ( -- * Interface+    withSession,+    ClientSession,++    -- ** Session information+    Raft.Client.sessionId,+    Raft.Client.lowestUnacknowledgedSequenceNum,+    Raft.Client.setLeader,++    -- ** Creating requests     newRequest,-    clientSession,++    -- ** Sending requests+    sendRequest,+    SessionError (..),++    -- * Other exports+    Microseconds,   ) where @@ -29,30 +41,28 @@ import Control.Monad (forever) import Control.Monad.IO.Class (liftIO) import Distributed.Consensus.Raft.Client-  ( ClientError,-    ClientImplementation (..),+  ( ClientImplementation (..),     ClientRequest,+    ClientSession,     Microseconds,-    RaftClientT,-    clientSession,+    SessionError (..),     newRequest,-    sessionId,-    withClientSession,   ) import Distributed.Consensus.Raft.Client qualified as Raft.Client-import System.Random.Stateful (randomIO) --- | Send a request to a Raft cluster.+-- | 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.+-- separate threads. However, you should call 'withSession' only once. ----- See 'request' to build an appropriate request.-withRaftClient ::+-- See 'newRequest' to build a request, and 'sendRequest' to send it.+withSession ::   (Serializable entry, Serializable result) =>-  ((forall a. RaftClientT entry NodeId result Process a -> Process a) -> Process b) ->+  -- | At least one node part of the cluster+  NodeId ->+  (ClientSession entry NodeId result Process -> Process b) ->   Process b-withRaftClient f = do+withSession clusterMember f = do   recvQueue <- liftIO newTQueueIO    mailPid <-@@ -69,16 +79,13 @@    thisNodeId <- getSelfNode -  withClientSession thisNodeId (impl recvQueue) f <* exit mailPid "Completed"+  Raft.Client.withSession thisNodeId clusterMember (impl recvQueue) f <* exit mailPid "Completed"   where     impl recvQueue =       ClientImplementation-        { sendRequest = (`nsendRemote` serverMailboxProcessName),-          receiveResponse = liftIO $ atomically $ readTQueue recvQueue,-          generateSessionId =-            const $-              liftIO $-                sessionId <$> randomIO <*> randomIO+        { sendClientRequest = (`nsendRemote` serverMailboxProcessName),+          receiveClientResponse = liftIO $ atomically $ readTQueue recvQueue,+          generateClientSessionId = Raft.Client.randomSessionId         }  clientMailboxProcessName :: String@@ -87,32 +94,27 @@ serverMailboxProcessName :: String serverMailboxProcessName = "raft-consensus-server-inbox" --- | Send a request to a Raft cluster.+-- | Send a client request to a Raft cluster, and wait for its result. ----- The user must take care to handle the possible 'ClientError's.+-- The user must take care to handle the possible 'SessionError's, and be+-- ready to retry with the same request. ----- 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.+-- Redirections are handled automatically, until the timeout expires. ----- Second, there is an unlikely, but real, possibility that the server+-- 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.---   It may be beneficial to keep a memory of all servers ever contacted for this---   particular purpose.+-- * 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. However, you should call 'withClientSession' only once.-sendClientRequest ::+-- separate threads.+sendRequest ::+  ClientSession entry NodeId result Process ->   Microseconds ->-  NodeId ->   ClientRequest entry NodeId ->-  RaftClientT-    entry-    NodeId-    result-    Process-    (Either (ClientError entry NodeId) (NodeId, result))-sendClientRequest = Raft.Client.sendClientRequest+  Process+    (Either SessionError result)+sendRequest = Raft.Client.sendRequest
tests/Test/Control/Distributed/Process/Raft.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-}  module Test.Control.Distributed.Process.Raft (tests) where@@ -8,11 +9,13 @@ import Control.Concurrent (threadDelay) import Control.Concurrent.Async (withAsync) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)-import Control.Distributed.Process (NodeId (NodeId), link, spawnLocal)+import Control.Distributed.Process (NodeId (NodeId), Process, link, spawnLocal) import Control.Distributed.Process.Node (LocalNode (localNodeId), initRemoteTable, newLocalNode, runProcess) import Control.Distributed.Process.Raft (networking)-import Control.Distributed.Process.Raft.Admin (getClusterConfiguration, joinCluster, leaveCluster, shutDown, withRaftAdmin)-import Control.Distributed.Process.Raft.Client (newRequest, sendClientRequest, withRaftClient)+import Control.Distributed.Process.Raft.Admin (getClusterConfiguration, joinCluster, leaveCluster, shutDown)+import qualified Control.Distributed.Process.Raft.Admin as Admin+import Control.Distributed.Process.Raft.Client (ClientSession, newRequest)+import qualified Control.Distributed.Process.Raft.Client as Client import Control.Monad (replicateM, replicateM_, void) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as BS@@ -25,12 +28,18 @@     RPC (..),     RPCResult (..),     Request (..),+    RequestPayload (..),+    RequestVote (..),     Response (..),+    ResponsePayload (..),     Snapshot (..),     SnapshotMetadata (..),     requestPayload,   )-import Distributed.Consensus.Raft.Admin (AdminCommand (..), AdminCommandResult (..), sendAdminCommand)+import Distributed.Consensus.Raft.Admin+  ( AdminCommand (..),+    AdminCommandResult (..),+  ) import Network.Transport (EndPointAddress (EndPointAddress), Transport) import qualified Network.Transport.InMemory as InMemory import System.Timeout (timeout)@@ -57,15 +66,23 @@     serverNetwork <- networking @() @() @()     liftIO $ putMVar ready ()     let expectations =-          [ (JoinCluster arbitraryOtherNodeId, JoinInitiated),-            (LeaveCluster, LeaveInitiated),-            (GetClusterConfiguration, ShutdownInitiated), -- mismatch-            (ShutDown, ShutdownInitiated)+          [ (RequestPayload $ JoinCluster arbitraryOtherNodeId, ResponsePayload JoinInitiated),+            (RequestPayload LeaveCluster, ResponsePayload LeaveInitiated),+            (RequestPayload GetClusterConfiguration, ResponsePayload ShutdownInitiated), -- mismatch+            (RequestPayload ShutDown, ResponsePayload ShutdownInitiated)           ]     for_ expectations $ \(expectation, response) -> do       req <- receiveAdminRequest serverNetwork       liftIO (requestPayload req @?= expectation)-      sendAdminResponse serverNetwork (requestOriginator req) (MkResponse (requestId req) Nothing response)+      sendAdminResponse+        serverNetwork+        (requestOriginator req)+        ( Response+            { responseRequestId = requestId req,+              responseClusterLeader = Nothing,+              responsePayload = response+            }+        )   where     arbitraryOtherNodeId :: NodeId     arbitraryOtherNodeId = NodeId $ EndPointAddress "some-arbitrary-node-id"@@ -73,13 +90,13 @@     sendAdminCommands ready transport serverNodeId = do       _ <- liftIO $ takeMVar ready       node <- newLocalNode transport initRemoteTable-      runProcess node $ withRaftAdmin $ \runAdmin -> runAdmin $ do+      runProcess node $ Admin.withSession serverNodeId $ \session -> do         -- Since the helper functions e.g. 'joinCluster' automatically wait for a response,         -- we spin up a new thread for each of them-        void $ joinCluster arbitraryOtherNodeId >>= sendAdminCommand maxBound serverNodeId-        void $ leaveCluster >>= sendAdminCommand maxBound serverNodeId-        void $ getClusterConfiguration >>= sendAdminCommand maxBound serverNodeId-        void $ shutDown >>= sendAdminCommand maxBound serverNodeId+        void $ joinCluster session arbitraryOtherNodeId >>= Admin.sendRequest session maxBound (Just serverNodeId)+        void $ leaveCluster session >>= Admin.sendRequest session maxBound (Just serverNodeId)+        void $ getClusterConfiguration session >>= Admin.sendRequest session maxBound (Just serverNodeId)+        void $ shutDown session >>= Admin.sendRequest session maxBound (Just serverNodeId)  testClientCommands :: IO Transport -> TestTree testClientCommands getTransport = testCase "Tests that client commands are communicated" $ do@@ -114,7 +131,7 @@     sendClientCommands ready transport serverNodeId = do       _ <- liftIO $ takeMVar ready       node <- newLocalNode transport initRemoteTable-      runProcess node $ withRaftClient @() @() $ \runClient -> do+      runProcess node $ Client.withSession serverNodeId $ \(session :: ClientSession () NodeId () Process) -> do         -- To demonstrate that pipelining works, we send multiple requests from separate clients         replicateM_ nRequests $           spawnLocal@@ -123,7 +140,7 @@               --               -- We basicaly yeet a message '()' in a separate process, which               -- blocks for as much time as possible, and then await that all requests be done-              void $ runClient (newRequest () >>= sendClientRequest maxBound serverNodeId)+              void (newRequest session () >>= Client.sendRequest session maxBound)             )             >>= link @@ -140,15 +157,28 @@       snapshotAt index =         IS           ( InstallSnapshot-              2-              senderId-              ( Snapshot-                  (SnapshotMetadata index 2)-                  (BS.replicate (2 * 1024 * 1024 + 5) 7)-                  (Simple mempty)-              )+              { isLeaderTerm = 2,+                isLeaderNode = senderId,+                isSnapshot =+                  Snapshot+                    { sMetadata =+                        SnapshotMetadata+                          { smLastIncludedIndex = index,+                            smLastIncludedTerm = 2+                          },+                      sData = BS.replicate (2 * 1024 * 1024 + 5) 7,+                      sCluster = Simple mempty+                    }+              }           )-      heartbeat = RequestVote 2 senderId 10 2+      heartbeat =+        RV $+          RequestVote+            { rvCandidateTerm = 2,+              rvCandidateNode = senderId,+              rvCandidateLastLogEntryIndex = 10,+              rvCandidateLastLogEntryTerm = 2+            }    timeout     10_000_000@@ -157,7 +187,21 @@             network <- networking @() @BS.ByteString @()             liftIO $ putMVar ready ()             replicateM 2 (receiveRPC network) >>= liftIO . putMVar firstTwo-            sendRPCResult network senderId (ISR (InstallSnapshotResult 2 receiverId (SnapshotMetadata 10 2)))+            sendRPCResult+              network+              senderId+              ( ISR+                  ( InstallSnapshotResult+                      { isrTerm = 2,+                        isrNode = receiverId,+                        isrSnapshotMetadata =+                          SnapshotMetadata+                            { smLastIncludedIndex = 10,+                              smLastIncludedTerm = 2+                            }+                      }+                  )+              )             receiveRPC network >>= liftIO . putMVar third         )         $ \_ -> do