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

-- | Build role-specific maintenance, observations and upstream probes from cleared backends.
module Ecluse.Composition.Maintenance (
    -- * The environment-dependent half
    StorePorts (..),
    BudgetPorts (..),
    storeScope,
    resolvedBudget,
    BuildUpstreamProbe,
    StoreBuilds (..),
    storeBuilds,
    buildStoreMaintenance,
    buildStoreObservation,
    buildUpstreamProbe,
    planStoreMaintenance,
    planStoreMaintenanceFor,

    -- * What the private upstream answers about public content
    readUpstreamSafety,
    upstreamFindings,
) where

import Data.Map.Strict qualified as Map
import Validation (eitherToValidation, validationToEither)

import Ecluse.Composition.BootError (
    Advisory (PrivateUpstreamUndecided),
    BootError (PrivateUpstreamProbeFailed, PrivateUpstreamUnsafe, StoreMaintenanceUnavailable),
    StoreMaintenanceReason (ClientBuildFailed, PrivateCacheUnavailable),
    refuseOnThrow,
 )
import Ecluse.Composition.Credential (CredentialProviders, CredentialTarget (..), lookupTargetProvider)
import Ecluse.Composition.Maintenance.Plan (
    ClearedBackend (cbAlphabet, cbControl, cbFetchManifest, cbUrl, cbUsername),
    ClearedControl (..),
    ClearedProtocolStore (..),
    overrideKey,
 )
import Ecluse.Composition.Sizing (newPooledManager)
import Ecluse.Config (
    DeletionConsent (DeletionPermitted),
    PrivateEndpoint (preTarget),
    QuotaOverride (qoQuotas, qoScope, qoWeights),
    StoreTag (TagCodeArtifact, TagRegistry, TagVerdaccio),
    Target (tgtTag),
    storeTagName,
 )
import Ecluse.Config.Target (resolvePrivateBackend)
import Ecluse.Core.BuildIdentity (identityManagerSettings)
import Ecluse.Core.Credential (ClientCredential (ClientCredential), CredentialProvider, bareCredential, mintSecret)
import Ecluse.Core.Deadline (Deadlines)
import Ecluse.Core.Ecosystem (Ecosystem)
import Ecluse.Core.Fault.Http (typedTlsManagerSettings)
import Ecluse.Core.Registry.Exchange (singleAttemptSettings)
import Ecluse.Core.Registry.Exchange.Types (ExchangeClient (ExchangeClient), untracedExchange)
import Ecluse.Core.Registry.Maintenance (
    StoreFacts (factBudget),
    StoreMaintenance (storeFacts),
    StoreManifestRead,
    StoreObservation (obFacts),
    meteredMaintenance,
    meteredObservation,
    storeFaultOfMetadata,
 )
import Ecluse.Core.Registry.Maintenance.Budget (
    QuotaOrigin (QuotaDeclared),
    QuotaScope,
    RequestGate,
    StoreBudget (bgCosts, bgOrigin, bgQuotas, bgScope),
    mkQuotaScope,
 )
import Ecluse.Core.Registry.Maintenance.Protocol (
    ProtocolRead (..),
    ProtocolStore (ProtocolStore, psDelete, psDeleteOrigin, psRead),
    newProtocolMaintenance,
    newProtocolObservation,
 )
import Ecluse.Core.Registry.Maintenance.Upstream (UpstreamSafety (Undecidable, Unsafe), noUpstreamMechanism)
import Ecluse.Core.Registry.Origin (OriginClient, originClient)
import Ecluse.Core.Registry.Sweep.Pacing (derivedCapacity)
import Ecluse.Core.Security (Limits (maxVersionCount), authorityLabel)
import Ecluse.Core.Security.Egress (RegistryUrl, registryUrlText)
import Ecluse.Core.Telemetry.Span (TracingPort)
import Ecluse.Runtime.Maintenance.CodeArtifact (newCodeArtifactCacheMaintenance, newCodeArtifactCacheObservation, newCodeArtifactMaintenance, newCodeArtifactObservation, newCodeArtifactUpstreamProbe)

-- | Per-target tracing and authentication, resolved before the store handles are built.
data StorePorts = StorePorts
    { StorePorts -> TracingPort
spTracing :: TracingPort
    -- ^ The tracing port the manifest read is bracketed by.
    , StorePorts -> Maybe CredentialProvider
spCredential :: Maybe CredentialProvider
    -- ^ The credential for this exact target. An anonymous protocol observation holds none.
    , StorePorts -> ByteString
spUserAgent :: ByteString
    -- ^ The precomputed identity shared by this store's registry requests.
    , StorePorts -> Deadlines
spDeadlines :: Deadlines
    -- ^ The process's sweeper, which bounds this store's registry requests.
    , StorePorts -> BudgetPorts
spBudget :: BudgetPorts
    -- ^ What this store's requests are counted and paced through.
    }

