module Cache (newInMemory, start, CacheM, getInbox) where import Control.Concurrent.STM ( TVar , atomically , newTVarIO , readTVar , readTVarIO , writeTVar ) import Intro import qualified Mail as M import qualified Queue as Q data Cache = Cache { count :: Int , inbox :: [M.Mail] } type CacheM = TVar Cache newInMemory :: IO CacheM newInMemory = newTVarIO newCache start :: Q.QueueM M.Mail -> CacheM -> IO () start queue cache = go where go :: IO () go = do mail <- Q.pull queue updateCache cache (`addMail` mail) go getInbox :: CacheM -> IO [M.Mail] getInbox c = inbox <$> readTVarIO c newCache :: Cache newCache = Cache 0 [] addMail :: Cache -> M.Mail -> Cache addMail cache mail = cache{count = count cache + 1, inbox = mail : inbox cache} updateCache :: CacheM -> (Cache -> Cache) -> IO () updateCache c f = atomically $ do cache <- readTVar c writeTVar c (f cache)