packages feed

raft-consensus-distributed-process (empty) → 0.1.0.0

raw patch · 10 files changed

+1081/−0 lines, 10 filesdep +arraydep +asyncdep +base

Dependencies added: array, async, base, distributed-process, io-classes, network-transport, network-transport-inmemory, primitive, raft-consensus, raft-consensus-distributed-process, random, stm, tasty, tasty-hunit, transformers

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for raft-consensus-distributed-process++## 0.1.0.0 -- 2026-11-26++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, +++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of the copyright holder nor the names of its+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,3 @@+# raft-consensus-distributed-process++Adapter to the `raft-consensus` library, specifically for use in Cloud Haskell (also known as `distributed-process`).
+ raft-consensus-distributed-process.cabal view
@@ -0,0 +1,107 @@+cabal-version:      3.4+name:               raft-consensus-distributed-process+version:            0.1.0.0+synopsis:           Cloud Haskell facilities to the Raft consensus protocol+-- description:+license:            BSD-3-Clause+license-file:       LICENSE+author:             Laurent P. René de Cotret+maintainer:         laurent.decotret@outlook.com+copyright:          Laurent P. René de Cotret+category:           Distributed Systems, Consensus, Cloud Haskell+build-type:         Simple+extra-doc-files:    README.md+                    CHANGELOG.md++source-repository head+    type: git+    location: https://github.com/LaurentRDC/distributed-consensus+    subdir: raft-consensus-distributed-process++common warnings+    ghc-options: -Wall+                 -Wcompat+                 -Widentities+                 -Wincomplete-uni-patterns+                 -Wincomplete-record-updates+                 -Wredundant-constraints+                 -fhide-source-paths+                 -Wpartial-fields+                 -Wunused-packages++library+    import:           warnings+    exposed-modules:  Control.Distributed.Process.Raft+    hs-source-dirs:   src+    -- GHC 9.6+ (base 4.18+) is required to infer types properly when+    -- using io-classes+    build-depends:    base >= 4.18 && <4.23+                    , distributed-process ^>=0.7+                    , raft-consensus-distributed-process:io-classes-instances+                    , raft-consensus ^>=0.1+                    , stm ^>=2.5+    default-language: GHC2021++library io-classes-instances+    import:           warnings+    hs-source-dirs:   src/instances+    exposed-modules:  Control.Distributed.Process.Raft.Instances+    build-depends:    base >= 4.18 && <4.23+                    , array+                    , async >= 2.1 && <2.3+                    , distributed-process ^>=0.7+                    , io-classes ^>=1.11+                    , io-classes:si-timers+                    , primitive >=0.7 && <0.11+                    , stm ^>=2.5+                    , transformers ^>=0.6+    default-language: GHC2021++library client+    import:           warnings+    hs-source-dirs:   src+    exposed-modules:  Control.Distributed.Process.Raft.Client+    visibility:       public+    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+                    , stm ^>=2.5+    default-language: GHC2021++library admin+    import:           warnings+    hs-source-dirs:   src+    exposed-modules:  Control.Distributed.Process.Raft.Admin+    visibility:       public+    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+                    , stm ^>=2.5+    default-language: GHC2021++-- The test suite name is shortened because otherwise+-- it can lead to paths that are too long for+-- Windows to handle+test-suite rcdp-test+    import:           warnings+    default-language: Haskell2010+    other-modules:    Test.Control.Distributed.Process.Raft+    type:             exitcode-stdio-1.0+    ghc-options:      -rtsopts -threaded -with-rtsopts=-N+    hs-source-dirs:   tests+    main-is:          Main.hs+    build-depends:    async+                    , base >= 4.18 && <4.23+                    , distributed-process+                    , raft-consensus-distributed-process+                    , raft-consensus-distributed-process:admin+                    , raft-consensus-distributed-process:client+                    , raft-consensus+                    , tasty ^>= 1.5+                    , tasty-hunit ^>= 0.10+                    , network-transport+                    , network-transport-inmemory
+ src/Control/Distributed/Process/Raft.hs view
@@ -0,0 +1,97 @@+{-# LANGUAGE LambdaCase #-}++module Control.Distributed.Process.Raft+  ( networking,+  )+where++import Control.Concurrent.STM (atomically, flushTQueue, newTQueueIO, readTQueue, retry, writeTQueue)+import Control.Distributed.Process (NodeId, Process, link, match, matchUnknown, nsendRemote, 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.IO.Class (liftIO)+import Data.List.NonEmpty (NonEmpty (..))+import Distributed.Consensus.Raft (Networking (..))++networking ::+  (Serializable entry, Serializable state, Serializable result) =>+  Process (Networking entry NodeId result state Process)+networking = do+  (rpcQueue, rpcResultQueue, clientRequestQueue, adminRequestQueue) <-+    liftIO $+      (,,,)+        <$> newTQueueIO+        <*> newTQueueIO+        <*> newTQueueIO+        <*> newTQueueIO++  -- 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)+  --+  -- It is important to keep the process name stable, as clients and admins+  -- need to receive/send based on these process names as well+  --+  -- TODO: it's not clear if 'nsendRemote' is measurably slower than 'send',+  --       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 serverMailboxProcessName (clientRecvLoop clientRequestQueue)+  spawnMailbox adminMailboxProcessName (adminRecvLoop adminRequestQueue)++  pure+    Networking+      { sendRPC = (`nsendRemote` rpcMailboxProcessName),+        sendRPCResult = (`nsendRemote` rpcMailboxProcessName),+        sendClientResponse = (`nsendRemote` remoteClientMailboxProcessName),+        sendAdminResponse = (`nsendRemote` adminMailboxProcessName),+        receiveRPC = liftIO $ atomically $ readTQueue rpcQueue,+        receiveRPCResult = liftIO $ atomically $ readTQueue rpcResultQueue,+        receiveAdminRequest = liftIO $ atomically $ readTQueue adminRequestQueue,+        receiveClientRequests = liftIO $ atomically $ do+          -- Flushing the queue and retrying on empty+          -- allows pipelining client requests+          flushTQueue clientRequestQueue >>= \case+            [] -> retry+            (r : rs) -> pure $ r :| rs+      }+  where+    spawnMailbox :: String -> Process () -> Process ()+    spawnMailbox processName mailbox = do+      pid <- spawnLocal mailbox+      link pid+      register processName pid++    rpcMailboxProcessName = "raft-consensus-mailbox"+    serverMailboxProcessName = "raft-consensus-server-inbox"+    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 ())+          ]+    clientRecvLoop clientRequestQueue =+      forever $+        receiveWait+          [ match $ liftIO . atomically . writeTQueue clientRequestQueue,+            -- flush the queue from unknown message types.+            matchUnknown (pure ())+          ]++    adminRecvLoop adminRequestQueue =+      forever $+        receiveWait+          [ match $ liftIO . atomically . writeTQueue adminRequestQueue,+            -- flush the queue from unknown message types.+            matchUnknown (pure ())+          ]
+ src/Control/Distributed/Process/Raft/Admin.hs view
@@ -0,0 +1,94 @@+module Control.Distributed.Process.Raft.Admin+  ( withRaftAdmin,++    -- * Re-exports+    AdminError (..),+    Microseconds,+    sendAdminCommand,+    joinCluster,+    leaveCluster,+    getClusterConfiguration,+    shutDown,+  )+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.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 qualified as Raft.Admin+import System.Random (randomIO)++-- | Send an admin request to a Raft cluster.+--+-- It is perfectly safe, and encouraged, to send separate requests in+-- separate threads.+withRaftAdmin ::+  ((forall a. RaftAdminT NodeId Process a -> Process a) -> Process b) ->+  Process b+withRaftAdmin f = do+  recvQueue <- liftIO newTQueueIO++  mailPid <-+    spawnLocal $+      forever $+        receiveWait+          [ match $ liftIO . atomically . writeTQueue recvQueue,+            matchUnknown $ pure ()+          ]++  link mailPid++  register adminMailboxProcessName mailPid++  thisNodeId <- getSelfNode++  withAdminSession thisNodeId (impl recvQueue) f <* exit mailPid "Completed"+  where+    impl recvQueue =+      AdminImplementation+        { sendAdminRequest = (`nsendRemote` adminMailboxProcessName),+          receiveAdminResponse = liftIO $ atomically $ readTQueue recvQueue,+          generateSessionId =+            const $+              liftIO $+                sessionId <$> randomIO <*> randomIO+        }++-- | This value needs to be kept in sync with 'Control.Distributed.Process.Raft'.+-- The alternative would be a tiny shared library...+adminMailboxProcessName :: String+adminMailboxProcessName = "raft-consensus-admin-mailbox"++sendAdminCommand ::+  Microseconds ->+  NodeId ->+  AdminRequest NodeId ->+  RaftAdminT+    NodeId+    Process+    ( Either+        (AdminError NodeId)+        (AdminCommandResult NodeId)+    )+sendAdminCommand = Raft.Admin.sendAdminCommand++joinCluster ::+  -- \| Node to join+  NodeId ->+  RaftAdminT NodeId Process (AdminRequest NodeId)+joinCluster = Raft.Admin.joinCluster++leaveCluster ::+  RaftAdminT NodeId Process (AdminRequest NodeId)+leaveCluster = Raft.Admin.leaveCluster++getClusterConfiguration ::+  RaftAdminT NodeId Process (AdminRequest NodeId)+getClusterConfiguration = Raft.Admin.getClusterConfiguration++shutDown ::+  RaftAdminT NodeId Process (AdminRequest NodeId)+shutDown = Raft.Admin.shutDown
+ src/Control/Distributed/Process/Raft/Client.hs view
@@ -0,0 +1,118 @@+{-# LANGUAGE ImportQualifiedPost #-}++module Control.Distributed.Process.Raft.Client+  ( withRaftClient,+    sendClientRequest,+    Microseconds,+    ClientError (..),+    newRequest,+    clientSession,+  )+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+  ( ClientError,+    ClientImplementation (..),+    ClientRequest,+    Microseconds,+    RaftClientT,+    clientSession,+    newRequest,+    sessionId,+    withClientSession,+  )+import Distributed.Consensus.Raft.Client qualified as Raft.Client+import System.Random.Stateful (randomIO)++-- | Send a request to a Raft cluster.+--+-- It is perfectly safe, and encouraged, to send separate requests in+-- separate threads.+--+-- See 'request' to build an appropriate request.+withRaftClient ::+  (Serializable entry, Serializable result) =>+  ((forall a. RaftClientT entry NodeId result Process a -> Process a) -> Process b) ->+  Process b+withRaftClient f = do+  recvQueue <- liftIO newTQueueIO++  mailPid <-+    spawnLocal $+      forever $+        receiveWait+          [ match $ liftIO . atomically . writeTQueue recvQueue,+            matchUnknown $ pure ()+          ]++  link mailPid++  register clientMailboxProcessName mailPid++  thisNodeId <- getSelfNode++  withClientSession thisNodeId (impl recvQueue) f <* exit mailPid "Completed"+  where+    impl recvQueue =+      ClientImplementation+        { sendRequest = (`nsendRemote` serverMailboxProcessName),+          receiveResponse = liftIO $ atomically $ readTQueue recvQueue,+          generateSessionId =+            const $+              liftIO $+                sessionId <$> randomIO <*> randomIO+        }++clientMailboxProcessName :: String+clientMailboxProcessName = "raft-consensus-client-inbox"++serverMailboxProcessName :: String+serverMailboxProcessName = "raft-consensus-server-inbox"++-- | Send a request to a Raft cluster.+--+-- The user must take care to handle the possible 'ClientError's.+--+-- 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.+--+-- Second, 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.+--+-- It is perfectly safe, and encouraged, to send separate requests in+-- separate threads. However, you should call 'withClientSession' only once.+sendClientRequest ::+  Microseconds ->+  NodeId ->+  ClientRequest entry NodeId ->+  RaftClientT+    entry+    NodeId+    result+    Process+    (Either (ClientError entry NodeId) (NodeId, result))+sendClientRequest = Raft.Client.sendClientRequest
+ src/instances/Control/Distributed/Process/Raft/Instances.hs view
@@ -0,0 +1,509 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeFamilies #-}+{-# OPTIONS_GHC -Wno-orphans #-}++{- HLINT ignore "Avoid lambda" -}++module Control.Distributed.Process.Raft.Instances () where++import Control.Concurrent qualified as IO+import Control.Concurrent.Async qualified as Async+import Control.Concurrent.Class.MonadMVar+  ( MonadInspectMVar (..),+    MonadLabelledMVar (..),+    MonadMVar (..),+    MonadTraceMVar (..),+  )+import Control.Concurrent.STM.TArray qualified as STM+import Control.Concurrent.STM.TBQueue qualified as STM+import Control.Concurrent.STM.TChan qualified as STM+import Control.Concurrent.STM.TMVar qualified as STM+import Control.Concurrent.STM.TQueue qualified as STM+import Control.Concurrent.STM.TSem qualified as STM+import Control.Concurrent.STM.TVar qualified as STM+import Control.Distributed.Process.Internal.Types+  ( Process (..),+    runLocalProcess,+  )+import Control.Exception qualified as IO+#if __GLASGOW_HASKELL__ >= 910+import Control.Exception.Annotation (ExceptionAnnotation)+#endif+import Control.Monad.Class.MonadAsync (MonadAsync (..))+import Control.Monad.Class.MonadEventlog (MonadEventlog (..))+import Control.Monad.Class.MonadFork+  ( MonadFork (..),+    MonadThread (..),+  )+import Control.Monad.Class.MonadST (MonadST (..))+import Control.Monad.Class.MonadSTM.Internal+  ( MonadInspectSTM (..),+    MonadLabelledSTM (..),+    MonadSTM (..),+    MonadTraceSTM (..),+  )+import Control.Monad.Class.MonadSay (MonadSay (..))+import Control.Monad.Class.MonadTest (MonadTest)+import Control.Monad.Class.MonadThrow+  ( ExitCase (ExitCaseException, ExitCaseSuccess),+    MonadCatch (..),+    MonadEvaluate (..),+    MonadMask (..),+    MonadThrow (..),+  )+import Control.Monad.Class.MonadTime+  ( MonadMonotonicTimeNSec (..),+    MonadTime (..),+  )+import Control.Monad.Class.MonadTime.SI qualified as SI+import Control.Monad.Class.MonadTimer+  ( MonadDelay (..),+    MonadTimer (..),+  )+import Control.Monad.Class.MonadTimer.SI qualified as SI+import Control.Monad.Class.MonadUnique (MonadUnique (..))+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Primitive (PrimMonad (..), RealWorld, stToPrim)+import Control.Monad.STM qualified as STM+import Control.Monad.Trans.Reader (ReaderT (..))+import Data.Array.Base (MArray (..))+import Data.Bifunctor (first)+import Data.Unique qualified as IO+import GHC.Conc.Sync qualified as IO (labelThread, threadLabel)+import GHC.Stack (HasCallStack)+import System.Timeout qualified as IO++withRunInIO :: ((forall x. Process x -> IO x) -> IO a) -> Process a+withRunInIO k = Process (ReaderT (\lproc -> k (runLocalProcess lproc)))+{-# INLINE withRunInIO #-}++liftRestore ::+  (forall x. IO x -> IO x) ->+  (forall x. Process x -> Process x)+liftRestore restore p =+  Process (ReaderT (\lproc -> restore (runLocalProcess lproc p)))+{-# INLINE liftRestore #-}++atomicallyIO :: (HasCallStack) => STM.STM a -> IO a+atomicallyIO = atomically+{-# INLINE atomicallyIO #-}++instance MonadThrow Process where+  throwIO = liftIO . IO.throwIO++  bracket acquire release use = withRunInIO $ \run ->+    IO.bracket (run acquire) (run . release) (run . use)+  bracket_ before after thing = withRunInIO $ \run ->+    IO.bracket_ (run before) (run after) (run thing)+  finally thing sequel = withRunInIO $ \run ->+    IO.finally (run thing) (run sequel)++#if __GLASGOW_HASKELL__ >= 910+  annotateIO :: forall e a. (ExceptionAnnotation e) => e -> Process a -> Process a+  annotateIO ann p = withRunInIO $ \run -> IO.annotateIO ann (run p)+#endif++instance MonadCatch Process where+  catch action handler = withRunInIO $ \run ->+    IO.catch (run action) (run . handler)++  catchJust p action handler = withRunInIO $ \run ->+    IO.catchJust p (run action) (run . handler)+  try action = withRunInIO $ \run -> IO.try (run action)+  tryJust p action = withRunInIO $ \run -> IO.tryJust p (run action)+  handle handler action = withRunInIO $ \run ->+    IO.handle (run . handler) (run action)+  handleJust p handler action = withRunInIO $ \run ->+    IO.handleJust p (run . handler) (run action)+  onException action what = withRunInIO $ \run ->+    IO.onException (run action) (run what)+  bracketOnError acquire release use = withRunInIO $ \run ->+    IO.bracketOnError (run acquire) (run . release) (run . use)++instance MonadMask Process where+  mask action = withRunInIO $ \run ->+    IO.mask (\restore -> run (action (liftRestore restore)))+  mask_ action = withRunInIO $ \run -> IO.mask_ (run action)++  uninterruptibleMask action = withRunInIO $ \run ->+    IO.uninterruptibleMask (\restore -> run (action (liftRestore restore)))+  uninterruptibleMask_ action = withRunInIO $ \run ->+    IO.uninterruptibleMask_ (run action)++  getMaskingState = liftIO IO.getMaskingState+  interruptible action = withRunInIO $ \run -> IO.interruptible (run action)+  allowInterrupt = liftIO IO.allowInterrupt++instance MonadEvaluate Process where+  evaluate = liftIO . IO.evaluate++newtype ProcessSTM a = ProcessSTM {runProcessSTM :: STM.STM a}+  deriving newtype (Functor, Applicative, Monad)++deriving newtype instance (Semigroup a) => Semigroup (ProcessSTM a)++deriving newtype instance (Monoid a) => Monoid (ProcessSTM a)++instance MonadThrow ProcessSTM where+  throwIO = ProcessSTM . STM.throwSTM++#if __GLASGOW_HASKELL__ >= 910+  annotateIO ::+    forall e a.+    (ExceptionAnnotation e) =>+    e -> ProcessSTM a -> ProcessSTM a+  annotateIO ann stm =+    stm `catch` \e -> throwIO (IO.addExceptionContext ann e)+#endif++instance MonadCatch ProcessSTM where+  catch action handler =+    ProcessSTM (STM.catchSTM (runProcessSTM action) (runProcessSTM . handler))++  generalBracket acquire release use = do+    resource <- acquire+    b <-+      use resource `catch` \e -> do+        _ <- release resource (ExitCaseException e)+        throwIO e+    c <- release resource (ExitCaseSuccess b)+    return (b, c)++instance MArray STM.TArray e ProcessSTM where+  getBounds = ProcessSTM . getBounds+  getNumElements = ProcessSTM . getNumElements+  unsafeRead arr = ProcessSTM . unsafeRead arr+  unsafeWrite arr i = ProcessSTM . unsafeWrite arr i+  newArray idxs = ProcessSTM . newArray idxs++instance MonadSTM Process where+  type STM Process = ProcessSTM++  atomically :: forall a. (HasCallStack) => ProcessSTM a -> Process a+  atomically = liftIO . atomicallyIO . runProcessSTM++  type TVar Process = STM.TVar+  type TMVar Process = STM.TMVar+  type TQueue Process = STM.TQueue+  type TBQueue Process = STM.TBQueue+  type TArray Process = STM.TArray+  type TSem Process = STM.TSem+  type TChan Process = STM.TChan++  newTVar = ProcessSTM . STM.newTVar+  readTVar = ProcessSTM . STM.readTVar+  writeTVar v = ProcessSTM . STM.writeTVar v+  retry = ProcessSTM STM.retry+  orElse a = ProcessSTM . STM.orElse (runProcessSTM a) . runProcessSTM+  modifyTVar v = ProcessSTM . STM.modifyTVar v+  modifyTVar' v = ProcessSTM . STM.modifyTVar' v+  stateTVar v = ProcessSTM . STM.stateTVar v+  swapTVar v = ProcessSTM . STM.swapTVar v+  check = ProcessSTM . STM.check++  newTMVar = ProcessSTM . STM.newTMVar+  newEmptyTMVar = ProcessSTM STM.newEmptyTMVar+  takeTMVar = ProcessSTM . STM.takeTMVar+  tryTakeTMVar = ProcessSTM . STM.tryTakeTMVar+  putTMVar v = ProcessSTM . STM.putTMVar v+  tryPutTMVar v = ProcessSTM . STM.tryPutTMVar v+  readTMVar = ProcessSTM . STM.readTMVar+  tryReadTMVar = ProcessSTM . STM.tryReadTMVar+  swapTMVar v = ProcessSTM . STM.swapTMVar v+  writeTMVar v = ProcessSTM . STM.writeTMVar v+  isEmptyTMVar = ProcessSTM . STM.isEmptyTMVar++  newTQueue = ProcessSTM STM.newTQueue+  readTQueue = ProcessSTM . STM.readTQueue+  tryReadTQueue = ProcessSTM . STM.tryReadTQueue+  peekTQueue = ProcessSTM . STM.peekTQueue+  tryPeekTQueue = ProcessSTM . STM.tryPeekTQueue+  flushTQueue = ProcessSTM . STM.flushTQueue+  writeTQueue v = ProcessSTM . STM.writeTQueue v+  isEmptyTQueue = ProcessSTM . STM.isEmptyTQueue+  unGetTQueue v = ProcessSTM . STM.unGetTQueue v++  newTBQueue = ProcessSTM . STM.newTBQueue+  readTBQueue = ProcessSTM . STM.readTBQueue+  tryReadTBQueue = ProcessSTM . STM.tryReadTBQueue+  peekTBQueue = ProcessSTM . STM.peekTBQueue+  tryPeekTBQueue = ProcessSTM . STM.tryPeekTBQueue+  flushTBQueue = ProcessSTM . STM.flushTBQueue+  writeTBQueue v = ProcessSTM . STM.writeTBQueue v+  lengthTBQueue = ProcessSTM . STM.lengthTBQueue+  isEmptyTBQueue = ProcessSTM . STM.isEmptyTBQueue+  isFullTBQueue = ProcessSTM . STM.isFullTBQueue+  unGetTBQueue v = ProcessSTM . STM.unGetTBQueue v++  newTSem = ProcessSTM . STM.newTSem+  waitTSem = ProcessSTM . STM.waitTSem+  signalTSem = ProcessSTM . STM.signalTSem+  signalTSemN n = ProcessSTM . STM.signalTSemN n++  newTChan = ProcessSTM STM.newTChan+  newBroadcastTChan = ProcessSTM STM.newBroadcastTChan+  dupTChan = ProcessSTM . STM.dupTChan+  cloneTChan = ProcessSTM . STM.cloneTChan+  readTChan = ProcessSTM . STM.readTChan+  tryReadTChan = ProcessSTM . STM.tryReadTChan+  peekTChan = ProcessSTM . STM.peekTChan+  tryPeekTChan = ProcessSTM . STM.tryPeekTChan+  writeTChan v = ProcessSTM . STM.writeTChan v+  unGetTChan v = ProcessSTM . STM.unGetTChan v+  isEmptyTChan = ProcessSTM . STM.isEmptyTChan++  newTVarIO = liftIO . STM.newTVarIO+  readTVarIO = liftIO . STM.readTVarIO+  newTMVarIO = liftIO . STM.newTMVarIO+  newEmptyTMVarIO = liftIO STM.newEmptyTMVarIO+  newTQueueIO = liftIO STM.newTQueueIO+  newTBQueueIO = liftIO . STM.newTBQueueIO+  newTChanIO = liftIO STM.newTChanIO+  newBroadcastTChanIO = liftIO STM.newBroadcastTChanIO++instance MonadLabelledSTM Process where+  labelTVar _ _ = return ()+  labelTMVar _ _ = return ()+  labelTQueue _ _ = return ()+  labelTBQueue _ _ = return ()+  labelTArray _ _ = return ()+  labelTSem _ _ = return ()+  labelTChan _ _ = return ()++  labelTVarIO _ _ = return ()+  labelTMVarIO _ _ = return ()+  labelTQueueIO _ _ = return ()+  labelTBQueueIO _ _ = return ()+  labelTArrayIO _ _ = return ()+  labelTSemIO _ _ = return ()+  labelTChanIO _ _ = return ()++instance MonadInspectSTM Process where+  type InspectMonadSTM Process = IO+  inspectTVar _ = STM.readTVarIO+  inspectTMVar _ = STM.atomically . STM.tryReadTMVar++instance MonadTraceSTM Process where+  traceTVar _ _ _ = return ()+  traceTMVar _ _ _ = return ()+  traceTQueue _ _ _ = return ()+  traceTBQueue _ _ _ = return ()+  traceTSem _ _ _ = return ()++  traceTVarIO _ _ = return ()+  traceTMVarIO _ _ = return ()+  traceTQueueIO _ _ = return ()+  traceTBQueueIO _ _ = return ()+  traceTSemIO _ _ = return ()++instance MonadMVar Process where+  type MVar Process = IO.MVar++  newEmptyMVar = liftIO IO.newEmptyMVar+  newMVar = liftIO . IO.newMVar+  takeMVar = liftIO . IO.takeMVar+  putMVar v = liftIO . IO.putMVar v+  readMVar = liftIO . IO.readMVar+  swapMVar v = liftIO . IO.swapMVar v+  tryTakeMVar = liftIO . IO.tryTakeMVar+  tryPutMVar v = liftIO . IO.tryPutMVar v+  tryReadMVar = liftIO . IO.tryReadMVar+  isEmptyMVar = liftIO . IO.isEmptyMVar++  withMVar v f = withRunInIO $ \run -> IO.withMVar v (run . f)+  withMVarMasked v f = withRunInIO $ \run -> IO.withMVarMasked v (run . f)+  modifyMVar_ v f = withRunInIO $ \run -> IO.modifyMVar_ v (run . f)+  modifyMVar v f = withRunInIO $ \run -> IO.modifyMVar v (run . f)+  modifyMVarMasked_ v f = withRunInIO $ \run -> IO.modifyMVarMasked_ v (run . f)+  modifyMVarMasked v f = withRunInIO $ \run -> IO.modifyMVarMasked v (run . f)++instance MonadInspectMVar Process where+  type InspectMVarMonad Process = IO+  inspectMVar _ = IO.tryReadMVar++instance MonadTraceMVar Process where+  traceMVarIO _ _ _ = return ()++instance MonadLabelledMVar Process where+  labelMVar _ _ = return ()++instance MonadThread Process where+  type ThreadId Process = IO.ThreadId+  myThreadId = liftIO IO.myThreadId+  labelThread t = liftIO . IO.labelThread t+  threadLabel = liftIO . IO.threadLabel++instance MonadFork Process where+  forkIO p = withRunInIO $ \run -> IO.forkIO (run p)+  forkOn n p = withRunInIO $ \run -> IO.forkOn n (run p)++  forkIOWithUnmask k = withRunInIO $ \run ->+    IO.forkIOWithUnmask (\unmask -> run (k (liftRestore unmask)))++  forkFinally p k = withRunInIO $ \run -> IO.forkFinally (run p) (run . k)++  throwTo t = liftIO . IO.throwTo t+  killThread = liftIO . IO.killThread+  yield = liftIO IO.yield+  getNumCapabilities = liftIO IO.getNumCapabilities++newtype ProcessAsync a = ProcessAsync {runProcessAsync :: Async.Async a}+  deriving (Eq, Ord, Functor)++instance MonadAsync Process where+  type Async Process = ProcessAsync++  async p = withRunInIO $ \run -> ProcessAsync <$> Async.async (run p)+  asyncBound p = withRunInIO $ \run -> ProcessAsync <$> Async.asyncBound (run p)+  asyncOn n p = withRunInIO $ \run -> ProcessAsync <$> Async.asyncOn n (run p)++  asyncThreadId = Async.asyncThreadId . runProcessAsync+  compareAsyncs a b =+    Async.compareAsyncs (runProcessAsync a) (runProcessAsync b)++  asyncWithUnmask k = withRunInIO $ \run ->+    ProcessAsync+      <$> Async.asyncWithUnmask+        (\unmask -> run (k (liftRestore unmask)))+  asyncOnWithUnmask n k = withRunInIO $ \run ->+    ProcessAsync+      <$> Async.asyncOnWithUnmask+        n+        (\unmask -> run (k (liftRestore unmask)))++  withAsync p f = withRunInIO $ \run ->+    Async.withAsync (run p) (run . f . ProcessAsync)+  withAsyncBound p f = withRunInIO $ \run ->+    Async.withAsyncBound (run p) (run . f . ProcessAsync)+  withAsyncOn n p f = withRunInIO $ \run ->+    Async.withAsyncOn n (run p) (run . f . ProcessAsync)++  withAsyncWithUnmask k f = withRunInIO $ \run ->+    Async.withAsyncWithUnmask+      (\unmask -> run (k (liftRestore unmask)))+      (run . f . ProcessAsync)+  withAsyncOnWithUnmask n k f = withRunInIO $ \run ->+    Async.withAsyncOnWithUnmask+      n+      (\unmask -> run (k (liftRestore unmask)))+      (run . f . ProcessAsync)++  waitSTM = ProcessSTM . Async.waitSTM . runProcessAsync+  pollSTM = ProcessSTM . Async.pollSTM . runProcessAsync+  waitCatchSTM = ProcessSTM . Async.waitCatchSTM . runProcessAsync++  waitAnySTM =+    ProcessSTM+      . fmap (first ProcessAsync)+      . Async.waitAnySTM+      . map runProcessAsync+  waitAnyCatchSTM =+    ProcessSTM+      . fmap (first ProcessAsync)+      . Async.waitAnyCatchSTM+      . map runProcessAsync+  waitEitherSTM a b = ProcessSTM (Async.waitEitherSTM (runProcessAsync a) (runProcessAsync b))+  waitEitherSTM_ a b = ProcessSTM (Async.waitEitherSTM_ (runProcessAsync a) (runProcessAsync b))+  waitEitherCatchSTM a b = ProcessSTM (Async.waitEitherCatchSTM (runProcessAsync a) (runProcessAsync b))+  waitBothSTM a b = ProcessSTM (Async.waitBothSTM (runProcessAsync a) (runProcessAsync b))++  wait = liftIO . Async.wait . runProcessAsync+  poll = liftIO . Async.poll . runProcessAsync+  waitCatch = liftIO . Async.waitCatch . runProcessAsync+  cancel = liftIO . Async.cancel . runProcessAsync+  uninterruptibleCancel = liftIO . Async.uninterruptibleCancel . runProcessAsync+  cancelWith a e = liftIO (Async.cancelWith (runProcessAsync a) e)++  waitAny =+    liftIO+      . fmap (first ProcessAsync)+      . Async.waitAny+      . map runProcessAsync+  waitAnyCatch =+    liftIO+      . fmap (first ProcessAsync)+      . Async.waitAnyCatch+      . map runProcessAsync+  waitAnyCancel =+    liftIO+      . fmap (first ProcessAsync)+      . Async.waitAnyCancel+      . map runProcessAsync+  waitAnyCatchCancel =+    liftIO+      . fmap (first ProcessAsync)+      . Async.waitAnyCatchCancel+      . map runProcessAsync++  waitEither a b = liftIO (Async.waitEither (runProcessAsync a) (runProcessAsync b))+  waitEither_ a b = liftIO (Async.waitEither_ (runProcessAsync a) (runProcessAsync b))+  waitEitherCatch a b = liftIO (Async.waitEitherCatch (runProcessAsync a) (runProcessAsync b))+  waitEitherCancel a b = liftIO (Async.waitEitherCancel (runProcessAsync a) (runProcessAsync b))+  waitEitherCatchCancel a b = liftIO (Async.waitEitherCatchCancel (runProcessAsync a) (runProcessAsync b))+  waitBoth a b = liftIO (Async.waitBoth (runProcessAsync a) (runProcessAsync b))++  race a b = withRunInIO $ \run -> Async.race (run a) (run b)+  race_ a b = withRunInIO $ \run -> Async.race_ (run a) (run b)+  concurrently a b = withRunInIO $ \run -> Async.concurrently (run a) (run b)+  concurrently_ a b = withRunInIO $ \run -> Async.concurrently_ (run a) (run b)++instance MonadDelay Process where+  threadDelay = liftIO . IO.threadDelay++instance MonadTimer Process where+  registerDelay = liftIO . STM.registerDelay+  timeout d p = withRunInIO $ \run -> IO.timeout d (run p)++instance MonadMonotonicTimeNSec Process where+  getMonotonicTimeNSec = liftIO getMonotonicTimeNSec++instance MonadTime Process where+  getCurrentTime = liftIO getCurrentTime++instance SI.MonadMonotonicTime Process++instance SI.MonadDelay Process where+  threadDelay = liftIO . SI.threadDelay++instance SI.MonadTimer Process where+  registerDelay = liftIO . SI.registerDelay++  registerDelayCancellable d = do+    (readTs, cancelTs) <- liftIO (SI.registerDelayCancellable d)+    return (ProcessSTM readTs, liftIO cancelTs)++  timeout d p = withRunInIO $ \run -> SI.timeout d (run p)++instance PrimMonad Process where+  type PrimState Process = RealWorld+  primitive = liftIO . primitive+  {-# INLINE primitive #-}++instance MonadST Process where+  stToIO = stToPrim++newtype ProcessUnique = ProcessUnique {getProcessUnique :: IO.Unique}+  deriving newtype (Eq, Ord)++instance MonadUnique Process where+  type Unique Process = ProcessUnique+  newUnique = liftIO (ProcessUnique <$> IO.newUnique)+  hashUnique = IO.hashUnique . getProcessUnique++instance MonadSay Process where+  say = liftIO . say++instance MonadEventlog Process where+  traceEventIO = liftIO . traceEventIO+  traceMarkerIO = liftIO . traceMarkerIO+  flushEventLog = liftIO flushEventLog++instance MonadTest Process
+ tests/Main.hs view
@@ -0,0 +1,7 @@+module Main (main) where++import qualified Test.Control.Distributed.Process.Raft (tests)+import Test.Tasty (defaultMain)++main :: IO ()+main = defaultMain Test.Control.Distributed.Process.Raft.tests
+ tests/Test/Control/Distributed/Process/Raft.hs view
@@ -0,0 +1,112 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module Test.Control.Distributed.Process.Raft (tests) where++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.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.IO.Class (liftIO)+import Data.Foldable (for_)+import Distributed.Consensus.Raft (Networking (..), Request (..), Response (..), requestPayload)+import Distributed.Consensus.Raft.Admin (AdminCommand (..), AdminCommandResult (..), sendAdminCommand)+import Network.Transport (EndPointAddress (EndPointAddress), Transport)+import qualified Network.Transport.InMemory as InMemory+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup, withResource)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++tests :: TestTree+tests = withResource InMemory.createTransport (\_ -> pure ()) $+  \getTransport ->+    testGroup+      "Control.Distributed.Process.Raft"+      [ testAdminCommands getTransport,+        testClientCommands getTransport+      ]++testAdminCommands :: IO Transport -> TestTree+testAdminCommands getTransport = testCase "Tests that admin commands are communicated" $ do+  t <- getTransport+  node <- newLocalNode t initRemoteTable+  ready <- newEmptyMVar+  let serverNodeId = localNodeId node+  withAsync (sendAdminCommands ready t serverNodeId) $ \_ -> runProcess node $ do+    serverNetwork <- networking @() @() @()+    liftIO $ putMVar ready ()+    let expectations =+          [ (JoinCluster arbitraryOtherNodeId, JoinInitiated),+            (LeaveCluster, LeaveInitiated),+            (GetClusterConfiguration, ShutdownInitiated), -- mismatch+            (ShutDown, ShutdownInitiated)+          ]+    for_ expectations $ \(expectation, response) -> do+      req <- receiveAdminRequest serverNetwork+      liftIO (requestPayload req @?= expectation)+      sendAdminResponse serverNetwork (requestOriginator req) (MkResponse (requestId req) Nothing response)+  where+    arbitraryOtherNodeId :: NodeId+    arbitraryOtherNodeId = NodeId $ EndPointAddress "some-arbitrary-node-id"++    sendAdminCommands ready transport serverNodeId = do+      _ <- liftIO $ takeMVar ready+      node <- newLocalNode transport initRemoteTable+      runProcess node $ withRaftAdmin $ \runAdmin -> runAdmin $ 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++testClientCommands :: IO Transport -> TestTree+testClientCommands getTransport = testCase "Tests that client commands are communicated" $ do+  t <- getTransport+  node <- newLocalNode t initRemoteTable+  ready <- newEmptyMVar+  let serverNodeId = localNodeId node++  timeout+    1_000_000+    ( withAsync (sendClientCommands ready t serverNodeId) $ \_ -> runProcess node $ do+        serverNetwork <- networking @() @() @()+        liftIO $ putMVar ready ()++        let waitForAllRequests n = do+              if n == nRequests+                then pure ()+                else do+                  liftIO $ threadDelay 10_000+                  reqs <- receiveClientRequests serverNetwork+                  waitForAllRequests (n + length reqs)++        -- The test waits for all requests to have arrived.+        -- If they don't, the test will timeout, counting as a failure+        waitForAllRequests 0+    )+    >>= \case+      Just _ -> pure ()+      Nothing -> liftIO $ assertFailure "Server did not receive expected number of requests"+  where+    nRequests = 3+    sendClientCommands ready transport serverNodeId = do+      _ <- liftIO $ takeMVar ready+      node <- newLocalNode transport initRemoteTable+      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)