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

-- | Cargo publication binds complete native metadata to unchanged verified archive bytes.
module Ecluse.Core.Registry.Cargo.Publish (
    cargoPublish,
    cargoPublishCodec,
    uploadClaims,
    preparePublishTarget,
    classifyPublish,
) where

import Data.Aeson (Value (..), encode)
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString.Lazy qualified as LBS
import Data.Text qualified as T
import Network.HTTP.Client (Request (method, requestBody, requestHeaders), RequestBody (RequestBodyBS, RequestBodyLBS))
import Network.HTTP.Types.Header (hAccept, hContentType)
import UnliftIO.Exception (evaluate)

import Ecluse.Core.Credential (ClientCredential)
import Ecluse.Core.Deadline (Deadlines, inspectionDeadline)
import Ecluse.Core.Package (PackageName, hashValue)
import Ecluse.Core.Registry (FetchFault (FetchUrlUnformable), ParseError (..), PublishBodyFault (PublishMalformed), PublishError (PublishError), PublishFault (..), UrlFormationError (UnparseableUrl), isSuccessStatus)
import Ecluse.Core.Registry.Adapter.Capability (AdapterPublish (..), MirrorRequirements (..), MirrorStateRequirement (DurableVersionState), PublishExtras (NoPublishExtras), PublishRequestBody (..), UploadEndpointRequirement (ExplicitUploadEndpoint), UploadIdentityRequirement (TokenIdentity), WorkerMetadataRead (NativeChargedWorkerRead))
import Ecluse.Core.Registry.CachedDocument (cargoCached)
import Ecluse.Core.Registry.Cargo.Archive (cargoPublicationAgreement, cargoPublicationMetadata, cargoUploadAgreement, inspectCargoArchive)
import Ecluse.Core.Registry.Cargo.Credential (cargoCredential)
import Ecluse.Core.Registry.Cargo.Discovery (cargoDiscovery, discoveryApi)
import Ecluse.Core.Registry.Cargo.Document (cargoRecords)
import Ecluse.Core.Registry.Cargo.Manifest (CargoPublishMetadata, checkDependencyRegistries, publishMetadataValue)
import Ecluse.Core.Registry.Cargo.Metadata (prepareCargoRead, prepareCargoReadAs)
import Ecluse.Core.Registry.Cargo.Mirror (cargoMirrorDocuments, cargoStateFormat)
import Ecluse.Core.Registry.Cargo.Project (projectName)
import Ecluse.Core.Registry.Cargo.Publish.Body qualified as Body
import Ecluse.Core.Registry.Cargo.Request (cargoIndexPath)
import Ecluse.Core.Registry.Cargo.Wire (decodeCargoRecord)
import Ecluse.Core.Registry.Metadata (MetadataError (MetadataUndecodable), VersionDoc (vdRaw))
import Ecluse.Core.Registry.MirrorUpload
import Ecluse.Core.Registry.MirrorUpload.Internal (checkedMirrorUploadData)
import Ecluse.Core.Registry.Origin (OriginClient (ocLimits, ocToken), originBaseUrl)
import Ecluse.Core.Registry.Publish (PublishCodec (..), relayPublishRequest)
import Ecluse.Core.Registry.Request (CredentialMapping, ServicePresentation, StoreOperation (StoreRead, StoreWrite), apiEndpoint, attachCredential, joinPath, metadataGet, parseRequestEither, presentedMapping)
import Ecluse.Core.Registry.ServedDocument (stringField)
import Ecluse.Core.Security.Egress (RegistryUrl, registryUrlText)
import Ecluse.Core.Security.Limits (Limits (maxMetadataBytes))
import Ecluse.Core.Server.Admission.Types (ChargeFactors (cfFullReadPermille))
import Ecluse.Core.Server.MemoryModel (saturatingCharge)
import Ecluse.Core.Version (renderVersion)

