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

-- | Native Cargo routes for the one sparse registry that replaces crates.io.
module Ecluse.Core.Registry.Cargo.Route.Internal (
    cargoRouter,
    cargoRoutes,
    cargoRouteSpecs,
    takeIndexPath,
    artifactCoordinate,
    indexContract,
    indexReplies,
    artifactContract,
    artifactReplies,
) where

import Data.List.NonEmpty qualified as NE
import Data.Text qualified as T
import Network.HTTP.Types (ResponseHeaders, Status, status200, status304, status401, status403, status404, status405, status406, status500, status502, status503)
import Network.Wai (Request, ResponseReceived)

import Ecluse.Core.Ecosystem (Ecosystem (Cargo))
import Ecluse.Core.Package (PackageName, pkgEcosystem, renderPackageName)
import Ecluse.Core.Registry.Cargo.Discovery (renderCargoDiscovery)
import Ecluse.Core.Registry.Cargo.Project (cargoArchiveFilename, projectName)
import Ecluse.Core.Registry.Cargo.Request (cargoIndexPath)
import Ecluse.Core.Server.Context (
    Handler,
    MountBinding (bindingPackumentDeps, bindingPublishDeps),
    MountRouter,
    PackumentDeps (..),
    RequestCtx (..),
    ResponseAction (..),
    RouteAction (RouteAction),
    pdPrivateBase,
 )
import Ecluse.Core.Server.Contract (
    BodySchema (SchemaOpaque, SchemaText),
    PassthroughBody (..),
    PassthroughResponse,
    RequestSpec (..),
    ResponseChoice (FirstResponse, SecondResponse),
    ResponseContract,
    ResponseValue,
    chooseContract,
    emptyContract,
    mediaContract,
    optionalBodyContract,
    passthroughContract,
    passthroughResponse,
    plainTextRefusal,
    responseValue,
 )
import Ecluse.Core.Server.Path (Filename, mkFilename)
import Ecluse.Core.Server.Pipeline.Packument (PackumentReplies (..), packumentAction)
import Ecluse.Core.Server.Pipeline.Packument.Response (MetadataResponse, keepPrivateUnauthorised, metadataReplies)
import Ecluse.Core.Server.Pipeline.Publish (PublishReplies (..), servePublish)
import Ecluse.Core.Server.Pipeline.Shared (edgeTokenMatches, forwardedCredential)
import Ecluse.Core.Server.Pipeline.Tarball (tarballAction)
import Ecluse.Core.Server.Pipeline.Tarball.Types (TarballReplies (..))
import Ecluse.Core.Server.Response (Refusal, refusalHelpBytes, renderRefusal)
import Ecluse.Core.Server.Response.Summary (detailedRejections)
import Ecluse.Core.Server.Route (Capture (..), MediaNegotiation (AcceptsAnything), MethodMatch (MethodPut, MethodRead), PatternSeg (SegCap, SegLit), Route (Route), RouteName (RouteName), routerOf, safeSegment)
import Ecluse.Core.Server.RouteDescription (RouteSpec, catchAllSpecs, specsOf, unsupportedPathParam)
import Ecluse.Core.Version (Version, mkVersion, renderVersion, versionKey, versionKeyIn)

-- | Route a request to the registry's discovery, index, archive and publication handlers.
cargoRouter :: MountRouter
cargoRouter :: MountRouter
cargoRouter = RouteAction -> [Route CargoCap] -> MountRouter
forall v. RouteAction -> [Route v] -> MountRouter
routerOf RouteAction
notFound [Route CargoCap]
cargoRoutes

data CargoCap = CargoProject PackageName | CargoVersion Version | CargoFile Text

