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

-- | First-party publication checks caller authority and body identity before target discovery or relay.
module Ecluse.Core.Server.Pipeline.Publish (
    PublishReplies (..),

    -- * The first-party publish handler
    servePublish,
) where

import Data.List (lookup)
import Network.HTTP.Types (ResponseHeaders, Status, hContentType, mkStatus, status400, status401, status403, status413, status500, status501, status502)
import Network.Wai (Request, RequestBodyLength (ChunkedBody, KnownLength), ResponseReceived, getRequestBodyChunk, requestBodyLength, requestHeaders)

import Ecluse.Core.Credential (ClientCredential)
import Ecluse.Core.Package (PackageName, renderPackageName)
import Ecluse.Core.Registry (
    FetchFault (FetchBoundExceeded, FetchCooldown, FetchTransport, FetchUrlUnformable),
    ParseError (parseErrorMessage),
    PublishBodyFault (PublishMalformed, PublishUnsupported),
    PublishRelayResponse (PublishRelayResponse),
 )
import Ecluse.Core.Registry.Adapter.Capability (AdapterPublish (publishCodec, publishCredential, publishRelay, publishRequestExtras, publishUploadClaims), PublishRequestBody (..))
import Ecluse.Core.Registry.Exchange (accumulatingCharge, withinServeCap)
import Ecluse.Core.Registry.Exchange.Types (ExchangeClient (ecDeadlines))
import Ecluse.Core.Registry.Metadata (MetadataError (..))
import Ecluse.Core.Registry.Origin (OriginClient (ocBaseRequest, ocChargeFullRead, ocClient), originClient)
import Ecluse.Core.Registry.Publish (PublishCodec (pcPrepareTarget, pcTargetReadPermille))
import Ecluse.Core.Registry.Request (ServicePresentation, credentialRecover, mkBaseRequest, nativePresentation)
import Ecluse.Core.Security (BodyLimit (PublishRequestBodyLimit), Limits (maxPublishRequestBytes, progressFloor), boundedRead)
import Ecluse.Core.Server.Admission.Budget (scaleCharge)
import Ecluse.Core.Server.Admission.Bytes (withByteAdmission)
import Ecluse.Core.Server.Admission.Meter (MemoryTicket, charge, newChargeRegion)
import Ecluse.Core.Server.Context (
    Handler,
    MountBinding (bindingPackumentDeps, bindingPublishDeps),
    PackumentDeps (pdHelp, pdMountBaseUrl),
    PublishDeps (..),
    ServeRuntime (..),
    ctxMount,
    ctxRuntime,
 )
import Ecluse.Core.Server.Pipeline.Shared
import Ecluse.Core.Server.Response (HelpMessage, appendHelp)

-- | Route-owned replies, including the publication target's unrestricted status codes.
data PublishReplies response = PublishReplies
    { forall response. PublishReplies response -> ByteString
publishAllowedMethods :: ByteString
    -- ^ Methods advertised when this route has no configured publication target.
    , forall response.
PublishReplies response
-> ResponseHeaders -> Maybe HelpMessage -> response
publishDisabledReply :: ResponseHeaders -> Maybe HelpMessage -> response
    -- ^ Preserve the route's disabled-publication response body.
    , forall response.
PublishReplies response
-> Status -> ResponseHeaders -> LByteString -> response
publishRelayed :: Status -> ResponseHeaders -> LByteString -> response
    -- ^ Relay the publication target's status and bytes.
    , forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError :: Status -> ResponseHeaders -> Text -> response
    -- ^ Emit an ecosystem-shaped local error.
    }

-- | Relay a configured first-party publish after authentication and body guards.
servePublish ::
    PublishReplies response ->
    Maybe PackageName ->
    Request ->
    (response -> IO ResponseReceived) ->
    Handler ResponseReceived
servePublish :: forall response.
PublishReplies response
-> Maybe PackageName
-> Request
-> (response -> IO ResponseReceived)
-> Handler ResponseReceived
servePublish PublishReplies response
replies Maybe PackageName
name Request
request response -> IO ResponseReceived
respond = do
    mount <- (RequestCtx -> MountBinding) -> Handler MountBinding
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks RequestCtx -> MountBinding
ctxMount
    case bindingPublishDeps mount of
        Maybe PublishDeps
