aboutsummaryrefslogtreecommitdiff
path: root/src/Cache.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Cache.hs')
-rw-r--r--src/Cache.hs46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/Cache.hs b/src/Cache.hs
new file mode 100644
index 0000000..b009770
--- /dev/null
+++ b/src/Cache.hs
@@ -0,0 +1,46 @@
+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)