-- | Capacity declarations and request gates resolved before store construction.
data BudgetPorts = BudgetPorts
    { BudgetPorts -> QuotaScope -> RequestGate
bpGateFor :: QuotaScope -> RequestGate
    , BudgetPorts -> Map Text QuotaOverride
bpOverrides :: Map Text QuotaOverride
    , BudgetPorts -> Rational
bpNominalPace :: Rational
    -- ^ The sweep's own package pace, which a backend publishing no quota is taken to run at.
    }

-- | Build maintenance for a cleared store under the resolved response limits.
type BuildStoreMaintenance = StorePorts -> Limits -> ClearedBackend -> IO StoreMaintenance

-- | Build observations without deletion, marker writes or publication.
type BuildStoreObservation = StorePorts -> Limits -> ClearedBackend -> IO StoreObservation

-- | Role-specific constructors. Preview construction never creates deletion handles.
data StoreBuilds = StoreBuilds
    { StoreBuilds -> BuildStoreMaintenance
sbDeleting :: BuildStoreMaintenance
    , StoreBuilds -> BuildStoreObservation
sbObserving :: BuildStoreObservation
    , StoreBuilds -> BuildUpstreamProbe
sbProbing :: BuildUpstreamProbe
    }

-- | The shipped builds.
storeBuilds :: StoreBuilds
storeBuilds :: StoreBuilds
storeBuilds =
    StoreBuilds
        { sbDeleting :: BuildStoreMaintenance
sbDeleting = BuildStoreMaintenance
buildStoreMaintenance
        , sbObserving :: BuildStoreObservation
sbObserving = BuildStoreObservation
buildStoreObservation
        , sbProbing :: BuildUpstreamProbe
sbProbing = BuildUpstreamProbe
buildUpstreamProbe
        }

-- | Build the probe for one private upstream under the role's own authority.
type BuildUpstreamProbe = Ecosystem -> PrivateEndpoint -> IO UpstreamSafety

-- | Probe the declared backend with the role's ambient identity, never a caller's credential.
buildUpstreamProbe :: BuildUpstreamProbe
buildUpstreamProbe :: BuildUpstreamProbe
buildUpstreamProbe Ecosystem
eco PrivateEndpoint
endpoint = case Target -> StoreTag
tgtTag Target
target of
    -- 'vetPrivateRepository' refuses an endpoint addressing no repository, so this resolution
    -- fails only for a value no loaded configuration carries, and there is nothing to ask about.
    StoreTag
TagCodeArtifact -> (ConfigError -> IO UpstreamSafety)
-> ((StoreBackend, CodeArtifactStore) -> IO UpstreamSafety)
-> Either ConfigError (StoreBackend, CodeArtifactStore)
-> IO UpstreamSafety
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (IO UpstreamSafety -> ConfigError -> IO UpstreamSafety
forall a b. a -> b -> a
const IO UpstreamSafety
forall (m :: * -> *). Applicative m => m UpstreamSafety
noUpstreamMechanism) (CodeArtifactStore -> IO UpstreamSafety
newCodeArtifactUpstreamProbe (CodeArtifactStore -> IO UpstreamSafety)
-> ((StoreBackend, CodeArtifactStore) -> CodeArtifactStore)
-> (StoreBackend, CodeArtifactStore)
-> IO UpstreamSafety
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (StoreBackend, CodeArtifactStore) -> CodeArtifactStore
forall a b. (a, b) -> b
snd) (Ecosystem
-> Target -> Either ConfigError (StoreBackend, CodeArtifactStore)
resolvePrivateBackend Ecosystem
eco Target
target)
    StoreTag
TagRegistry -> IO UpstreamSafety
forall (m :: * -> *). Applicative m => m UpstreamSafety
noUpstreamMechanism
    StoreTag
TagVerdaccio -> IO UpstreamSafety
forall (m :: * -> *). Applicative m => m UpstreamSafety
noUpstreamMechanism
  where
    target :: Target
target = PrivateEndpoint -> Target
preTarget PrivateEndpoint
endpoint

-- | Collect probe answers and refuse the affected mounts when a probe throws.
readUpstreamSafety :: [(Ecosystem, IO UpstreamSafety)] -> IO ([Advisory], Either [BootError] ())
readUpstreamSafety :: [(Ecosystem, IO UpstreamSafety)]
-> IO ([Advisory], Either [BootError] ())
readUpstreamSafety [(Ecosystem, IO UpstreamSafety)]
probes = ([[BootError]], [(Ecosystem, UpstreamSafety)])
-> ([Advisory], Either [BootError] ())
forall {t :: * -> *}.
Foldable t =>
(t [BootError], [(Ecosystem, UpstreamSafety)])
-> ([Advisory], Either [BootError] ())
settled (([[BootError]], [(Ecosystem, UpstreamSafety)])
 -> ([Advisory], Either [BootError] ()))