Nothing -> IO ResponseReceived -> Handler ResponseReceived
forall a. IO a -> Handler a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (response -> IO ResponseReceived
respond (PublishReplies response
-> ResponseHeaders -> Maybe HelpMessage -> response
forall response.
PublishReplies response
-> ResponseHeaders -> Maybe HelpMessage -> response
publishDisabledReply PublishReplies response
replies [(HeaderName
"Allow", PublishReplies response -> ByteString
forall response. PublishReplies response -> ByteString
publishAllowedMethods PublishReplies response
replies)] (PackumentDeps -> Maybe HelpMessage
pdHelp (MountBinding -> PackumentDeps
bindingPackumentDeps MountBinding
mount))))
        Just PublishDeps
deps -> PublishReplies response
-> PublishDeps
-> Text
-> Maybe ClientCredential
-> Maybe PackageName
-> Request
-> (response -> IO ResponseReceived)
-> Handler ResponseReceived
forall response.
PublishReplies response
-> PublishDeps
-> Text
-> Maybe ClientCredential
-> Maybe PackageName
-> Request
-> (response -> IO ResponseReceived)
-> Handler ResponseReceived
publishWithDeps PublishReplies response
replies PublishDeps
deps (PackumentDeps -> Text
pdMountBaseUrl (MountBinding -> PackumentDeps
bindingPackumentDeps MountBinding
mount)) (CredentialMapping -> ResponseHeaders -> Maybe ClientCredential
credentialRecover (AdapterPublish -> CredentialMapping
publishCredential (PublishDeps -> AdapterPublish
pubAdapter PublishDeps
deps)) (Request -> ResponseHeaders
requestHeaders Request
request)) Maybe PackageName
name Request
request response -> IO ResponseReceived
respond

-- The body is read under the byte gate alone, so a slow upload holds no CPU slot or memory charge.
-- Memory and CPU admission start after the read and cover inspection, target preparation and relay.
publishWithDeps ::
    PublishReplies response ->
    PublishDeps ->
    Text ->
    Maybe ClientCredential ->
    Maybe PackageName ->
    Request ->
    (response -> IO ResponseReceived) ->
    Handler ResponseReceived
publishWithDeps :: forall response.
PublishReplies response
-> PublishDeps
-> Text
-> Maybe ClientCredential
-> Maybe PackageName
-> Request
-> (response -> IO ResponseReceived)
-> Handler ResponseReceived
publishWithDeps PublishReplies response
replies PublishDeps
deps Text
registry Maybe ClientCredential
clientToken Maybe PackageName
name Request
request response -> IO ResponseReceived
respond
    | Bool -> Bool
not (Maybe Secret -> Maybe ClientCredential -> Bool
edgeTokenMatches (PublishDeps -> Maybe Secret
pubInboundToken PublishDeps
deps) Maybe ClientCredential
clientToken) =
        IO ResponseReceived -> Handler ResponseReceived
forall a. IO a -> Handler a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (response -> IO ResponseReceived
respond (PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status401 [] Text
unauthorisedMessage))
    | Just PackageName
pathName <- Maybe PackageName
name
    , Bool -> Bool
not (PublishDeps -> PackageName -> Bool
pubAllowed PublishDeps
deps PackageName
pathName) =
        IO ResponseReceived -> Handler ResponseReceived
forall a. IO a -> Handler a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (response -> IO ResponseReceived
respond (PublishReplies response -> PublishDeps -> PackageName -> response
forall response.
PublishReplies response -> PublishDeps -> PackageName -> response
outOfScope PublishReplies response
replies PublishDeps
deps PackageName
pathName))
    | Bool
otherwise = case AdapterPublish
-> ResponseHeaders -> Either PublishBodyFault PublishExtras
publishRequestExtras (PublishDeps -> AdapterPublish
pubAdapter PublishDeps
deps) (Request -> ResponseHeaders
requestHeaders Request
request) of
        Left PublishBodyFault
