-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

{- | Content-coding negotiation for served metadata, read from every @Accept-Encoding@ field
(RFC 9110, section 12.5.3). Écluse offers gzip and identity, and reads @x-gzip@ as gzip, as RFC
9110 section 8.4.1.3 asks of a recipient. Gzip wins a tie of positive qualities, a malformed
quality refuses its coding, and a refusal beats a duplicate offer. A request that excludes both
codings takes @406@. Identity-only metadata ignores the field.
-}
module Ecluse.Core.Server.Encoding (
    -- * The operator's setting
    MetadataCompression (..),

    -- * Negotiation
    ContentCoding (..),
    CodingChoice (..),
    chooseCoding,

    -- * Response headers
    gzipEncodingHeader,
    varyAcceptEncoding,
) where

import Data.ByteString.Char8 qualified as BS8
import Data.Char (isDigit)
import Network.HTTP.Types (Header, RequestHeaders, ResponseHeaders)
import Network.HTTP.Types.Header (hAcceptEncoding, hContentEncoding, hVary)

import Ecluse.Core.Server.FieldValue (fieldValues, listMembers, lowerAscii, memberParameters)

-- | Whether served metadata may be gzipped for a client that accepts it.
data MetadataCompression
    = -- | Gzip a listing when the request's @Accept-Encoding@ prefers it.
      GzipWhenAccepted
    | -- | Serve every listing in identity coding and ignore @Accept-Encoding@.
      IdentityOnly
    deriving stock (MetadataCompression -> MetadataCompression -> Bool
(MetadataCompression -> MetadataCompression -> Bool)
-> (MetadataCompression -> MetadataCompression -> Bool)
-> Eq MetadataCompression
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MetadataCompression -> MetadataCompression -> Bool
== :: MetadataCompression -> MetadataCompression -> Bool
$c/= :: MetadataCompression -> MetadataCompression -> Bool
/= :: MetadataCompression -> MetadataCompression -> Bool
Eq, Int -> MetadataCompression -> ShowS
[MetadataCompression] -> ShowS
MetadataCompression -> String
(Int -> MetadataCompression -> ShowS)
-> (MetadataCompression -> String)
-> ([MetadataCompression] -> ShowS)
-> Show MetadataCompression
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MetadataCompression -> ShowS
showsPrec :: Int -> MetadataCompression -> ShowS
$cshow :: MetadataCompression -> String
show :: MetadataCompression -> String
$cshowList :: [MetadataCompression] -> ShowS
showList :: [MetadataCompression] -> ShowS
Show)

-- | A content coding Écluse can serve a listing in.
data ContentCoding = IdentityCoding | GzipCoding
    deriving stock (ContentCoding -> ContentCoding -> Bool
(ContentCoding -> ContentCoding -> Bool)
-> (ContentCoding -> ContentCoding -> Bool) -> Eq ContentCoding
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ContentCoding -> ContentCoding -> Bool
== :: ContentCoding -> ContentCoding -> Bool
$c/= :: ContentCoding -> ContentCoding -> Bool
/= :: ContentCoding -> ContentCoding -> Bool
Eq, Int -> ContentCoding -> ShowS
[ContentCoding] -> ShowS
ContentCoding -> String
(Int -> ContentCoding -> ShowS)
-> (ContentCoding -> String)
-> ([ContentCoding] -> ShowS)
-> Show ContentCoding
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ContentCoding -> ShowS
showsPrec :: Int -> ContentCoding -> ShowS
$cshow :: ContentCoding -> String
show :: ContentCoding -> String
$cshowList :: [ContentCoding] -> ShowS
showList :: [ContentCoding] -> ShowS
Show)

-- | The coding a request selects, or the refusal when it excludes every coding Écluse serves.
data CodingChoice
    = ServeCoding ContentCoding
    | NoAcceptableCoding
    deriving stock (CodingChoice -> CodingChoice -> Bool
(CodingChoice -> CodingChoice -> Bool)
-> (CodingChoice -> CodingChoice -> Bool) -> Eq CodingChoice
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CodingChoice -> CodingChoice -> Bool
== :: CodingChoice -> CodingChoice -> Bool
$c/= :: CodingChoice -> CodingChoice -> Bool
/= :: CodingChoice -> CodingChoice -> Bool
Eq, Int -> CodingChoice -> ShowS
[CodingChoice] -> ShowS
CodingChoice -> String
(Int -> CodingChoice -> ShowS)
-> (CodingChoice -> String)
-> ([CodingChoice] -> ShowS)
-> Show CodingChoice
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CodingChoice -> ShowS
showsPrec :: Int -> CodingChoice -> ShowS
$cshow :: CodingChoice -> String
show :: CodingChoice -> String
$cshowList :: [CodingChoice] -> ShowS
showList :: [CodingChoice] -> ShowS
Show)

