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

{- | Shared HTTP requests with typed URL failures, ecosystem-specific credential presentation, and
the mechanisms a store can declare for service credentials. Requests parsed here refuse redirects,
including after credentials attach.
-}
module Ecluse.Core.Registry.Request (
    -- * Request finalisation
    sealRequest,
    finaliseRequest,

    -- * Credential presentation
    CredentialMapping,
    credentialMapping,
    credentialRecover,
    attachCredential,
    authorizationUnder,
    bareAuthorization,

    -- * Service credential presentation
    AuthMechanism (..),
    renderAuthMechanism,
    StoreOperation (..),
    ServicePresentation,
    nativePresentation,
    declaredPresentation,
    sendsCredentialUsername,
    presentedMapping,
    presentedRequest,

    -- * Request building
    metadataGet,
    artifactRequestByUrl,
    artifactGet,
    joinPath,
    apiEndpoint,
    sidecarUrl,
    parseRequestEither,

    -- * Requests under a base parsed once
    BaseRequest,
    mkBaseRequest,
    baseRequestUrl,
    requestAt,
) where

import Data.ByteArray.Encoding (Base (Base64), convertToBase)
import Data.ByteString qualified as BS
import Data.Char (isHexDigit)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Network.HTTP.Client (Request (decompress, redirectCount, requestHeaders), parseRequest)
import Network.HTTP.Client qualified as Client
import Network.HTTP.Types.Header (
    HeaderName,
    RequestHeaders,
    hAccept,
    hAcceptEncoding,
    hAuthorization,
 )
import Text.Show (showsPrec)

import Ecluse.Core.BuildIdentity (identifyRequest)
import Ecluse.Core.Credential (ClientCredential (credSecret), bareCredential, mkSecret, unSecret)
import Ecluse.Core.Registry (UrlFormationError (EmptyBaseUrl, UnparseableUrl))
import Ecluse.Core.Security.Egress (RegistryUrl, registryUrlText)
import Ecluse.Core.Text (isAsciiAlphaNum, joinUrlPath)

{- | Seal the outbound invariants onto a request, idempotently. A followed redirect could
re-send a credential cross-host or steer an anonymous fetch past the host allowlist.
-}
sealRequest :: Request -> Request
sealRequest :: Request -> Request
sealRequest Request
request = Request -> Request
identifyRequest Request
request{redirectCount = 0}

{- | Apply the ecosystem's injected credential attach, then seal the result through
'sealRequest'. The attach runs first, so it cannot reopen redirect following.
-}
finaliseRequest :: (Request -> Request) -> Request -> Request
finaliseRequest :: (Request -> Request) -> Request -> Request
finaliseRequest Request -> Request
attach = Request -> Request
sealRequest (Request -> Request) -> (Request -> Request) -> Request -> Request
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Request -> Request
attach

{- | One ecosystem's credential presentation, recovered as a value so an attach re-encodes rather
than replaying a header. The constructor is hidden, so no adapter spells its own attach point.
-}
data CredentialMapping = CredentialMapping
    { CredentialMapping -> RequestHeaders -> Maybe ClientCredential
credentialRecover :: RequestHeaders -> Maybe ClientCredential
    {- ^ 'Nothing' for a request carrying none in this ecosystem's form, which the edge gate
    denies rather than half-reading. The compare is over the secret half alone.
    -}
    , -- The header that carries an outbound credential: named per ecosystem, never assumed.
      CredentialMapping -> HeaderName
credentialHeader :: HeaderName
    , -- How a credential renders into that header's value (the ecosystem's own scheme).
      CredentialMapping -> ClientCredential -> ByteString
credentialRender :: ClientCredential -> ByteString
    }

{- | Declare an ecosystem's credential presentation. The constructor is hidden, so this is the
only way to build a 'CredentialMapping'.
-}
credentialMapping ::
    (RequestHeaders -> Maybe ClientCredential) ->
    HeaderName ->
    (ClientCredential -> ByteString) ->
    CredentialMapping
