packages feed

hs-hath-1.4.0: src/Hath/Server/Range.hs

-- | Conditional and partial requests for a file, which never changes: its id
-- names its content.
module Hath.Server.Range ( fileETag, notModified, requestedPart ) where

import qualified Data.ByteString.Char8 as BS
import qualified Data.List             as List

import           Hath.FileURI          ( FileURI(..) )

import           Network.HTTP.Types    ( ByteRange(..)
                                       , RequestHeaders
                                       , hIfNoneMatch
                                       , hIfRange
                                       , hRange
                                       , parseByteRanges
                                       )

import           Relude

fileETag :: FileURI -> ByteString
fileETag uri = "\"" <> fileHash uri <> "\""

-- | Weak ETag comparison per RFC 9110 13.1.2 (matches @*@ or @W/@-prefixed tags).
notModified :: ByteString -> RequestHeaders -> Bool
notModified etag headers
  = any (any matches . BS.split ',') [ v | ( n, v ) <- headers, n == hIfNoneMatch ]
  where
    matches tag = case BS.strip tag of
      "*" -> True
      t   -> fromMaybe t (BS.stripPrefix "W/" t) == etag

-- | Single byte range as @(offset, length)@, or 'Nothing' to send the whole file
-- (full-file, multi-range, unsatisfiable, or mismatched @If-Range@; RFC 9110 13.1.5, 14.2).
requestedPart :: ByteString -> Int -> RequestHeaders -> Maybe ( Int, Int )
requestedPart etag size headers = do
  ranges <- parseByteRanges =<< List.lookup hRange headers
  guard (all (== etag) (List.lookup hIfRange headers))
  ( offset, len ) <- case ranges of
    [ range ] -> bounds range
    _ -> Nothing
  ( fromInteger offset, fromInteger len ) <$ guard (( offset, len ) /= ( 0, n ))
  where
    n = toInteger size

    bounds = \case
      ByteRangeFrom from
        | from < n -> Just ( from, n - from )
      ByteRangeFromTo from to
        | from <= to, from < n -> Just ( from, min to (n - 1) - from + 1 )
      ByteRangeSuffix k
        | k > 0 -> Just ( max 0 (n - k), min k n )
      _ -> Nothing