-- A quality in thousandths, 0 to 1000. Zero refuses its coding.
type Quality = Int

-- The offers one request makes, after duplicates of each coding are combined.
data Offers = Offers
    { Offers -> Maybe Int
offerGzip :: Maybe Quality
    , Offers -> Maybe Int
offerIdentity :: Maybe Quality
    , Offers -> Maybe Int
offerAny :: Maybe Quality
    }

-- | Select a listing's coding. Identity stays acceptable unless excluded, and outranks gzip only by an explicit higher quality.
chooseCoding :: MetadataCompression -> RequestHeaders -> CodingChoice
chooseCoding :: MetadataCompression -> ResponseHeaders -> CodingChoice
chooseCoding MetadataCompression
policy ResponseHeaders
headers = case MetadataCompression
policy of
    MetadataCompression
IdentityOnly -> ContentCoding -> CodingChoice
ServeCoding ContentCoding
IdentityCoding
    MetadataCompression
GzipWhenAccepted -> Offers -> CodingChoice
decide (ResponseHeaders -> Offers
requestOffers ResponseHeaders
headers)

decide :: Offers -> CodingChoice
decide :: Offers -> CodingChoice
decide Offers
offers = case Offers -> Maybe Int
offerIdentity Offers
offers Maybe Int -> Maybe Int -> Maybe Int
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Offers -> Maybe Int
offerAny Offers
offers of
    Maybe Int
Nothing
        | Int
gzip Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 -> ContentCoding -> CodingChoice
ServeCoding ContentCoding
GzipCoding
        | Bool
otherwise -> ContentCoding -> CodingChoice
ServeCoding ContentCoding
IdentityCoding
    Just Int
plain
        | Int
gzip Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& Int
gzip Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
plain -> ContentCoding -> CodingChoice
ServeCoding ContentCoding
GzipCoding
        | Int
plain Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 -> ContentCoding -> CodingChoice
ServeCoding ContentCoding
IdentityCoding
        | Bool
otherwise -> CodingChoice
NoAcceptableCoding
  where
    gzip :: Int
gzip = Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
0 (Offers -> Maybe Int
offerGzip Offers
offers Maybe Int -> Maybe Int -> Maybe Int
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Offers -> Maybe Int
offerAny Offers
offers)

requestOffers :: RequestHeaders -> Offers
requestOffers :: ResponseHeaders -> Offers
requestOffers ResponseHeaders
headers =
    (Offers -> ByteString -> Offers)
-> Offers -> [ByteString] -> Offers
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Offers -> ByteString -> Offers
offer (Maybe Int -> Maybe Int -> Maybe Int -> Offers
Offers Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing Maybe Int
forall a. Maybe a
Nothing) ((ByteString -> [ByteString]) -> [ByteString] -> [ByteString]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ByteString -> [ByteString]
listMembers (HeaderName -> ResponseHeaders -> [ByteString]
forall name value. Eq name => name -> [(name, value)] -> [value]
fieldValues HeaderName
hAcceptEncoding ResponseHeaders
headers))

offer :: Offers -> ByteString -> Offers
offer :: Offers -> ByteString -> Offers
offer Offers
offers ByteString
member = case ByteString -> ByteString
lowerAscii ByteString
coding of
    ByteString
"gzip" -> Offers
offers{offerGzip = combine (offerGzip offers)}
    ByteString
"x-gzip" -> Offers
offers{offerGzip = combine (offerGzip offers)}
    ByteString
"identity" -> Offers
offers{offerIdentity = combine (offerIdentity offers)}
    ByteString
"*" -> Offers
offers{offerAny = combine (offerAny offers)}
    ByteString
_ -> Offers
offers
  where
    (ByteString
coding, [(ByteString, ByteString)]
parameters) = ByteString -> (ByteString, [(ByteString, ByteString)])
memberParameters ByteString
member
    quality :: Int
quality = Int -> (ByteString -> Int) -> Maybe ByteString -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
1000 (Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
0 (Maybe Int -> Int)
-> (ByteString -> Maybe Int) -> ByteString -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe Int
parseQuality) ([ByteString] -> Maybe ByteString
forall a. [a] -> Maybe a
listToMaybe [ByteString
value | (ByteString
name, ByteString
value) <- [(ByteString, ByteString)]
parameters, ByteString
name ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"q"])
    combine :: Maybe Int -> Maybe Int
combine = Int -> Maybe Int
forall a. a -> Maybe a
Just (Int -> Maybe Int) -> (Maybe Int -> Int) -> Maybe Int -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> (Int -> Int) -> Maybe Int -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
quality (\Int
previous -> if Int
previous Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 Bool -> Bool -> Bool
|| Int
quality Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 then Int
0 else Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
previous Int
quality)