-> ([Either [BootError] (Ecosystem, UpstreamSafety)]
    -> ([[BootError]], [(Ecosystem, UpstreamSafety)]))
-> [Either [BootError] (Ecosystem, UpstreamSafety)]
-> ([Advisory], Either [BootError] ())
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Either [BootError] (Ecosystem, UpstreamSafety)]
-> ([[BootError]], [(Ecosystem, UpstreamSafety)])
forall a b. [Either a b] -> ([a], [b])
partitionEithers ([Either [BootError] (Ecosystem, UpstreamSafety)]
 -> ([Advisory], Either [BootError] ()))
-> IO [Either [BootError] (Ecosystem, UpstreamSafety)]
-> IO ([Advisory], Either [BootError] ())
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ((Ecosystem, IO UpstreamSafety)
 -> IO (Either [BootError] (Ecosystem, UpstreamSafety)))
-> [(Ecosystem, IO UpstreamSafety)]
-> IO [Either [BootError] (Ecosystem, UpstreamSafety)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Ecosystem, IO UpstreamSafety)
-> IO (Either [BootError] (Ecosystem, UpstreamSafety))
forall {a}.
(Ecosystem, IO a) -> IO (Either [BootError] (Ecosystem, a))
answer [(Ecosystem, IO UpstreamSafety)]
probes
  where
    answer :: (Ecosystem, IO a) -> IO (Either [BootError] (Ecosystem, a))
answer (Ecosystem
eco, IO a
probe) = (a -> (Ecosystem, a))
-> Either [BootError] a -> Either [BootError] (Ecosystem, a)
forall a b.
(a -> b) -> Either [BootError] a -> Either [BootError] b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Ecosystem
eco,) (Either [BootError] a -> Either [BootError] (Ecosystem, a))
-> IO (Either [BootError] a)
-> IO (Either [BootError] (Ecosystem, a))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> BootError) -> IO a -> IO (Either [BootError] a)
forall a. (Text -> BootError) -> IO a -> IO (Either [BootError] a)
refuseOnThrow (Ecosystem -> Text -> BootError
PrivateUpstreamProbeFailed Ecosystem
eco) IO a
probe

    settled :: (t [BootError], [(Ecosystem, UpstreamSafety)])
-> ([Advisory], Either [BootError] ())
settled (t [BootError]
thrown, [(Ecosystem, UpstreamSafety)]
answers) =
        let ([Advisory]
advisories, Either [BootError] ()
refused) = [(Ecosystem, UpstreamSafety)]
-> ([Advisory], Either [BootError] ())
upstreamFindings [(Ecosystem, UpstreamSafety)]
answers
         in ([Advisory]
advisories, [BootError] -> Either [BootError] ()
refusals (t [BootError] -> [BootError]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat t [BootError]
thrown [BootError] -> [BootError] -> [BootError]
forall a. Semigroup a => a -> a -> a
<> [BootError] -> Either [BootError] () -> [BootError]
forall a b. a -> Either a b -> a
fromLeft [] Either [BootError] ()
refused))

-- | Refuse unsafe upstreams, advise on undecidable ones, and accept safe ones.
upstreamFindings :: [(Ecosystem, UpstreamSafety)] -> ([Advisory], Either [BootError] ())
upstreamFindings :: [(Ecosystem, UpstreamSafety)]
-> ([Advisory], Either [BootError] ())
upstreamFindings [(Ecosystem, UpstreamSafety)]
answers = ([Advisory]
advisories, [BootError] -> Either [BootError] ()
refusals [BootError]
unsafeMounts)
  where
    advisories :: [Advisory]
advisories = [Ecosystem -> UndecidabilityReason -> Advisory
PrivateUpstreamUndecided Ecosystem
eco UndecidabilityReason
reason | (Ecosystem
eco, Undecidable UndecidabilityReason
reason) <- [(Ecosystem, UpstreamSafety)]
answers]
    unsafeMounts :: [BootError]
unsafeMounts = [Ecosystem -> UnsafeReason -> BootError
PrivateUpstreamUnsafe Ecosystem
eco UnsafeReason
reason | (Ecosystem
eco, Unsafe UnsafeReason
reason) <- [(Ecosystem, UpstreamSafety)]
answers]

