shrub/pkg/hair/lib/Vere/Log.hs

55 lines
1.4 KiB
Haskell
Raw Normal View History

module Vere.Log where
import Database.LMDB.Raw
2019-05-29 21:33:09 +03:00
import ClassyPrelude
import Data.Void
import Data.ByteString.Unsafe
2019-05-29 03:32:39 +03:00
import GHC.Ptr (castPtr)
--------------------------------------------------------------------------------
data State = State
{ env :: MDB_env
, q :: TQueue Void
}
2019-05-29 03:32:39 +03:00
--------------------------------------------------------------------------------
init :: FilePath -> IO State
init dir = do
env <- mdb_env_create
mdb_env_set_maxdbs env 3
mdb_env_set_mapsize env (40 * 1024 * 1024 * 1024)
mdb_env_open env dir []
tq <- newTQueueIO
pure (State env tq)
shutdown :: State -> IO ()
shutdown s = mdb_env_close (env s)
2019-05-29 03:32:39 +03:00
--------------------------------------------------------------------------------
2019-05-29 21:33:09 +03:00
{-
Read one or more items from a TQueue, only blocking on the first item.
-}
readQueue :: TQueue a -> STM (NonNull [a])
2019-05-29 03:32:39 +03:00
readQueue q =
readTQueue q >>= go . singleton
where
2019-05-29 21:33:09 +03:00
go acc =
tryReadTQueue q >>= \case
Nothing -> pure (reverse acc)
Just item -> go (item <| acc)
2019-05-29 03:32:39 +03:00
byteStringAsMdbVal :: ByteString -> (MDB_val -> IO a) -> IO a
byteStringAsMdbVal bs k =
unsafeUseAsCStringLen bs \(ptr,sz) ->
k (MDB_val (fromIntegral sz) (castPtr ptr))
2019-05-29 21:33:09 +03:00
putRaw :: MDB_WriteFlags -> MDB_txn -> MDB_dbi -> ByteString -> ByteString
-> IO Bool
putRaw flags txn db key val =
2019-05-29 03:32:39 +03:00
byteStringAsMdbVal key \mKey ->
byteStringAsMdbVal val \mVal ->
mdb_put flags txn db mKey mVal