2015-12-23 22:34:51 +00:00
|
|
|
{- Handle for the Keys database.
|
|
|
|
-
|
|
|
|
- Copyright 2015 Joey Hess <id@joeyh.name>
|
|
|
|
-:
|
2019-03-13 19:48:14 +00:00
|
|
|
- Licensed under the GNU AGPL version 3 or higher.
|
2015-12-23 22:34:51 +00:00
|
|
|
-}
|
|
|
|
|
|
|
|
module Database.Keys.Handle (
|
|
|
|
DbHandle,
|
|
|
|
newDbHandle,
|
2016-07-19 18:02:49 +00:00
|
|
|
unavailableDbHandle,
|
2015-12-23 22:34:51 +00:00
|
|
|
DbState(..),
|
|
|
|
withDbState,
|
|
|
|
flushDbQueue,
|
2016-05-16 18:49:12 +00:00
|
|
|
closeDbHandle,
|
2015-12-23 22:34:51 +00:00
|
|
|
) where
|
|
|
|
|
|
|
|
import qualified Database.Queue as H
|
|
|
|
import Utility.Exception
|
|
|
|
|
|
|
|
import Control.Concurrent
|
|
|
|
import Control.Monad.IO.Class (liftIO, MonadIO)
|
2015-12-28 21:21:26 +00:00
|
|
|
import Control.Applicative
|
|
|
|
import Prelude
|
2015-12-23 22:34:51 +00:00
|
|
|
|
|
|
|
-- The MVar is always left full except when actions are run
|
|
|
|
-- that access the database.
|
|
|
|
newtype DbHandle = DbHandle (MVar DbState)
|
|
|
|
|
|
|
|
-- The database can be closed or open, but it also may have been
|
2016-02-12 18:15:28 +00:00
|
|
|
-- tried to open (for read) and didn't exist yet or is not readable.
|
|
|
|
data DbState = DbClosed | DbOpen H.DbQueue | DbUnavailable
|
2015-12-23 22:34:51 +00:00
|
|
|
|
|
|
|
newDbHandle :: IO DbHandle
|
|
|
|
newDbHandle = DbHandle <$> newMVar DbClosed
|
|
|
|
|
2016-07-19 18:02:49 +00:00
|
|
|
unavailableDbHandle :: IO DbHandle
|
|
|
|
unavailableDbHandle = DbHandle <$> newMVar DbUnavailable
|
|
|
|
|
2015-12-23 22:34:51 +00:00
|
|
|
-- Runs an action on the state of the handle, which can change its state.
|
|
|
|
-- The MVar is empty while the action runs, which blocks other users
|
|
|
|
-- of the handle from running.
|
|
|
|
withDbState
|
|
|
|
:: (MonadIO m, MonadCatch m)
|
|
|
|
=> DbHandle
|
2016-05-16 18:49:12 +00:00
|
|
|
-> (DbState -> m (v, DbState))
|
2015-12-23 22:34:51 +00:00
|
|
|
-> m v
|
|
|
|
withDbState (DbHandle mvar) a = do
|
|
|
|
st <- liftIO $ takeMVar mvar
|
|
|
|
go st `onException` (liftIO $ putMVar mvar st)
|
|
|
|
where
|
|
|
|
go st = do
|
|
|
|
(v, st') <- a st
|
|
|
|
liftIO $ putMVar mvar st'
|
|
|
|
return v
|
|
|
|
|
|
|
|
flushDbQueue :: DbHandle -> IO ()
|
|
|
|
flushDbQueue (DbHandle mvar) = go =<< readMVar mvar
|
|
|
|
where
|
|
|
|
go (DbOpen qh) = H.flushDbQueue qh
|
|
|
|
go _ = return ()
|
2016-05-16 18:49:12 +00:00
|
|
|
|
|
|
|
closeDbHandle :: DbHandle -> IO ()
|
|
|
|
closeDbHandle h = withDbState h go
|
|
|
|
where
|
|
|
|
go (DbOpen qh) = do
|
|
|
|
H.closeDbQueue qh
|
|
|
|
return ((), DbClosed)
|
|
|
|
go st = return ((), st)
|