-- Nothing found is nothing refused, which is what lets a whole pass report at once.
refusals :: [BootError] -> Either [BootError] ()
refusals :: [BootError] -> Either [BootError] ()
refusals [BootError]
found = if [BootError] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [BootError]
found then () -> Either [BootError] ()
forall a b. b -> Either a b
Right () else [BootError] -> Either [BootError] ()
forall a b. a -> Either a b
Left [BootError]
found

-- | Build maintenance using store-local metadata reads and backend-owned control credentials.
buildStoreMaintenance :: BuildStoreMaintenance
buildStoreMaintenance :: BuildStoreMaintenance
buildStoreMaintenance StorePorts
ports Limits
limits ClearedBackend
cleared = StorePorts
-> ClearedBackend -> StoreMaintenance -> StoreMaintenance
budgeted StorePorts
ports ClearedBackend
cleared (StoreMaintenance -> StoreMaintenance)
-> IO StoreMaintenance -> IO StoreMaintenance
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO StoreMaintenance
built
  where
    built :: IO StoreMaintenance
built = do
        (readManifest, client) <- StorePorts
-> Limits
-> ClearedBackend
-> IO (StoreManifestRead, ExchangeClient)
storeAccess StorePorts
ports Limits
limits ClearedBackend
cleared
        case cbControl cleared of
            ClearedCodeArtifact CodeArtifactStore
store -> Int
-> NameAlphabet
-> StoreManifestRead
-> CodeArtifactStore
-> IO StoreMaintenance
newCodeArtifactMaintenance (Limits -> Int
maxVersionCount Limits
limits) (ClearedBackend -> NameAlphabet
cbAlphabet ClearedBackend
cleared) StoreManifestRead
readManifest CodeArtifactStore
store
            ClearedCodeArtifactCache CodeArtifactStore
store -> Int
-> NameAlphabet
-> StoreManifestRead
-> CodeArtifactStore
-> IO StoreMaintenance
newCodeArtifactCacheMaintenance (Limits -> Int
maxVersionCount Limits
limits) (ClearedBackend -> NameAlphabet
cbAlphabet ClearedBackend
cleared) StoreManifestRead
readManifest CodeArtifactStore
store
            ClearedProtocol ClearedProtocolStore
store -> do
                deletionClient <- StorePorts -> IO ExchangeClient
storeClient StorePorts
ports
                pure (newProtocolMaintenance (protocolStore limits cleared store readManifest client deletionClient))

-- Resolve the capacity pool before metering requests against it.
budgeted :: StorePorts -> ClearedBackend -> StoreMaintenance -> StoreMaintenance
budgeted :: StorePorts
-> ClearedBackend -> StoreMaintenance -> StoreMaintenance
budgeted StorePorts
ports ClearedBackend
cleared StoreMaintenance
handle =
    (RequestGate -> StoreMaintenance -> StoreMaintenance
meteredMaintenance (StorePorts -> StoreFacts -> RequestGate
gateOver StorePorts
ports StoreFacts
facts) StoreMaintenance
handle){storeFacts = facts}
  where
    facts :: StoreFacts
facts = StorePorts -> ClearedBackend -> StoreFacts -> StoreFacts
resolvedFacts StorePorts
ports ClearedBackend
cleared (StoreMaintenance -> StoreFacts
storeFacts StoreMaintenance
handle)

-- | Build the cleared backend's observation capability without constructing deletion handles.
buildStoreObservation :: BuildStoreObservation
buildStoreObservation :: BuildStoreObservation
buildStoreObservation StorePorts
ports Limits
limits ClearedBackend
cleared = StoreObservation -> StoreObservation
observed (StoreObservation -> StoreObservation)
-> IO StoreObservation -> IO StoreObservation
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO StoreObservation
built
  where
    observed :: StoreObservation -> StoreObservation
observed StoreObservation
handle =
        let facts :: StoreFacts
facts = StorePorts -> ClearedBackend -> StoreFacts -> StoreFacts
resolvedFacts StorePorts
ports ClearedBackend
cleared (StoreObservation -> StoreFacts
obFacts StoreObservation
handle)
         in (RequestGate -> StoreObservation -> StoreObservation
meteredObservation (StorePorts -> StoreFacts -> RequestGate
gateOver StorePorts
ports StoreFacts
facts) StoreObservation
handle){obFacts = facts}
    built :: IO StoreObservation
built = do
        (readManifest, client) <- StorePorts
-> Limits
-> ClearedBackend
-> IO (StoreManifestRead, ExchangeClient)
storeAccess StorePorts
ports Limits
limits ClearedBackend
cleared
        case cbControl cleared of
            ClearedCodeArtifact CodeArtifactStore
store -> Int
-> NameAlphabet
-> StoreManifestRead
-> CodeArtifactStore
-> IO StoreObservation
newCodeArtifactObservation (Limits -> Int
maxVersionCount Limits
limits) (ClearedBackend -> NameAlphabet
cbAlphabet ClearedBackend
cleared) StoreManifestRead
readManifest CodeArtifactStore
store
            ClearedCodeArtifactCache CodeArtifactStore