-- | First-party relay preserves validated native bytes and the registry's response.
cargoPublish :: ChargeFactors -> AdapterPublish
cargoPublish :: ChargeFactors -> AdapterPublish
cargoPublish ChargeFactors
factors =
    AdapterPublish
        { publishCredential :: CredentialMapping
publishCredential = CredentialMapping
cargoCredential
        , publishRequestExtras :: RequestHeaders -> Either PublishBodyFault PublishExtras
publishRequestExtras = Either PublishBodyFault PublishExtras
-> RequestHeaders -> Either PublishBodyFault PublishExtras
forall a b. a -> b -> a
const (PublishExtras -> Either PublishBodyFault PublishExtras
forall a b. b -> Either a b
Right PublishExtras
NoPublishExtras)
        , publishRelay :: ServicePresentation
-> OriginClient
-> PackageName
-> PublishRequestBody
-> IO (Either FetchFault PublishRelayResponse)
publishRelay = \ServicePresentation
presentation OriginClient
origin PackageName
name PublishRequestBody
body -> OriginClient
-> Either UrlFormationError Request
-> IO (Either FetchFault PublishRelayResponse)
relayPublishRequest OriginClient
origin (CredentialMapping
-> OriginClient
-> PackageName
-> PublishRequestBody
-> Either UrlFormationError Request
relayRequest (ServicePresentation
-> StoreOperation -> CredentialMapping -> CredentialMapping
presentedMapping ServicePresentation
presentation StoreOperation
StoreWrite CredentialMapping
cargoCredential) OriginClient
origin PackageName
name PublishRequestBody
body)
        , publishUploadClaims :: Limits
-> (Int -> IO ())
-> Text
-> PublishRequestBody
-> IO (Either PublishBodyFault [Text])
publishUploadClaims = Limits
-> (Int -> IO ())
-> Text
-> PublishRequestBody
-> IO (Either PublishBodyFault [Text])
uploadClaims
        , publishCodec :: ServicePresentation -> PublishCodec
publishCodec = ChargeFactors -> ServicePresentation -> PublishCodec
cargoPublishCodec ChargeFactors
factors
        , publishMirrorRequirements :: MirrorRequirements
publishMirrorRequirements = WorkerMetadataRead
-> MirrorStateFormat
-> MirrorStateRequirement
-> MirrorRequirements
MirrorRequirements (PrepareRead -> WorkerMetadataRead
NativeChargedWorkerRead PrepareRead
prepareCargoRead) MirrorStateFormat
cargoStateFormat (MirrorDocuments -> MirrorStateRequirement
DurableVersionState MirrorDocuments
cargoMirrorDocuments)
        , publishUploadEndpoint :: UploadEndpointRequirement
publishUploadEndpoint = UploadEndpointRequirement
ExplicitUploadEndpoint
        , publishIdentity :: UploadIdentityRequirement
publishIdentity = UploadIdentityRequirement
TokenIdentity
        }