-- | Discovery, sparse records, archives and publication, with shared capture validation.
cargoRoutes :: [Route CargoCap]
cargoRoutes :: [Route CargoCap]
cargoRoutes =
    [ RouteName
-> MethodMatch
-> MediaNegotiation DiscoveryResponse
-> [PatternSeg CargoCap]
-> (ByteString
    -> [CargoCap] -> Maybe (ResponseAction DiscoveryResponse))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract DiscoveryResponse
-> Route CargoCap
forall v response.
RouteName
-> MethodMatch
-> MediaNegotiation response
-> [PatternSeg v]
-> (ByteString -> [v] -> Maybe (ResponseAction response))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract response
-> Route v
Route
        (Text -> RouteName
RouteName Text
"discovery")
        MethodMatch
MethodRead
        MediaNegotiation DiscoveryResponse
forall response. MediaNegotiation response
AcceptsAnything
        [Text -> PatternSeg CargoCap
forall v. Text -> PatternSeg v
SegLit Text
"config.json"]
        (\ByteString
_ [CargoCap]
captures -> ResponseAction DiscoveryResponse
discoveryAction ResponseAction DiscoveryResponse
-> Maybe () -> Maybe (ResponseAction DiscoveryResponse)
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 ([CargoCap] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [CargoCap]
captures))
        Text
"Discover the local sparse registry"
        Text
"Answered locally after edge authentication. Returns local archive locations, the publication API when publication is configured, and whether clients must authenticate."
        Maybe RequestSpec
forall a. Maybe a
Nothing
        ResponseContract DiscoveryResponse
discoveryContract
    , RouteName
-> MethodMatch
-> MediaNegotiation PassthroughResponse
-> [PatternSeg CargoCap]
-> (ByteString
    -> [CargoCap] -> Maybe (ResponseAction PassthroughResponse))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract PassthroughResponse
-> Route CargoCap
forall v response.
RouteName
-> MethodMatch
-> MediaNegotiation response
-> [PatternSeg v]
-> (ByteString -> [v] -> Maybe (ResponseAction response))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract response
-> Route v
Route
        (Text -> RouteName
RouteName Text
"archive")
        MethodMatch
MethodRead
        MediaNegotiation PassthroughResponse
forall response. MediaNegotiation response
AcceptsAnything
        [Text -> PatternSeg CargoCap
forall v. Text -> PatternSeg v
SegLit Text
"crates", Capture CargoCap -> PatternSeg CargoCap
forall v. Capture v -> PatternSeg v
SegCap Capture CargoCap
projectCapture, Capture CargoCap -> PatternSeg CargoCap
forall v. Capture v -> PatternSeg v
SegCap Capture CargoCap
versionCapture, Capture CargoCap -> PatternSeg CargoCap
forall v. Capture v -> PatternSeg v
SegCap Capture CargoCap
fileCapture]
        ( \ByteString
method -> \case
            [CargoProject PackageName
name, CargoVersion Version
version, CargoFile Text
file] -> TarballReplies PassthroughResponse
-> ByteString
-> PackageName
-> Version
-> Filename
-> ResponseAction PassthroughResponse
forall response.
TarballReplies response
-> ByteString
-> PackageName
-> Version
-> Filename
-> ResponseAction response
tarballAction TarballReplies PassthroughResponse
artifactReplies ByteString
method PackageName
name Version
version (Filename -> ResponseAction PassthroughResponse)
-> Maybe Filename -> Maybe (ResponseAction PassthroughResponse)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PackageName -> Version -> Text -> Maybe Filename
artifactCoordinate PackageName
name Version
version Text
file
            [CargoCap]
_ -> Maybe (ResponseAction PassthroughResponse)
forall a. Maybe a
Nothing
        )
        Text
"Fetch a crate archive"
        Text
"The explicit crate, version and logical filename must agree. A first-party crate never falls back to a public source."
        Maybe RequestSpec
forall a. Maybe a
Nothing
        ResponseContract PassthroughResponse
artifactContract
    , RouteName
-> MethodMatch
-> MediaNegotiation PassthroughResponse
-> [PatternSeg CargoCap]
-> (ByteString
    -> [CargoCap] -> Maybe (ResponseAction PassthroughResponse))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract PassthroughResponse
-> Route CargoCap
forall v response.
RouteName
-> MethodMatch
-> MediaNegotiation response
-> [PatternSeg v]
-> (ByteString -> [v] -> Maybe (ResponseAction response))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract response
-> Route v
Route
        (Text -> RouteName
RouteName Text
"publish")
        MethodMatch
MethodPut
        MediaNegotiation PassthroughResponse
forall response. MediaNegotiation response
AcceptsAnything
        ((Text -> PatternSeg CargoCap) -> [Text] -> [PatternSeg CargoCap]
forall a b. (a -> b) -> [a] -> [b]
map Text -> PatternSeg CargoCap
forall v. Text -> PatternSeg v
SegLit [Text
"api", Text
"v1", Text
"crates", Text
"new"])
        (\ByteString
_ [CargoCap]
captures -> PassthroughResponse
-> (Request
    -> (PassthroughResponse -> IO ResponseReceived)
    -> Handler ResponseReceived)
-> ResponseAction PassthroughResponse
forall response.
response
-> (Request
    -> (response -> IO ResponseReceived) -> Handler ResponseReceived)
-> ResponseAction response
RunPipeline (PublishReplies PassthroughResponse
-> Status -> [Header] -> Text -> PassthroughResponse
forall response.
PublishReplies response -> Status -> [Header] -> Text -> response
publishError PublishReplies PassthroughResponse
publishReplies Status
status500 [] Text
"internal server error") (PublishReplies PassthroughResponse
-> Maybe PackageName
-> Request
-> (PassthroughResponse -> IO ResponseReceived)
-> Handler ResponseReceived
forall response.
PublishReplies response
-> Maybe PackageName
-> Request
-> (response -> IO ResponseReceived)
-> Handler ResponseReceived
servePublish PublishReplies PassthroughResponse
publishReplies Maybe PackageName
forall a. Maybe a
Nothing) ResponseAction PassthroughResponse
-> Maybe () -> Maybe (ResponseAction PassthroughResponse)
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 ([CargoCap] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [CargoCap]
captures))
        Text
"Publish a first-party crate"
        Text
"Relays the validated native upload under the configured publication authority. Other registry management operations have no route."
        (RequestSpec -> Maybe RequestSpec
forall a. a -> Maybe a
Just (Text -> Bool -> BodySchema -> RequestSpec
RequestSpec Text
"The native metadata and crate archive, with uint32 length framing." Bool
True (ByteString -> BodySchema
SchemaOpaque ByteString
"application/octet-stream")))
        ResponseContract PassthroughResponse
publishContract
    , RouteName
-> MethodMatch
-> MediaNegotiation IndexResponse
-> [PatternSeg CargoCap]
-> (ByteString
    -> [CargoCap] -> Maybe (ResponseAction IndexResponse))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract IndexResponse
-> Route CargoCap
forall v response.
RouteName
-> MethodMatch
-> MediaNegotiation response
-> [PatternSeg v]
-> (ByteString -> [v] -> Maybe (ResponseAction response))
-> Text
-> Text
-> Maybe RequestSpec
-> ResponseContract response
-> Route v
Route
        (Text -> RouteName
RouteName Text
"index")
        MethodMatch
MethodRead
        MediaNegotiation IndexResponse
forall response. MediaNegotiation response
AcceptsAnything
        [Capture CargoCap -> PatternSeg CargoCap
forall v. Capture v -> PatternSeg v
SegCap Capture CargoCap
indexCapture]
        (\ByteString
method -> \case [CargoProject PackageName
name] -> ResponseAction IndexResponse
-> Maybe (ResponseAction IndexResponse)
forall a. a -> Maybe a
Just (PackumentReplies IndexResponse
-> ByteString -> PackageName -> ResponseAction IndexResponse
forall response.
PackumentReplies response
-> ByteString -> PackageName -> ResponseAction response
packumentAction PackumentReplies IndexResponse
indexReplies ByteString
method PackageName
name); [CargoCap]
_ -> Maybe (ResponseAction IndexResponse)
forall a. Maybe a
Nothing)
        Text
"Read a crate's sparse index"
        Text
"Returns caller-authorised private records merged with admitted public records. A first-party crate reads only the private origin."
        Maybe RequestSpec
forall a. Maybe a
Nothing
        ResponseContract IndexResponse
indexContract
    ]