store -> Int
-> NameAlphabet
-> StoreManifestRead
-> CodeArtifactStore
-> IO StoreObservation
newCodeArtifactCacheObservation (Limits -> Int
maxVersionCount Limits
limits) (ClearedBackend -> NameAlphabet
cbAlphabet ClearedBackend
cleared) StoreManifestRead
readManifest CodeArtifactStore
store
            ClearedProtocol ClearedProtocolStore
store ->
                StoreObservation -> IO StoreObservation
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ProtocolRead -> StoreObservation
newProtocolObservation (Limits
-> ClearedBackend
-> ClearedProtocolStore
-> StoreManifestRead
-> ExchangeClient
-> ProtocolRead
protocolRead Limits
limits ClearedBackend
cleared ClearedProtocolStore
store StoreManifestRead
readManifest ExchangeClient
client))

resolvedFacts :: StorePorts -> ClearedBackend -> StoreFacts -> StoreFacts
resolvedFacts :: StorePorts -> ClearedBackend -> StoreFacts -> StoreFacts
resolvedFacts StorePorts
ports ClearedBackend
cleared StoreFacts
facts =
    StoreFacts
facts{factBudget = resolvedBudget (spBudget ports) (cbUrl cleared) (factBudget facts)}

-- The gate for the pool this store's resolved capacity landed in.
gateOver :: StorePorts -> StoreFacts -> RequestGate
gateOver :: StorePorts -> StoreFacts -> RequestGate
gateOver StorePorts
ports StoreFacts
facts = BudgetPorts -> QuotaScope -> RequestGate
bpGateFor (StorePorts -> BudgetPorts
spBudget StorePorts
ports) (StoreBudget -> QuotaScope
bgScope (StoreFacts -> StoreBudget
factBudget StoreFacts
facts))

-- | Default to one capacity pool per authority, shared by paths on that host.
storeScope :: RegistryUrl -> QuotaScope
storeScope :: RegistryUrl -> QuotaScope
storeScope = Text -> QuotaScope
mkQuotaScope (Text -> QuotaScope)
-> (RegistryUrl -> Text) -> RegistryUrl -> QuotaScope
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
authorityLabel (Text -> Text) -> (RegistryUrl -> Text) -> RegistryUrl -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RegistryUrl -> Text
registryUrlText

-- What the operator declared about this exact store, where they declared anything.
matchingOverride :: Map Text QuotaOverride -> RegistryUrl -> Maybe QuotaOverride
matchingOverride :: Map Text QuotaOverride -> RegistryUrl -> Maybe QuotaOverride
matchingOverride Map Text QuotaOverride
overrides RegistryUrl
url = Text -> Map Text QuotaOverride -> Maybe QuotaOverride
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Text -> Text
overrideKey (RegistryUrl -> Text
registryUrlText RegistryUrl
url)) Map Text QuotaOverride
keyed
  where
    keyed :: Map Text QuotaOverride
keyed = [(Text, QuotaOverride)] -> Map Text QuotaOverride
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Text -> Text
overrideKey Text
key, QuotaOverride
override) | (Text
key, QuotaOverride
override) <- Map Text QuotaOverride -> [(Text, QuotaOverride)]
forall k a. Map k a -> [(k, a)]
Map.toList Map Text QuotaOverride
overrides]

-- | Apply declared capacity over backend defaults, deriving any remaining quota from the sweep pace.
resolvedBudget :: BudgetPorts -> RegistryUrl -> StoreBudget -> StoreBudget
resolvedBudget :: BudgetPorts -> RegistryUrl -> StoreBudget -> StoreBudget
resolvedBudget BudgetPorts
ports RegistryUrl
url StoreBudget
budget =
    -- The derivation runs last and only bites where nothing else declared a quota, so an entry
    -- naming a scope or a weight alone still leaves the store a capacity.
    Rational -> StoreBudget -> StoreBudget
derivedCapacity (BudgetPorts -> Rational
bpNominalPace BudgetPorts
ports) (StoreBudget
-> (QuotaOverride -> StoreBudget)
-> Maybe QuotaOverride
-> StoreBudget
forall b a. b -> (a -> b) -> Maybe a -> b
maybe StoreBudget
located (StoreBudget -> QuotaOverride -> StoreBudget
declared StoreBudget
located) (Map Text QuotaOverride -> RegistryUrl -> Maybe QuotaOverride
matchingOverride (BudgetPorts -> Map Text QuotaOverride
bpOverrides BudgetPorts
ports) RegistryUrl
url))
  where
    -- A backend that names its own pool keeps it. One that names none is pooled by its authority.
    located :: StoreBudget
