packages feed

raft-consensus-wal (empty) → 0.1.0.0

raw patch · 5 files changed

+272/−0 lines, 5 filesdep +basedep +binarydep +bytestring

Dependencies added: base, binary, bytestring, containers, exceptions, file-io, filepath, raft-consensus, wal

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for raft-consensus-wal++## 0.1.0.0 -- 2026-11-26++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Laurent P. René de Cotret+++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-wal++Adapter to the `raft-consensus` library, specifically for persistence using write-ahead logs via the `wal` package.
+ raft-consensus-wal.cabal view
@@ -0,0 +1,43 @@+cabal-version:      3.4+name:               raft-consensus-wal+version:            0.1.0.0+synopsis:           Write-ahead log support for the raft-consensus library+-- description:+homepage:           https://github.com/LaurentRDC/distributed-consensus+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+build-type:         Simple+extra-doc-files:    CHANGELOG.md+                    README.md++-- extra-source-files:++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:  Distributed.Consensus.Raft.WAL+    hs-source-dirs:   src+    default-language: Haskell2010+    build-depends:    base >= 4.18 && <4.23+                    , bytestring ^>=0.12+                    , binary ^>=0.8+                    , containers >=0.7 && <0.9+                    , exceptions ^>=0.10+                    , filepath >=1.5 && <1.6+                    , file-io ^>=0.2+                    , raft-consensus ^>=0.1+                    , wal ^>=0.1
+ src/Distributed/Consensus/Raft/WAL.hs view
@@ -0,0 +1,192 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- I like <&>+{- HLINT ignore "Functor law" -}+module Distributed.Consensus.Raft.WAL+  ( withPersistence,++    -- * Codecs+    WALCodec (..),++    -- ** Built-in codec+    binaryWALCodec,+  )+where++import Control.Exception (SomeException, try)+import Control.Monad (when)+import Control.Monad.Catch (MonadMask)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.Binary (Binary)+import qualified Data.Binary as Binary+import Data.Binary.Get (runGetOrFail)+import qualified Data.ByteString.Lazy as BSL+import Data.Foldable (traverse_)+import Data.Functor ((<&>))+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.List.NonEmpty (nonEmpty)+import qualified Data.Map.Strict as Map+import Distributed.Consensus.Raft (LogEntry, LogIndex, Persistence (..), Snapshot, Term)+import GHC.Generics (Generic)+import System.File.OsPath (withBinaryFile)+import qualified System.File.OsPath as IO+import System.IO (IOMode (..))+import qualified System.IO.File.Durable as Durable+import System.IO.WAL (WALCodec (..), WALConfig (..), activeSegment, append, appendMany, binaryWALCodec, replaySegment, rotate, withWriteAheadLog)+import System.OsPath (OsPath, unsafeEncodeUtf, (</>))+import qualified System.OsPath as OsPath++data RaftRecord entry node state+  = SnapshotRecord (Snapshot node state)+  | LogRecord (Term, LogIndex, LogEntry entry node)+  | -- | Truncating the write-ahead log is done by changing+    -- how the read-back is done+    TruncateFrom LogIndex+  deriving (Generic)++instance (Binary entry, Binary node, Binary state) => Binary (RaftRecord entry node state)++-- | A function to run a Raft cluster with the provided 'Persistence'+-- instance based on a disk-backed write-ahead log.+--+-- This function takes care of all the details related to setting+-- up the log directory, rotating log files, and persisting+-- small pieces of data (e.g. terms and votes) separately+-- from the log files.+--+-- Log files are rotated on Raft server snapshot. This means that every+-- log file is standalone; there is no need to keep any other file+-- than the most current one, except perhaps for auditing.+--+-- If the directory where log files should be stored doesn't exist,+-- it will be created (including its parents if needed).+withPersistence ::+  ( MonadIO m,+    Binary node,+    MonadMask m+  ) =>+  -- | Directory where files should be stored. This directory need not be empty. The+  -- Raft server will restore its state based on the contents of the directory.+  OsPath ->+  -- | Codec to encode and decode data to/from the log. If you don't want to choose,+  -- just use 'binaryWALCodec'. If you want to squeeze as much performance as you can,+  -- you will need to created your own 'WALCodec'.+  --+  -- This codec is only relevant for data in the write-ahead log. Smaller pieces of data+  -- (e.g. a server's current term or commit index) is serialized to small files+  -- using the 'Binary' instance.+  WALCodec (RaftRecord entry node state) ->+  -- | Continuation+  (Persistence entry node state m -> m a) ->+  m a+withPersistence dir codec f = do+  withWriteAheadLog+    codec+    ( WALConfig+        { maxSegmentBytes = maxBound, -- Rotation happens on snapshot+          directory = dir </> unsafeEncodeUtf "wal"+        }+    )+    $ \wal ->+      let persistence =+            -- In our persistence scheme, snapshots and log entries are stored in the write-ahead log,+            -- while votes and terms are stored in local files. This is to show how we can mix things+            -- inside the same persistence layer. In practice, you might want to put everything in+            -- the write-ahead log.+            --+            -- The write-ahead log is naturally broken down into segments, or files. One invariant+            -- we will enforce below: every segment, except the first one, begins with a snapshot.+            -- When writing a snapshot to the WAL, we first rotate to a new segment.+            --+            -- This means that we only ever need to read back the active segment (i.e. latest one)+            Persistence+              { readLogEntriesFrom = \_ -> readLogEntries wal,+                writeLogEntry = \_processId -> traverse_ (appendMany wal) . nonEmpty . map LogRecord,+                truncateLogEntriesFrom = \_processId -> append wal . TruncateFrom,+                readTerm = readTermFromFile,+                writeTerm = writeTermToFile,+                readVotedFor = readVotedForFromFile,+                writeVotedFor = writeVotedForToFile,+                readSnapshot = readSnapshotFromWAL wal,+                writeSnapshot = writeSnapshotToWAL wal,+                readCommitIndex = readCommitIndexFromFile,+                writeCommitIndex = writeCommitIndexToFile+              }+       in f persistence+  where+    readLogEntries wal minLogIndex = do+      -- We assume that we'll never need to read log entries before the+      -- latest snapshot, AND that every WAL file starts with a snapshot,+      -- so we only need to read the last WAL segment+      ref <- liftIO $ newIORef mempty+      seg <- activeSegment wal+      -- We deliberately use a Map since WAL doesn't support overwriting.+      -- "Overwriting" the WAL is done by writing the latest record instead.+      replaySegment+        wal+        seg+        ( \case+            SnapshotRecord _ -> pure ()+            LogRecord (term, logIx, entry) ->+              when (logIx >= minLogIndex) (modifyIORef' ref (Map.insert (term, logIx) entry))+            TruncateFrom logIndex ->+              modifyIORef' ref (Map.filterWithKey (\(_term, ix) _entry -> ix < logIndex))+        )+      liftIO (readIORef ref)+        <&> Map.toAscList+        <&> map (\((t, ix), e) -> (t, ix, e))++    termFile = dir </> unsafeEncodeUtf "term"+    voteFile term = dir </> unsafeEncodeUtf "vote" <> OsPath.unsafeEncodeUtf (show (toInteger term))+    commitIndexFile = dir </> unsafeEncodeUtf "commit_index"++    readTermFromFile _node = liftIO $ try (IO.readFile termFile) >>= either (\(_ :: SomeException) -> pure 0) (pure . Binary.decode)++    writeTermToFile _node = writeDurably termFile++    readCommitIndexFromFile _node = liftIO $ try (IO.readFile commitIndexFile) >>= either (\(_ :: SomeException) -> pure 0) (pure . Binary.decode)+    -- Recall that the commit index doesn't need to be persisted durably like other parts of the+    -- Raft state. By using 'writeFile' instead of something more durable, we considerably increase the+    -- throughput of a Raft cluster (at least 2x on my laptop)+    writeCommitIndexToFile _node = liftIO . IO.writeFile commitIndexFile . Binary.encode++    readVotedForFromFile _node term =+      liftIO $+        try+          ( withBinaryFile (voteFile term) ReadMode $ \h ->+              BSL.hGetContents h+                <&> runGetOrFail Binary.get+                >>= \case+                  Left (_, _, errmsg) -> fail errmsg+                  Right (_, _, v) -> pure v+          )+          >>= either (\(_ :: SomeException) -> pure Nothing) (pure . Just)++    writeVotedForToFile _node term Nothing = liftIO $ Durable.removeFileDurable (voteFile term)+    writeVotedForToFile _node term (Just v) = writeDurably (voteFile term) v++    readSnapshotFromWAL wal _node = do+      ref <- liftIO $ newIORef Nothing+      seg <- activeSegment wal+      replaySegment+        wal+        seg+        ( \case+            SnapshotRecord snap -> writeIORef ref (Just snap)+            LogRecord {} -> pure ()+            TruncateFrom {} -> pure ()+        )+      liftIO (readIORef ref)++    writeSnapshotToWAL wal _node snap = do+      _ <- rotate wal+      append wal (SnapshotRecord snap)++writeDurably :: (MonadIO m, Binary a) => OsPath -> a -> m ()+writeDurably file =+  liftIO+    . Durable.writeFileAtomic file+    . BSL.toStrict+    . Binary.encode