packages feed

hs-hath-1.4.0: src/Hath/Locate.hs

{-# LANGUAGE DataKinds #-}

-- | Finding a requested file: in the cache, or else upstream.
module Hath.Locate ( Located(..), locateResource, usableReply, heldBytes ) where

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

import           Control.Concurrent       ( forkIOWithUnmask )
import           Control.Exception        ( finally, mask, mask_, onException )

import qualified Data.ByteString.Char8    as BS
import           Data.ByteString.Internal ( fromForeignPtr, fromForeignPtr0, mallocByteString )
import           Data.ByteString.Unsafe   ( unsafeUseAsCStringLen )
import qualified Data.List                as List
import qualified Data.Map.Strict          as Map
import           Data.String.Interpolate  ( i )

import           Foreign.ForeignPtr       ( ForeignPtr, withForeignPtr )
import           Foreign.Marshal.Utils    ( copyBytes )
import           Foreign.Ptr              ( castPtr, plusPtr )

import           Hath.Cache               ( Cache, CacheHit, lookupFile, storeFile )
import           Hath.Config              ( ClientConfig )
import           Hath.Download            ( receive, via )
import           Hath.Error               ( HathError )
import           Hath.FileURI             ( FileURI(..), renderFileURIBytes )
import           Hath.Log                 ( logInfo, logWarning )
import           Hath.Protocol            ( hathRequestToken, outgoingHeaders, sha1Hex )
import           Hath.RPC                 ( RPC, connectMicros, fileSources )
import           Hath.Settings            ( HathSettings(maxAllowedFileSize), imageProxy )
import           Hath.Stats               ( StatsEnv, addDownload, incFetched )

import qualified Network.HTTP.Client      as HC
import           Network.HTTP.Types       ( Header
                                          , Status
                                          , hContentLength
                                          , status404
                                          , status500
                                          , status502
                                          , status503
                                          , statusCode
                                          )

import           Polysemy
import           Polysemy.Error           ( Error, catch )
import           Polysemy.Final           ( withWeavingToFinal )
import           Polysemy.Reader          ( Reader, ask )

import           Relude                   hiding ( Reader, ask )

import           System.IO.Error          ( ioError, mkIOError, resourceVanishedErrorType )
import           System.IO.Unsafe         ( unsafePerformIO )

import           UnliftIO                 ( retrySTM, timeout, try )

data Located
  = Stored !CacheHit
    -- | A cache miss, coming in from upstream on a thread of its own, which
    -- caches the file once it is complete. Call it with a chunk writer to
    -- relay the file as it arrives; it throws if the download breaks off.
  | Streamed !Relay

type Relay = (ByteString -> IO ()) -> IO ()

-- | Cache lookup with upstream fetch fallback (serves any file routed here;
-- static ranges only affect cache pruning). A file already coming in for
-- another request is relayed from that download. Returns 503 if 'bufferBudget' is full.
locateResource
  :: Members
    '[ Cache
     , RPC
     , Reader StatsEnv
     , Log Message
     , Reader ClientConfig
     , Error HathError
     , Embed IO
     , Final IO
     ]
    r
  => HathSettings
  -> ByteString
  -> FileURI
  -> ( ByteString, ByteString )
  -> Sem r (Either Status Located)