located
        | StoreBudget -> QuotaScope
bgScope StoreBudget
budget QuotaScope -> QuotaScope -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> QuotaScope
mkQuotaScope Text
"" = StoreBudget
budget{bgScope = storeScope url}
        | Bool
otherwise = StoreBudget
budget

-- A declared capacity wins per dimension, and a declared weight scales that kind's own costs.
declared :: StoreBudget -> QuotaOverride -> StoreBudget
declared :: StoreBudget -> QuotaOverride -> StoreBudget
declared StoreBudget
budget QuotaOverride
override =
    StoreBudget
budget
        { bgScope = maybe (bgScope budget) mkQuotaScope (qoScope override)
        , bgQuotas = Map.union (qoQuotas override) (bgQuotas budget)
        , bgOrigin = if Map.null (qoQuotas override) then bgOrigin budget else QuotaDeclared
        , bgCosts = Map.mapWithKey weighted (bgCosts budget)
        }
  where
    weighted :: RequestKind -> Map k Rational -> Map k Rational
weighted RequestKind
kind Map k Rational
costs = Map k Rational
-> (Rational -> Map k Rational) -> Maybe Rational -> Map k Rational
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map k Rational
costs (\Rational
weight -> (Rational -> Rational) -> Map k Rational -> Map k Rational
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map (Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
* Rational
weight) Map k Rational
costs) (RequestKind -> Map RequestKind Rational -> Maybe Rational
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup RequestKind
kind (QuotaOverride -> Map RequestKind Rational
qoWeights QuotaOverride
override))

-- One client of the store's own, and the manifest read that leads over it.
storeAccess :: StorePorts -> Limits -> ClearedBackend -> IO (StoreManifestRead, ExchangeClient)
storeAccess :: StorePorts
-> Limits
-> ClearedBackend
-> IO (StoreManifestRead, ExchangeClient)
storeAccess StorePorts
ports Limits
limits ClearedBackend
cleared = do
    client <- StorePorts -> IO ExchangeClient
storeClient StorePorts
ports
    pure (storeManifestRead ports limits cleared client, client)

-- Resolve the current secret for each read because managed tokens expire.
storeManifestRead :: StorePorts -> Limits -> ClearedBackend -> ExchangeClient -> StoreManifestRead
storeManifestRead :: StorePorts
-> Limits -> ClearedBackend -> ExchangeClient -> StoreManifestRead
storeManifestRead StorePorts
ports Limits
limits ClearedBackend
cleared ExchangeClient
client PackageName
name = do
    token <- (CredentialProvider -> IO Secret)
-> Maybe CredentialProvider -> IO (Maybe Secret)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Maybe a -> f (Maybe b)
traverse CredentialProvider -> IO Secret
mintSecret (StorePorts -> Maybe CredentialProvider
spCredential StorePorts
ports)
    first storeFaultOfMetadata
        <$> cbFetchManifest cleared (spTracing ports) (storeOrigin limits cleared client (ClientCredential (cbUsername cleared) <$> token)) name

storeOrigin :: Limits -> ClearedBackend -> ExchangeClient -> Maybe ClientCredential -> OriginClient
storeOrigin :: Limits
-> ClearedBackend
-> ExchangeClient
-> Maybe ClientCredential
-> OriginClient
storeOrigin Limits
limits ClearedBackend
cleared ExchangeClient
client = Limits
-> ExchangeClient
-> RegistryUrl
-> Maybe ClientCredential
-> OriginClient
originClient Limits
limits ExchangeClient
client (ClearedBackend -> RegistryUrl
cbUrl ClearedBackend
cleared)

-- Disable hidden HTTP replay so every attempt consumes the store's request budget.
storeClient :: StorePorts -> IO ExchangeClient
storeClient :: StorePorts -> IO ExchangeClient
storeClient StorePorts
ports = do
    manager <- Int -> ManagerSettings -> IO Manager
newPooledManager Int
storeConnections (ByteString -> ManagerSettings -> ManagerSettings
identityManagerSettings (StorePorts -> ByteString
spUserAgent StorePorts
ports) (ManagerSettings -> ManagerSettings
singleAttemptSettings ManagerSettings
typedTlsManagerSettings))
    pure (ExchangeClient manager (spDeadlines ports) untracedExchange)

-- One store, swept package by package, so the pool holds what one in-flight request needs.
storeConnections :: Int
storeConnections :: Int
storeConnections = Int
4