-- | Require the native logical filename without inferring a version from hyphenated text.
artifactCoordinate :: PackageName -> Version -> Text -> Maybe Filename
artifactCoordinate :: PackageName -> Version -> Text -> Maybe Filename
artifactCoordinate PackageName
name Version
version Text
file = do
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (PackageName -> Ecosystem
pkgEcosystem PackageName
name Ecosystem -> Ecosystem -> Bool
forall a. Eq a => a -> a -> Bool
== Ecosystem
Cargo)
    _ <- Either ParseError PackageName -> Maybe PackageName
forall l r. Either l r -> Maybe r
rightToMaybe (Text -> Either ParseError PackageName
projectName (PackageName -> Text
renderPackageName PackageName
name))
    _ <- versionKeyIn Cargo version
    guard (file == cargoArchiveFilename (renderPackageName name) version)
    mkFilename file

-- | Accept only the exact lower-case native sparse lookup path.
takeIndexPath :: [Text] -> Maybe (PackageName, [Text])
takeIndexPath :: [Text] -> Maybe (PackageName, [Text])
takeIndexPath [Text]
segments = do
    raw <- [Text] -> Maybe Text
forall a. [a] -> Maybe a
listToMaybe ([Text] -> [Text]
forall a. [a] -> [a]
reverse [Text]
segments)
    name <- rightToMaybe (projectName raw)
    guard (segments == T.splitOn "/" (cargoIndexPath name))
    pure (name, [])

indexCapture :: Capture CargoCap
indexCapture :: Capture CargoCap
indexCapture = Text
-> Text
-> ([Text] -> Maybe (CargoCap, [Text]))
-> (CargoCap -> [Text])
-> Capture CargoCap
forall v.
Text
-> Text
-> ([Text] -> Maybe (v, [Text]))
-> (v -> [Text])
-> Capture v
Capture Text
"indexPath" Text
"The lower-case native sparse path, including its name prefix." (((PackageName, [Text]) -> (CargoCap, [Text]))
-> Maybe (PackageName, [Text]) -> Maybe (CargoCap, [Text])
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((PackageName -> CargoCap)
-> (PackageName, [Text]) -> (CargoCap, [Text])
forall a b c. (a -> b) -> (a, c) -> (b, c)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first PackageName -> CargoCap
CargoProject) (Maybe (PackageName, [Text]) -> Maybe (CargoCap, [Text]))
-> ([Text] -> Maybe (PackageName, [Text]))
-> [Text]
-> Maybe (CargoCap, [Text])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Maybe (PackageName, [Text])
takeIndexPath) (\case CargoProject PackageName
name -> HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"/" (PackageName -> Text
cargoIndexPath PackageName
name); CargoCap
_ -> [])