fault -> IO ResponseReceived -> Handler ResponseReceived
forall a. IO a -> Handler a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (response -> IO ResponseReceived
respond (PublishReplies response
-> PublishDeps -> PublishBodyFault -> response
forall response.
PublishReplies response
-> PublishDeps -> PublishBodyFault -> response
bodyRefusal PublishReplies response
replies PublishDeps
deps PublishBodyFault
fault))
        Right PublishExtras
extras
            | Bool
overDeclaredCap -> IO ResponseReceived -> Handler ResponseReceived
forall a. IO a -> Handler a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (response -> IO ResponseReceived
respond (PublishReplies response -> PublishDeps -> response
forall response. PublishReplies response -> PublishDeps -> response
publishTooLarge PublishReplies response
replies PublishDeps
deps))
            | Bool
otherwise -> do
                rt <- (RequestCtx -> ServeRuntime) -> Handler ServeRuntime
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks RequestCtx -> ServeRuntime
ctxRuntime
                liftIO $ do
                    outcome <- withByteAdmission (srMetrics rt) (pubBodyBudget deps) bodyWeight (readThenAdmit rt extras)
                    respond (fromMaybe (bodyBudgetShed replies deps) outcome)
  where
    overDeclaredCap :: Bool
overDeclaredCap = case Request -> RequestBodyLength
requestBodyLength Request
request of
        KnownLength Word64
n -> Word64
n Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (PublishDeps -> Int
pubMaxRequestBytes PublishDeps
deps)
        RequestBodyLength
ChunkedBody -> Bool
False

    bodyWeight :: Int
bodyWeight = case Request -> RequestBodyLength
requestBodyLength Request
request of
        KnownLength Word64
n -> Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
n
        RequestBodyLength
ChunkedBody -> PublishDeps -> Int
pubMaxRequestBytes PublishDeps
deps

    (Maybe ClientCredential
credential, ServicePresentation
presentation) = PublishDeps
-> Maybe ClientCredential
-> (Maybe ClientCredential, ServicePresentation)
publicationAuthority PublishDeps
deps Maybe ClientCredential
clientToken

    readThenAdmit :: ServeRuntime -> PublishExtras -> IO response
readThenAdmit ServeRuntime
rt PublishExtras
extras =
        BodyLimit
-> IO ByteString -> IO (Either LimitError (Int, ByteString))
forall (m :: * -> *).
Monad m =>
BodyLimit
-> m ByteString -> m (Either LimitError (Int, ByteString))
boundedRead (Int -> BodyLimit
PublishRequestBodyLimit (PublishDeps -> Int
pubMaxRequestBytes PublishDeps
deps)) (Request -> IO ByteString
getRequestBodyChunk Request
request) IO (Either LimitError (Int, ByteString))
-> (Either LimitError (Int, ByteString) -> IO response)
-> IO response
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
            Left LimitError
_ -> response -> IO response
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishReplies response -> PublishDeps -> response
forall response. PublishReplies response -> PublishDeps -> response
publishTooLarge PublishReplies response
replies PublishDeps
deps)
            Right (Int
_, ByteString
bytes) -> do
                let body :: PublishRequestBody
body = ByteString
-> Maybe ByteString -> PublishExtras -> PublishRequestBody
PublishRequestBody ByteString
bytes (HeaderName -> ResponseHeaders -> Maybe ByteString
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
hContentType (Request -> ResponseHeaders
requestHeaders Request
request)) PublishExtras
extras
                ServeRuntime
-> (ResponseHeaders -> IO response)
-> (MemoryTicket -> IO response)
-> (response -> IO response)
-> IO response
forall (m :: * -> *) received a.
MonadUnliftIO m =>
ServeRuntime
-> (ResponseHeaders -> m received)
-> (MemoryTicket -> m a)
-> (a -> m received)
-> m received
withMetadataAdmission
                    ServeRuntime