credentialMapping :: (RequestHeaders -> Maybe ClientCredential)
-> HeaderName
-> (ClientCredential -> ByteString)
-> CredentialMapping
credentialMapping RequestHeaders -> Maybe ClientCredential
recover HeaderName
header ClientCredential -> ByteString
render =
    CredentialMapping
        { credentialRecover :: RequestHeaders -> Maybe ClientCredential
credentialRecover = RequestHeaders -> Maybe ClientCredential
recover
        , credentialHeader :: HeaderName
credentialHeader = HeaderName
header
        , credentialRender :: ClientCredential -> ByteString
credentialRender = ClientCredential -> ByteString
render
        }

{- | Attach a credential to an outbound request under the mapping's own header, then finalise it
through 'finaliseRequest'. A 'Nothing' attaches no header, and the seal still applies.
-}
attachCredential :: CredentialMapping -> Maybe ClientCredential -> Request -> Request
attachCredential :: CredentialMapping -> Maybe ClientCredential -> Request -> Request
attachCredential CredentialMapping
mapping Maybe ClientCredential
credential = (Request -> Request) -> Request -> Request
finaliseRequest ((Request -> Request) -> Request -> Request)
-> (Request -> Request) -> Request -> Request
forall a b. (a -> b) -> a -> b
$ case Maybe ClientCredential
credential of
    Maybe ClientCredential
Nothing -> Request -> Request
forall a. a -> a
id
    Just ClientCredential
presented -> \Request
request ->
        Request
request
            { requestHeaders =
                (credentialHeader mapping, credentialRender mapping presented) : requestHeaders request
            }

{- | The first @Authorization@ header's remainder when it carries @scheme@ (compared without
case), with the separating spaces dropped. Another scheme or no header yields 'Nothing'.
-}
authorizationUnder :: Text -> RequestHeaders -> Maybe Text
authorizationUnder :: Text -> RequestHeaders -> Maybe Text
authorizationUnder Text
scheme RequestHeaders
headers = do
    (_, raw) <- (Header -> Bool) -> RequestHeaders -> Maybe Header
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
== HeaderName
hAuthorization) (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) RequestHeaders
headers
    let (presented, rest) = T.break (== ' ') (decodeUtf8 raw)
    guard (T.toLower presented == T.toLower scheme)
    pure (T.dropWhile (== ' ') rest)

{- | A scheme-less credential from exactly one non-empty @Authorization@ line whose bytes are all
in RFC 9110's field-value set: visible ASCII, space and tab. Any other presentation yields 'Nothing'.
-}
bareAuthorization :: RequestHeaders -> Maybe ClientCredential
bareAuthorization :: RequestHeaders -> Maybe ClientCredential
bareAuthorization RequestHeaders
headers = case [ByteString
value | (HeaderName
name, ByteString
value) <- RequestHeaders
headers, HeaderName
name HeaderName -> HeaderName -> Bool
forall a. Eq a => a -> a -> Bool
== HeaderName
hAuthorization] of
    [ByteString
value] | Bool -> Bool
not (ByteString -> Bool
BS.null ByteString
value), (Word8 -> Bool) -> ByteString -> Bool
BS.all Word8 -> Bool
forall {a}. (Num a, Ord a) => a -> Bool
fieldByte ByteString
value -> Secret -> ClientCredential
bareCredential (Secret -> ClientCredential)
-> (Text -> Secret) -> Text -> ClientCredential
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Secret
mkSecret (Text -> ClientCredential) -> Maybe Text -> Maybe ClientCredential
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either UnicodeException Text -> Maybe Text
forall l r. Either l r -> Maybe r
rightToMaybe (ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
value)
    [ByteString]
_ -> Maybe ClientCredential
forall a. Maybe a
Nothing
  where
    fieldByte :: a -> Bool
fieldByte a
byte = a
byte a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
0x09 Bool -> Bool -> Bool
|| (a
byte a -> a -> Bool
forall a. Ord a => a -> a -> Bool
>= a
0x20 Bool -> Bool -> Bool
&& a
byte a -> a -> Bool
forall a. Ord a => a -> a -> Bool
<= a
0x7E)

