packages feed

hs-hath-1.4.0: test/FilesystemSpec.hs

{-# LANGUAGE DataKinds #-}

module FilesystemSpec ( filesystemSpecs ) where

import           Colog                 ( LogAction(..), Message )
import           Colog.Polysemy        ( Log, runLogAction )

import qualified Data.ByteString       as BS
import           Data.Time.Clock.POSIX ( getPOSIXTime, posixSecondsToUTCTime )

import           Hath.Cache            ( Cache, CacheHit(..), deleteFile, lookupFile, storeFile )
import           Hath.Cache.Filesystem ( FsCache
                                       , cachedBytes
                                       , cachedFiles
                                       , evict
                                       , openFsCache
                                       , runCacheFilesystem
                                       , saveState
                                       )
import           Hath.Error            ( HathError )
import           Hath.FileURI          ( FileURI(..) )
import           Hath.Protocol         ( sha1Hex )

import           Polysemy
import           Polysemy.Error        ( Error, runError )

import           Relude

import           System.Directory      ( createDirectoryIfMissing
                                       , doesFileExist
                                       , removeDirectory
                                       , removeFile
                                       , setModificationTime
                                       )
import           System.FilePath       ( (</>), takeDirectory )
import           System.IO.Temp        ( withSystemTempDirectory )

import           Test.Hspec

uriFor :: ByteString -> FileURI
uriFor content
  = FileURI { fileHash = sha1Hex content
            , fileSize = BS.length content
            , fileXRes = 800
            , fileYRes = 600
            , fileExt  = "jpg"
            }

runFs :: FsCache -> Sem '[ Cache, Log Message, Error HathError, Embed IO ] a -> IO a
runFs fs program = do
  result <- runM
    . runError @HathError
    . runLogAction @IO @Message (LogAction $ const pass)
    . runCacheFilesystem fs
    $ program
  either (\e -> fail $ "unexpected error: " <> show e) pure result

store :: FsCache -> ByteString -> IO ()
store fs content = runFs fs $ storeFile (uriFor content) content

served :: FsCache -> ByteString -> IO (Maybe FilePath)
served fs content = runFs fs (lookupFile (uriFor content)) <&> \case
  Just (LocalFile path) -> Just path
  _ -> Nothing

withCache :: (FilePath -> FsCache -> IO a) -> IO a
withCache k = withSystemTempDirectory "hath-test" $ \tmp -> do
  let root = tmp </> "cache"
  open root >>= k root

open :: FilePath -> IO FsCache
open root = openFsCache root (pure 0) False False

age :: Int -> FilePath -> IO ()
age days path = do
  now <- getPOSIXTime
  setModificationTime path (posixSecondsToUTCTime (now - fromIntegral (days * 86400)))

filesystemSpecs :: Spec
filesystemSpecs = describe "Filesystem cache" $ do
  let content = "test content for Filesystem storage"

  it "stores a file and serves hits straight from disk" $ withCache $ \_ fs -> do
    store fs content
    served fs content >>= \case
      Nothing   -> expectationFailure "expected a hit"
      Just path -> readFileBS path >>= (`shouldBe` content)

  it "misses a file it never stored" $ withCache $ \_ fs -> served fs content
    >>= (`shouldBe` Nothing)

  it "drops a truncated file instead of serving it" $ withCache $ \_ fs -> do
    store fs content
    Just path <- served fs content
    writeFileBS path (BS.take 5 content)
    served fs content >>= (`shouldBe` Nothing)
    doesFileExist path >>= (`shouldBe` False)

  it "deletes a file; deleting one it does not have is no error" $ withCache $ \_ fs -> do
    store fs content
    Just path <- served fs content
    runFs fs $ deleteFile (uriFor content)
    doesFileExist path >>= (`shouldBe` False)
    served fs content >>= (`shouldBe` Nothing)
    runFs fs $ deleteFile (uriFor content)

  it "evicts the least recently served files, and only its own" $ withCache $ \root fs -> do
    let ( a, b, c ) = ( BS.replicate 1000 97, BS.replicate 1000 98, BS.replicate 1000 99 )
    paths <- forM [ a, b, c ] $ \x -> store fs x >> fromMaybe (error "stored") <$> served fs x
    forM_ (zip paths [ 100, 200, 300 ]) $ \( p, t )
      -> setModificationTime p (posixSecondsToUTCTime t)
    createDirectoryIfMissing True (root </> "abcd")
    writeFileBS (root </> "notes.txt") "not ours"
    writeFileBS (root </> "abcd" </> "other") "not ours"
    -- the ages as files on disk have them, which serving a then changes
    fs' <- openFsCache root (pure 0) True False
    void $ served fs' a
    evict fs' 1000 >>= (`shouldBe` ( 1, 1000 ))
    mapM doesFileExist paths >>= (`shouldBe` [ True, False, True ])
    mapM doesFileExist [ root </> "notes.txt", root </> "abcd" </> "other" ]
      >>= (`shouldBe` [ True, True ])
    cachedBytes fs' `shouldReturn` 2000

  it "evicts nothing from an empty cache" $ withCache $ \_ fs -> evict fs 1000 `shouldReturn` ( 0, 0 )

  it "takes the totals saved at shutdown instead of scanning, once" $ withCache $ \root fs -> do
    store fs content
    saveState fs
    -- a file the saved totals do not know of
    let other = "another file, stored behind the cache's back"
        dir   = decodeUtf8 (BS.take 4 (sha1Hex other))
    createDirectoryIfMissing True (root </> dir)
    writeFileBS (root </> dir </> (dir <> "-other")) other
    reopened <- open root
    cachedFiles reopened `shouldReturn` 1
    cachedBytes reopened `shouldReturn` fromIntegral (BS.length content)
    -- they were used up: a crash now must not leave them for the next start
    rescanned <- open root
    cachedFiles rescanned `shouldReturn` 2

  it "scans when a directory the saved totals name is gone" $ withCache $ \root fs -> do
    store fs content
    Just path <- served fs content
    saveState fs
    removeFile path
    removeDirectory (takeDirectory path)
    reopened <- open root
    cachedFiles reopened `shouldReturn` 0

  it "checks a file not served for a week before serving it" $ withCache $ \_ fs -> do
    store fs content
    Just path <- served fs content
    let corrupt = BS.map (const 120) content
    writeFileBS path corrupt
    -- served recently: not checked yet
    served fs content >>= (`shouldBe` Just path)
    age 8 path
    served fs content >>= (`shouldBe` Nothing)
    doesFileExist path >>= (`shouldBe` False)
    cachedFiles fs `shouldReturn` 0

  it "serves an intact file not served for a week" $ withCache $ \_ fs -> do
    store fs content
    Just path <- served fs content
    age 8 path
    served fs content >>= (`shouldBe` Just path)

  it "deletes the files that fail their SHA-1 when verifying at start" $ withCache $ \root fs -> do
    store fs content
    Just path <- served fs content
    writeFileBS path (BS.map (const 120) content)
    verified <- openFsCache root (pure 0) False True
    cachedFiles verified `shouldReturn` 0
    doesFileExist path >>= (`shouldBe` False)

  it "does not store a file that would leave the disk under its reserve"
    $ withSystemTempDirectory "hath-test" $ \tmp -> do
      fs <- openFsCache tmp (pure (2 ^ (62 :: Int))) False False
      store fs content
      served fs content >>= (`shouldBe` Nothing)
      cachedFiles fs `shouldReturn` 0