packages feed

raft-consensus-0.2.0.0: src/Distributed/Consensus/Raft/Messaging.hs

{-# LANGUAGE DeriveGeneric #-}

module Distributed.Consensus.Raft.Messaging
  ( Request (..),
    RequestPayload (..),
    request,
    Response (..),
    ResponsePayload (..),
  )
where

import Data.Binary (Binary)
import Distributed.Consensus.Raft.Domain (SequenceNum)
import GHC.Generics (Generic)

data RequestPayload request
  = Heartbeat
  | RequestPayload !request
  deriving (Eq, Show, Generic)

request :: RequestPayload request -> Maybe request
request (RequestPayload req) = Just req
request _ = Nothing

instance (Binary request) => Binary (RequestPayload request)

-- | Request incoming to the Raft cluster.
--
-- This is an envelope that collects things that any request
-- needs to be processed end-to-end.
data Request id node payload
  = Request
  { -- | Identifies the request, and its response.
    requestId :: !id,
    -- | The node to send the response to.
    requestOriginator :: !node,
    -- | Lowest sequence number for a request whose response has been received.
    requestOldestOutstanding :: !SequenceNum,
    requestPayload :: !(RequestPayload payload)
  }
  deriving (Eq, Show, Generic)

instance (Binary id, Binary node, Binary payload) => Binary (Request id node payload)

data ResponsePayload response
  = HeartbeatEcho
  | NotLeader
  | SessionExpired
  | ResponsePayload !response
  deriving (Eq, Show, Generic)

instance (Binary response) => Binary (ResponsePayload response)

data Response id node payload
  = Response
  { responseRequestId :: !id,
    responseClusterLeader :: !(Maybe node),
    responsePayload :: !(ResponsePayload payload)
  }
  deriving (Eq, Show, Generic)

instance (Binary id, Binary node, Binary payload) => Binary (Response id node payload)