-- | How a secret travels on @Authorization@, named without reference to an ecosystem or a store.
data AuthMechanism
    = -- | @Bearer@ followed by the secret.
      AuthBearer
    | -- | HTTP Basic over this username and the secret.
      AuthBasic Text
    | -- | The secret alone, with no scheme.
      AuthRawKey
    deriving stock (AuthMechanism -> AuthMechanism -> Bool
(AuthMechanism -> AuthMechanism -> Bool)
-> (AuthMechanism -> AuthMechanism -> Bool) -> Eq AuthMechanism
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AuthMechanism -> AuthMechanism -> Bool
== :: AuthMechanism -> AuthMechanism -> Bool
$c/= :: AuthMechanism -> AuthMechanism -> Bool
/= :: AuthMechanism -> AuthMechanism -> Bool
Eq, Int -> AuthMechanism -> ShowS
[AuthMechanism] -> ShowS
AuthMechanism -> String
(Int -> AuthMechanism -> ShowS)
-> (AuthMechanism -> String)
-> ([AuthMechanism] -> ShowS)
-> Show AuthMechanism
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AuthMechanism -> ShowS
showsPrec :: Int -> AuthMechanism -> ShowS
$cshow :: AuthMechanism -> String
show :: AuthMechanism -> String
$cshowList :: [AuthMechanism] -> ShowS
showList :: [AuthMechanism] -> ShowS
Show)

-- | The @Authorization@ value a credential renders to under a mechanism.
renderAuthMechanism :: AuthMechanism -> ClientCredential -> ByteString
renderAuthMechanism :: AuthMechanism -> ClientCredential -> ByteString
renderAuthMechanism AuthMechanism
mechanism ClientCredential
credential = case AuthMechanism
mechanism of
    AuthMechanism
AuthBearer -> ByteString
"Bearer " ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Text -> ByteString
forall a b. ConvertUtf8 a b => a -> b
encodeUtf8 Text
secret
    AuthBasic Text
username -> ByteString
"Basic " ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Base -> ByteString -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
Base -> bin -> bout
convertToBase Base
Base64 (Text -> ByteString
forall a b. ConvertUtf8 a b => a -> b
encodeUtf8 (Text
username Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
secret) :: ByteString)
    AuthMechanism
AuthRawKey -> Text -> ByteString
forall a b. ConvertUtf8 a b => a -> b
encodeUtf8 Text
secret
  where
    secret :: Text
secret = Secret -> Text
unSecret (ClientCredential -> Secret
credSecret ClientCredential
credential)

-- | The half of a store's protocol a service credential is presented to.
data StoreOperation = StoreRead | StoreWrite
    deriving stock (StoreOperation -> StoreOperation -> Bool
(StoreOperation -> StoreOperation -> Bool)
-> (StoreOperation -> StoreOperation -> Bool) -> Eq StoreOperation
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: StoreOperation -> StoreOperation -> Bool
== :: StoreOperation -> StoreOperation -> Bool
$c/= :: StoreOperation -> StoreOperation -> Bool
/= :: StoreOperation -> StoreOperation -> Bool
Eq, Int -> StoreOperation -> ShowS
[StoreOperation] -> ShowS
StoreOperation -> String
(Int -> StoreOperation -> ShowS)
-> (StoreOperation -> String)
-> ([StoreOperation] -> ShowS)
-> Show StoreOperation
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> StoreOperation -> ShowS
showsPrec :: Int -> StoreOperation -> ShowS
$cshow :: StoreOperation -> String
show :: StoreOperation -> String
$cshowList :: [StoreOperation] -> ShowS
showList :: [StoreOperation] -> ShowS
Show)

