packages feed

wal (empty) → 0.1.0.0

raw patch · 12 files changed

+1509/−0 lines, 12 filesdep +Win32dep +asyncdep +attoparsec

Dependencies added: Win32, async, attoparsec, base, binary, bytestring, containers, crc32c, directory, exceptions, file-io, filepath, hedgehog, os-string, stm, tasty, tasty-bench, tasty-hedgehog, temporary, unix, wal

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for wal++## 0.1.0.0 -- YYYY-mm-dd++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c), 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,8 @@+# wal++## Build++Run `$ cabal build` to build the project+## Documentation++Run `$ cabal haddock --open` to generate a reference for the API of the project.
+ bench/Main.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE NumericUnderscores #-}++module Main (main) where++import Control.Concurrent.Async (replicateConcurrently_)+import Control.Monad (replicateM)+import Data.Binary (Binary)+import Data.ByteString (StrictByteString)+import qualified Data.ByteString as BS+import qualified Data.List.NonEmpty as NonEmpty+import GHC.Generics (Generic)+import System.IO.Temp (withSystemTempDirectory)+import System.IO.WAL+import System.OsPath (encodeFS)+import Test.Tasty (localOption)+import Test.Tasty.Bench++newtype Entry = Entry StrictByteString+  deriving (Generic)++instance Binary Entry++main :: IO ()+main =+  withSystemTempDirectory "wal-bench" $ \dirFP -> do+    dir <- encodeFS dirFP+    let config =+          WALConfig+            { directory = dir,+              maxSegmentBytes = maxBound+            }++        codec = binaryWALCodec++        entry = Entry (BS.replicate 1024 0x08) -- 1 kB+        batch = flip replicate entry++    withWriteAheadLog codec config $ \wal -> do+      defaultMain . map (localOption WallTime) $+        [ bgroup+            "append"+            [ bench "single" $+                whnfIO (append wal entry)+            ],+          bgroup+            "appendMany"+            [ bench (show batchSize) $+                whnfIO (appendMany wal (NonEmpty.fromList (batch batchSize)))+            | batchSize <- [100, 1000, 10_000]+            ],+          let threadBlocks = [1, 4, 8, 32, 64, 128]+              totalNumberOfWrites = maximum threadBlocks+           in bgroup+                ("concurrent append (" <> show totalNumberOfWrites <> " total writes)")+                [ bench (show numThreads <> " threads") $+                    whnfIO (replicateConcurrently_ numThreads (replicateM numWritesPerThread $ append wal entry))+                | numThreads <- threadBlocks,+                  let numWritesPerThread = totalNumberOfWrites `div` numThreads+                ]+        ]
+ src/System/IO/File/Durable.hs view
@@ -0,0 +1,89 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE QuasiQuotes #-}++-- | Low-level, cross-platform file operations whose effects are+-- guaranteed to have reached stable storage once they return.+module System.IO.File.Durable+  ( -- * Low-level handles+    FHandle,+    open,+    openRead,+    size,+    readSome,+    writeAll,+    flush,+    syncDirectory,+    close,++    -- * Whole-file operations+    writeFileAtomic,+    removeFileDurable,+  )+where++import Control.Exception (bracket)+import Data.ByteString (StrictByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Internal as BSI+import Data.Word (Word8)+import Foreign.Ptr (Ptr, castPtr, plusPtr)+import System.Directory.OsPath (removeFile, renameFile)+import System.IO.Error (isDoesNotExistError, tryIOError)+import System.OsPath (OsPath, osp, takeDirectory)+import qualified System.OsString as OsString+#ifdef mingw32_HOST_OS+import System.IO.File.Durable.Windows as X+    ( FHandle, open, openRead, size, write, readBuf, flush, syncDirectory, close )+#else+import System.IO.File.Durable.Unix as X+    ( FHandle, open, openRead, size, write, readBuf, flush, syncDirectory, close )+#endif++-- | Read up to the given number of bytes+readSome :: FHandle -> Int -> IO StrictByteString+readSome h n = BSI.createUptoN n $ \ptr -> fromIntegral <$> readBuf h ptr (fromIntegral n)++-- | Write a whole buffer+writeAll :: FHandle -> Ptr Word8 -> Int -> IO ()+writeAll h ptr len+  | len <= 0 = pure ()+  | otherwise = do+      -- write(2) rejects requests larger than INT_MAX bytes on macOS+      written <- fromIntegral <$> write h ptr (fromIntegral (min len (1024 * 1024 * 1024)))+      if written == 0+        then fail "writeAll: no bytes were written"+        else writeAll h (ptr `plusPtr` written) (len - written)++-- | Write durably to a file: once 'writeFileAtomic' returns, the new contents+-- will survive hardware failures, restarts, and crashes.+writeFileAtomic :: OsPath -> StrictByteString -> IO ()+writeFileAtomic path bytes = do+  removeIfExists tmp+  bracket (open tmp) close $ \h -> do+    BS.useAsCStringLen bytes $ \(ptr, len) -> writeAll h (castPtr ptr) len+    flush h+  renameFile tmp path+  syncDirectory (parentDirectory path)+  where+    tmp = path <> [osp|.tmp|]++-- | Remove a file and make the removal durable. If the file does not+-- exist, this function does nothing.+removeFileDurable :: OsPath -> IO ()+removeFileDurable path = do+  removeIfExists path+  syncDirectory (parentDirectory path)++removeIfExists :: OsPath -> IO ()+removeIfExists path =+  tryIOError (removeFile path) >>= \case+    Left e | not (isDoesNotExistError e) -> ioError e+    _ -> pure ()++parentDirectory :: OsPath -> OsPath+parentDirectory path+  | OsString.null dir = [osp|.|]+  | otherwise = dir+  where+    dir = takeDirectory path
+ src/System/IO/File/Durable/Unix.hs view
@@ -0,0 +1,107 @@+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE ForeignFunctionInterface #-}++module System.IO.File.Durable.Unix+  ( FHandle,+    open,+    openRead,+    size,+    write,+    readBuf,+    flush,+    syncDirectory,+    close,+  )+where++#if defined(darwin_HOST_OS)+import Control.Monad (when)+#endif+import Control.Exception (bracket)+import Data.Word (Word32, Word8)+import Foreign (Ptr)+import Foreign.C (CInt (..), throwErrnoIfMinus1Retry_)+#if defined(darwin_HOST_OS)+import Foreign.C (eINTR, eNOTSUP, getErrno, throwErrno)+#endif+import System.OsPath (OsPath)+import System.OsString.Internal.Types (getOsString)+import System.Posix+  ( Fd (Fd),+    OpenFileFlags (append, creat),+    OpenMode (ReadOnly, WriteOnly),+    closeFd,+    defaultFileFlags,+    fdReadBuf,+    fdWriteBuf,+    stdFileMode,+  )+import System.Posix.IO.PosixString (openFd)+import System.Posix.Internals (fdFileSize)++newtype FHandle = FHandle Fd++-- should handle opening flags correctly+open :: OsPath -> IO FHandle+open filename =+  FHandle+    <$> openFd+      (getOsString filename)+      WriteOnly+      defaultFileFlags+        { creat = Just stdFileMode,+          append = True+        }++openRead :: OsPath -> IO FHandle+openRead filename = FHandle <$> openFd (getOsString filename) ReadOnly defaultFileFlags++size :: FHandle -> IO Integer+size (FHandle (Fd h)) = fdFileSize h++write :: FHandle -> Ptr Word8 -> Word32 -> IO Word32+write (FHandle fd) data' length' = fmap fromIntegral $ fdWriteBuf fd data' $ fromIntegral length'++readBuf :: FHandle -> Ptr Word8 -> Word32 -> IO Word32+readBuf (FHandle fd) data' length' = fmap fromIntegral $ fdReadBuf fd data' $ fromIntegral length'++-- | Block until everything written to the file has reached stable storage.+flush :: FHandle -> IO ()+flush (FHandle (Fd c_fd)) = fullSync c_fd++-- | Block until the entries of a directory (e.g. newly-created files) have+-- been persisted.+syncDirectory :: OsPath -> IO ()+syncDirectory dirname =+  bracket (openFd (getOsString dirname) ReadOnly defaultFileFlags) closeFd $+    \(Fd c_fd) -> fullSync c_fd++fullSync :: CInt -> IO ()+#if defined(darwin_HOST_OS)+-- On Mac OS, fsync only hands data over to the drive, which may keep it in a+-- volatile cache. F_FULLFSYNC also asks the drive to flush that cache.+-- Some filesystems (e.g. SMB) don't support F_FULLFSYNC, in which case we+-- fall back to fsync, like the Go standard library does.+fullSync c_fd = do+  result <- c_fcntl c_fd c_F_FULLFSYNC+  when (result == -1) $ do+    errno <- getErrno+    if errno == eINTR+      then fullSync c_fd+      else+        if errno == eNOTSUP+          then throwErrnoIfMinus1Retry_ "fsync" (c_fsync c_fd)+          else throwErrno "fcntl(F_FULLFSYNC)"++foreign import capi safe "fcntl.h fcntl" c_fcntl :: CInt -> CInt -> IO CInt++foreign import capi "fcntl.h value F_FULLFSYNC" c_F_FULLFSYNC :: CInt+#else+fullSync c_fd = throwErrnoIfMinus1Retry_ "fsync" (c_fsync c_fd)+#endif++foreign import ccall "fsync" c_fsync :: CInt -> IO CInt++close :: FHandle -> IO ()+close (FHandle fd) = closeFd fd
+ src/System/IO/File/Durable/Windows.hs view
@@ -0,0 +1,70 @@+module System.IO.File.Durable.Windows+  ( FHandle,+    open,+    openRead,+    size,+    write,+    readBuf,+    flush,+    syncDirectory,+    close,+  )+where++import Control.Exception (onException)+import Data.Bits ((.|.))+import Data.Word (Word32, Word8)+import Foreign (Ptr)+import System.IO+import System.OsPath (OsPath)+import System.OsString.Internal.Types (getOsString)+import System.Win32+  ( HANDLE,+    closeHandle,+    fILE_ATTRIBUTE_NORMAL,+    fILE_END,+    fILE_SHARE_READ,+    fILE_SHARE_WRITE,+    flushFileBuffers,+    gENERIC_READ,+    gENERIC_WRITE,+    oPEN_ALWAYS,+    oPEN_EXISTING,+    setFilePointerEx,+    win32_ReadFile,+    win32_WriteFile,+  )+import System.Win32.File (BY_HANDLE_FILE_INFORMATION (bhfiSize), getFileInformationByHandle)+import System.Win32.WindowsString.File (createFile)++newtype FHandle = FHandle HANDLE++open :: OsPath -> IO FHandle+open filename = do+  h <- createFile (getOsString filename) gENERIC_WRITE fILE_SHARE_READ Nothing oPEN_ALWAYS fILE_ATTRIBUTE_NORMAL Nothing+  _ <- setFilePointerEx h 0 fILE_END `onException` closeHandle h+  pure (FHandle h)++-- | Unlike 'withBinaryFile', this can open a file which is open for writing.+openRead :: OsPath -> IO FHandle+openRead filename =+  FHandle <$> createFile (getOsString filename) gENERIC_READ (fILE_SHARE_READ .|. fILE_SHARE_WRITE) Nothing oPEN_EXISTING fILE_ATTRIBUTE_NORMAL Nothing++size :: FHandle -> IO Integer+size (FHandle handle) = fromIntegral . bhfiSize <$> getFileInformationByHandle handle++write :: FHandle -> Ptr Word8 -> Word32 -> IO Word32+write (FHandle handle) data' length = win32_WriteFile handle data' length Nothing++readBuf :: FHandle -> Ptr Word8 -> Word32 -> IO Word32+readBuf (FHandle handle) data' length = win32_ReadFile handle data' length Nothing++flush :: FHandle -> IO ()+flush (FHandle handle) = flushFileBuffers handle++-- Windows has no equivalent to flushing a directory+syncDirectory :: OsPath -> IO ()+syncDirectory _ = pure ()++close :: FHandle -> IO ()+close (FHandle handle) = closeHandle handle
+ src/System/IO/WAL.hs view
@@ -0,0 +1,549 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TupleSections #-}++-- I like using <&>, sue me hlint+{- HLINT ignore "Functor law" -}++-- |+-- Module      : System.IO.WAL+-- Description : A generic, durable, rotating write-ahead log.+module System.IO.WAL+  ( -- * Write-ahead log+    withWriteAheadLog,+    WriteAheadLog,++    -- ** Writing+    append,+    appendMany,++    -- ** Manual rotation+    rotate,++    -- ** Reading+    Segment,+    segmentPath,+    segments,+    activeSegment,+    replayAll,+    replaySegment,++    -- ** Configuration+    WALCodec (..),+    binaryWALCodec,+    rawWALCodec,+    WALConfig (..),+  )+where++import Control.Concurrent (forkIOWithUnmask)+import Control.Concurrent.MVar (MVar, modifyMVar, newEmptyMVar, newMVar, putMVar, readMVar, takeMVar, tryPutMVar, withMVar)+import Control.Concurrent.STM+  ( TQueue,+    TVar,+    atomically,+    flushTQueue,+    newTQueueIO,+    newTVarIO,+    readTVar,+    retry,+    writeTQueue,+    writeTVar,+  )+import Control.Exception+  ( SomeException,+    catch,+    displayException,+    evaluate,+    mask_,+    throwIO,+    try,+  )+import Control.Monad (forM_, unless, void, when)+import Control.Monad.Catch (MonadMask, bracket)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.Attoparsec.ByteString (Parser)+import qualified Data.Attoparsec.ByteString as Parser+import Data.Bifunctor (bimap, first)+import Data.Binary (Binary, decodeOrFail, put)+import Data.Binary.Put (execPut)+import Data.Bits (Bits (shiftL, (.|.)))+import Data.ByteString (StrictByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Unsafe as BSU+import Data.Digest.CRC32C (crc32c)+import Data.Foldable (traverse_)+import Data.Functor ((<&>))+import Data.IORef+  ( IORef,+    modifyIORef',+    newIORef,+    readIORef,+    writeIORef,+  )+import Data.List (sortOn)+import Data.List.NonEmpty (NonEmpty)+import qualified Data.List.NonEmpty as NonEmpty+import Data.Maybe (mapMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Word (Word32, Word64)+import Foreign.Ptr (castPtr)+import System.Directory.OsPath+  ( createDirectoryIfMissing,+    doesDirectoryExist,+    doesFileExist,+    listDirectory,+  )+import System.File.OsPath (withBinaryFile)+import System.IO+  ( Handle,+    IOMode (..),+    hSetFileSize,+  )+import System.IO.File.Durable (FHandle)+import qualified System.IO.File.Durable as WALFile+import System.OsPath (OsPath, osp, takeDirectory, unsafeEncodeUtf, (</>))+import System.OsString (OsString)+import qualified System.OsString as OsString+import Text.Printf (printf)+import Text.Read (readMaybe)++-- | Represents a reference to a write-ahead log.+--+-- Append to the log using 'append'. Once 'append' returns, the+-- log has been updated durably.+-- 'append' is a slow operation. You can batch appends using 'appendMany',+-- which commits all appends at once, atomically.+--+-- If writing to the log ever fails, the log refuses any further writes+-- until it is reopened.+--+-- A write-ahead log is really a directory of files, called /segments/.+-- When the log gets long enough, the active file rotates automatically.+-- This can also be done manually using 'rotate'. You can list+-- existing segments using 'segments'.+--+-- You can read back the entire log in sequential order using 'replayAll'.+-- You can also read back specific segments using 'replaySegment'. You+-- can read and write to the log concurrently.+--+-- Using the same 'WriteAheadLog' from multiple threads is safe, and+-- efficient: throughput increases linearly with the number of writer+-- threads.+data WriteAheadLog a = WriteAheadLog+  { walCodec :: !(WALCodec a),+    walConfig :: !WALConfig,+    walHandle :: !(MVar WALHandle),+    -- | The active segment, and the number of bytes persisted.+    walActive :: !(IORef (Segment, Word64)),+    -- | In case an error has happened when trying to append, we must+    -- be able to share this with other threads.+    --+    -- TODO: is there a more elegant way to handle errors in a multi-+    -- threaded environment?+    walFailure :: !(IORef (Maybe SomeException)),+    -- | Appends waiting for the writer thread+    walAppends :: !(TQueue Append),+    -- | Once set, no more appends are accepted+    walClosed :: !(TVar Bool),+    -- | Filled once the writer thread has stopped+    walWriterDone :: !(MVar ())+  }++-- | Framed entries for the writer thread to write, and where to+-- report the outcome+data Append = Append !StrictByteString !(MVar (Either SomeException ()))++-- | How to encode and decode write-ahead log entries.+--+-- A 'binaryWALCodec' is provided if you want to reuse instances from+-- the 'binary' package.+data WALCodec a = WALCodec+  { encodeEntry :: a -> BB.Builder,+    decodeEntry :: StrictByteString -> Either String a+  }++-- | 'WALCodec' making use of the 'Binary' typeclass.+--+-- This is often convenient, but less performant, than alternatives.+binaryWALCodec :: (Binary a) => WALCodec a+binaryWALCodec =+  let trd (_, _, !x) = x+   in WALCodec+        { encodeEntry = execPut . put,+          decodeEntry =+            bimap+              trd+              trd+              . decodeOrFail+              . BL.fromStrict+        }++-- | 'WALCodec' which doesn't decode payloads+rawWALCodec :: WALCodec StrictByteString+rawWALCodec =+  WALCodec+    { encodeEntry = BB.byteString,+      decodeEntry = Right+    }++-- | Configuration+data WALConfig = WALConfig+  { -- | Once the active segment reaches this size, the next append+    -- goes to a new segment.+    maxSegmentBytes :: !Word64,+    -- | Directory where to write write-ahead log files. This directory need+    -- not be empty.+    directory :: !OsPath+  }++-- | Open a 'WriteAheadLog' based on an input configuration, and a codec+-- to encode and decode entries.+--+-- If the configuration points to an existing directory, the 'WriteAheadLog'+-- will pick back up from where it last stopped. To reset a 'WriteAheadLog',+-- its associated directory must be emptied.+--+-- The log is closed once the continuation returns, or throws an exception.+-- All queued appends will be flushed before terminating.+withWriteAheadLog ::+  (MonadIO m, MonadMask m) =>+  WALCodec a ->+  WALConfig ->+  (WriteAheadLog a -> m b) ->+  m b+withWriteAheadLog codec config =+  bracket (liftIO (open codec config)) (liftIO . close)++-- | Open a write-ahead log.+--+-- If the directory where log files should be stored doesn't exist,+-- it will be created (including its parents if needed).+--+-- If active log file is torn, the partial log entry will be+-- removed such that the log is repaired.+open :: WALCodec a -> WALConfig -> IO (WriteAheadLog a)+open codec config = do+  createDirectoryDurably (directory config)++  segs <- listSegmentsFromDir (directory config)+  let latest = case map fst segs of+        [] -> 0+        ns -> maximum ns++  let path = directory config </> segmentPath latest++  exists <- doesFileExist path+  if exists+    then withBinaryFile path ReadWriteMode $ \h -> do+      v <- validSize h+      hSetFileSize h (fromIntegral v)+    else do+      withBinaryFile path WriteMode (const (pure ()))+      WALFile.syncDirectory (directory config)++  h <- WALFile.open path+  sz <- WALFile.size h+  wal <-+    WriteAheadLog+      codec+      config+      <$> newMVar (WALHandle h path)+      <*> newIORef (latest, fromIntegral sz)+      <*> newIORef Nothing+      <*> newTQueueIO+      <*> newTVarIO False+      <*> newEmptyMVar++  -- 'open' runs with asynchronous exceptions masked, which the writer+  -- thread would otherwise inherit+  _ <- forkIOWithUnmask $ \unmask -> do+    unmask (runWriter wal) `catch` \e -> do+      -- Nothing will write the appends which are still queued+      queued <- atomically $ do+        writeTVar (walClosed wal) True+        flushTQueue (walAppends wal)+      traverse_ (\(Append _ done) -> reply done (Left e)) queued+    putMVar (walWriterDone wal) ()+  pure wal+  where+    reply done = void . tryPutMVar done++    runWriter wal = do+      appends <- atomically $ do+        appends <- flushTQueue (walAppends wal)+        closed <- readTVar (walClosed wal)+        when (null appends && not closed) retry+        pure appends+      unless (null appends) $ do+        writeAppends wal appends `catch` \e -> do+          traverse_ (\(Append _ done) -> reply done (Left e)) appends+          throwIO (e :: SomeException)+        runWriter wal++    writeAppends _ [] = pure ()+    writeAppends wal appends@(Append _ firstDone : others) = do+      rotated <- try $ withActiveSegment wal $ \handle -> do+        written <- snd <$> readIORef (walActive wal)+        if written >= maxSegmentBytes (walConfig wal)+          then void <$> rotateLocked wal handle+          else pure (handle, ())++      case rotated of+        Left e -> reply firstDone (Left e) >> writeAppends wal others+        Right () -> do+          written <- snd <$> readIORef (walActive wal)+          let (batch, rest) = fillSegment (maxSegmentBytes (walConfig wal)) written appends+              bytes = BS.concat [b | Append b _ <- batch]+          result <- try $ withActiveSegment wal $ \handle@(WALHandle h _) -> do+            durably wal $+              BSU.unsafeUseAsCStringLen bytes $ \(ptr, len) -> do+                WALFile.writeAll h (castPtr ptr) len+                WALFile.flush h+            modifyIORef' (walActive wal) $ \(seg, total) ->+              let !total' = total + fromIntegral (BS.length bytes) in (seg, total')+            pure (handle, ())+          traverse_ (\(Append _ done) -> reply done result) batch+          writeAppends wal rest+      where+        fillSegment maxBytes = go+          where+            go _ [] = ([], [])+            go written (append'@(Append bytes _) : rest)+              | written' >= maxBytes = ([append'], rest)+              | otherwise = first (append' :) (go written' rest)+              where+                written' = written + fromIntegral (BS.length bytes)++close :: WriteAheadLog a -> IO ()+close wal = do+  -- The writer thread writes the appends which are already queued, then stops+  atomically (writeTVar (walClosed wal) True)+  readMVar (walWriterDone wal)+  withMVar (walHandle wal) $ \(WALHandle h _) -> WALFile.close h++createDirectoryDurably :: OsPath -> IO ()+createDirectoryDurably dir = do+  exists <- doesDirectoryExist dir+  unless exists $ do+    let parent = takeDirectory dir+    when (parent /= dir) (createDirectoryDurably parent)+    createDirectoryIfMissing False dir+    WALFile.syncDirectory parent++-- | Entries in the Log are structured as:+--+-- * 4 bytes for the length of the payload, encoded as a little-endian Word32;+-- * 4 bytes for the checksum (crc32), encoded as a little-endian Word32;+-- * N payload bytes+frame :: BB.Builder -> BB.Builder+frame payloadB =+  let payload = BL.toStrict (BB.toLazyByteString payloadB)+      len = fromIntegral (BS.length payload) :: Word32+      crc = crc32c payload+   in BB.word32LE len <> BB.word32LE crc <> BB.byteString payload++anyWord32le :: Parser Word32+anyWord32le = Parser.take 4 <&> pack . BS.reverse+  where+    pack :: (Bits a, Num a) => StrictByteString -> a+    pack = B.foldl' (\n h -> (n `shiftL` 8) .|. fromIntegral h) 0++-- | Parse the payload of an entry, checking its integrity.+payloadP :: Parser StrictByteString+payloadP = do+  len <- anyWord32le+  checksum <- anyWord32le+  bytes <- Parser.take (fromIntegral len)+  if crc32c bytes /= checksum+    then fail "WAL: checksum mismatch (torn or corrupted write)"+    else pure bytes++-- 'ensureFileDurable' requires a known 'OsPath',+-- which we must keep in sync with a 'Handle'+data WALHandle = WALHandle !FHandle !OsPath++newtype Segment = MkSegment Word32+  deriving (Show, Eq)+  deriving newtype (Ord, Enum, Integral, Real, Num, Read)++segPrefix :: OsString+segPrefix = [osp|wal-|]++segSuffix :: OsString+segSuffix = [osp|.log|]++segmentPath :: Segment -> OsPath+segmentPath (MkSegment n) = unsafeEncodeUtf $ printf "wal-%06d.log" (fromIntegral n :: Int)++listSegmentsFromDir :: (MonadIO m) => OsPath -> m [(Segment, OsPath)]+listSegmentsFromDir dir =+  liftIO $+    listDirectory dir+      <&> mapMaybe (\fp -> (,fp) <$> parseSegment fp)+      <&> sortOn fst+  where+    parseSegment f = do+      OsString.stripPrefix segPrefix f+        >>= OsString.stripSuffix segSuffix+        >>= OsString.decodeUtf+        >>= readMaybe++-- | List all segments relevant to this write-ahead log.+--+-- This can be used to replay the appropriate segments.+-- See 'activeSegment' for the most recent segment.+segments :: (MonadIO m) => WriteAheadLog a -> m (Set Segment)+segments wal =+  listSegmentsFromDir (directory (walConfig wal))+    <&> fmap fst+    <&> Set.fromList++-- | Return the active segment of the write-ahead log+activeSegment :: (MonadIO m) => WriteAheadLog a -> m Segment+activeSegment = liftIO . fmap fst . readIORef . walActive++-- | Append a single entry to the log. Once 'append' returns,+-- the entry is durably stored on disk.+--+-- Prefer to use 'appendMany' as much as possible, as it is much,+-- much faster.+--+-- Appending to the log may result in the log file rotating+-- to a new file.+append :: (MonadIO m) => WriteAheadLog a -> a -> m ()+append wal = appendMany wal . NonEmpty.singleton++-- | Append a batch of entries to the log. Once 'appendMany'+-- returns, the entries are durably stored on disk.+--+-- Appending to the log may result in the log file rotating+-- to a new file.+appendMany :: (MonadIO m) => WriteAheadLog a -> NonEmpty a -> m ()+appendMany wal xs = liftIO $ do+  bytes <- evaluate (BL.toStrict (BB.toLazyByteString (foldMap (frame . encodeEntry (walCodec wal)) xs)))++  -- TODO: we don't necessarily need to wait! That depends+  --       on what the user wants. There should be a notion+  --       of synchronicity-ness+  done <- newEmptyMVar+  enqueued <- atomically $ do+    closed <- readTVar (walClosed wal)+    unless closed (writeTQueue (walAppends wal) (Append bytes done))+    pure (not closed)+  unless enqueued (fail "WAL: the log is closed")+  takeMVar done >>= either throwIO pure++-- | Close the current segment and open a fresh, empty one.+rotate :: (MonadIO m) => WriteAheadLog a -> m Segment+rotate wal = liftIO $ withActiveSegment wal (rotateLocked wal)++-- | Implementation of 'rotate', for when we already have access to+-- the active segment. If rotating fails, the active segment doesn't change.+rotateLocked :: WriteAheadLog a -> WALHandle -> IO (WALHandle, Segment)+rotateLocked wal (WALHandle h _) = do+  durably wal (WALFile.flush h)++  n' <- (+ 1) . fst <$> readIORef (walActive wal)+  let path = directory (walConfig wal) </> segmentPath n'++  -- The next segment file is overwritten+  withBinaryFile path WriteMode (const (pure ()))+  WALFile.syncDirectory (directory (walConfig wal))++  h' <- WALFile.open path+  WALFile.close h++  writeIORef (walActive wal) (n', 0)++  pure (WALHandle h' path, n')++-- | Run an action with exclusive access to the active segment.+--+-- Interrupting the action with an asynchronous exception (e.g. from+-- 'System.Timeout.timeout') could leave a partial entry, or a closed+-- handle, behind; such exceptions are deferred until the action completes.+-- Threads waiting for access can still be interrupted.+withActiveSegment :: WriteAheadLog a -> (WALHandle -> IO (WALHandle, b)) -> IO b+withActiveSegment wal = mask_ . modifyMVar (walHandle wal)++-- | Write to the active segment.+-- To prevent data corruption in a multi-threaded context,+-- once a write fails, `durably` will stop working.+durably :: WriteAheadLog a -> IO b -> IO b+durably wal act = do+  failure <- readIORef (walFailure wal)+  forM_ failure $ \e ->+    fail ("WAL: refusing to write, since an earlier write failed (" <> displayException e <> ")")+  act `catch` \e -> do+    writeIORef (walFailure wal) (Just e)+    throwIO (e :: SomeException)++-- | Stream the contents of a write-ahead log segment.+--+-- See 'segments' to fetch available segments for a given 'WriteAheadLog'+--+-- Replaying stops at the first entry which is incomplete or fails its+-- checksum, as happens when a crash interrupts a write. An entry which+-- passes its checksum, but can't be decoded, is an error.+--+-- It is safe to replay the segment to which we are currently writing, and+-- doing so doesn't block appends. Only the entries which were durably+-- written when replaying started are replayed.+replaySegment ::+  (MonadIO m) =>+  WriteAheadLog a ->+  Segment ->+  (a -> IO ()) ->+  m ()+replaySegment wal segment onEntry = liftIO $ do+  (active, durable) <- readIORef (walActive wal)+  let limit = if active == segment then durable else maxBound+  bracket (WALFile.openRead (directory (walConfig wal) </> segmentPath segment)) WALFile.close $ \h ->+    streamPayloads (WALFile.readSome h) limit $ \payload ->+      either+        (\e -> fail ("WAL: decode error: " <> e))+        onEntry+        (decodeEntry (walCodec wal) payload)++-- | Replay every segment in the log directory, oldest first, feeding each+-- decoded entry to the given callback in order.+replayAll :: (MonadIO m) => WriteAheadLog a -> (a -> IO ()) -> m ()+replayAll wal onEntry = do+  segs <- listSegmentsFromDir (directory (walConfig wal))+  forM_ segs $ \(seg, _) -> replaySegment wal seg onEntry++-- | Stream the payloads of a segment's entries, in order.+--+-- Streaming stops at the first entry which is incomplete or fails+-- its checksum, or after reading the given number of bytes.+streamPayloads :: (Int -> IO StrictByteString) -> Word64 -> (StrictByteString -> IO ()) -> IO ()+streamPayloads readChunk limit onPayload = go limit (Parser.parse payloadP BS.empty)+  where+    go remaining (Parser.Done rest payload) = onPayload payload >> go remaining (Parser.parse payloadP rest)+    go remaining (Parser.Partial continue) = do+      chunk <- readChunk (fromIntegral (min remaining (64 * 1024)))+      go (remaining - fromIntegral (BS.length chunk)) (continue chunk)+    -- Either we've reached the end of the segment, or the next entry+    -- is torn or corrupted; both mark the end of the valid entries.+    go _ Parser.Fail {} = pure ()++-- | Returns the size of the data that only includes valid+-- write-ahead log entries.+--+-- This can be used to truncate write-ahead log files to+-- remove partial entries.+validSize :: Handle -> IO Word64+validSize h = do+  validSizeRef <- newIORef (0 :: Word64)++  streamPayloads (BS.hGet h) maxBound $ \payload ->+    modifyIORef' validSizeRef (\v -> v + 4 + 4 + fromIntegral (BS.length payload))+  readIORef validSizeRef
+ tests/Main.hs view
@@ -0,0 +1,12 @@+module Main (main) where++import qualified Test.System.IO.File.Durable (tests)+import qualified Test.System.IO.WAL (tests)+import Test.Tasty (defaultMain, localOption, testGroup)+import Test.Tasty.Hedgehog (HedgehogTestLimit (..))++main :: IO ()+main =+  defaultMain $+    localOption (HedgehogTestLimit (Just 25)) $ -- durable file operations are SLOW+      testGroup "wal" [Test.System.IO.File.Durable.tests, Test.System.IO.WAL.tests]
+ tests/Test/System/IO/File/Durable.hs view
@@ -0,0 +1,83 @@+module Test.System.IO.File.Durable (tests) where++import Control.Exception (bracket)+import Control.Monad.IO.Class (liftIO)+import qualified Data.ByteString as BS+import Foreign.Ptr (castPtr)+import Hedgehog (annotate, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Directory.OsPath (doesFileExist, listDirectory)+import System.File.OsPath (readFile')+import System.IO.File.Durable (close, open, openRead, readSome, removeFileDurable, writeAll, writeFileAtomic)+import System.IO.Temp (withSystemTempDirectory)+import System.OsPath (encodeFS, unsafeEncodeUtf, (</>))+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testProperty)++tests :: TestTree+tests =+  testGroup+    "System.IO.File.Durable"+    [ testWriteFileAtomic,+      testWriteFileAtomicIgnoresStaleTemporary,+      testRemoveFileDurable,+      testReadWhileWriting+    ]++testWriteFileAtomic :: TestTree+testWriteFileAtomic = testProperty "writeFileAtomic" $ property $ do+  old <- forAll $ Gen.bytes (Range.linear 0 64)+  new <- forAll $ Gen.bytes (Range.linear 0 64)+  (contents, files) <- liftIO $ withSystemTempDirectory "durable-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    let path = dir </> unsafeEncodeUtf "file"+    writeFileAtomic path old+    writeFileAtomic path new+    (,) <$> readFile' path <*> listDirectory dir+  contents === new+  length files === 1++testWriteFileAtomicIgnoresStaleTemporary :: TestTree+testWriteFileAtomicIgnoresStaleTemporary = testProperty "writeFileAtomic discards a temporary file left over by a crash" $ property $ do+  stale <- forAll $ Gen.bytes (Range.linear 1 64)+  new <- forAll $ Gen.bytes (Range.linear 0 64)+  contents <- liftIO $ withSystemTempDirectory "durable-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    let path = dir </> unsafeEncodeUtf "file"+    BS.writeFile (tmpDir <> "/file.tmp") stale+    writeFileAtomic path new+    readFile' path+  annotate "the stale bytes must not be appended to or mixed with the new contents"+  contents === new++testRemoveFileDurable :: TestTree+testRemoveFileDurable = testProperty "removeFileDurable removes a file if it exists" $ property $ do+  bytes <- forAll $ Gen.bytes (Range.linear 0 64)+  (existsBefore, existsAfter) <- liftIO $ withSystemTempDirectory "durable-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    let path = dir </> unsafeEncodeUtf "file"+    removeFileDurable path+    writeFileAtomic path bytes+    before <- doesFileExist path+    removeFileDurable path+    after <- doesFileExist path+    pure (before, after)+  (existsBefore, existsAfter) === (True, False)++testReadWhileWriting :: TestTree+testReadWhileWriting = testProperty "A file can be read while it is open for writing" $ property $ do+  before <- forAll $ Gen.bytes (Range.linear 1 64)+  after <- forAll $ Gen.bytes (Range.linear 1 64)+  seen <- liftIO $ withSystemTempDirectory "durable-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    let path = dir </> unsafeEncodeUtf "file"+        write h bytes = BS.useAsCStringLen bytes $ \(ptr, len) -> writeAll h (castPtr ptr) len+    bracket (open path) close $+      \w -> bracket (openRead path) close $ \r -> do+        write w before+        seenBefore <- readSome r 128+        write w after+        seenAfter <- readSome r 128+        pure (seenBefore, seenAfter)+  seen === (before, after)
+ tests/Test/System/IO/WAL.hs view
@@ -0,0 +1,399 @@+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE TupleSections #-}++module Test.System.IO.WAL (tests) where++import Control.Concurrent.Async (async, forConcurrently, wait, withAsync)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar, takeMVar, tryPutMVar)+import Control.Exception (SomeException, try)+import Control.Monad (replicateM, unless)+import Control.Monad.IO.Class (liftIO)+import Data.Bits (complement)+import Data.ByteString (StrictByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as Builder+import qualified Data.ByteString.Char8 as BS8+import Data.Either (isLeft)+import Data.Foldable (for_, toList, traverse_)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List (isPrefixOf, sort)+import Data.List.NonEmpty (nonEmpty)+import qualified Data.List.NonEmpty as NonEmpty+import Data.Traversable (for)+import Data.Word (Word64)+import Hedgehog (Gen, annotate, assert, failure, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.File.OsPath (withBinaryFile)+import System.IO (IOMode (..), SeekMode (..), hFileSize, hSeek, hSetFileSize)+import System.IO.Temp (withSystemTempDirectory)+import System.IO.WAL+import System.OsPath (encodeFS, (</>))+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testProperty)++tests :: TestTree+tests =+  testGroup+    "System.IO.WAL"+    [ testTripping,+      testReplayIgnorePartialWrites,+      testOpenRepairsPartialWrites,+      testOpenRepairsCorruptedRecords,+      testReplayFailsOnUndecodableRecords,+      testSingleVsManyAppend,+      testAutomaticRotation,+      testConcurrentAppends,+      testCloseWhileAppending,+      testReplayWhileAppending,+      testAppendWhileReplaying+    ]++testTripping :: TestTree+testTripping = testProperty "Writing to WAL and replaying" $ property $ do+  replayedRef <- liftIO $ newIORef []+  entriesSegment1 <- forAll $ Gen.list (Range.linear 0 10) (Gen.bytes (Range.linear 0 24))+  entriesSegment2 <- forAll $ Gen.list (Range.linear 0 10) (Gen.bytes (Range.linear 0 24))++  replayed <- liftIO $ withSystemTempDirectory "wal-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      for_ entriesSegment1 (append wal)+      unless (null entriesSegment2) $ do+        _ <- rotate wal+        for_ entriesSegment2 (append wal)++      -- prepending to a list is faster, but then+      -- we need to reverse the output+      replayAll wal (\e -> modifyIORef' replayedRef (e :))+      reverse <$> readIORef replayedRef++  (entriesSegment1 <> entriesSegment2) === replayed++testReplayIgnorePartialWrites :: TestTree+testReplayIgnorePartialWrites = testProperty "Reading from a partially-written WAL surfaces works" $ property $ do+  entries <- forAll $ Gen.list (Range.linear 0 1024) (Gen.bytes (Range.linear 0 107))++  let toFramedSize bytes = 4 + 4 + BS.length bytes+      fullFileSize = sum (toFramedSize <$> entries)++  truncationPoint <- forAll $ Gen.integral (Range.linear 0 fullFileSize)++  let go _ numEntries [] = numEntries+      go lengthSoFar numEntries (e : es) =+        let extended = lengthSoFar + toFramedSize e+         in if extended > truncationPoint+              then numEntries+              else go extended (numEntries + 1) es+      expectedPrefixLength = go 0 0 entries+      expectedPrefix = take expectedPrefixLength entries++  -- sanity check+  annotate $ "Expected prefix: " <> show expectedPrefix+  assert (expectedPrefix `isPrefixOf` entries)++  replayed <- liftIO $ withSystemTempDirectory "wal-testing-partial" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      traverse_ (appendMany wal) (nonEmpty entries)++    let fp = dir </> segmentPath 0+    liftIO+      $ withBinaryFile+        fp+        ReadWriteMode+      $ flip hSetFileSize (toInteger truncationPoint)++    replayedRef <- liftIO $ newIORef []+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      -- prepending to a list is faster, but then+      -- we need to reverse the output+      replayAll wal (\e -> modifyIORef' replayedRef (e :))+      reverse <$> readIORef replayedRef++  replayed === expectedPrefix++testOpenRepairsPartialWrites :: TestTree+testOpenRepairsPartialWrites = testProperty "Opening a partially-torn WAL results in torn records being truncated" $ property $ do+  entries <- forAll $ Gen.list (Range.linear 0 1024) (Gen.bytes (Range.linear 0 107))++  let toFramedSize bytes = 4 + 4 + BS.length bytes+      fullFileSize = sum (toFramedSize <$> entries)++  truncationPoint <- forAll $ Gen.integral (Range.linear 0 fullFileSize)++  let go _ numEntries [] = numEntries+      go lengthSoFar numEntries (e : es) =+        let extended = lengthSoFar + toFramedSize e+         in if extended > truncationPoint+              then numEntries+              else go extended (numEntries + 1) es+      expectedPrefixLength = go 0 0 entries+      expectedPrefix = take expectedPrefixLength entries++  -- sanity check+  annotate $ "Expected prefix: " <> show expectedPrefix+  assert (expectedPrefix `isPrefixOf` entries)++  size <- liftIO $ withSystemTempDirectory "wal-testing-partial" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      traverse_ (appendMany wal) (nonEmpty entries)++    let fp = dir </> segmentPath 0+    liftIO+      $ withBinaryFile+        fp+        ReadWriteMode+      $ flip hSetFileSize (toInteger truncationPoint)++    -- Open the WAL but do nothing+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \_wal -> pure ()++    liftIO $ withBinaryFile fp ReadMode hFileSize++  fromIntegral size === sum (toFramedSize <$> expectedPrefix)++testOpenRepairsCorruptedRecords :: TestTree+testOpenRepairsCorruptedRecords = testProperty "Opening a WAL with a corrupted record truncates the log at that record" $ property $ do+  entries <- forAll $ Gen.list (Range.linear 1 1024) (Gen.bytes (Range.linear 0 107))+  corrupted <- forAll $ Gen.int (Range.linear 0 (length entries - 1))++  let toFramedSize bytes = 4 + 4 + BS.length bytes+      expectedPrefix = take corrupted entries+      checksumOffset = sum (toFramedSize <$> expectedPrefix) + 4++  (replayed, size) <- liftIO $ withSystemTempDirectory "wal-testing-corrupted" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      traverse_ (appendMany wal) (nonEmpty entries)++    let fp = dir </> segmentPath 0+    withBinaryFile fp ReadWriteMode $ \h -> do+      hSeek h AbsoluteSeek (toInteger checksumOffset)+      byte <- BS.hGet h 1+      hSeek h AbsoluteSeek (toInteger checksumOffset)+      BS.hPut h (BS.map complement byte)++    replayed <- timeout 10_000_000 $ withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      replayedRef <- newIORef []+      replayAll wal (\e -> modifyIORef' replayedRef (e :))+      reverse <$> readIORef replayedRef++    (replayed,) <$> withBinaryFile fp ReadMode hFileSize++  replayed === Just expectedPrefix+  fromIntegral size === sum (toFramedSize <$> expectedPrefix)++testReplayFailsOnUndecodableRecords :: TestTree+testReplayFailsOnUndecodableRecords = testProperty "Replaying a record which can't be decoded is an error" $ property $ do+  before <- forAll $ Gen.list (Range.linear 0 100) (Gen.bytes (Range.linear 0 24))+  after <- forAll $ Gen.list (Range.linear 0 100) (Gen.bytes (Range.linear 0 24))++  let undecodable = BS8.pack "undecodable"+      pickyCodec =+        testCodec+          { decodeEntry = \bytes ->+              if bytes == undecodable+                then Left "undecodable entry"+                else Right bytes+          }++  result <- liftIO $ withSystemTempDirectory "wal-testing-undecodable" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal ->+      for_ (before <> [undecodable] <> after) (append wal)++    timeout 10_000_000 $ withWriteAheadLog pickyCodec (WALConfig maxBound dir) $ \wal ->+      try (replayAll wal (const (pure ())))++  fmap isLeft (result :: Maybe (Either SomeException ())) === Just True++testSingleVsManyAppend :: TestTree+testSingleVsManyAppend = testProperty "append and appendMany give the same result" $ property $ do+  entriesBatched <-+    forAll $+      Gen.list+        (Range.linear 0 100)+        ( Gen.nonEmpty+            (Range.linear 1 3)+            (Gen.bytes (Range.linear 0 24))+        )++  walBound <- forAll $ Gen.word64 (Range.linear 5 200_000_000)++  let entries = foldMap NonEmpty.toList entriesBatched++  replayedSingle <- liftIO $ withSystemTempDirectory "wal-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig walBound dir) $ \wal -> do+      for_ entries (append wal)++      replayedRef <- liftIO $ newIORef []+      replayAll wal (\e -> modifyIORef' replayedRef (e :))+      reverse <$> readIORef replayedRef++  replayedSingle === entries++  replayedMany <- liftIO $ withSystemTempDirectory "wal-testing" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    withWriteAheadLog testCodec (WALConfig walBound dir) $ \wal -> do+      for_ entriesBatched (appendMany wal)++      replayedRef <- liftIO $ newIORef []+      replayAll wal (\e -> modifyIORef' replayedRef (e :))+      reverse <$> readIORef replayedRef++  replayedMany === entries++testAutomaticRotation :: TestTree+testAutomaticRotation = testProperty "Segments rotate automatically once they are full" $ property $ do+  entries <- forAll $ Gen.list (Range.linear 1 100) (Gen.bytes (Range.linear 0 24))+  maxBytes <- forAll $ Gen.word64 (Range.linear 8 256)++  replayed <- liftIO $ withSystemTempDirectory "wal-testing-rotation" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    timeout 10_000_000 $ withWriteAheadLog testCodec (WALConfig maxBytes dir) $ \wal -> do+      for_ entries (append wal)++      segs <- toList <$> segments wal+      for segs $ \seg -> do+        replayedRef <- newIORef []+        replaySegment wal seg (\e -> modifyIORef' replayedRef (e :))+        reverse <$> readIORef replayedRef++  replayed === Just (expectedSegments maxBytes entries)++expectedSegments :: Word64 -> [StrictByteString] -> [[StrictByteString]]+expectedSegments maxBytes = go 0 []+  where+    go _ current [] = [reverse current]+    go written current (e : es)+      | written >= maxBytes = reverse current : go (framedSize e) [e] es+      | otherwise = go (written + framedSize e) (e : current) es++    framedSize e = fromIntegral (4 + 4 + BS.length e)++testConcurrentAppends :: TestTree+testConcurrentAppends = testProperty "Concurrent appends are all written, in order for each thread" $ property $ do+  entries <- forAll genThreadEntries+  maxBytes <- forAll $ Gen.choice [Gen.word64 (Range.linear 8 256), pure maxBound]++  replayed <- liftIO $ withSystemTempDirectory "wal-testing-concurrent" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    timeout 30_000_000 $ withWriteAheadLog testCodec (WALConfig maxBytes dir) $ \wal -> do+      _ <- forConcurrently entries (traverse_ (append wal))++      segs <- toList <$> segments wal+      for segs $ \seg -> do+        replayedRef <- newIORef []+        replaySegment wal seg (\e -> modifyIORef' replayedRef (e :))+        reverse <$> readIORef replayedRef++  case replayed of+    Nothing -> annotate "Timed out" >> failure+    Just perSegment -> do+      let inLog = concat perSegment+      sort inLog === sort (concat entries)+      for_ entries $ \threadEntries ->+        filter (`elem` threadEntries) inLog === threadEntries+      perSegment === expectedSegments maxBytes inLog++testCloseWhileAppending :: TestTree+testCloseWhileAppending = testProperty "Closing a log while appending to it keeps exactly the successful appends" $ property $ do+  entries <- forAll genThreadEntries++  result <- liftIO $ withSystemTempDirectory "wal-testing-close" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    let config = WALConfig maxBound dir+    timeout 30_000_000 $ do+      (wal, appenders) <- withWriteAheadLog testCodec config $ \wal ->+        (wal,) <$> traverse (async . appendUntilClosed wal) entries+      successes <- traverse wait appenders++      appendAfterClose <- try (append wal (BS8.pack "too late"))++      replayed <- withWriteAheadLog testCodec config $ \wal' -> do+        replayedRef <- newIORef []+        replayAll wal' (\e -> modifyIORef' replayedRef (e :))+        reverse <$> readIORef replayedRef+      pure (successes, replayed, isLeft (appendAfterClose :: Either SomeException ()))++  case result of+    Nothing -> annotate "Timed out" >> failure+    Just (successes, replayed, appendAfterCloseFailed) -> do+      assert appendAfterCloseFailed+      sort replayed === sort (concat successes)+      for_ (zip entries successes) $ \(threadEntries, threadSuccesses) -> do+        assert (threadSuccesses `isPrefixOf` threadEntries)+        filter (`elem` threadEntries) replayed === threadSuccesses+  where+    appendUntilClosed _ [] = pure []+    appendUntilClosed wal (e : es) = do+      appended <- try (append wal e)+      case appended :: Either SomeException () of+        Left _ -> pure []+        Right () -> (e :) <$> appendUntilClosed wal es++testReplayWhileAppending :: TestTree+testReplayWhileAppending = testProperty "Replaying the active segment while appending to it sees a prefix of that segment" $ property $ do+  entries <- forAll genThreadEntries+  numReplays <- forAll $ Gen.int (Range.linear 1 20)+  maxBytes <- forAll $ Gen.choice [Gen.word64 (Range.linear 8 256), pure maxBound]++  result <- liftIO $ withSystemTempDirectory "wal-testing-replay" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    timeout 30_000_000 $ withWriteAheadLog testCodec (WALConfig maxBytes dir) $ \wal -> do+      let replay seg = do+            replayedRef <- newIORef []+            replaySegment wal seg (\e -> modifyIORef' replayedRef (e :))+            (seg,) . reverse <$> readIORef replayedRef+          replayActive = activeSegment wal >>= replay+      snapshots <-+        forConcurrently (Left numReplays : map Right entries) $+          either (`replicateM` replayActive) (\es -> [] <$ traverse_ (append wal) es)+      finals <- segments wal >>= traverse replay . toList+      pure (concat snapshots, finals)++  case result of+    Nothing -> annotate "Timed out" >> failure+    Just (snapshots, finals) -> do+      sort (concatMap snd finals) === sort (concat entries)+      for_ snapshots $ \(seg, snapshot) -> assert (any (\(s, final) -> s == seg && snapshot `isPrefixOf` final) finals)++testAppendWhileReplaying :: TestTree+testAppendWhileReplaying = testProperty "Appending while replaying the active segment doesn't block" $ property $ do+  before <- forAll $ Gen.list (Range.linear 1 10) (Gen.bytes (Range.linear 0 24))+  after <- forAll $ Gen.list (Range.linear 1 10) (Gen.bytes (Range.linear 0 24))++  result <- liftIO $ withSystemTempDirectory "wal-testing-append-replay" $ \tmpDir -> do+    dir <- encodeFS tmpDir+    timeout 10_000_000 $ withWriteAheadLog testCodec (WALConfig maxBound dir) $ \wal -> do+      for_ before (append wal)+      started <- newEmptyMVar+      proceed <- newEmptyMVar+      let replay onEntry = do+            replayedRef <- newIORef []+            seg <- activeSegment wal+            replaySegment wal seg (\e -> onEntry >> modifyIORef' replayedRef (e :))+            reverse <$> readIORef replayedRef+      -- The replay is held up mid-way, while this thread appends+      withAsync (replay (tryPutMVar started () >> readMVar proceed)) $ \replaying -> do+        takeMVar started+        for_ after (append wal)+        putMVar proceed ()+        (,) <$> wait replaying <*> replay (pure ())++  result === Just (before, before <> after)++genThreadEntries :: Gen [[StrictByteString]]+genThreadEntries = do+  paddings <- Gen.list (Range.linear 1 8) (Gen.list (Range.linear 0 20) (Gen.int (Range.linear 0 24)))+  pure+    [ [BS8.pack (show (thread, i)) <> BS.replicate padding 0 | (i, padding) <- zip [0 :: Int ..] threadPaddings]+    | (thread, threadPaddings) <- zip [0 :: Int ..] paddings+    ]++testCodec :: WALCodec StrictByteString+testCodec = WALCodec Builder.byteString pure
+ wal.cabal view
@@ -0,0 +1,97 @@+cabal-version:      3.4+name:               wal+version:            0.1.0.0+synopsis:           Write-ahead log implementation+-- 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:           System+build-type:         Simple+extra-doc-files:    README.md+                    CHANGELOG.md++source-repository head+    type: git+    location: https://github.com/LaurentRDC/distributed-consensus+    subdir: wal++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:  System.IO.WAL+                      System.IO.File.Durable+    build-depends:    attoparsec+                    , base >= 4.18 && <4.23+                      -- binary is already in the dependency closure, so adding+                      -- it here is "free"+                    , binary ^>=0.8+                    , bytestring ^>=0.12+                    , containers >=0.7 && <0.9+                    , crc32c ^>=0.2+                    , directory >=1.3.8.0 && <1.4+                    , filepath ^>=1.5+                    , file-io ^>=0.2+                    , os-string ^>=2.0+                    , exceptions ^>=0.10+                    , stm ^>=2.5+    hs-source-dirs:   src+    default-language: Haskell2010++    if os(windows)+      other-modules:    System.IO.File.Durable.Windows+      build-depends:  Win32 ^>=2.14+    else+      other-modules:    System.IO.File.Durable.Unix+      build-depends:  unix ^>=2.8++test-suite wal-test+    import:           warnings+    default-language: Haskell2010+    other-modules:    Test.System.IO.File.Durable+                      Test.System.IO.WAL+    type:             exitcode-stdio-1.0+    ghc-options:      -rtsopts -threaded -with-rtsopts=-N+    hs-source-dirs:   tests+    main-is:          Main.hs+    build-depends:    async+                    , base >= 4.18 && <4.23+                    , bytestring+                    , directory+                    , file-io+                    , filepath+                    , hedgehog ^>=1.7+                    , tasty ^>= 1.5+                    , tasty-hedgehog+                    , temporary+                    , wal++benchmark wal+  import:           warnings+  default-language: Haskell2010+  type:             exitcode-stdio-1.0+  hs-source-dirs:   bench+  main-is:          Main.hs+  ghc-options:      -rtsopts -threaded -with-rtsopts=-N+  build-depends:    async+                  , base+                  , binary+                  , bytestring+                  , filepath+                  , tasty+                  , tasty-bench+                  , temporary+                  , wal