-- | A native archive proves physical presence only. Completion also requires the retained crates.io row.
cargoPublishCodec :: ChargeFactors -> ServicePresentation -> PublishCodec
cargoPublishCodec :: ChargeFactors -> ServicePresentation -> PublishCodec
cargoPublishCodec ChargeFactors
factors ServicePresentation
presentation =
    PublishCodec
        { pcPrepareSource :: PackageName
-> Version
-> VersionDoc
-> Either PublishFault (MirrorInventory, Value)
pcPrepareSource = \PackageName
name Version
version VersionDoc
doc -> do
            source <- PublishFault
-> Maybe CargoDocument -> Either PublishFault CargoDocument
forall l r. l -> Maybe r -> Either l r
maybeToRight (Text -> PublishFault
PublishSourceUnavailable Text
"Cargo snapshot has no paired source index") (VersionDoc -> Maybe CachedDoc
vdRaw VersionDoc
doc Maybe CachedDoc
-> (CachedDoc -> Maybe CargoDocument) -> Maybe CargoDocument
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
-> CachedDoc -> Maybe CargoDocument
forall a b. (a, b) -> b
snd (CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
cargoCached)
            inventory <- checkedMirrorInventory name version doc (CargoMirrorRead source)
            row <- case cargoRecords source of
                [(EntryKey
_, Value
value)] -> Value -> Either PublishFault Value
forall a b. b -> Either a b
Right Value
value
                [(EntryKey, Value)]
_ -> PublishFault -> Either PublishFault Value
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable Text
"Cargo publication requires one selected source row")
            pure (inventory, row)
        , pcPrepareUpload :: Deadlines
-> Limits
-> (Int -> IO ())
-> MirrorInventory
-> Value
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
pcPrepareUpload = Deadlines
-> Limits
-> (Int -> IO ())
-> MirrorInventory
-> Value
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
prepareUpload
        , pcMirrorCompanion :: Maybe MirrorCompanion
pcMirrorCompanion = Maybe MirrorCompanion
forall a. Maybe a
Nothing
        , pcNativeComplete :: PackageName -> Version -> PackageInfo -> Bool
pcNativeComplete = \PackageName
_ Version
_ PackageInfo
_ -> Bool
False
        , pcTargetRead :: PrepareRead
pcTargetRead = CredentialMapping -> PrepareRead
prepareCargoReadAs CredentialMapping
readAs
        , pcTargetReadPermille :: Int
pcTargetReadPermille = ChargeFactors -> Int
cfFullReadPermille ChargeFactors
factors
        , pcProbeRequest :: Text
-> Maybe ClientCredential
-> PackageName
-> Either UrlFormationError Request
pcProbeRequest = \Text
target Maybe ClientCredential
token PackageName
name -> CredentialMapping
-> Maybe ClientCredential -> Method -> Request -> Request
metadataGet CredentialMapping
readAs Maybe ClientCredential
token Method
"text/plain" (Request -> Request)
-> Either UrlFormationError Request
-> Either UrlFormationError Request
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> Text -> Either UrlFormationError Text
joinPath Text
target (PackageName -> Text
cargoIndexPath PackageName
name) 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)
        , pcVersionListWalk :: Maybe (Limits -> Cursor -> Step VersionListState)
pcVersionListWalk = Maybe (Limits -> Cursor -> Step VersionListState)
forall a. Maybe a
Nothing
        , pcPrepareTarget :: OriginClient
-> RegistryUrl -> IO (Either MetadataError RegistryUrl)
pcPrepareTarget = CredentialMapping
-> OriginClient
-> RegistryUrl
-> IO (Either MetadataError RegistryUrl)
preparePublishTarget CredentialMapping
readAs
        , pcPublishRequest :: Text
-> Maybe ClientCredential
-> PublishPlan
-> MirrorUploadData CargoPublishMetadata
-> Either PublishFault Request
pcPublishRequest = \Text
target Maybe ClientCredential
credential PublishPlan
_ MirrorUploadData CargoPublishMetadata
upload -> do
            body <- (ParseError -> PublishFault)
-> Either ParseError LByteString -> Either PublishFault LByteString
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 (Text -> PublishFault
PublishSourceUnavailable (Text -> PublishFault)
-> (ParseError -> Text) -> ParseError -> PublishFault
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ParseError -> Text
parseErrorMessage) (Value -> Method -> Either ParseError LByteString
Body.encodeUpload (CargoPublishMetadata -> Value
publishMetadataValue (MirrorUploadData CargoPublishMetadata -> CargoPublishMetadata
forall metadata. MirrorUploadData metadata -> metadata
uploadMetadata MirrorUploadData CargoPublishMetadata
upload)) (MirrorUploadData CargoPublishMetadata -> Method
forall metadata. MirrorUploadData metadata -> Method
uploadBytes MirrorUploadData CargoPublishMetadata
upload))
            first (PublishFetch . FetchUrlUnformable) (bodyRequest (presentedMapping presentation StoreWrite cargoCredential) target credential (RequestBodyLBS body))
        , pcPublishOutcome :: Int -> Method -> Either PublishFault ()
pcPublishOutcome = Int -> Method -> Either PublishFault ()
classifyPublish
        }
  where
    readAs :: CredentialMapping
