packages feed

hs-hath-1.4.0: src/Hath/Cache/Filesystem.hs

{-# LANGUAGE DataKinds #-}

-- | The Filesystem backend: files on disk as @root\/xxxx\/fileid@, a directory per
-- static range. Hits are served straight from the file ('LocalFile'); the file's
-- mtime is the LRU clock, and 'runEvictor' keeps the cache under the disk limit
-- the server assigns.
module Hath.Cache.Filesystem
  ( FsCache
  , openFsCache
  , cachedFiles
  , cachedBytes
  , saveState
  , runCacheFilesystem
  , runEvictor
  , evict
  ) where

import           Colog                   ( Message )
import           Colog.Polysemy          ( Log )

import           Control.Concurrent      ( threadDelay )

import           Crypto.Hash             ( SHA1, hashlazy )

import           Data.ByteArray.Encoding ( Base(Base16), convertToBase )
import qualified Data.ByteString.Char8   as BS
import qualified Data.Map.Strict         as Map
import qualified Data.Set                as Set
import           Data.String.Interpolate ( i )
import qualified Data.Text               as T
import           Data.Time.Clock.POSIX   ( getPOSIXTime )

import           Hath.AtomicFile         ( writeFileAtomic )
import           Hath.Cache              ( Cache(..), CacheHit(..) )
import           Hath.Cache.FileStatus   ( regularFile, touch )
import           Hath.DiskSpace          ( availableBytes )
import           Hath.Error              ( HathError(..) )
import           Hath.FileURI            ( FileURI(..), parseFileURI, renderFileURIBytes )
import           Hath.Log                ( logError, logWarning )

import           Polysemy
import           Polysemy.Error          ( Error, throw )

import           Relude

import           System.Directory        ( createDirectoryIfMissing
                                         , doesDirectoryExist
                                         , listDirectory
                                         , removeFile
                                         )
import           System.FilePath         ( (</>), takeDirectory, takeFileName )

import           UnliftIO.Exception      ( tryAny )

data FsCache
  = FsCache { fsRoot    :: !FilePath
            , fsReserve :: !(IO Int64)
              -- ^ minimum free bytes to keep on disk
            , fsRanges  :: !(IORef (Map Text Range))
              -- ^ by directory; one that holds nothing has no entry
            }

data Range = Range { rangeBytes :: !Int64, rangeFiles :: !Int, rangeOldest :: !Int64 }
  deriving ( Eq, Show )

-- | Open the cache at @root@ with what the last shutdown saved of it, or else
-- scan it (official CacheHandler.java:83-160); @rescan@ ignores what was saved,
-- and @verify@ also checks every file's SHA-1, deleting those that fail.
openFsCache :: FilePath -> IO Int64 -> Bool -> Bool -> IO FsCache
openFsCache root reserve rescan verify = do
  createDirectoryIfMissing True root
  saved <- if rescan || verify
    then pure Nothing
    else loadState root
  -- from now on the file would be out of date, and a crash must not leave it behind
  void $ tryAny $ removeFile (statePath root)
  ranges <- case saved of
    Just ranges -> ranges <$ putStrLn [i|Cache: #{describe ranges}, as saved at the last shutdown|]
    Nothing     -> do
      putStrLn $ if verify
        then "Verifying the cache..."
        else "Scanning the cache..."
      ( ranges, corrupt ) <- scan root verify
      putStrLn [i|Cache: #{describe ranges}|]
      when (corrupt > 0) $ putStrLn [i|Deleted #{corrupt} files that failed their SHA-1 check|]
      pure ranges
  FsCache root reserve <$> newIORef ranges
  where
    describe ranges
      = [i|#{sum (rangeFiles <$> ranges)} files, #{sum (rangeBytes <$> ranges) `div` mib} MiB|]
        :: Text

cachedFiles :: FsCache -> IO Int
cachedFiles fs = sum . fmap rangeFiles <$> readIORef (fsRanges fs)

cachedBytes :: FsCache -> IO Int64
cachedBytes fs = sum . fmap rangeBytes <$> readIORef (fsRanges fs)

statePath :: FilePath -> FilePath
statePath root = root </> "hs-hath.state"

stateHeader :: Text
stateHeader = "hs-hath cache state 1"

saveState :: FsCache -> IO ()
saveState fs = do
  ranges <- readIORef (fsRanges fs)
  -- an empty state file would skip the scan even if the cache files return
  unless (null ranges) $ writeFileAtomic (statePath (fsRoot fs)) $ encodeUtf8 $ unlines $ stateHeader
    : [ unwords [ dir, show bytes, show files, show oldest ]
      | ( dir, Range bytes files oldest ) <- Map.toList ranges
      ]

loadState :: FilePath -> IO (Maybe (Map Text Range))
loadState root = tryAny (decodeUtf8 <$> readFileBS (statePath root)) >>= \case
  Right content
    | header : rows <- lines content, header == stateHeader, Just ranges <- traverse row rows -> do
      present <- allM (doesDirectoryExist . (root </>) . toString . fst) ranges
      pure $ Map.fromList ranges <$ guard present
  _ -> pure Nothing
  where
    row line = case words line of
      [ dir, bytes, files, oldest ]
        | T.length dir == 4 -> (,) dir
          <$> (Range <$> readMaybe (toString bytes) <*> readMaybe (toString files)
               <*> readMaybe (toString oldest))
      _ -> Nothing

scan :: FilePath -> Bool -> IO ( Map Text Range, Int )
scan root verify = do
  dirs <- filter ((== 4) . length) <$> listDirectory root
  foldlM visit ( mempty, 0 ) dirs
  where
    visit ( ranges, corrupt ) dir = do
      files <- listRange root (toText dir)
      kept <- if verify
        then filterM intact files
        else pure files
      let range = Range (sum [ size | ( _, size, _ ) <- kept ]) (length kept)
            (foldl' min maxBound [ mtime | ( mtime, _, _ ) <- kept ]) <$ guard (not (null kept))
      pure ( maybe ranges (\r -> Map.insert (toText dir) r ranges) range
           , corrupt + length files - length kept
           )

    intact ( _, _, path ) = case parseFileURI (BS.pack (takeFileName path)) of
      Nothing  -> pure True
      Just uri -> tryAny (sha1File path) >>= \case
        Right hash
          | hash /= fileHash uri -> False <$ tryAny (removeFile path)
        _ -> pure True

-- | (mtime, size, path) of our files in one directory: those named for it.
listRange :: FilePath -> Text -> IO [ ( Int64, Int64, FilePath ) ]
listRange root dir = do
  names <- fromRight [] <$> tryAny (listDirectory (root </> toString dir))
  fmap catMaybes $ forM (filter (toString dir `isPrefixOf`) names) $ \name -> do
    let path = root </> toString dir </> name
    tryAny (regularFile path) <&> \case
      Right (Just ( size, mtime )) -> Just ( mtime, size, path )
      _ -> Nothing

sha1File :: FilePath -> IO ByteString
sha1File path = do
  content <- readFileLBS path
  pure $! convertToBase Base16 (hashlazy @SHA1 content)

fileURIToPath :: FilePath -> FileURI -> FilePath
fileURIToPath root uri = root </> take 4 fileId </> fileId
  where
    -- no directory traversal through a crafted file id. A file id is ASCII
    -- ('Hath.FileURI.parseFileURI' admits nothing else), so Char8 reads it exactly.
    fileId = takeFileName (BS.unpack (renderFileURIBytes uri))

rangeOf :: FilePath -> Text
rangeOf = toText . takeFileName . takeDirectory

added :: FsCache -> FilePath -> Int64 -> Int64 -> IO ()
added fs path size mtime = atomicModifyIORef'_ (fsRanges fs)
  $ Map.insertWith grow (rangeOf path) (Range size 1 mtime)
  where
    grow _ r = Range (rangeBytes r + size) (rangeFiles r + 1) (min mtime (rangeOldest r))

removeCached :: FsCache -> FilePath -> Int64 -> IO (Either SomeException ())
removeCached fs path size = do
  removed <- tryAny (removeFile path)
  whenRight_ removed $ \() -> atomicModifyIORef'_ (fsRanges fs) $ Map.update shrink (rangeOf path)
  pure removed
  where
    shrink r
      | rangeFiles r <= 1 = Nothing
      | otherwise = Just r { rangeBytes = rangeBytes r - size, rangeFiles = rangeFiles r - 1 }

-- | A file served before this long ago gets its SHA-1 checked before it is
-- served again (official CacheHandler.java:417, a week).
checkAfterSeconds :: Int64
checkAfterSeconds = 7 * 86400

runCacheFilesystem :: Members '[ Embed IO, Log Message, Error HathError ] r
                   => FsCache
                   -> Sem (Cache : r) a
                   -> Sem r a
runCacheFilesystem fs = interpret $ \case
  LookupFile uri      -> do
    let path = fileURIToPath (fsRoot fs) uri
    embed (tryAny (regularFile path)) >>= \case
      Right (Just ( size, mtime ))
        | size /= fromIntegral (fileSize uri) -> do
          -- truncated (written in place by an older version): drop it so it gets refetched
          void $ embed $ removeCached fs path size
          pure Nothing
        | otherwise -> do
          now <- embed unixTime
          intact <- if mtime < now - checkAfterSeconds
            then embed $ either (const True) (== fileHash uri) <$> tryAny (sha1File path)
            else pure True
          if intact
            then do
              -- a hit makes the file the newest, so eviction takes it last
              void $ embed $ tryAny $ touch path
              pure $ Just $ LocalFile path
            else do
              logWarning [i|#{uri} failed its SHA-1 check; deleted from the cache|]
              void $ embed $ removeCached fs path size
              pure Nothing
      _ -> pure Nothing

  StoreFile uri bytes -> do
    let path = fileURIToPath (fsRoot fs) uri
        size = fromIntegral (BS.length bytes)
    reserve <- embed $ fsReserve fs
    available <- embed $ availableBytes (fsRoot fs)
    if maybe False (< reserve + size) available
      then logWarning [i|Not caching #{uri}: less than #{reserve `div` mib} MiB would be left on the disk|]
      else do
        replaced <- embed $ tryAny (regularFile path)
        embed (tryAny (writeFileAtomic path bytes)) >>= \case
          Left err -> do
            logError [i|Filesystem write failed for #{path}: #{err}|]
            throw $ StorageError (show err)
          Right () -> embed $ do
            whenJust (join (rightToMaybe replaced)) $ \( old, _ ) -> removeCachedCount fs path old
            added fs path size =<< unixTime

  DeleteFile uri      -> do
    let path = fileURIToPath (fsRoot fs) uri
    embed (tryAny (regularFile path)) >>= \case
      Right (Just ( size, _ )) -> embed (removeCached fs path size) >>= \case
        Left err -> throw $ StorageError [i|Could not delete #{path}: #{err}|]
        Right () -> pass
      _ -> pass

removeCachedCount :: FsCache -> FilePath -> Int64 -> IO ()
removeCachedCount fs path size = atomicModifyIORef'_ (fsRanges fs) $ Map.adjust shrink (rangeOf path)
  where
    shrink r = r { rangeBytes = rangeBytes r - size, rangeFiles = rangeFiles r - 1 }

-- | Evict this far below the limit, so eviction does not run on every write:
-- 100 MiB like the official client, less for tiny limits.
wantFree :: Int64 -> Int64
wantFree limit = min (100 * mib) (limit `div` 10)

-- | Keep the cache under the disk limit (0 = no limit yet), forever.
runEvictor :: FsCache -> IO Int64 -> IO Void
runEvictor fs getLimit = infinitely $ do
  limit <- getLimit
  used <- cachedBytes fs
  when (limit > 0 && used > limit) $ tryAny (evict fs (used - limit + wantFree limit)) >>= \case
    Left err           -> putStrLn [i|Cache eviction failed: #{err}|]
    Right ( 0, _ )     -> pass
    Right ( n, bytes ) -> putStrLn
      [i|Evicted #{n} least recently served files (#{bytes `div` mib} MiB) to stay under the disk limit|]
  threadDelay (10 * 1000000)

-- | Delete at least @want@ bytes (or until empty) starting from the directory with
-- the oldest file, taking files within 'slack' of its oldest mtime
-- (official CacheHandler.checkAndPruneCache).
evict :: FsCache -> Int64 -> IO ( Int, Int64 )
evict fs want = go 0 0
  where
    go n freed
      | freed >= want = pure ( n, freed )
      | otherwise = readIORef (fsRanges fs) >>= \ranges -> case oldestRange ranges of
        Nothing              -> pure ( n, freed )
        Just ( dir, oldest ) -> do
          now <- unixTime
          files <- sortOn fst3 <$> listRange (fsRoot fs) dir
          let cutoff  = oldest + slack (now - oldest)
              victims = takeBytes (want - freed) (takeWhile ((< cutoff) . fst3) files)
          gone <- fmap catMaybes $ forM victims $ \( _, size, path ) -> rightToMaybe
            . (( path, size ) <$) <$> removeCached fs path size
          let deleted = Set.fromList (map fst gone)
          atomicModifyIORef'_ (fsRanges fs) $ case filter ((`Set.notMember` deleted) . thd3) files of
            []           -> Map.delete dir
            ( t, _, _ ) : _ -> Map.adjust (\r -> r { rangeOldest = t }) dir
          go (n + length gone) (freed + sum (map snd gone))

    oldestRange = Map.foldlWithKey' older Nothing

    older found dir r = case found of
      Just ( _, t )
        | t <= rangeOldest r -> found
      _ -> Just ( dir, rangeOldest r )

    -- official CacheHandler.java:579-594
    slack age
      | age > 180 * day = 30 * day
      | age > 90 * day = 7 * day
      | age > 30 * day = 3 * day
      | otherwise = day

    day = 86400

    takeBytes k (x@( _, size, _ ) : xs)
      | k > 0 = x : takeBytes (k - size) xs
    takeBytes _ _ = []

    fst3 ( a, _, _ ) = a

    thd3 ( _, _, c ) = c

unixTime :: IO Int64
unixTime = floor <$> getPOSIXTime

mib :: Int64
mib = 1048576