-- RFC 9110's qvalue: "0" with up to three decimals, or "1" with up to three zero decimals.
parseQuality :: ByteString -> Maybe Quality
parseQuality :: ByteString -> Maybe Int
parseQuality ByteString
raw = case ByteString -> Maybe (Char, ByteString)
BS8.uncons ByteString
raw of
    Just (Char
whole, ByteString
rest)
        | Char
whole Char -> String -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [Char
'0', Char
'1']
        , Just ByteString
decimals <- ByteString -> Maybe ByteString
fraction ByteString
rest -> do
            let value :: Int
value = (if Char
whole Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'1' then Int
1000 else Int
0) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ ByteString -> Int
thousandths ByteString
decimals
            Int
value Int -> Maybe () -> Maybe Int
forall a b. a -> Maybe b -> Maybe a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Int
value Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
1000)
    Maybe (Char, ByteString)
_ -> Maybe Int
forall a. Maybe a
Nothing
  where
    fraction :: ByteString -> Maybe ByteString
fraction ByteString
rest = case ByteString -> Maybe (Char, ByteString)
BS8.uncons ByteString
rest of
        Maybe (Char, ByteString)
Nothing -> ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
""
        Just (Char
'.', ByteString
digits) | ByteString -> Int
BS8.length ByteString
digits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
3 Bool -> Bool -> Bool
&& (Char -> Bool) -> ByteString -> Bool
BS8.all Char -> Bool
isDigit ByteString
digits -> ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
digits
        Maybe (Char, ByteString)
_ -> Maybe ByteString
forall a. Maybe a
Nothing
    thousandths :: ByteString -> Int
thousandths ByteString
digits = (Int -> Char -> Int) -> Int -> ByteString -> Int
forall a. (a -> Char -> a) -> a -> ByteString -> a
BS8.foldl' (\Int
total Char
c -> Int
total Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
10 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
c Int -> Int -> Int
forall a. Num a => a -> a -> a
- Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
'0') Int
0 (Int -> ByteString -> ByteString
BS8.take Int
3 (ByteString
digits ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
"000"))

-- | The @Content-Encoding@ header of a gzip listing.
gzipEncodingHeader :: Header
gzipEncodingHeader :: Header
gzipEncodingHeader = (HeaderName
hContentEncoding, ByteString
"gzip")

-- | Add @Accept-Encoding@ to a response's @Vary@, keeping the field names already listed.
varyAcceptEncoding :: ResponseHeaders -> ResponseHeaders
varyAcceptEncoding :: ResponseHeaders -> ResponseHeaders
varyAcceptEncoding ResponseHeaders
headers
    | (ByteString -> Bool) -> [ByteString] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ByteString -> Bool
forall {a}. (Eq a, IsString a) => a -> Bool
covers [ByteString]
varied = ResponseHeaders
headers
    | Bool
otherwise = case (Header -> Bool)
-> ResponseHeaders -> (ResponseHeaders, ResponseHeaders)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break ((HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
== HeaderName
hVary) (HeaderName -> Bool) -> (Header -> HeaderName) -> Header -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Header -> HeaderName
forall a b. (a, b) -> a
fst) ResponseHeaders
headers of
        (ResponseHeaders
before, (HeaderName
name, ByteString
value) : ResponseHeaders
after) -> ResponseHeaders
before ResponseHeaders -> ResponseHeaders -> ResponseHeaders
forall a. Semigroup a => a -> a -> a
<> ((HeaderName
name, ByteString
value ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
", Accept-Encoding") Header -> ResponseHeaders -> ResponseHeaders
forall a. a -> [a] -> [a]
: ResponseHeaders
after)
        (ResponseHeaders, ResponseHeaders)
_ -> ResponseHeaders
headers ResponseHeaders -> ResponseHeaders -> ResponseHeaders
forall a. Semigroup a => a -> a -> a
<> [(HeaderName
hVary, ByteString
"Accept-Encoding")]
  where
    varied :: [ByteString]
varied = (ByteString -> ByteString) -> [ByteString] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map ByteString -> ByteString
lowerAscii ((ByteString -> [ByteString]) -> [ByteString] -> [ByteString]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ByteString -> [ByteString]
listMembers (HeaderName -> ResponseHeaders -> [ByteString]
forall name value. Eq name => name -> [(name, value)] -> [value]
fieldValues HeaderName
hVary ResponseHeaders
headers))
    covers :: a -> Bool
covers a
member = a
member a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
"*" Bool -> Bool -> Bool
|| a
member a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
"accept-encoding"