42 lines
1.0 KiB
Haskell
42 lines
1.0 KiB
Haskell
module Breve.UrlTable
|
|
( UrlTable
|
|
, load
|
|
, insert
|
|
, extract
|
|
) where
|
|
|
|
import Breve.Generator
|
|
|
|
import Control.Monad (forever)
|
|
import Control.Concurrent (forkIO, threadDelay)
|
|
import Text.Read (readMaybe)
|
|
import qualified Data.HashTable.IO as H
|
|
|
|
type UrlTable = H.CuckooHashTable Name Url
|
|
|
|
-- | Periodically write a url table to a file
|
|
sync :: UrlTable -> FilePath -> IO ()
|
|
sync table file = forever $ do
|
|
threadDelay (round 3.0e8)
|
|
content <- show <$> H.toList table
|
|
writeFile file content
|
|
|
|
-- | Load a url table from a file
|
|
load :: FilePath -> IO UrlTable
|
|
load file = do
|
|
content <- readFile file
|
|
table <- case readMaybe content of
|
|
Just list -> H.fromList list
|
|
Nothing -> H.new
|
|
forkIO (sync table file)
|
|
return table
|
|
|
|
-- | Insert the url in a table and return the name
|
|
insert :: UrlTable -> Url -> IO Name
|
|
insert table url = H.insert table new url >> return new
|
|
where new = nameHash url
|
|
|
|
-- | Lookup a table for the associated url
|
|
extract :: UrlTable -> Name -> IO (Maybe Url)
|
|
extract = H.lookup
|