protocolStore :: Limits -> ClearedBackend -> ClearedProtocolStore -> StoreManifestRead -> ExchangeClient -> ExchangeClient -> ProtocolStore
protocolStore :: Limits
-> ClearedBackend
-> ClearedProtocolStore
-> StoreManifestRead
-> ExchangeClient
-> ExchangeClient
-> ProtocolStore
protocolStore Limits
limits ClearedBackend
cleared ClearedProtocolStore
store StoreManifestRead
readManifest ExchangeClient
client ExchangeClient
deletionClient =
    ProtocolStore
        { psRead :: ProtocolRead
psRead = Limits
-> ClearedBackend
-> ClearedProtocolStore
-> StoreManifestRead
-> ExchangeClient
-> ProtocolRead
protocolRead Limits
limits ClearedBackend
cleared ClearedProtocolStore
store StoreManifestRead
readManifest ExchangeClient
client
        , psDeleteOrigin :: OriginClient
psDeleteOrigin = Limits
-> ClearedBackend
-> ExchangeClient
-> Maybe ClientCredential
-> OriginClient
storeOrigin Limits
limits ClearedBackend
cleared ExchangeClient
deletionClient (Secret -> ClientCredential
bareCredential (Secret -> ClientCredential)
-> Maybe Secret -> Maybe ClientCredential
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ClearedProtocolStore -> Maybe Secret
cpsToken ClearedProtocolStore
store)
        , psDelete :: VersionDelete
psDelete = ClearedProtocolStore -> VersionDelete
cpsDelete ClearedProtocolStore
store
        }

protocolRead :: Limits -> ClearedBackend -> ClearedProtocolStore -> StoreManifestRead -> ExchangeClient -> ProtocolRead
protocolRead :: Limits
-> ClearedBackend
-> ClearedProtocolStore
-> StoreManifestRead
-> ExchangeClient
-> ProtocolRead
protocolRead Limits
limits ClearedBackend
cleared ClearedProtocolStore
store StoreManifestRead
readManifest ExchangeClient
client =
    ProtocolRead
        { prOrigin :: OriginClient
prOrigin = Limits
-> ClearedBackend
-> ExchangeClient
-> Maybe ClientCredential
-> OriginClient
storeOrigin Limits
limits ClearedBackend
cleared ExchangeClient
client (Secret -> ClientCredential
bareCredential (Secret -> ClientCredential)
-> Maybe Secret -> Maybe ClientCredential
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ClearedProtocolStore -> Maybe Secret
cpsToken ClearedProtocolStore
store)
        , prReadManifest :: StoreManifestRead
prReadManifest = StoreManifestRead
readManifest
        , prListing :: StoreListing
prListing = ClearedProtocolStore -> StoreListing
cpsListing ClearedProtocolStore
store
        , prCodec :: PublishCodec
prCodec = ClearedProtocolStore -> PublishCodec
cpsCodec ClearedProtocolStore
store
        , prBackendName :: Text
prBackendName = StoreTag -> Text
storeTagName (ClearedProtocolStore -> StoreTag
cpsTag ClearedProtocolStore
store)
        , prPermitDeletion :: Bool
prPermitDeletion = ClearedProtocolStore -> DeletionConsent
cpsConsent ClearedProtocolStore
store DeletionConsent -> DeletionConsent -> Bool
forall a. Eq a => a -> a -> Bool
== DeletionConsent
DeletionPermitted
        , prConsentDescriptor :: Text
prConsentDescriptor = ClearedProtocolStore -> Text
cpsConsentKey ClearedProtocolStore
store
        }

-- | Build each cleared store and collect all construction refusals before returning.
planStoreMaintenance ::
    (StorePorts -> Limits -> ClearedBackend -> IO store) ->
    TracingPort ->
    Deadlines ->
    ByteString ->
    BudgetPorts ->
    CredentialProviders ->
    Limits ->
    Map Ecosystem ClearedBackend ->
    IO (Either [BootError] (Map Ecosystem store))
planStoreMaintenance :: forall store.
(StorePorts -> Limits -> ClearedBackend -> IO store)
-> TracingPort
-> Deadlines
-> ByteString
-> BudgetPorts
-> CredentialProviders
-> Limits
-> Map Ecosystem ClearedBackend
-> IO (Either [BootError] (Map Ecosystem store))
planStoreMaintenance = CredentialTarget
-> (StorePorts -> Limits -> ClearedBackend -> IO store)
-> TracingPort
-> Deadlines
-> ByteString
-> BudgetPorts
-> CredentialProviders
-> Limits
-> Map Ecosystem ClearedBackend
-> IO (Either [BootError] (Map Ecosystem store))
forall store.
CredentialTarget
-> (StorePorts -> Limits -> ClearedBackend -> IO store)
-> TracingPort
-> Deadlines
-> ByteString
-> BudgetPorts
-> CredentialProviders
-> Limits
-> Map Ecosystem ClearedBackend
-> IO (Either [BootError] (Map Ecosystem store))
planStoreMaintenanceFor CredentialTarget
MirrorCredential