readAs = ServicePresentation
-> StoreOperation -> CredentialMapping -> CredentialMapping
presentedMapping ServicePresentation
presentation StoreOperation
StoreRead CredentialMapping
cargoCredential

prepareUpload :: Deadlines -> Limits -> (Int -> IO ()) -> MirrorInventory -> Value -> ExpectedMirrorFile -> VerifiedArtifactBytes -> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
prepareUpload :: Deadlines
-> Limits
-> (Int -> IO ())
-> MirrorInventory
-> Value
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
prepareUpload Deadlines
deadlines Limits
limits Int -> IO ()
charge MirrorInventory
inventory Value
row ExpectedMirrorFile
file VerifiedArtifactBytes
verified =
    Deadlines
-> PublishFault
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
forall e a. Deadlines -> e -> IO (Either e a) -> IO (Either e a)
inspectionDeadline Deadlines
deadlines (Text -> PublishFault
PublishSourceUnavailable Text
"Cargo publication preparation exceeded its deadline") IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
prepare
  where
    prepare :: IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
prepare = case Value -> Either PublishFault Text
sourceName Value
row of
        Left PublishFault
fault -> Either PublishFault (MirrorUploadData CargoPublishMetadata)
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishFault
-> Either PublishFault (MirrorUploadData CargoPublishMetadata)
forall a b. a -> Either a b
Left PublishFault
fault)
        Right Text
name -> do
            inspected <- Limits
-> (Int -> IO ())
-> Text
-> Text
-> Maybe Text
-> Method
-> IO (Either ParseError CargoArchiveMetadata)
inspectCargoArchive Limits
limits Int -> IO ()
charge Text
name (Version -> Text
renderVersion (MirrorInventory -> Version
inventoryVersion MirrorInventory
inventory)) (Text -> Maybe Text
forall a. a -> Maybe a
Just (Hash -> Text
hashValue (VerifiedArtifactBytes -> Hash
verifiedTargetHash VerifiedArtifactBytes
verified))) (VerifiedArtifactBytes -> Method
verifiedBytes VerifiedArtifactBytes
verified)
            case inspected of
                Left ParseError
fault -> Either PublishFault (MirrorUploadData CargoPublishMetadata)
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishFault
-> Either PublishFault (MirrorUploadData CargoPublishMetadata)
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable (ParseError -> Text
parseErrorMessage ParseError
fault)))
                Right CargoArchiveMetadata
archive -> do
                    metadata <- Limits
-> (Int -> IO ())
-> CargoArchiveMetadata
-> IO (Either ParseError CargoPublishMetadata)
cargoPublicationMetadata Limits
limits Int -> IO ()
charge CargoArchiveMetadata
archive
                    case metadata of
                        Left ParseError
fault -> Either PublishFault (MirrorUploadData CargoPublishMetadata)
-> IO (Either PublishFault (MirrorUploadData CargoPublishMetadata))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishFault
-> Either PublishFault (MirrorUploadData CargoPublishMetadata)
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable (ParseError -> Text
parseErrorMessage ParseError
fault)))
                        Right CargoPublishMetadata
extracted -> do
                            agreement <- Limits
-> (Int -> IO ())
-> CargoArchiveMetadata
-> Value
-> CargoPublishMetadata
-> IO (Either ParseError CargoPublishMetadata)
cargoPublicationAgreement Limits
limits Int -> IO ()
charge CargoArchiveMetadata
archive Value
row CargoPublishMetadata
extracted
                            -- Final decisions must run while the preparation timer remains active.
                            evaluate $ do
                                checked <- first (PublishSourceUnavailable . parseErrorMessage) agreement
                                let metadataBytes = Int64 -> LByteString -> LByteString
LBS.take (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Limits -> Int
maxMetadataBytes Limits
limits) Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
+ Int64
1) (Value -> LByteString
forall a. ToJSON a => a -> LByteString
encode (CargoPublishMetadata -> Value
publishMetadataValue CargoPublishMetadata
checked))
                                when (LBS.length metadataBytes > fromIntegral (maxMetadataBytes limits)) (Left (PublishSourceUnavailable "Cargo publication metadata exceeds its byte bound"))
                                checkedMirrorUploadData inventory file verified checked