projectCapture :: Capture CargoCap
projectCapture :: Capture CargoCap
projectCapture = Text
-> Text
-> ([Text] -> Maybe (CargoCap, [Text]))
-> (CargoCap -> [Text])
-> Capture CargoCap
forall v.
Text
-> Text
-> ([Text] -> Maybe (v, [Text]))
-> (v -> [Text])
-> Capture v
Capture Text
"crate" Text
"The crate's exact published spelling." [Text] -> Maybe (CargoCap, [Text])
consume (\case CargoProject PackageName
name -> [PackageName -> Text
renderPackageName PackageName
name]; CargoCap
_ -> [])
  where
    consume :: [Text] -> Maybe (CargoCap, [Text])
consume = \case
        Text
raw : [Text]
rest -> (\PackageName
name -> (PackageName -> CargoCap
CargoProject PackageName
name, [Text]
rest)) (PackageName -> (CargoCap, [Text]))
-> Maybe PackageName -> Maybe (CargoCap, [Text])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either ParseError PackageName -> Maybe PackageName
forall l r. Either l r -> Maybe r
rightToMaybe (Text -> Either ParseError PackageName
projectName Text
raw)
        [Text]
_ -> Maybe (CargoCap, [Text])
forall a. Maybe a
Nothing

versionCapture :: Capture CargoCap
versionCapture :: Capture CargoCap
versionCapture = Text
-> Text
-> ([Text] -> Maybe (CargoCap, [Text]))
-> (CargoCap -> [Text])
-> Capture CargoCap
forall v.
Text
-> Text
-> ([Text] -> Maybe (v, [Text]))
-> (v -> [Text])
-> Capture v
Capture Text
"version" Text
"The raw native Cargo version." [Text] -> Maybe (CargoCap, [Text])
consume (\case CargoVersion Version
version -> [Version -> Text
renderVersion Version
version]; CargoCap
_ -> [])
  where
    consume :: [Text] -> Maybe (CargoCap, [Text])
consume = \case
        Text
raw : [Text]
rest -> let version :: Version
version = Ecosystem -> Text -> Version
mkVersion Ecosystem
Cargo Text
raw in (Version -> CargoCap
CargoVersion Version
version, [Text]
rest) (CargoCap, [Text]) -> Maybe VersionKey -> Maybe (CargoCap, [Text])
forall a b. a -> Maybe b -> Maybe a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Version -> Maybe VersionKey
versionKey Version
version
        [Text]
_ -> Maybe (CargoCap, [Text])
forall a. Maybe a
Nothing

fileCapture :: Capture CargoCap
fileCapture :: Capture CargoCap
fileCapture = Text
-> Text
-> ([Text] -> Maybe (CargoCap, [Text]))
-> (CargoCap -> [Text])
-> Capture CargoCap
forall v.
Text
-> Text
-> ([Text] -> Maybe (v, [Text]))
-> (v -> [Text])
-> Capture v
Capture Text
"file" Text
"The exact crate-version.crate logical filename." ((Text -> CargoCap) -> [Text] -> Maybe (CargoCap, [Text])
forall v. (Text -> v) -> [Text] -> Maybe (v, [Text])
safeSegment Text -> CargoCap
CargoFile) (\case CargoFile Text
file -> [Text
file]; CargoCap
_ -> [])

type IndexResponse = MetadataResponse (Maybe LByteString)

-- | Responses for admitted sparse metadata and local refusals.
indexContract :: ResponseContract IndexResponse
indexContract :: ResponseContract IndexResponse
indexContract =
    ResponseContract (ResponseValue LByteString)
-> ResponseContract
     (ResponseChoice
        (ResponseValue ())
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseChoice
                          (ResponseValue (Maybe LByteString))
                          (ResponseValue (Maybe LByteString)))))))))
-> ResponseContract IndexResponse
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text
-> BodySchema
-> ResponseContract (ResponseValue LByteString)
mediaContract Status
status200 Text
"Admitted native sparse records." (ByteString -> BodySchema
SchemaOpaque ByteString
"text/plain")) (ResponseContract
   (ResponseChoice
      (ResponseValue ())
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseChoice
                     (ResponseValue (Maybe LByteString))
                     (ResponseChoice
                        (ResponseValue (Maybe LByteString))
                        (ResponseValue (Maybe LByteString)))))))))
 -> ResponseContract IndexResponse)