-- | Plan a target slot with its own credentials and accumulate all backend construction refusals.
planStoreMaintenanceFor ::
    CredentialTarget ->
    (StorePorts -> Limits -> ClearedBackend -> IO store) ->
    TracingPort ->
    Deadlines ->
    ByteString ->
    BudgetPorts ->
    CredentialProviders ->
    Limits ->
    Map Ecosystem ClearedBackend ->
    IO (Either [BootError] (Map Ecosystem store))
planStoreMaintenanceFor :: forall store.
CredentialTarget
-> (StorePorts -> Limits -> ClearedBackend -> IO store)
-> TracingPort
-> Deadlines
-> ByteString
-> BudgetPorts
-> CredentialProviders
-> Limits
-> Map Ecosystem ClearedBackend
-> IO (Either [BootError] (Map Ecosystem store))
planStoreMaintenanceFor CredentialTarget
target StorePorts -> Limits -> ClearedBackend -> IO store
build TracingPort
tracing Deadlines
deadlines ByteString
renderedAgent BudgetPorts
budget CredentialProviders
credentials Limits
limits Map Ecosystem ClearedBackend
backends =
    Validation [BootError] (Map Ecosystem store)
-> Either [BootError] (Map Ecosystem store)
forall e a. Validation e a -> Either e a
validationToEither (Validation [BootError] (Map Ecosystem store)
 -> Either [BootError] (Map Ecosystem store))
-> (Map Ecosystem (Either [BootError] store)
    -> Validation [BootError] (Map Ecosystem store))
-> Map Ecosystem (Either [BootError] store)
-> Either [BootError] (Map Ecosystem store)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Either [BootError] store -> Validation [BootError] store)
-> Map Ecosystem (Either [BootError] store)
-> Validation [BootError] (Map Ecosystem store)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Map Ecosystem a -> f (Map Ecosystem b)
traverse Either [BootError] store -> Validation [BootError] store
forall e a. Either e a -> Validation e a
eitherToValidation (Map Ecosystem (Either [BootError] store)
 -> Either [BootError] (Map Ecosystem store))
-> IO (Map Ecosystem (Either [BootError] store))
-> IO (Either [BootError] (Map Ecosystem store))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Ecosystem -> ClearedBackend -> IO (Either [BootError] store))
-> Map Ecosystem ClearedBackend
-> IO (Map Ecosystem (Either [BootError] store))
forall (t :: * -> *) k a b.
Applicative t =>
(k -> a -> t b) -> Map k a -> t (Map k b)
Map.traverseWithKey Ecosystem -> ClearedBackend -> IO (Either [BootError] store)
planOne Map Ecosystem ClearedBackend
backends
  where
    planOne :: Ecosystem -> ClearedBackend -> IO (Either [BootError] store)
planOne Ecosystem
eco ClearedBackend
backend =
        (Text -> BootError) -> IO store -> IO (Either [BootError] store)
forall a. (Text -> BootError) -> IO a -> IO (Either [BootError] a)
refuseOnThrow (Ecosystem -> StoreMaintenanceReason -> BootError
StoreMaintenanceUnavailable Ecosystem
eco (StoreMaintenanceReason -> BootError)
-> (Text -> StoreMaintenanceReason) -> Text -> BootError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> StoreMaintenanceReason
reason) (StorePorts -> Limits -> ClearedBackend -> IO store
build (Ecosystem -> StorePorts
portsFor Ecosystem
eco) Limits
limits ClearedBackend
backend)
    reason :: Text -> StoreMaintenanceReason
reason = case CredentialTarget
target of
        CredentialTarget
MirrorCredential -> Text -> StoreMaintenanceReason
ClientBuildFailed
        CredentialTarget
PrivateCacheCredential -> Text -> StoreMaintenanceReason
PrivateCacheUnavailable (Text -> StoreMaintenanceReason)
-> (Text -> Text) -> Text -> StoreMaintenanceReason
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text
"client build failed: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>)
    portsFor :: Ecosystem -> StorePorts
portsFor Ecosystem
eco =
        StorePorts
            { spTracing :: TracingPort
spTracing = TracingPort
tracing
            , spUserAgent :: ByteString
spUserAgent = ByteString
renderedAgent
            , spDeadlines :: Deadlines
spDeadlines = Deadlines
deadlines
            , spCredential :: Maybe CredentialProvider
spCredential = CredentialTarget
-> Ecosystem -> CredentialProviders -> Maybe CredentialProvider
lookupTargetProvider CredentialTarget
target Ecosystem
eco CredentialProviders
credentials
            , spBudget :: BudgetPorts
spBudget = BudgetPorts
budget
            }