{- | How a store asks for a service credential on reads and on writes. An operation it declares
nothing for keeps the ecosystem's own credential mapping.
-}
data ServicePresentation = ServicePresentation (Maybe AuthMechanism) (Maybe AuthMechanism)
    deriving stock (ServicePresentation -> ServicePresentation -> Bool
(ServicePresentation -> ServicePresentation -> Bool)
-> (ServicePresentation -> ServicePresentation -> Bool)
-> Eq ServicePresentation
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ServicePresentation -> ServicePresentation -> Bool
== :: ServicePresentation -> ServicePresentation -> Bool
$c/= :: ServicePresentation -> ServicePresentation -> Bool
/= :: ServicePresentation -> ServicePresentation -> Bool
Eq, Int -> ServicePresentation -> ShowS
[ServicePresentation] -> ShowS
ServicePresentation -> String
(Int -> ServicePresentation -> ShowS)
-> (ServicePresentation -> String)
-> ([ServicePresentation] -> ShowS)
-> Show ServicePresentation
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ServicePresentation -> ShowS
showsPrec :: Int -> ServicePresentation -> ShowS
$cshow :: ServicePresentation -> String
show :: ServicePresentation -> String
$cshowList :: [ServicePresentation] -> ShowS
showList :: [ServicePresentation] -> ShowS
Show)

-- | A store that declares nothing: every operation keeps the ecosystem's own presentation.
nativePresentation :: ServicePresentation
nativePresentation :: ServicePresentation
nativePresentation = Maybe AuthMechanism -> Maybe AuthMechanism -> ServicePresentation
ServicePresentation Maybe AuthMechanism
forall a. Maybe a
Nothing Maybe AuthMechanism
forall a. Maybe a
Nothing

-- | A store that declares its mechanism for each operation.
declaredPresentation :: (StoreOperation -> AuthMechanism) -> ServicePresentation
declaredPresentation :: (StoreOperation -> AuthMechanism) -> ServicePresentation
declaredPresentation StoreOperation -> AuthMechanism
mechanism = Maybe AuthMechanism -> Maybe AuthMechanism -> ServicePresentation
ServicePresentation (AuthMechanism -> Maybe AuthMechanism
forall a. a -> Maybe a
Just (StoreOperation -> AuthMechanism
mechanism StoreOperation
StoreRead)) (AuthMechanism -> Maybe AuthMechanism
forall a. a -> Maybe a
Just (StoreOperation -> AuthMechanism
mechanism StoreOperation
StoreWrite))

{- | The mapping a service credential renders through for one operation: the declared mechanism on
@Authorization@, or the ecosystem's mapping unchanged. Recovery stays the ecosystem's own.
-}
presentedMapping :: ServicePresentation -> StoreOperation -> CredentialMapping -> CredentialMapping
presentedMapping :: ServicePresentation
-> StoreOperation -> CredentialMapping -> CredentialMapping
presentedMapping ServicePresentation
presentation StoreOperation
operation CredentialMapping
native = case ServicePresentation -> StoreOperation -> Maybe AuthMechanism
declaredMechanism ServicePresentation
presentation StoreOperation
operation of
    Maybe AuthMechanism
Nothing -> CredentialMapping
native
    Just AuthMechanism
mechanism -> CredentialMapping
native{credentialHeader = hAuthorization, credentialRender = renderAuthMechanism mechanism}

{- | Whether an operation sends the credential's own username. Only the ecosystem's own mapping can:
a declared mechanism sends the secret alone or the store's own Basic username.
-}
sendsCredentialUsername :: ServicePresentation -> StoreOperation -> Bool
sendsCredentialUsername :: ServicePresentation -> StoreOperation -> Bool
sendsCredentialUsername ServicePresentation
presentation = Maybe AuthMechanism -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe AuthMechanism -> Bool)
-> (StoreOperation -> Maybe AuthMechanism)
-> StoreOperation
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ServicePresentation -> StoreOperation -> Maybe AuthMechanism
declaredMechanism ServicePresentation
presentation

declaredMechanism :: ServicePresentation -> StoreOperation -> Maybe AuthMechanism
declaredMechanism :: ServicePresentation -> StoreOperation -> Maybe AuthMechanism
declaredMechanism (ServicePresentation Maybe AuthMechanism
onRead Maybe AuthMechanism
onWrite) = \case
    StoreOperation
StoreRead -> Maybe AuthMechanism
onRead
    StoreOperation
StoreWrite -> Maybe AuthMechanism
onWrite