-> ResponseContract
     (ResponseChoice
        (ResponseValue ())
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseChoice
                          (ResponseValue (Maybe LByteString))
                          (ResponseValue (Maybe LByteString)))))))))
-> ResponseContract IndexResponse
forall a b. (a -> b) -> a -> b
$
        ResponseContract (ResponseValue ())
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseValue (Maybe LByteString))))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue ())
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseChoice
                          (ResponseValue (Maybe LByteString))
                          (ResponseValue (Maybe LByteString)))))))))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status -> Text -> ResponseContract (ResponseValue ())
emptyContract Status
status304 Text
"The admitted records match the supplied validator.") (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseChoice
                     (ResponseValue (Maybe LByteString))
                     (ResponseValue (Maybe LByteString))))))))
 -> ResponseContract
      (ResponseChoice
         (ResponseValue ())
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseChoice
                     (ResponseValue (Maybe LByteString))
                     (ResponseChoice
                        (ResponseValue (Maybe LByteString))
                        (ResponseChoice
                           (ResponseValue (Maybe LByteString))
                           (ResponseValue (Maybe LByteString))))))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseValue (Maybe LByteString))))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue ())
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseChoice
                          (ResponseValue (Maybe LByteString))
                          (ResponseValue (Maybe LByteString)))))))))
forall a b. (a -> b) -> a -> b
$
            ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseValue (Maybe LByteString)))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseValue (Maybe LByteString))))))))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status401 Text
"Authentication is required.") (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseValue (Maybe LByteString)))))))
 -> ResponseContract
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseChoice
                     (ResponseValue (Maybe LByteString))
                     (ResponseChoice
                        (ResponseValue (Maybe LByteString))
                        (ResponseValue (Maybe LByteString)))))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseValue (Maybe LByteString)))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseChoice
                       (ResponseValue (Maybe LByteString))
                       (ResponseValue (Maybe LByteString))))))))
forall a b. (a -> b) -> a -> b
$
                ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseValue (Maybe LByteString))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseValue (Maybe LByteString)))))))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status403 Text
"Access was refused.") (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseValue (Maybe LByteString))))))
 -> ResponseContract
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseChoice
                     (ResponseValue (Maybe LByteString))
                     (ResponseValue (Maybe LByteString))))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseValue (Maybe LByteString))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseChoice
                    (ResponseValue (Maybe LByteString))
                    (ResponseValue (Maybe LByteString)))))))
forall a b. (a -> b) -> a -> b
$
                    ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseValue (Maybe LByteString)))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseValue (Maybe LByteString))))))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status404 Text
"No package is available in this registry: no configured upstream has the name or lists a version of it, or no version passed policy and admission.") (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseValue (Maybe LByteString)))))
 -> ResponseContract
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseChoice
                  (ResponseValue (Maybe LByteString))
                  (ResponseValue (Maybe LByteString)))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseValue (Maybe LByteString)))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseChoice
                 (ResponseValue (Maybe LByteString))
                 (ResponseValue (Maybe LByteString))))))
forall a b. (a -> b) -> a -> b
$
                        ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseValue (Maybe LByteString))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseValue (Maybe LByteString)))))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status406 Text
"The requested encoding is unavailable.") (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseValue (Maybe LByteString))))
 -> ResponseContract
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseChoice
               (ResponseValue (Maybe LByteString))
               (ResponseValue (Maybe LByteString))))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseValue (Maybe LByteString))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseChoice
              (ResponseValue (Maybe LByteString))
              (ResponseValue (Maybe LByteString)))))
forall a b. (a -> b) -> a -> b
$
                            ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseValue (Maybe LByteString)))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseValue (Maybe LByteString))))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status500 Text
"The registry could not decide.") (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseValue (Maybe LByteString)))
 -> ResponseContract
      (ResponseChoice
         (ResponseValue (Maybe LByteString))
         (ResponseChoice
            (ResponseValue (Maybe LByteString))
            (ResponseValue (Maybe LByteString)))))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseValue (Maybe LByteString)))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseChoice
           (ResponseValue (Maybe LByteString))
           (ResponseValue (Maybe LByteString))))
forall a b. (a -> b) -> a -> b
$
                                ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseValue (Maybe LByteString)))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract
                                    (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status502 Text
"An origin reply was invalid or unusable, such as a different identity or an index file whose every row is malformed.")
                                    (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status503 Text
"The registry is temporarily unavailable.")

refusalContract :: Status -> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract :: Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status Text
description = Status
-> Text
-> BodySchema
-> ResponseContract (ResponseValue (Maybe LByteString))
optionalBodyContract Status
status Text
description (ByteString -> BodySchema
SchemaText ByteString
"text/plain")

