2022-03-21 13:39:49 +03:00
|
|
|
module Hasura.GraphQL.Execute.Subscription.TMap
|
2019-08-28 15:19:21 +03:00
|
|
|
( TMap,
|
|
|
|
new,
|
|
|
|
reset,
|
|
|
|
null,
|
|
|
|
lookup,
|
|
|
|
insert,
|
|
|
|
delete,
|
|
|
|
toList,
|
2022-03-21 13:39:49 +03:00
|
|
|
replace,
|
|
|
|
union,
|
|
|
|
filterWithKey,
|
|
|
|
getMap,
|
2019-08-28 15:19:21 +03:00
|
|
|
)
|
|
|
|
where
|
2021-09-24 01:56:37 +03:00
|
|
|
|
2019-08-28 15:19:21 +03:00
|
|
|
import Control.Concurrent.STM
|
|
|
|
import Data.HashMap.Strict qualified as Map
|
2022-03-21 13:39:49 +03:00
|
|
|
import Hasura.Prelude hiding (lookup, null, toList, union)
|
2019-08-28 15:19:21 +03:00
|
|
|
|
|
|
|
-- | A coarse-grained transactional map implemented by simply wrapping a 'Map.HashMap' in a 'TVar'.
|
|
|
|
-- Compared to "StmContainers.Map", this provides much faster iteration over the elements at the
|
|
|
|
-- cost of significantly increased contention on writes.
|
|
|
|
newtype TMap k v = TMap {unTMap :: TVar (Map.HashMap k v)}
|
|
|
|
|
|
|
|
new :: STM (TMap k v)
|
|
|
|
new = TMap <$> newTVar Map.empty
|
|
|
|
|
|
|
|
reset :: TMap k v -> STM ()
|
|
|
|
reset = flip writeTVar Map.empty . unTMap
|
|
|
|
|
|
|
|
null :: TMap k v -> STM Bool
|
|
|
|
null = fmap Map.null . readTVar . unTMap
|
|
|
|
|
2022-11-15 14:25:04 +03:00
|
|
|
lookup :: Hashable k => k -> TMap k v -> STM (Maybe v)
|
2019-08-28 15:19:21 +03:00
|
|
|
lookup k = fmap (Map.lookup k) . readTVar . unTMap
|
|
|
|
|
2022-11-15 14:25:04 +03:00
|
|
|
insert :: Hashable k => v -> k -> TMap k v -> STM ()
|
2020-03-18 04:31:22 +03:00
|
|
|
insert !v k mapTv = modifyTVar' (unTMap mapTv) $ Map.insert k v
|
2019-08-28 15:19:21 +03:00
|
|
|
|
2022-11-15 14:25:04 +03:00
|
|
|
delete :: Hashable k => k -> TMap k v -> STM ()
|
2019-08-28 15:19:21 +03:00
|
|
|
delete k mapTv = modifyTVar' (unTMap mapTv) $ Map.delete k
|
|
|
|
|
|
|
|
toList :: TMap k v -> STM [(k, v)]
|
|
|
|
toList = fmap Map.toList . readTVar . unTMap
|
2022-03-21 13:39:49 +03:00
|
|
|
|
|
|
|
filterWithKey :: (k -> v -> Bool) -> TMap k v -> STM ()
|
|
|
|
filterWithKey f mapTV = modifyTVar' (unTMap mapTV) $ Map.filterWithKey f
|
|
|
|
|
|
|
|
replace :: TMap k v -> Map.HashMap k v -> STM ()
|
|
|
|
replace mapTV v = void $ swapTVar (unTMap mapTV) v
|
|
|
|
|
2022-11-15 14:25:04 +03:00
|
|
|
union :: Hashable k => TMap k v -> TMap k v -> STM (TMap k v)
|
2022-03-21 13:39:49 +03:00
|
|
|
union mapA mapB = do
|
|
|
|
l <- readTVar $ unTMap mapA
|
|
|
|
r <- readTVar $ unTMap mapB
|
|
|
|
TMap <$> newTVar (Map.union l r)
|
|
|
|
|
|
|
|
getMap :: TMap k v -> STM (Map.HashMap k v)
|
|
|
|
getMap = readTVar . unTMap
|