rt
                    (\ResponseHeaders
headers -> response -> IO response
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
shedStatus ResponseHeaders
headers Text
shedMessage))
                    (\MemoryTicket
ticket -> PublishReplies response
-> PublishDeps
-> Text
-> MemoryTicket
-> OriginClient
-> ServicePresentation
-> Maybe PackageName
-> PublishRequestBody
-> IO response
forall response.
PublishReplies response
-> PublishDeps
-> Text
-> MemoryTicket
-> OriginClient
-> ServicePresentation
-> Maybe PackageName
-> PublishRequestBody
-> IO response
inspectAndRelay PublishReplies response
replies PublishDeps
deps Text
registry MemoryTicket
ticket (PublishDeps
-> ServeRuntime -> Maybe ClientCredential -> OriginClient
publicationTarget PublishDeps
deps ServeRuntime
rt Maybe ClientCredential
credential) ServicePresentation
presentation Maybe PackageName
name PublishRequestBody
body)
                    response -> IO response
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

-- The byte reservation, the memory ticket and the CPU slot all stay held through the relay.
inspectAndRelay ::
    PublishReplies response ->
    PublishDeps ->
    Text ->
    MemoryTicket ->
    OriginClient ->
    ServicePresentation ->
    Maybe PackageName ->
    PublishRequestBody ->
    IO response
inspectAndRelay :: forall response.
PublishReplies response
-> PublishDeps
-> Text
-> MemoryTicket
-> OriginClient
-> ServicePresentation
-> Maybe PackageName
-> PublishRequestBody
-> IO response
inspectAndRelay PublishReplies response
replies PublishDeps
deps Text
registry MemoryTicket
ticket OriginClient
target ServicePresentation
presentation Maybe PackageName
name PublishRequestBody
body = do
    workspace <- (Int -> IO ()) -> IO (Int -> IO ())
newChargeRegion (MemoryTicket -> Int -> IO ()
charge MemoryTicket
ticket)
    claims <- publishUploadClaims (pubAdapter deps) ((pubLimits deps){maxPublishRequestBytes = pubMaxRequestBytes deps}) workspace registry body
    case claims of
        Left PublishBodyFault
fault -> response -> IO response
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishReplies response
-> PublishDeps -> PublishBodyFault -> response
forall response.
PublishReplies response
-> PublishDeps -> PublishBodyFault -> response
bodyRefusal PublishReplies response
replies PublishDeps
deps PublishBodyFault
fault)
        Right [Text]
declared -> case [Text] -> Either response PackageName
resolveName [Text]
declared of
            Left response
refusal -> response -> IO response
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure response
refusal
            Right PackageName
agreed -> do
                outcome <- Deadlines
-> ProgressFloor
-> (FetchFault -> MetadataError)
-> IO (Either MetadataError PublishRelayResponse)
-> IO (Either MetadataError PublishRelayResponse)
forall e a.
Deadlines
-> ProgressFloor
-> (FetchFault -> e)
-> IO (Either e a)
-> IO (Either e a)
withinServeCap (ExchangeClient -> Deadlines
ecDeadlines (OriginClient -> ExchangeClient
ocClient OriginClient
target)) (Limits -> ProgressFloor
progressFloor (PublishDeps -> Limits
pubLimits PublishDeps
deps)) FetchFault -> MetadataError
MetadataFetch (IO (Either MetadataError PublishRelayResponse)
 -> IO (Either MetadataError PublishRelayResponse))
-> IO (Either MetadataError PublishRelayResponse)
-> IO (Either MetadataError PublishRelayResponse)
forall a b. (a -> b) -> a -> b
$ do
                    fullRead <- (Int -> IO ()) -> IO (Int -> IO ())
accumulatingCharge (Int -> IO ()
workspace (Int -> IO ()) -> (Int -> Int) -> Int -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int -> Int
scaleCharge (PublishCodec -> Int
pcTargetReadPermille PublishCodec
codec))
                    prepared <- pcPrepareTarget codec target{ocChargeFullRead = fullRead} (pubTargetUrl deps)
                    case prepared of
                        Left MetadataError