-- | Render public policy and evaluation diagnostics, keeping access refusals and misses quiet.
indexReplies :: PackumentReplies IndexResponse
indexReplies :: PackumentReplies IndexResponse
indexReplies =
    (([ServeDecision] -> Text)
-> (Refusal -> Maybe LByteString) -> PackumentReplies IndexResponse
forall refusal.
([ServeDecision] -> Text)
-> (Refusal -> refusal)
-> PackumentReplies (MetadataResponse refusal)
metadataReplies [ServeDecision] -> Text
detailedRejections Refusal -> Maybe LByteString
renderedRefusal)
        { packumentUnauthorised = packumentUnauthorised quiet
        , packumentPrivateRefused = keepPrivateUnauthorised quiet
        , packumentNotFound = packumentNotFound quiet
        }
  where
    plain :: PackumentReplies IndexResponse
plain = ([ServeDecision] -> Text)
-> (Refusal -> Maybe LByteString) -> PackumentReplies IndexResponse
forall refusal.
([ServeDecision] -> Text)
-> (Refusal -> refusal)
-> PackumentReplies (MetadataResponse refusal)
metadataReplies [ServeDecision] -> Text
detailedRejections Refusal -> Maybe LByteString
refusalHelpBytes
    quiet :: PackumentReplies IndexResponse
quiet = PackumentReplies IndexResponse
plain{packumentUnauthorised = \[Header]
headers -> PackumentReplies IndexResponse
-> [Header] -> Refusal -> IndexResponse
forall response.
PackumentReplies response -> [Header] -> Refusal -> response
packumentUnauthorised PackumentReplies IndexResponse
plain ([Header]
challenge [Header] -> [Header] -> [Header]
forall a. Semigroup a => a -> a -> a
<> [Header]
headers)}

renderedRefusal :: Refusal -> Maybe LByteString
renderedRefusal :: Refusal -> Maybe LByteString
renderedRefusal = LByteString -> Maybe LByteString
forall a. a -> Maybe a
Just (LByteString -> Maybe LByteString)
-> (Refusal -> LByteString) -> Refusal -> Maybe LByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> LByteString
forall l s. LazyStrict l s => s -> l
fromStrict (ByteString -> LByteString)
-> (Refusal -> ByteString) -> Refusal -> LByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
forall a b. ConvertUtf8 a b => a -> b
encodeUtf8 (Text -> ByteString) -> (Refusal -> Text) -> Refusal -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Refusal -> Text
renderRefusal

-- | Native archives share streamed responses and local refusal status codes.
artifactContract :: ResponseContract PassthroughResponse
artifactContract :: ResponseContract PassthroughResponse
artifactContract = Text -> ResponseContract PassthroughResponse
passthroughContract Text
"Relays the selected archive. Authentication, admission, integrity and availability failures return a local refusal. A private upstream reply that was invalid or unusable answers a local `502`."

-- | Render public archive diagnostics while access refusals and missing archives keep quiet bodies.
artifactReplies :: TarballReplies PassthroughResponse
artifactReplies :: TarballReplies PassthroughResponse
artifactReplies =
    TarballReplies
        { tarballError :: Status -> [Header] -> Refusal -> PassthroughResponse
tarballError = \Status
status -> Bool -> Status -> [Header] -> Refusal -> PassthroughResponse
archiveRefusal (Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
status401 Bool -> Bool -> Bool
|| Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
status404) Status
status
        , tarballPrivateRefused :: Int -> [Header] -> Refusal -> PassthroughResponse
tarballPrivateRefused = \Int
code -> Bool -> Status -> [Header] -> Refusal -> PassthroughResponse
archiveRefusal Bool
True (if Int
code Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
401 then Status
status401 else Status
status403)
        , tarballStream :: Status -> [Header] -> StreamingBody -> PassthroughResponse
tarballStream = \Status
status [Header]
headers StreamingBody
body -> Status -> [Header] -> PassthroughBody -> PassthroughResponse
passthroughResponse Status
status [Header]
headers (StreamingBody -> PassthroughBody
PassthroughStream StreamingBody
body)
        , tarballEmpty :: Status -> [Header] -> PassthroughResponse
tarballEmpty = \Status
status [Header]
headers -> Status -> [Header] -> PassthroughBody -> PassthroughResponse
passthroughResponse Status
status [Header]
headers PassthroughBody
PassthroughEmpty
        }

-- A quiet refusal carries only configured help, and every 401 carries the native challenge.
archiveRefusal :: Bool -> Status -> ResponseHeaders -> Refusal -> PassthroughResponse
archiveRefusal :: Bool -> Status -> [Header] -> Refusal -> PassthroughResponse
archiveRefusal Bool
quiet Status
status [Header]
headers Refusal
refusal =
    Status -> [Header] -> PassthroughBody -> PassthroughResponse
passthroughResponse
        Status