{- | Form a request anonymously, then attach the credential under @mapping@. The builder must use its
credential only to attach it, as every native request builder here does.
-}
presentedRequest :: CredentialMapping -> Maybe ClientCredential -> (Maybe ClientCredential -> Either e Request) -> Either e Request
presentedRequest :: forall e.
CredentialMapping
-> Maybe ClientCredential
-> (Maybe ClientCredential -> Either e Request)
-> Either e Request
presentedRequest CredentialMapping
mapping Maybe ClientCredential
credential Maybe ClientCredential -> Either e Request
build = CredentialMapping -> Maybe ClientCredential -> Request -> Request
attachCredential CredentialMapping
mapping Maybe ClientCredential
credential (Request -> Request) -> Either e Request -> Either e Request
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe ClientCredential -> Either e Request
build Maybe ClientCredential
forall a. Maybe a
Nothing

-- | Negotiate compressed metadata under the ecosystem's media type and credential presentation.
metadataGet :: CredentialMapping -> Maybe ClientCredential -> ByteString -> Request -> Request
metadataGet :: CredentialMapping
-> Maybe ClientCredential -> ByteString -> Request -> Request
metadataGet CredentialMapping
mapping Maybe ClientCredential
credential ByteString
mediaType Request
base =
    CredentialMapping -> Maybe ClientCredential -> Request -> Request
attachCredential CredentialMapping
mapping Maybe ClientCredential
credential (Request -> Request) -> Request -> Request
forall a b. (a -> b) -> a -> b
$
        Request
base
            { requestHeaders =
                (hAccept, mediaType)
                    : (hAcceptEncoding, "gzip")
                    : requestHeaders base
            }

-- | Build the artifact @GET@ at the preserved upstream URL through 'artifactGet'.
artifactRequestByUrl :: CredentialMapping -> Maybe ClientCredential -> Text -> Either UrlFormationError Request
artifactRequestByUrl :: CredentialMapping
-> Maybe ClientCredential
-> Text
-> Either UrlFormationError Request
artifactRequestByUrl CredentialMapping
mapping Maybe ClientCredential
credential Text
url = CredentialMapping -> Maybe ClientCredential -> Request -> Request
artifactGet CredentialMapping
mapping Maybe ClientCredential
credential (Request -> Request)
-> Either UrlFormationError Request
-> Either UrlFormationError Request
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Either UrlFormationError Request
parseRequestEither Text
url

{- | Make a parsed request the artifact @GET@, in identity coding and never decompressed.
Without the field, http-client asks for gzip, and gzip bytes miss the advertised digest.
-}
artifactGet :: CredentialMapping -> Maybe ClientCredential -> Request -> Request
artifactGet :: CredentialMapping -> Maybe ClientCredential -> Request -> Request
artifactGet CredentialMapping
mapping Maybe ClientCredential
credential Request
base =
    CredentialMapping -> Maybe ClientCredential -> Request -> Request
attachCredential CredentialMapping
mapping Maybe ClientCredential
credential (Request -> Request) -> Request -> Request
forall a b. (a -> b) -> a -> b
$
        Request
base
            { decompress = const False
            , requestHeaders = (hAcceptEncoding, "identity") : requestHeaders base
            }

{- | Join a base URL and an already-encoded path with exactly one slash, whatever trailing
slashes the configured base writes.
-}
joinPath :: Text -> Text -> Either UrlFormationError Text
joinPath :: Text -> Text -> Either UrlFormationError Text
joinPath Text
baseUrl Text
path
    | Text -> Bool
T.null Text
baseUrl = UrlFormationError -> Either UrlFormationError Text
forall a b. a -> Either a b
Left UrlFormationError
EmptyBaseUrl
    | Bool
otherwise = Text -> Either UrlFormationError Text
forall a b. b -> Either a b
Right (Text -> Text -> Text
joinUrlPath Text
baseUrl Text
path)

{- | Parse a URL into the sealed request every adapter builds from ('sealRequest'). The URL comes
from configuration and an already-safe name, so a parse failure here is a configuration fault.
-}
parseRequestEither :: Text -> Either UrlFormationError Request
parseRequestEither :: Text -> Either UrlFormationError Request
parseRequestEither Text
url =
    case String -> Maybe Request
