packages feed

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

{-# 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, 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 (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 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)
networking = do
  (rpcQueue, rpcResultQueue, clientRequestQueue, adminRequestQueue) <-
    liftIO $
      (,,,)
        <$> newTQueueIO
        <*> newTQueueIO
        <*> 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)
  --
  -- 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 snapshotsInFlight rpcQueue rpcResultQueue mempty)
  spawnMailbox serverMailboxProcessName (clientRecvLoop clientRequestQueue)
  spawnMailbox adminMailboxProcessName (adminRecvLoop adminRequestQueue)

  pure
    Networking
      { 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),
        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 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
          [ 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 ())
          ]

-- * 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
  }