status
        (if Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
status401 then [Header]
challenge [Header] -> [Header] -> [Header]
forall a. Semigroup a => a -> a -> a
<> [Header]
headers else [Header]
headers)
        (PassthroughBody
-> (LByteString -> PassthroughBody)
-> Maybe LByteString
-> PassthroughBody
forall b a. b -> (a -> b) -> Maybe a -> b
maybe PassthroughBody
PassthroughEmpty LByteString -> PassthroughBody
PassthroughBytes ((if Bool
quiet then Refusal -> Maybe LByteString
refusalHelpBytes else Refusal -> Maybe LByteString
renderedRefusal) Refusal
refusal))

type DiscoveryResponse = ResponseChoice (ResponseValue LByteString) (ResponseChoice (ResponseValue (Maybe LByteString)) (ResponseValue (Maybe LByteString)))

discoveryContract :: ResponseContract DiscoveryResponse
discoveryContract :: ResponseContract DiscoveryResponse
discoveryContract =
    ResponseContract (ResponseValue LByteString)
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseValue (Maybe LByteString)))
-> ResponseContract DiscoveryResponse
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract (Status
-> Text
-> BodySchema
-> ResponseContract (ResponseValue LByteString)
mediaContract Status
status200 Text
"Local sparse registry discovery." (ByteString -> BodySchema
SchemaOpaque ByteString
"application/json")) (ResponseContract
   (ResponseChoice
      (ResponseValue (Maybe LByteString))
      (ResponseValue (Maybe LByteString)))
 -> ResponseContract DiscoveryResponse)
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseValue (Maybe LByteString)))
-> ResponseContract DiscoveryResponse
forall a b. (a -> b) -> a -> b
$
        ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseContract
     (ResponseChoice
        (ResponseValue (Maybe LByteString))
        (ResponseValue (Maybe LByteString)))
forall a b.
ResponseContract a
-> ResponseContract b -> ResponseContract (ResponseChoice a b)
chooseContract
            (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status401 Text
"The client must retry with a Cargo credential provider.")
            (Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status503 Text
"Discovery could not be answered.")

discoveryAction :: ResponseAction DiscoveryResponse
discoveryAction :: ResponseAction DiscoveryResponse
discoveryAction = DiscoveryResponse
-> (Request
    -> (DiscoveryResponse -> IO ResponseReceived)
    -> Handler ResponseReceived)
-> ResponseAction DiscoveryResponse
forall response.
response
-> (Request
    -> (response -> IO ResponseReceived) -> Handler ResponseReceived)
-> ResponseAction response
RunPipeline (Status -> [Header] -> Text -> DiscoveryResponse
discoveryError Status
status503 [] Text
"registry discovery is unavailable") Request
-> (DiscoveryResponse -> IO ResponseReceived)
-> Handler ResponseReceived
serveDiscovery

{- Discovery reads no upstream. Authentication is required whenever a private upstream or the
edge token is configured, so a private outage surfaces at the first index read instead. -}
serveDiscovery :: Request -> (DiscoveryResponse -> IO ResponseReceived) -> Handler ResponseReceived
serveDiscovery :: Request
-> (DiscoveryResponse -> IO ResponseReceived)
-> Handler ResponseReceived
serveDiscovery Request
request DiscoveryResponse -> IO ResponseReceived
respond = do
    mount <- (RequestCtx -> MountBinding) -> Handler MountBinding
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks RequestCtx -> MountBinding
ctxMount
    let deps = MountBinding -> PackumentDeps
bindingPackumentDeps MountBinding
mount
    liftIO . respond $
        if edgeTokenMatches (pdInboundToken deps) (forwardedCredential mount request)
            then
                FirstResponse . responseValue [("Cache-Control", "no-store")] . fromStrict $
                    renderCargoDiscovery
                        (pdMountBaseUrl deps <> "/crates/{crate}/{version}/{crate}-{version}.crate")
                        (pdMountBaseUrl deps <$ guard (isJust (bindingPublishDeps mount)))
                        (isJust (pdInboundToken deps) || isJust (pdPrivateBase deps))
            else discoveryError status401 challenge "authentication required"

discoveryError :: Status -> ResponseHeaders -> Text -> DiscoveryResponse
discoveryError :: Status -> [Header] -> Text -> DiscoveryResponse
discoveryError Status
status [Header]
headers Text
message =
    let value :: ResponseValue (Maybe LByteString)
value = [Header] -> Maybe LByteString -> ResponseValue (Maybe LByteString)
forall a. [Header] -> a -> ResponseValue a
responseValue ((HeaderName
"Cache-Control", ByteString
"no-store") Header -> [Header] -> [Header]
forall a. a -> [a] -> [a]
: [Header]
headers) (LByteString -> Maybe LByteString
forall a. a -> Maybe a
Just (ByteString -> LByteString
forall l s. LazyStrict l s => s -> l
fromStrict (Text -> ByteString
forall a b. ConvertUtf8 a b => a -> b
encodeUtf8 Text
message)))
     in ResponseChoice
  (ResponseValue (Maybe LByteString))
  (ResponseValue (Maybe LByteString))