forall (m :: * -> *). MonadThrow m => String -> m Request
parseRequest (Text -> String
forall a. ToString a => a -> String
toString Text
url) of
        Just Request
request -> Request -> Either UrlFormationError Request
forall a b. b -> Either a b
Right (Request -> Request
sealRequest Request
request)
        Maybe Request
Nothing -> UrlFormationError -> Either UrlFormationError Request
forall a b. a -> Either a b
Left (Text -> UrlFormationError
UnparseableUrl Text
url)

{- | Parse an already-encoded API path under a configured root. A root with a query or a fragment
is refused with @refusal@, because the joined path would land inside it.
-}
apiEndpoint :: UrlFormationError -> Text -> Text -> Either UrlFormationError Request
apiEndpoint :: UrlFormationError
-> Text -> Text -> Either UrlFormationError Request
apiEndpoint UrlFormationError
refusal Text
root Text
path = do
    Bool -> Either UrlFormationError () -> Either UrlFormationError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ((Char -> Bool) -> Text -> Bool
T.any Char -> Bool
queryOrFragment Text
root) (UrlFormationError -> Either UrlFormationError ()
forall a b. a -> Either a b
Left UrlFormationError
refusal)
    Text -> Text -> Either UrlFormationError Text
joinPath Text
root Text
path Either UrlFormationError Text
-> (Text -> Either UrlFormationError Request)
-> Either UrlFormationError Request
forall a b.
Either UrlFormationError a
-> (a -> Either UrlFormationError b) -> Either UrlFormationError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either UrlFormationError Request
parseRequestEither

-- | Append the companion suffix to the path while preserving query and fragment text.
sidecarUrl :: Text -> Text
sidecarUrl :: Text -> Text
sidecarUrl Text
url = Text
path Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
".metadata" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
suffix
  where
    (Text
path, Text
suffix) = (Char -> Bool) -> Text -> (Text, Text)
T.break Char -> Bool
queryOrFragment Text
url

-- The characters that end a URL's path.
queryOrFragment :: Char -> Bool
queryOrFragment :: Char -> Bool
queryOrFragment Char
c = Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'?' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'#'

{- | An upstream base URL and its one parse, so a request under it appends its path rather than
parsing the joined URL again. 'mkBaseRequest' is the only builder.
-}
data BaseRequest = BaseRequest RegistryUrl (Maybe Request)

-- The parse is a function of the URL, so the URL alone decides equality and display.
instance Eq BaseRequest where
    BaseRequest
left == :: BaseRequest -> BaseRequest -> Bool
== BaseRequest
right = BaseRequest -> RegistryUrl
baseRequestUrl BaseRequest
left RegistryUrl -> RegistryUrl -> Bool
forall a. Eq a => a -> a -> Bool
== BaseRequest -> RegistryUrl
baseRequestUrl BaseRequest
right

instance Show BaseRequest where
    showsPrec :: Int -> BaseRequest -> ShowS
showsPrec Int
precedence = Int -> RegistryUrl -> ShowS
forall a. Show a => Int -> a -> ShowS
showsPrec Int
precedence (RegistryUrl -> ShowS)
-> (BaseRequest -> RegistryUrl) -> BaseRequest -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BaseRequest -> RegistryUrl
baseRequestUrl

{- | Parse @url@ joined to an empty path, which is the request every path under it extends. A URL
with a query or a fragment keeps no parse, because a path joined after either lands inside it.
-}
mkBaseRequest :: RegistryUrl -> BaseRequest
mkBaseRequest :: RegistryUrl -> BaseRequest
mkBaseRequest RegistryUrl
url = RegistryUrl -> Maybe Request -> BaseRequest
BaseRequest RegistryUrl
url Maybe Request
directory
  where
    text :: Text
text = RegistryUrl -> Text
registryUrlText RegistryUrl
url
    directory :: Maybe Request
directory
        | (Char -> Bool) -> Text -> Bool
T.any Char -> Bool
queryOrFragment Text
text = Maybe Request
forall a. Maybe a
Nothing
        | Bool
