packages feed

raft-consensus-distributed-process-0.1.1.0: tests/Test/Control/Distributed/Process/Raft.hs

{-# 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), 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, replicateM_, void)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import Data.Foldable (for_)
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
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,
        testSnapshotNotResentWhileInFlight 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
            ( -- 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"