-> DiscoveryResponse
forall a b. b -> ResponseChoice a b
SecondResponse (if Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
status401 then ResponseValue (Maybe LByteString)
-> ResponseChoice
     (ResponseValue (Maybe LByteString))
     (ResponseValue (Maybe LByteString))
forall a b. a -> ResponseChoice a b
FirstResponse ResponseValue (Maybe LByteString)
value else ResponseValue (Maybe LByteString)
-> ResponseChoice
     (ResponseValue (Maybe LByteString))
     (ResponseValue (Maybe LByteString))
forall a b. b -> ResponseChoice a b
SecondResponse ResponseValue (Maybe LByteString)
value)

challenge :: ResponseHeaders
challenge :: [Header]
challenge = [(HeaderName
"WWW-Authenticate", ByteString
"Cargo")]

publishContract :: ResponseContract PassthroughResponse
publishContract :: ResponseContract PassthroughResponse
publishContract = Text -> ResponseContract PassthroughResponse
passthroughContract Text
"Relays the publication target's response after first-party authority and native upload validation. Disabled publication returns 405."

publishReplies :: PublishReplies PassthroughResponse
publishReplies :: PublishReplies PassthroughResponse
publishReplies =
    PublishReplies
        { publishAllowedMethods :: ByteString
publishAllowedMethods = ByteString
"PUT"
        , publishDisabledReply :: [Header] -> Maybe HelpMessage -> PassthroughResponse
publishDisabledReply = \[Header]
headers Maybe HelpMessage
_ -> Status -> [Header] -> Text -> PassthroughResponse
plainTextRefusal Status
status405 [Header]
headers Text
"publishing is not enabled on this view"
        , publishRelayed :: Status -> [Header] -> LByteString -> PassthroughResponse
publishRelayed = \Status
status [Header]
headers LByteString
body -> Status -> [Header] -> PassthroughBody -> PassthroughResponse
passthroughResponse Status
status (if Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
status401 then [Header]
challenge [Header] -> [Header] -> [Header]
forall a. Semigroup a => a -> a -> a
<> [Header]
headers else [Header]
headers) (LByteString -> PassthroughBody
PassthroughBytes LByteString
body)
        , publishError :: Status -> [Header] -> Text -> PassthroughResponse
publishError = \Status
status [Header]
headers -> Status -> [Header] -> Text -> PassthroughResponse
plainTextRefusal Status
status (if Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
status401 then [Header]
challenge [Header] -> [Header] -> [Header]
forall a. Semigroup a => a -> a -> a
<> [Header]
headers else [Header]
headers)
        }

notFound :: RouteAction
notFound :: RouteAction
notFound = ResponseContract (ResponseValue (Maybe LByteString))
-> ResponseAction (ResponseValue (Maybe LByteString))
-> RouteAction
forall response.
ResponseContract response -> ResponseAction response -> RouteAction
RouteAction ResponseContract (ResponseValue (Maybe LByteString))
notFoundContract (ResponseValue (Maybe LByteString)
-> ResponseAction (ResponseValue (Maybe LByteString))
forall response. response -> ResponseAction response
AnswerLocally ([Header] -> Maybe LByteString -> ResponseValue (Maybe LByteString)
forall a. [Header] -> a -> ResponseValue a
responseValue [] Maybe LByteString
forall a. Maybe a
Nothing))

notFoundContract :: ResponseContract (ResponseValue (Maybe LByteString))
notFoundContract :: ResponseContract (ResponseValue (Maybe LByteString))
notFoundContract = Status
-> Text -> ResponseContract (ResponseValue (Maybe LByteString))
refusalContract Status
status404 Text
"No native route claims this path."

-- | Describe the native routes from their live route table.
cargoRouteSpecs :: NonEmpty RouteSpec
cargoRouteSpecs :: NonEmpty RouteSpec
cargoRouteSpecs = ResponseContract (ResponseValue (Maybe LByteString))
-> ParamSpec -> NonEmpty RouteSpec
forall r. ResponseContract r -> ParamSpec -> NonEmpty RouteSpec
catchAllSpecs ResponseContract (ResponseValue (Maybe LByteString))
notFoundContract ParamSpec
unsupportedPathParam NonEmpty RouteSpec -> [RouteSpec] -> NonEmpty RouteSpec
forall a. NonEmpty a -> [a] -> NonEmpty a
`NE.appendList` (Route CargoCap -> [RouteSpec]) -> [Route CargoCap] -> [RouteSpec]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Route CargoCap -> [RouteSpec]
forall v. Route v -> [RouteSpec]
specsOf [Route CargoCap]
cargoRoutes