otherwise = Either UrlFormationError Request -> Maybe Request
forall l r. Either l r -> Maybe r
rightToMaybe (Text -> Text -> Either UrlFormationError Text
joinPath Text
text Text
"" Either UrlFormationError Text
-> (Text -> Either UrlFormationError Request)
-> Either UrlFormationError Request
forall a b.
Either UrlFormationError a
-> (a -> Either UrlFormationError b) -> Either UrlFormationError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either UrlFormationError Request
parseRequestEither)

-- | The URL the base was parsed from.
baseRequestUrl :: BaseRequest -> RegistryUrl
baseRequestUrl :: BaseRequest -> RegistryUrl
baseRequestUrl (BaseRequest RegistryUrl
url Maybe Request
_) = RegistryUrl
url

{- | The request for the base joined to an already-encoded @suffix@, equal to 'parseRequestEither' of
the joined URL. It parses that URL only when the base kept no parse or the suffix is not verbatim.
-}
requestAt :: BaseRequest -> Text -> Either UrlFormationError Request
requestAt :: BaseRequest -> Text -> Either UrlFormationError Request
requestAt base :: BaseRequest
base@(BaseRequest RegistryUrl
url Maybe Request
_) Text
suffix =
    Either UrlFormationError Request
-> (Request -> Either UrlFormationError Request)
-> Maybe Request
-> Either UrlFormationError Request
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Text -> Text -> Either UrlFormationError Text
joinPath (RegistryUrl -> Text
registryUrlText RegistryUrl
url) Text
suffix Either UrlFormationError Text
-> (Text -> Either UrlFormationError Request)
-> Either UrlFormationError Request
forall a b.
Either UrlFormationError a
-> (a -> Either UrlFormationError b) -> Either UrlFormationError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either UrlFormationError Request
parseRequestEither) Request -> Either UrlFormationError Request
forall a b. b -> Either a b
Right (BaseRequest -> Text -> Maybe Request
requestUnder BaseRequest
base Text
suffix)

requestUnder :: BaseRequest -> Text -> Maybe Request
requestUnder :: BaseRequest -> Text -> Maybe Request
requestUnder (BaseRequest RegistryUrl
_ Maybe Request
directory) Text
suffix = do
    request <- Maybe Request
directory
    guard (verbatimPath suffix)
    pure request{Client.path = Client.path request <> encodeUtf8 suffix}

-- How far a scan of path text has got: between characters, inside an escape, or past a refusal.
data PathScan = Between | AwaitingFirstHexDigit | AwaitingSecondHexDigit | Refused
    deriving stock (PathScan -> PathScan -> Bool
(PathScan -> PathScan -> Bool)
-> (PathScan -> PathScan -> Bool) -> Eq PathScan
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PathScan -> PathScan -> Bool
== :: PathScan -> PathScan -> Bool
$c/= :: PathScan -> PathScan -> Bool
/= :: PathScan -> PathScan -> Bool
Eq)

{- Text that http-client's parse keeps as path byte for byte: unreserved characters, @\@@, @/@,
and complete escapes. An encoded component writes nothing else. -}
verbatimPath :: Text -> Bool
verbatimPath :: Text -> Bool
verbatimPath = (PathScan -> PathScan -> Bool
forall a. Eq a => a -> a -> Bool
== PathScan
Between) (PathScan -> Bool) -> (Text -> PathScan) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PathScan -> Char -> PathScan) -> PathScan -> Text -> PathScan
forall a. (a -> Char -> a) -> a -> Text -> a
T.foldl' PathScan -> Char -> PathScan
step PathScan
Between
  where
    step :: PathScan -> Char -> PathScan
step PathScan
Between Char
c
        | Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'%' = PathScan
AwaitingFirstHexDigit
        | Char -> Bool
isAsciiAlphaNum Char
c Bool -> Bool -> Bool
|| Char
c Char -> String -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` (String
"-._~@/" :: String) = PathScan
Between
    step PathScan
AwaitingFirstHexDigit Char
c | Char -> Bool
isHexDigit Char
c = PathScan
AwaitingSecondHexDigit
    step PathScan
AwaitingSecondHexDigit Char
c | Char -> Bool
isHexDigit Char
c = PathScan
Between
    step PathScan
_ Char
_ = PathScan
Refused