packages feed

raft-consensus-distributed-process 0.1.0.0 → 0.1.1.0

raw patch · 4 files changed

+287/−25 lines, 4 filesdep +binarydep +bytestringdep +containersPVP ok

version bump matches the API change (PVP)

Dependencies added: binary, bytestring, containers

API changes (from Hackage documentation)

+ Control.Distributed.Process.Raft: instance Data.Binary.Class.Binary Control.Distributed.Process.Raft.RPCChunk
+ Control.Distributed.Process.Raft: instance GHC.Internal.Generics.Generic Control.Distributed.Process.Raft.RPCChunk

Files

CHANGELOG.md view
@@ -1,5 +1,10 @@ # Revision history for raft-consensus-distributed-process +## 0.1.1.0 -- 2026-11-30++* 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  * 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.0.0+version:            0.1.1.0 synopsis:           Cloud Haskell facilities to the Raft consensus protocol -- description: license:            BSD-3-Clause@@ -36,6 +36,9 @@     -- GHC 9.6+ (base 4.18+) is required to infer types properly when     -- using io-classes     build-depends:    base >= 4.18 && <4.23+                    , binary ^>=0.8+                    , bytestring ^>=0.12+                    , containers >=0.7 && <0.9                     , distributed-process ^>=0.7                     , raft-consensus-distributed-process:io-classes-instances                     , raft-consensus ^>=0.1@@ -96,6 +99,7 @@     main-is:          Main.hs     build-depends:    async                     , base >= 4.18 && <4.23+                    , bytestring                     , distributed-process                     , raft-consensus-distributed-process                     , raft-consensus-distributed-process:admin
src/Control/Distributed/Process/Raft.hs view
@@ -6,17 +6,63 @@ where  import Control.Concurrent.STM (atomically, flushTQueue, newTQueueIO, readTQueue, retry, writeTQueue)-import Control.Distributed.Process (NodeId, Process, link, match, matchUnknown, nsendRemote, receiveWait, register, spawnLocal)+import Control.Distributed.Process (NodeId, Process, getSelfNode, link, match, matchUnknown, nsendRemote, receiveTimeout, receiveWait, register, spawnLocal) -- Simply importing the instances here is enough -- for someone else importing Control.Distributed.Process.Raft -- to get access to the instances import Control.Distributed.Process.Raft.Instances () import Control.Distributed.Process.Serializable (Serializable)-import Control.Monad (forever)+import Control.Monad (forM_, forever, when) import Control.Monad.IO.Class (liftIO)+import Data.Binary (Binary)+import Data.Binary qualified as Binary+import Data.ByteString (StrictByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as BSL+import Data.Function ((&))+import Data.Functor (($>))+import Data.IORef (IORef, atomicModifyIORef', newIORef)+import Data.List (genericLength) import Data.List.NonEmpty (NonEmpty (..))-import Distributed.Consensus.Raft (Networking (..))+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Word (Word64)+import Distributed.Consensus.Raft+  ( InstallSnapshotResult (isrNode),+    Networking (..),+    RPC (IS),+    RPCResult (ISR),+  )+import GHC.Clock (getMonotonicTime)+import GHC.Generics (Generic) +-- | Provides a 'Networking' implementation suitable for a Cloud Haskell cluster.+--+-- For example:+--+-- @+-- runProcess localNode $+--     raftNetwork <- 'networking'+--     conf <- simpleConfig =<< getSelfNode+--     peers <- ...+--     let implementation = Implementation { networking = raftNetwork+--                                         , stateMachine = ...+--                                         , persistence = ...+--                                         , tracer = ...+--                                         }+--     withRaftServer conf peers initialState implementation $ do+--         ...+-- @+--+-- Persistence must be provided separately, for example via a package+-- like @raft-consensus-wal@.+--+-- Snapshots are automatically chunked and sent over multiple messages+-- to prevent any issues related to large snapshots.+--+-- There is one caveat: only one Raft server can be created per node.+-- Failure to uphold this will result in an exception on startup. networking ::   (Serializable entry, Serializable state, Serializable result) =>   Process (Networking entry NodeId result state Process)@@ -29,6 +75,8 @@         <*> newTQueueIO         <*> newTQueueIO +  snapshotsInFlight <- liftIO $ newIORef mempty+   -- Registering the mailbox process under a name   -- is what allows other nodes to send messages to this node   -- knowing only a `NodeId` (essentially host:port)@@ -40,13 +88,31 @@   --       If it is, we could use a IORef to cache a 'Map NodeId ProcessId'.   --       Then, on the first 'sendX', we first query the node to ask which   --       'ProcessId' is the mailbox one-  spawnMailbox rpcMailboxProcessName (recvLoop rpcQueue rpcResultQueue)+  spawnMailbox rpcMailboxProcessName (recvLoop snapshotsInFlight rpcQueue rpcResultQueue mempty)   spawnMailbox serverMailboxProcessName (clientRecvLoop clientRequestQueue)   spawnMailbox adminMailboxProcessName (adminRecvLoop adminRequestQueue)    pure     Networking-      { sendRPC = (`nsendRemote` rpcMailboxProcessName),+      { sendRPC = \destination rpc -> case rpc of+          IS _ -> do+            started <- liftIO $ startSendingSnapshot snapshotsInFlight destination+            when started $ do+              sender <- getSelfNode+              let chunks = rpcToChunks rpc+              forM_ (zip [0 ..] chunks) $ \(ix, chunk) -> do+                nsendRemote+                  destination+                  rpcMailboxProcessName+                  ( RPCChunk+                      { rcSender = sender,+                        rcIndex = ix,+                        rcCount = genericLength chunks,+                        rcBytes = chunk+                      }+                  )+                liftIO $ updateSnapshotInFlight snapshotsInFlight destination+          _ -> nsendRemote destination rpcMailboxProcessName rpc,         sendRPCResult = (`nsendRemote` rpcMailboxProcessName),         sendClientResponse = (`nsendRemote` remoteClientMailboxProcessName),         sendAdminResponse = (`nsendRemote` adminMailboxProcessName),@@ -72,14 +138,29 @@     remoteClientMailboxProcessName = "raft-consensus-client-inbox"     adminMailboxProcessName = "raft-consensus-admin-mailbox" -    recvLoop rpcQueue rpcResultQueue =-      forever $-        receiveWait-          [ match $ liftIO . atomically . writeTQueue rpcQueue,-            match $ liftIO . atomically . writeTQueue rpcResultQueue,-            -- flush the queue from unknown message types.-            matchUnknown (pure ())-          ]+    recvLoop snapshotsInFlight rpcQueue rpcResultQueue received = do+      now <- liftIO getMonotonicTime+      let partialSnapshots = Map.filter (\partial -> now - pUpdated partial < 30_000_000) received+      receiveTimeout+        -- It's important to timeout at some point, because we want to filter partialSnapshots+        -- for transfers which are too old.+        (round snapshotChunkTimeout * 1_000_000)+        [ match $ \rpc ->+            liftIO (atomically $ writeTQueue rpcQueue rpc)+              $> partialSnapshots,+          match $ \result -> do+            case result of+              ISR answer -> liftIO (endSnapshotInFlight snapshotsInFlight (isrNode answer))+              _ -> pure ()++            liftIO $+              atomically $+                writeTQueue rpcResultQueue result+                  $> partialSnapshots, -- flush the queue from unknown message types.+          match $ accumulateRPCChunks (liftIO . atomically . writeTQueue rpcQueue) partialSnapshots,+          matchUnknown (pure partialSnapshots)+        ]+        >>= recvLoop snapshotsInFlight rpcQueue rpcResultQueue . fromMaybe partialSnapshots     clientRecvLoop clientRequestQueue =       forever $         receiveWait@@ -95,3 +176,109 @@             -- flush the queue from unknown message types.             matchUnknown (pure ())           ]++-- * Chunking snapshots++-- TODO: make chunk timeout and size configurable.++-- | Amount of time to wait for another snapshot chunk, in seconds. Beyond waiting this+-- long, the snapshot should be considered stale and purged.+snapshotChunkTimeout :: Double+snapshotChunkTimeout = 30++-- | Maximum number of bytes in each snapshot chunk.+-- This is relatively small so as to not block a connection for two long,+-- for transports that experience head-of-line blocking (e.g. TCP)+snapshotChunkSize :: Word64+snapshotChunkSize = 1024 * 1024++startSendingSnapshot :: IORef (Map NodeId Double) -> NodeId -> IO Bool+startSendingSnapshot snapshotsInFlight destination = do+  now <- getMonotonicTime+  atomicModifyIORef' snapshotsInFlight $ \inflight ->+    let live = Map.filter (\updated -> now - updated < snapshotChunkTimeout) inflight+     in if destination `Map.member` live+          then (live, False)+          else (Map.insert destination now inflight, True)++updateSnapshotInFlight :: IORef (Map NodeId Double) -> NodeId -> IO ()+updateSnapshotInFlight inFlight destination = do+  now <- getMonotonicTime+  atomicModifyIORef' inFlight $ \transfers ->+    let updatedTransfers = Map.update (const (Just now)) destination transfers+     in (updatedTransfers, ())++endSnapshotInFlight :: IORef (Map NodeId Double) -> NodeId -> IO ()+endSnapshotInFlight snapshotsInFlight destination =+  atomicModifyIORef' snapshotsInFlight $ \transfers ->+    let updatedTransfers = Map.delete destination transfers+     in (updatedTransfers, ())++accumulateRPCChunks ::+  (Binary a) =>+  (a -> Process ()) ->+  Map NodeId Partial ->+  RPCChunk ->+  Process (Map NodeId Partial)+accumulateRPCChunks deliver partials (RPCChunk sender index count bytes) = do+  now <- liftIO getMonotonicTime+  let others = Map.delete sender partials+      received+        | index == 0 =+            Just+              ( Partial+                  { pNext = 1,+                    pChunks = [bytes],+                    pUpdated = now+                  }+              )+        | Just p <- Map.lookup sender partials,+          pNext p == index =+            Just+              ( Partial+                  { pNext = succ index,+                    pChunks =+                      bytes : pChunks p,+                    pUpdated = now+                  }+              )+        | otherwise = Nothing++  case received of+    Nothing -> pure others+    Just p+      | index + 1 >= count -> do+          case Binary.decodeOrFail (BSL.fromChunks (reverse (pChunks p))) of+            Right (rest, _, message) | BSL.null rest -> deliver message+            _ -> pure ()+          pure others+      | otherwise -> pure $ Map.insert sender p others++rpcToChunks :: (Binary entry, Binary node, Binary state) => RPC entry node state -> [StrictByteString]+rpcToChunks rpc =+  Binary.encode rpc+    & BSL.toStrict+    & splitEvery (fromIntegral snapshotChunkSize)+  where+    splitEvery n bs+      | BS.null bs = []+      | otherwise =+          let (piece, rest) = BS.splitAt n bs+           in piece : splitEvery n rest++data RPCChunk+  = RPCChunk+  { rcSender :: !NodeId,+    rcIndex :: !Word64,+    rcCount :: !Word64,+    rcBytes :: !StrictByteString+  }+  deriving (Generic)++instance Binary RPCChunk++data Partial = Partial+  { pNext :: !Word64,+    pChunks :: ![StrictByteString],+    pUpdated :: !Double+  }
tests/Test/Control/Distributed/Process/Raft.hs view
@@ -8,15 +8,28 @@ import Control.Concurrent (threadDelay) import Control.Concurrent.Async (withAsync) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)-import Control.Distributed.Process (NodeId (NodeId), spawnLocal)+import Control.Distributed.Process (NodeId (NodeId), 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.Monad (replicateM_, void)+import Control.Monad (replicateM, replicateM_, void) import Control.Monad.IO.Class (liftIO)+import qualified Data.ByteString as BS import Data.Foldable (for_)-import Distributed.Consensus.Raft (Networking (..), Request (..), Response (..), requestPayload)+import Distributed.Consensus.Raft+  ( ClusterConfiguration (Simple),+    InstallSnapshot (..),+    InstallSnapshotResult (..),+    Networking (..),+    RPC (..),+    RPCResult (..),+    Request (..),+    Response (..),+    Snapshot (..),+    SnapshotMetadata (..),+    requestPayload,+  ) import Distributed.Consensus.Raft.Admin (AdminCommand (..), AdminCommandResult (..), sendAdminCommand) import Network.Transport (EndPointAddress (EndPointAddress), Transport) import qualified Network.Transport.InMemory as InMemory@@ -30,7 +43,8 @@     testGroup       "Control.Distributed.Process.Raft"       [ testAdminCommands getTransport,-        testClientCommands getTransport+        testClientCommands getTransport,+        testSnapshotNotResentWhileInFlight getTransport       ]  testAdminCommands :: IO Transport -> TestTree@@ -103,10 +117,62 @@       runProcess node $ withRaftClient @() @() $ \runClient -> do         -- To demonstrate that pipelining works, we send multiple requests from separate clients         replicateM_ nRequests $-          spawnLocal $ do-            -- We're re-using the 'request' mechanism even though there's no-            -- logic in the server to process a request and send a response.-            ---            -- 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)+          spawnLocal+            ( -- We're re-using the 'request' mechanism even though there's no+              -- logic in the server to process a request and send a response.+              --+              -- 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)+            )+            >>= link++testSnapshotNotResentWhileInFlight :: IO Transport -> TestTree+testSnapshotNotResentWhileInFlight getTransport = testCase "Test snapshot chunking" $ do+  t <- getTransport+  sender <- newLocalNode t initRemoteTable+  receiver <- newLocalNode t initRemoteTable+  ready <- newEmptyMVar+  firstTwo <- newEmptyMVar+  third <- newEmptyMVar+  let senderId = localNodeId sender+      receiverId = localNodeId receiver+      snapshotAt index =+        IS+          ( InstallSnapshot+              2+              senderId+              ( Snapshot+                  (SnapshotMetadata index 2)+                  (BS.replicate (2 * 1024 * 1024 + 5) 7)+                  (Simple mempty)+              )+          )+      heartbeat = RequestVote 2 senderId 10 2++  timeout+    10_000_000+    ( withAsync+        ( runProcess receiver $ do+            network <- networking @() @BS.ByteString @()+            liftIO $ putMVar ready ()+            replicateM 2 (receiveRPC network) >>= liftIO . putMVar firstTwo+            sendRPCResult network senderId (ISR (InstallSnapshotResult 2 receiverId (SnapshotMetadata 10 2)))+            receiveRPC network >>= liftIO . putMVar third+        )+        $ \_ -> do+          takeMVar ready+          runProcess sender $ do+            network <- networking @() @BS.ByteString @()+            sendRPC network receiverId (snapshotAt 10)+            sendRPC network receiverId (snapshotAt 11)+            sendRPC network receiverId heartbeat+            _ <- receiveRPCResult network+            sendRPC network receiverId (snapshotAt 12)+          (,) <$> takeMVar firstTwo <*> takeMVar third+    )+    >>= \case+      Just (received, later) -> do+        received @?= [snapshotAt 10, heartbeat]+        later @?= snapshotAt 12+      Nothing -> assertFailure "Receiver did not get the expected RPCs"