sourceName :: Value -> Either PublishFault Text
sourceName :: Value -> Either PublishFault Text
sourceName = \case
    Object Object
fields -> PublishFault -> Maybe Text -> Either PublishFault Text
forall l r. l -> Maybe r -> Either l r
maybeToRight (Text -> PublishFault
PublishSourceUnavailable Text
"Cargo source row has no published name") (Key -> Object -> Maybe Text
stringField Key
"name" Object
fields)
    Value
_ -> PublishFault -> Either PublishFault Text
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable Text
"Cargo source row is not an object")

{- | Bind resolver claims to the verified archive, and dependencies to crates.io or this proxy, before any
publication discovery or upstream write.
-}
uploadClaims :: Limits -> (Int -> IO ()) -> Text -> PublishRequestBody -> IO (Either PublishBodyFault [Text])
uploadClaims :: Limits
-> (Int -> IO ())
-> Text
-> PublishRequestBody
-> IO (Either PublishBodyFault [Text])
uploadClaims Limits
limits Int -> IO ()
charge Text
registry PublishRequestBody
body = do
    decoded <- Limits
-> (Int -> IO ())
-> Method
-> IO (Either ParseError (CargoUploadBody, Int))
Body.readUpload Limits
limits Int -> IO ()
charge (PublishRequestBody -> Method
publishBodyBytes PublishRequestBody
body)
    case decoded of
        Left ParseError
fault -> Either PublishBodyFault [Text]
-> IO (Either PublishBodyFault [Text])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed ParseError
fault))
        Right (CargoUploadBody
upload, Int
metadataCost) -> do
            let archive :: Method
archive = CargoUploadBody -> Method
Body.uploadArchive CargoUploadBody
upload
                withMetadata :: a -> IO ()
withMetadata a
cost = Int -> IO ()
charge (Integer -> Int
saturatingCharge (Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
metadataCost Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ a -> Integer
forall a. Integral a => a -> Integer
toInteger a
cost))
            inspected <- Limits
-> (Int -> IO ())
-> Text
-> Text
-> Maybe Text
-> Method
-> IO (Either ParseError CargoArchiveMetadata)
inspectCargoArchive Limits
limits Int -> IO ()
forall {a}. Integral a => a -> IO ()
withMetadata (CargoUploadBody -> Text
Body.uploadName CargoUploadBody
upload) (CargoUploadBody -> Text
Body.uploadVersion CargoUploadBody
upload) Maybe Text
forall a. Maybe a
Nothing Method
archive
            case inspected of
                Left ParseError
fault -> Either PublishBodyFault [Text]
-> IO (Either PublishBodyFault [Text])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed ParseError
fault))
                Right CargoArchiveMetadata
metadata -> do
                    let publication :: Text
publication = Text -> Text
sparseRegistry Text
registry
                    agreement <- Limits
-> (Int -> IO ())
-> Int
-> Text
-> Value
-> CargoArchiveMetadata
-> IO (Either ParseError ())
cargoUploadAgreement Limits
limits Int -> IO ()
forall {a}. Integral a => a -> IO ()
withMetadata Int
metadataCost Text
publication (CargoUploadBody -> Value
Body.uploadMetadata CargoUploadBody
upload) CargoArchiveMetadata
metadata
                    pure . first PublishMalformed $ do
                        agreement
                        checkDependencyRegistries [publication] (Body.uploadMetadata upload)
                        pure [Body.uploadName upload]

-- The mount's own sparse index, which a null upload dependency source also names.
sparseRegistry :: Text -> Text
sparseRegistry :: Text -> Text
sparseRegistry Text
registry = Text
"sparse+" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (Char -> Bool) -> Text -> Text
T.dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/') Text
registry Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"/"