fault -> Either MetadataError PublishRelayResponse
-> IO (Either MetadataError PublishRelayResponse)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MetadataError -> Either MetadataError PublishRelayResponse
forall a b. a -> Either a b
Left MetadataError
fault)
                        Right RegistryUrl
approved -> (FetchFault -> MetadataError)
-> Either FetchFault PublishRelayResponse
-> Either MetadataError PublishRelayResponse
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first FetchFault -> MetadataError
MetadataFetch (Either FetchFault PublishRelayResponse
 -> Either MetadataError PublishRelayResponse)
-> IO (Either FetchFault PublishRelayResponse)
-> IO (Either MetadataError PublishRelayResponse)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AdapterPublish
-> ServicePresentation
-> OriginClient
-> PackageName
-> PublishRequestBody
-> IO (Either FetchFault PublishRelayResponse)
publishRelay (PublishDeps -> AdapterPublish
pubAdapter PublishDeps
deps) ServicePresentation
presentation OriginClient
target{ocBaseRequest = mkBaseRequest approved} PackageName
agreed PublishRequestBody
body
                pure (either (targetRefusal replies deps) (renderRelay replies deps . Right) outcome)
  where
    codec :: PublishCodec
codec = AdapterPublish -> ServicePresentation -> PublishCodec
publishCodec (PublishDeps -> AdapterPublish
pubAdapter PublishDeps
deps) ServicePresentation
presentation

    resolveName :: [Text] -> Either response PackageName
resolveName [Text]
claims = case Maybe PackageName
name of
        Just PackageName
pathName -> case (Text -> Maybe PackageName) -> PackageName -> [Text] -> Maybe Text
bodyNameDisagreement (PublishDeps -> Text -> Maybe PackageName
pubProjectName PublishDeps
deps) PackageName
pathName [Text]
claims of
            Just Text
declared -> response -> Either response PackageName
forall a b. a -> Either a b
Left (PublishReplies response
-> PublishDeps -> PackageName -> Text -> response
forall response.
PublishReplies response
-> PublishDeps -> PackageName -> Text -> response
bodyNameMismatch PublishReplies response
replies PublishDeps
deps PackageName
pathName Text
declared)
            Maybe Text
Nothing -> PackageName -> Either response PackageName
forall a b. b -> Either a b
Right PackageName
pathName
        Maybe PackageName
Nothing -> case [Text]
claims of
            [] -> response -> Either response PackageName
forall a b. a -> Either a b
Left response
invalidName
            Text
declared : [Text]
remaining -> case PublishDeps -> Text -> Maybe PackageName
pubProjectName PublishDeps
deps Text
declared of
                Maybe PackageName
Nothing -> response -> Either response PackageName
forall a b. a -> Either a b
Left response
invalidName
                Just PackageName
agreed
                    | Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust ((Text -> Maybe PackageName) -> PackageName -> [Text] -> Maybe Text
bodyNameDisagreement (PublishDeps -> Text -> Maybe PackageName
pubProjectName PublishDeps
deps) PackageName
agreed [Text]
remaining) -> response -> Either response PackageName
forall a b. a -> Either a b
Left response
invalidName
                    | Bool -> Bool
not (PublishDeps -> PackageName -> Bool
pubAllowed PublishDeps
deps PackageName
agreed) -> response -> Either response PackageName
forall a b. a -> Either a b
Left (PublishReplies response -> PublishDeps -> PackageName -> response
forall response.
PublishReplies response -> PublishDeps -> PackageName -> response
outOfScope PublishReplies response
replies PublishDeps
deps PackageName
agreed)
                    | Bool
otherwise -> PackageName -> Either response PackageName
forall a b. b -> Either a b
Right PackageName
agreed
    invalidName :: response
invalidName = PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status400 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the publish body must declare one valid agreed package name")

publicationTarget :: PublishDeps -> ServeRuntime -> Maybe ClientCredential -> OriginClient
publicationTarget :: PublishDeps
-> ServeRuntime -> Maybe ClientCredential -> OriginClient
publicationTarget PublishDeps
deps ServeRuntime
rt =
    Limits
