packages feed

orchid-0.0.6: src/Network/Orchid/Backend/CachingBackend.hs

module Network.Orchid.Backend.CachingBackend (cachingBackend) where

#if (__GLASGOW_HASKELL__ < 609)
import Control.Exception hiding (IOException)
#else
import Control.Exception
#endif

import System.Posix.Files
import System.Directory
import qualified System.IO.UTF8 as U

import Network.Orchid.Core.Backend

#if (__GLASGOW_HASKELL__ < 609)
type IOException = Exception
#endif

cachingBackend :: FilePath -> Backend -> Backend
cachingBackend cache backend = Backend {
    store    = store backend
  , delete   = delete backend
  , retrieve = cachedRetrieve cache backend
  , history  = history backend
  }

-------- backend procedures ---------------------------------------------------

cachedRetrieve :: FilePath -> Backend -> FilePath -> Revision -> IO (Maybe String)
cachedRetrieve cache backend file rev = do
  hit <- (try $ U.readFile $ concat [cache, file, "?", name rev]) :: IO (Either IOException String)
  case hit of
    -- Cache hit, use this one.
    Right doc -> return $ Just doc
    -- No cache hit, forward to backend and store in cache dir.
    Left e -> do
      doc <- retrieve backend file rev
--       maybe (return ()) (U.writeFile $ concat [cache, file, "?", name rev]) doc
      return doc