-- | Discovery cannot grant an API root. The complete configured base path must agree before a token is attached.
preparePublishTarget :: CredentialMapping -> OriginClient -> RegistryUrl -> IO (Either MetadataError RegistryUrl)
preparePublishTarget :: CredentialMapping
-> OriginClient
-> RegistryUrl
-> IO (Either MetadataError RegistryUrl)
preparePublishTarget CredentialMapping
readAs OriginClient
origin RegistryUrl
approved = do
    discovered <- CredentialMapping
-> OriginClient -> IO (Either MetadataError CargoDiscovery)
cargoDiscovery CredentialMapping
readAs OriginClient
origin
    pure $ do
        discovery <- discovered
        advertised <- maybeToRight MetadataUndecodable (discoveryApi discovery)
        unless (T.dropWhileEnd (== '/') advertised == T.dropWhileEnd (== '/') (registryUrlText approved)) (Left MetadataUndecodable)
        pure approved

relayRequest :: CredentialMapping -> OriginClient -> PackageName -> PublishRequestBody -> Either UrlFormationError Request
relayRequest :: CredentialMapping
-> OriginClient
-> PackageName
-> PublishRequestBody
-> Either UrlFormationError Request
relayRequest CredentialMapping
writeAs OriginClient
origin PackageName
name PublishRequestBody
body = do
    upload <- (ParseError -> UrlFormationError)
-> Either ParseError CargoUploadBody
-> Either UrlFormationError CargoUploadBody
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 (UrlFormationError -> ParseError -> UrlFormationError
forall a b. a -> b -> a
const (Text -> UrlFormationError
UnparseableUrl Text
"Cargo relay body is not a valid native upload")) (Limits -> Method -> Either ParseError CargoUploadBody
Body.decodeUpload (OriginClient -> Limits
ocLimits OriginClient
origin) (PublishRequestBody -> Method
publishBodyBytes PublishRequestBody
body))
    unless (projectName (Body.uploadName upload) == Right name) (Left (UnparseableUrl "Cargo relay name differs from the authorised package"))
    bodyRequest writeAs (originBaseUrl origin) (ocToken origin) (RequestBodyBS (publishBodyBytes body))

bodyRequest :: CredentialMapping -> Text -> Maybe ClientCredential -> RequestBody -> Either UrlFormationError Request
bodyRequest :: CredentialMapping
-> Text
-> Maybe ClientCredential
-> RequestBody
-> Either UrlFormationError Request
bodyRequest CredentialMapping
writeAs Text
target Maybe ClientCredential
credential RequestBody
body = do
    base <- UrlFormationError
-> Text -> Text -> Either UrlFormationError Request
apiEndpoint (Text -> UrlFormationError
UnparseableUrl Text
"Cargo API root must not contain a query or fragment") Text
target Text
"api/v1/crates/new"
    pure . attachCredential writeAs credential $
        base
            { method = "PUT"
            , requestHeaders = [(hContentType, "application/octet-stream"), (hAccept, "application/json")]
            , requestBody = body
            }

-- | A duplicate reply and a native errors response both require independent target proof.
classifyPublish :: Int -> ByteString -> Either PublishFault ()
classifyPublish :: Int -> Method -> Either PublishFault ()
classifyPublish Int
status Method
body
    | Int -> Bool
isSuccessStatus Int
status
    , Right (Object Object
fields) <- Int -> Method -> Either CargoRecordError Value
decodeCargoRecord Int
32 Method
body
    , Bool -> (Value -> Bool) -> Maybe Value -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True Value -> Bool
emptyErrors (Key -> Object -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"errors" Object
fields) =
        () -> Either PublishFault ()
forall a b. b -> Either a b
Right ()
    | Bool
otherwise = PublishFault -> Either PublishFault ()
forall a b. a -> Either a b
Left (PublishError -> PublishFault
PublishRejected (Text -> PublishError
PublishError (Text
"Cargo publication failed with HTTP status " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show Int
status)))
  where
    emptyErrors :: Value -> Bool
emptyErrors = \case
        Array Array
errors -> Array -> Bool
forall a. Vector a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Array
errors
        Value
_ -> Bool
False