pykinos-core-0.1.1.0: src/Pykinos/Storage/WalSlab.hs
{-# LANGUAGE BangPatterns #-}
-- | Module: Pykinos.Storage.WalSlab
-- Description: Segmented append-only write-ahead log (WAL) with Castagnoli CRC32C framing
-- License: EUPL-1.2 OR Apache-2.0
--
-- Frames records as @(magic :: Word32, len :: Word32, epoch :: Word64, crc32c :: Word32, payload)@
-- with deterministic torn-tail recovery on replay. Pure Castagnoli CRC32C protects data integrity.
module Pykinos.Storage.WalSlab
( WalRecord(..)
, WalSlab
, newWalSlab
, appendWalRecord
, walSlabBytes
, replayWalSlab
, computeCrc32c
) where
import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar, readMVar)
import Control.Monad.ST (runST)
import Data.Bits (shiftL, shiftR, xor, (.&.), (.|.))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.ByteString (ByteString)
import Data.Primitive.PrimArray
( PrimArray
, indexPrimArray
, newPrimArray
, unsafeFreezePrimArray
, writePrimArray
)
import Data.Word (Word32, Word64, Word8)
-- | Fixed 32-bit WAL header magic token: "WAL0" (0x57414C30).
walMagic :: Word32
walMagic = 0x57414C30
-- | Individual record extracted from a WAL slab.
data WalRecord = WalRecord
{ recEpoch :: {-# UNPACK #-} !Word64
, recPayload :: !ByteString
} deriving stock (Eq, Show)
-- | In-memory append-only WAL buffer.
newtype WalSlab = WalSlab (MVar BSL.ByteString)
-- | Creates an empty WAL buffer.
newWalSlab :: IO WalSlab
newWalSlab = WalSlab <$> newMVar BSL.empty
-- | Castagnoli CRC32C lookup table (polynomial 0x82F63B78).
crc32cTable :: PrimArray Word32
crc32cTable = runST $ do
marr <- newPrimArray 256
let fill !i
| i >= 256 = pure ()
| otherwise = do
writePrimArray marr i (makeEntry i)
fill (i + 1)
fill 0
unsafeFreezePrimArray marr
where
makeEntry !b = go (8 :: Int) (fromIntegral b :: Word32)
go 0 !crc = crc
go !step !crc
| crc .&. 1 /= 0 = go (step - 1) ((crc `shiftR` 1) `xor` 0x82F63B78)
| otherwise = go (step - 1) (crc `shiftR` 1)
-- | Computes the Castagnoli CRC32C checksum of a ByteString.
computeCrc32c :: ByteString -> Word32
computeCrc32c bs =
let !crc0 = 0xFFFFFFFF :: Word32
!crcFinal = BS.foldl' updateCrc crc0 bs
in crcFinal `xor` 0xFFFFFFFF
where
updateCrc !crc !b =
let !idx = fromIntegral ((crc `xor` fromIntegral b) .&. 0xFF)
!entry = indexPrimArray crc32cTable idx
in (crc `shiftR` 8) `xor` entry
-- | Serializes a 32-bit word into 4 bytes (little-endian).
putWord32LE :: Word32 -> [Word8]
putWord32LE !w =
[ fromIntegral (w .&. 0xFF)
, fromIntegral ((w `shiftR` 8) .&. 0xFF)
, fromIntegral ((w `shiftR` 16) .&. 0xFF)
, fromIntegral ((w `shiftR` 24) .&. 0xFF)
]
-- | Serializes a 64-bit word into 8 bytes (little-endian).
putWord64LE :: Word64 -> [Word8]
putWord64LE !w =
[ fromIntegral (w .&. 0xFF)
, fromIntegral ((w `shiftR` 8) .&. 0xFF)
, fromIntegral ((w `shiftR` 16) .&. 0xFF)
, fromIntegral ((w `shiftR` 24) .&. 0xFF)
, fromIntegral ((w `shiftR` 32) .&. 0xFF)
, fromIntegral ((w `shiftR` 40) .&. 0xFF)
, fromIntegral ((w `shiftR` 48) .&. 0xFF)
, fromIntegral ((w `shiftR` 56) .&. 0xFF)
]
-- | Decodes a 32-bit word from 4 bytes (little-endian).
getWord32LE :: ByteString -> Word32
getWord32LE bs =
let b0 = fromIntegral (BS.index bs 0) :: Word32
b1 = fromIntegral (BS.index bs 1) :: Word32
b2 = fromIntegral (BS.index bs 2) :: Word32
b3 = fromIntegral (BS.index bs 3) :: Word32
in b0 .|. (b1 `shiftL` 8) .|. (b2 `shiftL` 16) .|. (b3 `shiftL` 24)
-- | Decodes a 64-bit word from 8 bytes (little-endian).
getWord64LE :: ByteString -> Word64
getWord64LE bs =
let b0 = fromIntegral (BS.index bs 0) :: Word64
b1 = fromIntegral (BS.index bs 1) :: Word64
b2 = fromIntegral (BS.index bs 2) :: Word64
b3 = fromIntegral (BS.index bs 3) :: Word64
b4 = fromIntegral (BS.index bs 4) :: Word64
b5 = fromIntegral (BS.index bs 5) :: Word64
b6 = fromIntegral (BS.index bs 6) :: Word64
b7 = fromIntegral (BS.index bs 7) :: Word64
in b0 .|. (b1 `shiftL` 8) .|. (b2 `shiftL` 16) .|. (b3 `shiftL` 24)
.|. (b4 `shiftL` 32) .|. (b5 `shiftL` 40) .|. (b6 `shiftL` 48) .|. (b7 `shiftL` 56)
-- | Appends a record to the WAL buffer with Castagnoli CRC32C framing.
appendWalRecord :: WalSlab -> Word64 -> ByteString -> IO ()
appendWalRecord (WalSlab mvar) !epoch !payload = do
let !len = fromIntegral (BS.length payload) :: Word32
!crc = computeCrc32c payload
!headerBytes = BS.pack $ concat
[ putWord32LE walMagic
, putWord32LE len
, putWord64LE epoch
, putWord32LE crc
]
!chunk = BSL.fromStrict (headerBytes <> payload)
modifyMVar_ mvar (\buf -> pure (buf <> chunk))
-- | Returns the entire current byte stream of the WAL buffer.
walSlabBytes :: WalSlab -> IO ByteString
walSlabBytes (WalSlab mvar) = BSL.toStrict <$> readMVar mvar
-- | Replays a WAL byte stream, verifying headers and checksums.
-- Returns @(validRecords, tornTailDetected)@.
replayWalSlab :: ByteString -> ([WalRecord], Bool)
replayWalSlab bytes = go bytes []
where
go !remBytes !acc
| BS.null remBytes = (reverse acc, False)
| BS.length remBytes < 20 =
-- Fewer than 20 bytes remaining: torn header detected
(reverse acc, True)
| otherwise =
let !magic = getWord32LE (BS.take 4 remBytes)
!len = fromIntegral (getWord32LE (BS.take 4 (BS.drop 4 remBytes))) :: Int
!epoch = getWord64LE (BS.take 8 (BS.drop 8 remBytes))
!crc = getWord32LE (BS.take 4 (BS.drop 16 remBytes))
in if magic /= walMagic || BS.length remBytes < 20 + len
then (reverse acc, True)
else
let !payload = BS.take len (BS.drop 20 remBytes)
!actualCrc = computeCrc32c payload
in if actualCrc /= crc
then (reverse acc, True) -- Corrupted payload: torn tail detected
else
let !rec = WalRecord epoch payload
!nextRem = BS.drop (20 + len) remBytes
in go nextRem (rec : acc)