-> ExchangeClient
-> RegistryUrl
-> Maybe ClientCredential
-> OriginClient
originClient
        ((PublishDeps -> Limits
pubLimits PublishDeps
deps){maxPublishRequestBytes = pubMaxRequestBytes deps})
        (ServeRuntime -> ExchangeClient
srPrivateClient ServeRuntime
rt)
        (PublishDeps -> RegistryUrl
pubReadUrl PublishDeps
deps)

-- Static publication credentials require an authenticated edge, and present as the target's store asks.
publicationAuthority :: PublishDeps -> Maybe ClientCredential -> (Maybe ClientCredential, ServicePresentation)
publicationAuthority :: PublishDeps
-> Maybe ClientCredential
-> (Maybe ClientCredential, ServicePresentation)
publicationAuthority PublishDeps
deps Maybe ClientCredential
clientToken = case (PublishDeps -> Maybe Secret
pubInboundToken PublishDeps
deps, PublishDeps -> Maybe ClientCredential
pubStaticCredential PublishDeps
deps) of
    (Just Secret
_, Just ClientCredential
staticToken) -> (ClientCredential -> Maybe ClientCredential
forall a. a -> Maybe a
Just ClientCredential
staticToken, PublishDeps -> ServicePresentation
pubStaticPresentation PublishDeps
deps)
    (Maybe Secret, Maybe ClientCredential)
_ -> (Maybe ClientCredential
clientToken, ServicePresentation
nativePresentation)

targetRefusal :: PublishReplies response -> PublishDeps -> MetadataError -> response
targetRefusal :: forall response.
PublishReplies response -> PublishDeps -> MetadataError -> response
targetRefusal PublishReplies response
replies PublishDeps
deps = \case
    MetadataFetch FetchFault
fault -> PublishReplies response
-> PublishDeps
-> Either FetchFault PublishRelayResponse
-> response
forall response.
PublishReplies response
-> PublishDeps
-> Either FetchFault PublishRelayResponse
-> response
renderRelay PublishReplies response
replies PublishDeps
deps (FetchFault -> Either FetchFault PublishRelayResponse
forall a b. a -> Either a b
Left FetchFault
fault)
    MetadataBoundExceeded LimitError
fault -> PublishReplies response
-> PublishDeps
-> Either FetchFault PublishRelayResponse
-> response
forall response.
PublishReplies response
-> PublishDeps
-> Either FetchFault PublishRelayResponse
-> response
renderRelay PublishReplies response
replies PublishDeps
deps (FetchFault -> Either FetchFault PublishRelayResponse
forall a b. a -> Either a b
Left (LimitError -> FetchFault
FetchBoundExceeded LimitError
fault))
    MetadataAuthorisationFailure Int
status -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies (Int -> ByteString -> Status
mkStatus Int
status ByteString
"") [] Text
"the publication registry refused access"
    MetadataHttpFailure Int
status Maybe RetryAfter
_ -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies (Int -> ByteString -> Status
mkStatus Int
status ByteString
"") [] Text
"the publication registry discovery failed"
    MetadataError
MetadataAbsent -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status502 [] Text
"the publication registry has no discovery document"
    MetadataError
MetadataUndecodable -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status502 [] Text
"the publication registry discovery is malformed or names an unapproved API root"
    MetadataNameMismatch Text
_ -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status502 [] Text
"the publication registry discovery identity disagrees"

renderRelay ::
    PublishReplies response ->
    PublishDeps ->
    Either FetchFault PublishRelayResponse ->
    response
renderRelay :: forall response.
PublishReplies response
-> PublishDeps
-> Either FetchFault PublishRelayResponse
-> response
renderRelay PublishReplies response
replies PublishDeps
deps = \case
    Right (PublishRelayResponse Int
code LByteString
relayed) ->
        PublishReplies response
