packages feed

raft-consensus-serialise-instances-0.2.0.0: tests/Interface/Server.hs

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}

-- This module exists for a single purpose: to show that all of the
-- types required to write an 'Implementation' are exported by
-- "Distributed.Consensus.Raft".
--
-- To ensure this, we implement de/serialisation via the
-- @serialise@ package, using the instances from this package.
module Interface.Server
  ( implementation,
    CounterOp (..),
    Node,
    Result,
  )
where

import Codec.Serialise (Serialise, deserialise, serialise)
import qualified Data.ByteString.Lazy as BSL
import Data.Functor ((<&>))
import Distributed.Consensus.Raft
  ( Implementation (..),
    Networking (..),
    Persistence (..),
    StateMachineStep (..),
    nullTracer,
  )
import Distributed.Consensus.Raft.Serialise.Instances ()
import GHC.Generics (Generic)

type State = Int

type Result = Int

type Node = Int

data CounterOp = ReadCounter | Increment | Decrement
  deriving (Generic)

instance Serialise CounterOp

implementation :: Implementation CounterOp Node Result State IO
implementation =
  Implementation
    { persistence =
        Persistence
          { readLogEntriesFrom = \_ _ -> BSL.getContents <&> deserialise,
            writeLogEntry = \_ -> BSL.putStr . serialise,
            truncateLogEntriesFrom = \_ _ -> pure (),
            readTerm = \_ -> BSL.getContents <&> deserialise,
            writeTerm = \_ -> BSL.putStr . serialise,
            readVotedFor = \_ _ -> BSL.getContents <&> deserialise,
            writeVotedFor = \_ _ _ -> pure (),
            readSnapshot = \_ -> BSL.getContents <&> deserialise,
            writeSnapshot = \_ -> BSL.putStr . serialise,
            readCommitIndex = \_ -> BSL.getContents <&> deserialise,
            writeCommitIndex = \_ _ -> pure ()
          },
      stateMachine = \case
        ReadCounter -> Read id
        Increment -> Transition $ \st -> (succ st, succ st)
        Decrement -> Transition $ \st -> (pred st, pred st),
      networking =
        Networking
          { sendRPC = \_ -> BSL.putStr . serialise,
            sendRPCResult = \_ -> BSL.putStr . serialise,
            sendClientResponse = \_ -> BSL.putStr . serialise,
            sendAdminResponse = \_ -> BSL.putStr . serialise,
            receiveRPC = BSL.getContents <&> deserialise,
            receiveRPCResult = BSL.getContents <&> deserialise,
            receiveClientRequests = BSL.getContents <&> deserialise,
            receiveAdminRequest = BSL.getContents <&> deserialise
          },
      tracer = nullTracer
    }