locateResource settings fileId uri ( fileIndex, xres ) = lookupFile uri >>= \case
  Just hit -> pure $ Right $ Stored hit
  Nothing  -> do
    cfg <- ask @ClientConfig
    sources <- lowerToIO $ fileSources fileIndex xres fileId `catch` \(e :: HathError)
      -> [] <$ logWarning [i|srfetch failed for #{uri}: #{e}|]
    begin <- lowerToIO $ logInfo [i|Fetching resource: #{uri}|]
    fetched <- lowerToIO incFetched
    warn <- deferToIO logWarning
    -- runs on the download's thread, after the handler has returned
    finish <- deferToIO $ \case
      Left why      -> logWarning [i|Fetching #{uri} failed: #{why}|]
      Right content -> do
        addDownload (BS.length content)
        -- a failed cache write only costs us the next hit
        catch @HathError (storeFile uri content)
          $ \e -> logWarning [i|Cache write failed for #{uri}: #{e}|]
    embed $ fmap Streamed <$> shared (renderFileURIBytes uri) (\landed -> do
      void begin
      urls <- filter (not . BS.null) . fromMaybe [] <$> sources
      openUpstream cfg settings fileId uri urls >>= \case
        Left status    -> Left status <$ warn [i|Could not fetch #{uri}: #{statusCode status}|]
        Right response -> download uri response finish landed >>= \case
          Just relay -> Right relay <$ fetched
          Nothing    -> Left status503
            <$ warn
              [i|Not fetching #{uri}: the downloads under way hold #{bufferBudget `div` 1048576} MiB already|])

-- | Misses under way, by file id, each with what its first request found.
inFlight :: TVar (Map ByteString (TMVar (Either Status Relay)))
inFlight = unsafePerformIO (newTVarIO mempty)

{-# NOINLINE inFlight #-}

-- | Fetch a file with @lead@, unless another request is fetching it already: then
-- take what that one gets. @lead@ is given what its download must call when it is
-- over, which lets the next miss of the file fetch it again.
shared :: ByteString -> (IO () -> IO (Either Status Relay)) -> IO (Either Status Relay)
shared key lead = mask $ \restore -> join $ atomically $ do
  flights <- readTVar inFlight
  case Map.lookup key flights of
    Just flight -> pure $ restore $ atomically $ readTMVar flight
    Nothing     -> do
      flight <- newEmptyTMVar
      writeTVar inFlight (Map.insert key flight flights)
      let forget = modifyTVar' inFlight (Map.update (\f -> f <$ guard (f /= flight)) key)
          settle result = atomically $ do
            void $ tryPutTMVar flight result
            when (isLeft result) forget
      pure $ do
        result <- restore (lead (atomically forget)) `onException` settle (Left status500)
        result <$ settle result

-- | Open the first valid upstream source (ProxyFileDownloader.java:71-111), through
-- the image proxy if one is set. Caller must close the response. Returns 404 if
-- no sources, 502 if one answered, 500 otherwise.
openUpstream :: ClientConfig
             -> HathSettings
             -> ByteString
             -> FileURI
             -> [ ByteString ]
             -> IO (Either Status (HC.Response HC.BodyReader))
openUpstream cfg settings fileId uri urls
  | null urls = pure (Left status404)
  | otherwise = firstOpened status500 urls
  where
    request url = do
      req <- HC.parseRequest (BS.unpack url)
      pure
        req { HC.requestHeaders
                = outgoingHeaders [ ( "Hath-Request", hathRequestToken cfg fileId ) ]
              -- 5 s to connect, then 30 s for the headers (ProxyFileDownloader.java:86-87)
            , HC.responseTimeout = HC.responseTimeoutMicro (connectMicros + seconds 30)
            }

    open url = case request url of
      Nothing  -> pure Unreachable
      Just req -> do
        ( manager, sent ) <- via (imageProxy settings) req
        try @IO @HC.HttpException (HC.responseOpen sent manager) >>= \case
          Right response
            | usableReply
                (maxAllowedFileSize settings)
                uri
                (statusCode (HC.responseStatus response))
                (HC.responseHeaders response) -> pure (Opened response)
            | otherwise -> HC.responseClose response $> Answered
          Left (HC.HttpExceptionRequest _ HC.ConnectionTimeout) -> pure Unreachable
          Left (HC.HttpExceptionRequest _ (HC.ConnectionFailure _)) -> pure Unreachable
          Left _ -> pure Answered

    firstOpened failure = \case
      []         -> pure (Left failure)
      url : rest -> open url >>= \case
        Opened response -> pure (Right response)
        Answered        -> firstOpened status502 rest
        Unreachable     -> firstOpened failure rest

data Attempt
  = Opened !(HC.Response HC.BodyReader)
  | Answered
    -- ^ it answered, but not with the file
  | Unreachable

-- | Whether an upstream reply, given its status and headers, is the file
-- (ProxyFileDownloader.java:92-107): it must announce the file's length, and a
-- file larger than @max_allowed_filesize@ is not taken.
usableReply :: Int -> FileURI -> Int -> [ Header ] -> Bool
usableReply maxAllowedFileSize uri status headers
  = status == 200 && announced == Just (fileSize uri) && fileSize uri <= maxAllowedFileSize
  where
    announced = readMaybe . BS.unpack =<< List.lookup hContentLength headers

-- | Fetch into a shared buffer on a background thread (survives reader disconnect,
-- matching ProxyFileDownloader), calling @landed@ when it is over. Returns
-- 'Nothing' if 'bufferBudget' is exceeded.
download :: FileURI
         -> HC.Response HC.BodyReader
         -> (Either Text ByteString -> IO ())
         -> IO ()
         -> IO (Maybe Relay)
download uri response finish landed = mask_ $ reserve size >>= \case
  False -> Nothing <$ HC.responseClose response
  -- what is reserved must be released whatever happens, or the budget shrinks for good
  True  -> flip onException (release size >> HC.responseClose response) $ do
    buffer <- mallocByteString size
    progress <- newTVarIO (Receiving 0)
    let keep offset chunk = do
          copyInto buffer offset chunk
          atomically $ writeTVar progress (Receiving (offset + BS.length chunk))
    void $ forkIOWithUnmask $ \unmask -> flip finally (release size >> landed) $ unmask $ do
      -- 30 s for every read and 300 s for the whole (ProxyFileDownloader.java:186-200)
      received <- fromMaybe (Left "it took over 300 s")
        <$> timeout (seconds 300) (receive (seconds 30) size (HC.responseBody response) keep)
        `finally` HC.responseClose response
      atomically $ writeTVar progress (either (const Broken) (const Received) received)
      finish $ received >> verified (fromForeignPtr0 buffer size)
    pure (Just (relay buffer progress))
  where
    size = fileSize uri

    verified content
      | sha1Hex content == fileHash uri = Right content
      | otherwise = Left "its SHA-1 does not match the file id"

    relay buffer progress write = go 0
      where
        go sent = atomically (beyond sent) >>= \case
          Receiving filled -> write (fromForeignPtr buffer sent (filled - sent)) >> go filled
          Received         -> when (sent < size) $ write (fromForeignPtr buffer sent (size - sent))
          -- the kind of error a peer that went away raises: Warp drops the
          -- reader's connection, as it must for a body shorter than announced,
          -- and does not print it (the download logs why)
          Broken           -> ioError
            (mkIOError resourceVanishedErrorType "upstream broke off" Nothing Nothing)

        beyond sent = readTVar progress >>= \case
          Receiving filled
            | filled <= sent -> retrySTM
          settled          -> pure settled

data Progress = Receiving !Int | Received | Broken

-- | Cap total in-flight miss buffers to prevent memory exhaustion on hot misses.
-- ponytail: a fixed 512 MiB; make it an option if a node has less to spare
bufferBudget :: Int
bufferBudget = 512 * 1024 * 1024

-- | A single file larger than 'bufferBudget' is still allowed when nothing else is in flight.
withinBudget :: Int -> Int -> Bool
withinBudget taken size = taken == 0 || taken + size <= bufferBudget

held :: TVar Int
held = unsafePerformIO (newTVarIO 0)

{-# NOINLINE held #-}

heldBytes :: IO Int
heldBytes = readTVarIO held

reserve :: Int -> IO Bool
reserve size = atomically $ do
  taken <- readTVar held
  let fits = withinBudget taken size
  fits <$ when fits (writeTVar held (taken + size))

release :: Int -> IO ()
release size = atomically $ modifyTVar' held (subtract size)

copyInto :: ForeignPtr Word8 -> Int -> ByteString -> IO ()
copyInto buffer offset chunk = unsafeUseAsCStringLen chunk $ \( source, len )
  -> withForeignPtr buffer $ \start -> copyBytes (start `plusPtr` offset) (castPtr source) len

seconds :: Int -> Int
seconds = (* 1000000)

deferToIO :: Member (Final IO) r => (x -> Sem r ()) -> Sem r (x -> IO ())
deferToIO k = withWeavingToFinal $ \s lower _ -> pure ((\x -> void (lower (k x <$ s))) <$ s)

lowerToIO :: Member (Final IO) r => Sem r a -> Sem r (IO (Maybe a))
lowerToIO action = withWeavingToFinal $ \s lower ins -> pure ((ins <$> lower (action <$ s)) <$ s)