-> Status -> ResponseHeaders -> LByteString -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> LByteString -> response
publishRelayed PublishReplies response
replies (Int -> ByteString -> Status
mkStatus Int
code ByteString
"") [] LByteString
relayed
    -- An invalid target is local configuration. Transport failures belong to the target.
    Left (FetchUrlUnformable UrlFormationError
_urlErr) ->
        PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status500 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the publication target URL is misconfigured")
    Left (FetchTransport TransportFault
_fault) ->
        PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status502 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the publication target could not be reached")
    Left (FetchCooldown RetryAfter
_retry) ->
        PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status502 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the publication target could not be reached")
    Left (FetchBoundExceeded LimitError
_limit) ->
        PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status502 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the publication target could not be reached")

bodyRefusal :: PublishReplies response -> PublishDeps -> PublishBodyFault -> response
bodyRefusal :: forall response.
PublishReplies response
-> PublishDeps -> PublishBodyFault -> response
bodyRefusal PublishReplies response
replies PublishDeps
deps = \case
    PublishMalformed ParseError
fault -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status400 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) (ParseError -> Text
parseErrorMessage ParseError
fault))
    PublishUnsupported Text
reason -> PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status501 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
reason)

-- Body capacity uses the read path's 503 status and retry hint.
bodyBudgetShed :: PublishReplies response -> PublishDeps -> response
bodyBudgetShed :: forall response. PublishReplies response -> PublishDeps -> response
bodyBudgetShed PublishReplies response
replies PublishDeps
deps =
    PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
shedStatus [Header
shedRetryAfter] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the server is at its publish-body capacity; retry shortly")

publishTooLarge :: PublishReplies response -> PublishDeps -> response
publishTooLarge :: forall response. PublishReplies response -> PublishDeps -> response
publishTooLarge PublishReplies response
replies PublishDeps
deps =
    PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status413 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
"the publish body exceeds the maximum accepted request size")

outOfScope :: PublishReplies response -> PublishDeps -> PackageName -> response
outOfScope :: forall response.
PublishReplies response -> PublishDeps -> PackageName -> response
outOfScope PublishReplies response
replies PublishDeps
deps PackageName
name =
    PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status403 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
message)
  where
    message :: Text
    message :: Text
message =
        Text
"refusing to publish '"
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> PackageName -> Text
renderPackageName PackageName
name
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"': its name is outside the first-party namespaces this deployment declares (the anti-shadowing guard against publishing a name that shadows a public package)"

bodyNameMismatch :: PublishReplies response -> PublishDeps -> PackageName -> Text -> response
bodyNameMismatch :: forall response.
PublishReplies response
-> PublishDeps -> PackageName -> Text -> response
bodyNameMismatch PublishReplies response
replies PublishDeps
deps PackageName
name Text
declared =
    PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
forall response.
PublishReplies response
-> Status -> ResponseHeaders -> Text -> response
publishError PublishReplies response
replies Status
status403 [] (Maybe HelpMessage -> Text -> Text
appendHelp (PublishDeps -> Maybe HelpMessage
pubHelp PublishDeps
deps) Text
message)
  where
    message :: Text
    message :: Text
message =
        Text
"refusing to publish '"
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> PackageName -> Text
renderPackageName PackageName
name
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"': the document body declares the name '"
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
declared
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"', which disagrees with the requested package name the first-party guard authorised (the anti-shadowing guard against publishing a name the guard never saw)"

-- A body-driven target must not write a name the URL-path guard never authorised.
bodyNameDisagreement :: (Text -> Maybe PackageName) -> PackageName -> [Text] -> Maybe Text
bodyNameDisagreement :: (Text -> Maybe PackageName) -> PackageName -> [Text] -> Maybe Text
bodyNameDisagreement Text -> Maybe PackageName
canonicalise PackageName
name = (Text -> Bool) -> [Text] -> Maybe Text
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find Text -> Bool
disagrees
  where
    disagrees :: Text -> Bool
disagrees Text
declared = Text -> Maybe PackageName
canonicalise Text
declared Maybe PackageName -> Maybe PackageName -> Bool
forall a. Eq a => a -> a -> Bool
/= PackageName -> Maybe PackageName
forall a. a -> Maybe a
Just PackageName
name