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

{- | Integrity admission, metric projections, and the denial audit trail that the packument
and tarball handlers share and their specs reach directly. Importing this module opts out of
the stability promise of the public hub, "Ecluse.Core.Server.Pipeline".

The @module@ field on every line emitted here is 'pipelineInternalModule', a fixed operator
filter key rather than the source module path.
-}
module Ecluse.Core.Server.Pipeline.Internal (
    -- * The operator log-filter keys
    pipelineModule,
    pipelineInternalModule,

    -- * Integrity-floor admission (pure)
    admitByIntegrity,

    -- * Metric-label projections (pure)
    packumentServeDecision,
    statusServeDecision,
    serveDecisionClass,
    denialLabels,
    evalTier,
    transienceCause,

    -- * Metric emits (off a serve outcome)
    recordDenials,
    recordEffectfulFailures,

    -- * Denial audit trail (structured log)
    VersionVerdict (..),
    DenialAudit (..),
    denialAuditPayload,
    logDenials,
    logSkippedChecks,
    logSkippedChecksOnce,
) where

import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text qualified as T
import Katip (KatipContext, Severity (DebugS), SimpleLogPayload, katipAddContext, logFM, ls, sl)

import Ecluse.Core.Cve.Types (DbEtag (..))
import Ecluse.Core.Package (
    Artifact (artHashes),
    PackageDetails (pkgArtifacts),
    PackageInfo (infoDistTags, infoVersions),
    PackageName,
    renderPackageName,
 )
import Ecluse.Core.Package.Integrity (
    IntegrityFloor,
    VersionIntegrity (BelowFloor, MeetsFloor, NoIntegrity),
    classifyDigests,
    partitionByFloor,
 )
import Ecluse.Core.Rules (PreparedRule, prepResilience)
import Ecluse.Core.Rules.Outage (AdmissionIdentity (AdmissionIdentity), logSkippedCheckEvidence)
import Ecluse.Core.Rules.Types (
    Decision (Admitted, Blocked, BlockedByDefault, Undecidable),
    Reason,
    SkippedCheck (SkippedUnavailable),
    reasonAdvisories,
 )
import Ecluse.Core.Server.Response (
    PackumentStatus (PackumentBadGateway, PackumentDenied, PackumentForbidden, PackumentOk, PackumentServerError, PackumentUnavailable),
    RejectReason (BelowIntegrityFloor, ByPolicy, MissingIntegrity, Unavailable, UpstreamInvalid),
    Rejection (Rejection),
    RuleName (RuleName),
    ServeDecision (Admit, Reject),
    Transience (WillResolve, WontResolve),
    packumentStatus,
 )
import Ecluse.Core.Telemetry.Metrics qualified as Metric
import Ecluse.Core.Telemetry.Record (MetricsPort, mpRuleDenial, mpRuleEffectfulFailure)
import Ecluse.Core.Version (renderVersion)

-- | The @module@ field of the pipeline's own lines, and of any line a request logs whose site names none.
pipelineModule :: Text
pipelineModule :: Text
pipelineModule = Text
"Ecluse.Server.Pipeline"

-- | The @module@ field every line in this family carries, held stable so an operator's saved filter keeps matching.
pipelineInternalModule :: Text
pipelineInternalModule :: Text
pipelineInternalModule = Text
"Ecluse.Server.Pipeline.Internal"

{- | Keep each version's files whose strongest digest meets the floor, so a version drops only when
none survives, as at the download gate. Each dropped version keeps its refusal beside its version, so
its audit line can name it.
-}
admitByIntegrity ::
    (IntegrityFloor floor) =>
    floor ->
    -- The refusal for a version whose digest is too weak ('BelowFloor').
    ServeDecision ->
    -- The refusal for a version with no digest ('NoIntegrity'). Each gate passes its own wording.
    ServeDecision ->
    PackageInfo ->
    (PackageInfo, [VersionVerdict])
admitByIntegrity :: forall floor.
IntegrityFloor floor =>
floor
-> ServeDecision
-> ServeDecision
-> PackageInfo
-> (PackageInfo, [VersionVerdict])
admitByIntegrity floor
floorSpec ServeDecision
belowFloorRefusal ServeDecision
missingRefusal PackageInfo
info
    -- A listing whose every file clears the floor keeps every version whole, so skip the rebuild.
    | (PackageDetails -> Bool) -> Map Text PackageDetails -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((Artifact -> Bool) -> NonEmpty Artifact -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Artifact -> Bool
fileMeetsFloor (NonEmpty Artifact -> Bool)
-> (PackageDetails -> NonEmpty Artifact) -> PackageDetails -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PackageDetails -> NonEmpty Artifact
pkgArtifacts) (PackageInfo -> Map Text PackageDetails
infoVersions PackageInfo
info) = (Map Text PackageDetails -> PackageInfo
withVersions (PackageInfo -> Map Text PackageDetails
infoVersions PackageInfo
info), [])
    | Bool
otherwise = (Map Text PackageDetails -> PackageInfo
withVersions Map Text PackageDetails
admissible, [VersionVerdict]
refusals)
  where
    fileMeetsFloor :: Artifact -> Bool
fileMeetsFloor Artifact
file = floor -> [Hash] -> VersionIntegrity
forall floor.
IntegrityFloor floor =>
floor -> [Hash] -> VersionIntegrity
classifyDigests floor
floorSpec (Artifact -> [Hash]
artHashes Artifact
file) VersionIntegrity -> VersionIntegrity -> Bool
forall a. Eq a => a -> a -> Bool
== VersionIntegrity
MeetsFloor

    withVersions :: Map Text PackageDetails -> PackageInfo
withVersions Map Text PackageDetails
versions =
        PackageInfo
info
            { infoVersions = versions
            , infoDistTags = Map.filter ((`Map.member` versions) . renderVersion) (infoDistTags info)
            }

    partitioned :: Map Text (Either VersionIntegrity PackageDetails)
    partitioned :: Map Text (Either VersionIntegrity PackageDetails)
partitioned = (PackageDetails -> Either VersionIntegrity PackageDetails)
-> Map Text PackageDetails
-> Map Text (Either VersionIntegrity PackageDetails)
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map PackageDetails -> Either VersionIntegrity PackageDetails
admitArtifacts (PackageInfo -> Map Text PackageDetails
infoVersions PackageInfo
info)

    admitArtifacts :: PackageDetails -> Either VersionIntegrity PackageDetails
admitArtifacts PackageDetails
details =
        (\NonEmpty Artifact
survivors -> PackageDetails
details{pkgArtifacts = survivors}) (NonEmpty Artifact -> PackageDetails)
-> Either VersionIntegrity (NonEmpty Artifact)
-> Either VersionIntegrity PackageDetails
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> floor
-> (Artifact -> [Hash])
-> NonEmpty Artifact
-> Either VersionIntegrity (NonEmpty Artifact)
forall floor file.
IntegrityFloor floor =>
floor
-> (file -> [Hash])
-> NonEmpty file
-> Either VersionIntegrity (NonEmpty file)
partitionByFloor floor
floorSpec Artifact -> [Hash]
artHashes (PackageDetails -> NonEmpty Artifact
pkgArtifacts PackageDetails
details)

    admissible :: Map Text PackageDetails
    admissible :: Map Text PackageDetails
admissible = (Either VersionIntegrity PackageDetails -> Maybe PackageDetails)
-> Map Text (Either VersionIntegrity PackageDetails)
-> Map Text PackageDetails
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
Map.mapMaybe Either VersionIntegrity PackageDetails -> Maybe PackageDetails
forall l r. Either l r -> Maybe r
rightToMaybe Map Text (Either VersionIntegrity PackageDetails)
partitioned

    -- 'Map.foldrWithKey' visits keys in ascending order and each arm prepends, so the below-floor
    -- refusals precede the missing-integrity ones, each in key order.
    refusals :: [VersionVerdict]
    refusals :: [VersionVerdict]
refusals = [VersionVerdict]
below [VersionVerdict] -> [VersionVerdict] -> [VersionVerdict]
forall a. Semigroup a => a -> a -> a
<> [VersionVerdict]
missing
      where
        ([VersionVerdict]
below, [VersionVerdict]
missing) = (Text
 -> Either VersionIntegrity PackageDetails
 -> ([VersionVerdict], [VersionVerdict])
 -> ([VersionVerdict], [VersionVerdict]))
-> ([VersionVerdict], [VersionVerdict])
-> Map Text (Either VersionIntegrity PackageDetails)
-> ([VersionVerdict], [VersionVerdict])
forall k a b. (k -> a -> b -> b) -> b -> Map k a -> b
Map.foldrWithKey Text
-> Either VersionIntegrity PackageDetails
-> ([VersionVerdict], [VersionVerdict])
-> ([VersionVerdict], [VersionVerdict])
forall {b}.
Text
-> Either VersionIntegrity b
-> ([VersionVerdict], [VersionVerdict])
-> ([VersionVerdict], [VersionVerdict])
bucket ([], []) Map Text (Either VersionIntegrity PackageDetails)
partitioned
        bucket :: Text
-> Either VersionIntegrity b
-> ([VersionVerdict], [VersionVerdict])
-> ([VersionVerdict], [VersionVerdict])
bucket Text
version (Left VersionIntegrity
BelowFloor) ([VersionVerdict]
b, [VersionVerdict]
m) = (Text -> ServeDecision -> VersionVerdict
VersionVerdict Text
version ServeDecision
belowFloorRefusal VersionVerdict -> [VersionVerdict] -> [VersionVerdict]
forall a. a -> [a] -> [a]
: [VersionVerdict]
b, [VersionVerdict]
m)
        bucket Text
version (Left VersionIntegrity
NoIntegrity) ([VersionVerdict]
b, [VersionVerdict]
m) = ([VersionVerdict]
b, Text -> ServeDecision -> VersionVerdict
VersionVerdict Text
version ServeDecision
missingRefusal VersionVerdict -> [VersionVerdict] -> [VersionVerdict]
forall a. a -> [a] -> [a]
: [VersionVerdict]
m)
        -- 'partitionByFloor' never reports 'MeetsFloor' as a refusal, and a 'Right' is a survivor.
        bucket Text
_ (Left VersionIntegrity
MeetsFloor) ([VersionVerdict], [VersionVerdict])
acc = ([VersionVerdict], [VersionVerdict])
acc
        bucket Text
_ (Right b
_) ([VersionVerdict], [VersionVerdict])
acc = ([VersionVerdict], [VersionVerdict])
acc

-- | The bounded @ecluse.serve.decision@ value of a no-survivors packument: a refusal is a denial, the rest unavailable.
packumentServeDecision :: [ServeDecision] -> Metric.Decision
packumentServeDecision :: [ServeDecision] -> Decision
packumentServeDecision = PackumentStatus -> Decision
statusServeDecision (PackumentStatus -> Decision)
-> ([ServeDecision] -> PackumentStatus)
-> [ServeDecision]
-> Decision
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ServeDecision] -> PackumentStatus
packumentStatus

-- | 'packumentServeDecision' over a folded status, so the no-survivors path walks the decisions once.
statusServeDecision :: PackumentStatus -> Metric.Decision
statusServeDecision :: PackumentStatus -> Decision
statusServeDecision = \case
    PackumentStatus
PackumentOk -> Decision
Metric.Admit
    PackumentStatus
PackumentDenied -> Decision
Metric.Deny
    PackumentStatus
PackumentForbidden -> Decision
Metric.Deny
    PackumentUnavailable Maybe RetryAfter
_ -> Decision
Metric.Unavailable
    PackumentStatus
PackumentBadGateway -> Decision
Metric.Unavailable
    PackumentStatus
PackumentServerError -> Decision
Metric.Unavailable

-- | Classify a single artifact-path serve decision into the bounded metric decision.
serveDecisionClass :: ServeDecision -> Metric.Decision
serveDecisionClass :: ServeDecision -> Decision
serveDecisionClass = \case
    ServeDecision
Admit -> Decision
Metric.Admit
    Reject (Rejection RejectReason
reason Text
_) -> case RejectReason
reason of
        ByPolicy{} -> Decision
Metric.Deny
        RejectReason
MissingIntegrity -> Decision
Metric.Deny
        RejectReason
BelowIntegrityFloor -> Decision
Metric.Deny
        Unavailable{} -> Decision
Metric.Unavailable
        RejectReason
UpstreamInvalid -> Decision
Metric.Unavailable

-- | The @ecluse.rule.denials@ labels: the deciding rule of a policy denial, and the bounded reason class.
denialLabels :: RejectReason -> (Maybe Text, Metric.ReasonClass)
denialLabels :: RejectReason -> (Maybe Text, ReasonClass)
denialLabels = \case
    ByPolicy (RuleName Text
name) [Reason]
_ -> (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
name, ReasonClass
Metric.ReasonPolicy)
    RejectReason
MissingIntegrity -> (Maybe Text
forall a. Maybe a
Nothing, ReasonClass
Metric.ReasonMissingIntegrity)
    RejectReason
BelowIntegrityFloor -> (Maybe Text
forall a. Maybe a
Nothing, ReasonClass
Metric.ReasonBelowIntegrityFloor)
    Unavailable Transience
_ -> (Maybe Text
forall a. Maybe a
Nothing, ReasonClass
Metric.ReasonUnavailable)
    RejectReason
UpstreamInvalid -> (Maybe Text
forall a. Maybe a
Nothing, ReasonClass
Metric.ReasonUnavailable)

-- | The rule-evaluation tier of a duration: effectful when any prepared rule reads through a resilience policy.
evalTier :: [PreparedRule] -> Metric.Tier
evalTier :: [PreparedRule] -> Tier
evalTier [PreparedRule]
rules = if (PreparedRule -> Bool) -> [PreparedRule] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe Resilience -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Resilience -> Bool)
-> (PreparedRule -> Maybe Resilience) -> PreparedRule -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PreparedRule -> Maybe Resilience
prepResilience) [PreparedRule]
rules then Tier
Metric.Effectful else Tier
Metric.Structural

-- | Map an undecidable verdict's transience to the bounded @ecluse.rule.effectful.failures@ cause.
transienceCause :: Transience -> Metric.Cause
transienceCause :: Transience -> Cause
transienceCause = \case
    WillResolve Maybe RetryAfter
_ -> Cause
Metric.Connection
    Transience
WontResolve -> Cause
Metric.OtherCause

-- | Count @ecluse.rule.denials@ once per rejected decision, labelled by 'denialLabels'.
recordDenials :: MetricsPort -> [ServeDecision] -> IO ()
recordDenials :: MetricsPort -> [ServeDecision] -> IO ()
recordDenials MetricsPort
metrics = (ServeDecision -> IO ()) -> [ServeDecision] -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ ServeDecision -> IO ()
recordOne
  where
    recordOne :: ServeDecision -> IO ()
    recordOne :: ServeDecision -> IO ()
recordOne = \case
        ServeDecision
Admit -> IO ()
forall (f :: * -> *). Applicative f => f ()
pass
        Reject (Rejection RejectReason
reason Text
_) ->
            let (Maybe Text
rule, ReasonClass
reasonClass) = RejectReason -> (Maybe Text, ReasonClass)
denialLabels RejectReason
reason
             in MetricsPort -> Maybe Text -> ReasonClass -> IO ()
mpRuleDenial MetricsPort
metrics Maybe Text
rule ReasonClass
reasonClass

-- | Count each 'Undecidable' decision, the signal that an effectful rule could not consult its source.
recordEffectfulFailures :: MetricsPort -> [Decision] -> IO ()
recordEffectfulFailures :: MetricsPort -> [Decision] -> IO ()
recordEffectfulFailures MetricsPort
metrics = (Decision -> IO ()) -> [Decision] -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ Decision -> IO ()
recordOne
  where
    recordOne :: Decision -> IO ()
    recordOne :: Decision -> IO ()
recordOne = \case
        Undecidable Transience
transience Reason
_ -> MetricsPort -> Cause -> IO ()
mpRuleEffectfulFailure MetricsPort
metrics (Transience -> Cause
transienceCause Transience
transience)
        Admitted{} -> IO ()
forall (f :: * -> *). Applicative f => f ()
pass
        Blocked{} -> IO ()
forall (f :: * -> *). Applicative f => f ()
pass
        BlockedByDefault{} -> IO ()
forall (f :: * -> *). Applicative f => f ()
pass

-- | A per-version serve outcome beside its version, so a denial's audit line can name the version it refused.
data VersionVerdict = VersionVerdict
    { VersionVerdict -> Text
vvVersion :: Text
    , VersionVerdict -> ServeDecision
vvDecision :: ServeDecision
    }
    deriving stock (VersionVerdict -> VersionVerdict -> Bool
(VersionVerdict -> VersionVerdict -> Bool)
-> (VersionVerdict -> VersionVerdict -> Bool) -> Eq VersionVerdict
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: VersionVerdict -> VersionVerdict -> Bool
== :: VersionVerdict -> VersionVerdict -> Bool
$c/= :: VersionVerdict -> VersionVerdict -> Bool
/= :: VersionVerdict -> VersionVerdict -> Bool
Eq, Int -> VersionVerdict -> ShowS
[VersionVerdict] -> ShowS
VersionVerdict -> String
(Int -> VersionVerdict -> ShowS)
-> (VersionVerdict -> String)
-> ([VersionVerdict] -> ShowS)
-> Show VersionVerdict
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> VersionVerdict -> ShowS
showsPrec :: Int -> VersionVerdict -> ShowS
$cshow :: VersionVerdict -> String
show :: VersionVerdict -> String
$cshowList :: [VersionVerdict] -> ShowS
showList :: [VersionVerdict] -> ShowS
Show)

-- | Everything one denial audit line records. A shadow swap can make the emit-time 'DbEtag' differ from the decision's.
data DenialAudit = DenialAudit
    { DenialAudit -> PackageName
daPackage :: PackageName
    , DenialAudit -> Text
daVersion :: Text
    , DenialAudit -> Maybe Text
daRule :: Maybe Text
    , DenialAudit -> ReasonClass
daReasonClass :: Metric.ReasonClass
    , DenialAudit -> Maybe DbEtag
daAdvisoryEtag :: Maybe DbEtag
    , DenialAudit -> [Reason]
daReasons :: [Reason]
    -- ^ The reasons a policy denial gave. The @cve@ field joins the advisories still affecting the version.
    }

-- | Render a 'DenialAudit' to the structured payload katip folds into the line's @data@ object.
denialAuditPayload :: DenialAudit -> SimpleLogPayload
denialAuditPayload :: DenialAudit -> SimpleLogPayload
denialAuditPayload DenialAudit
da =
    PackageName -> Text -> Maybe DbEtag -> SimpleLogPayload
versionAuditPayload (DenialAudit -> PackageName
daPackage DenialAudit
da) (DenialAudit -> Text
daVersion DenialAudit
da) (DenialAudit -> Maybe DbEtag
daAdvisoryEtag DenialAudit
da)
        SimpleLogPayload -> SimpleLogPayload -> SimpleLogPayload
forall a. Semigroup a => a -> a -> a
<> SimpleLogPayload
-> (Text -> SimpleLogPayload) -> Maybe Text -> SimpleLogPayload
forall b a. b -> (a -> b) -> Maybe a -> b
maybe SimpleLogPayload
forall a. Monoid a => a
mempty (Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"rule") (DenialAudit -> Maybe Text
daRule DenialAudit
da)
        SimpleLogPayload -> SimpleLogPayload -> SimpleLogPayload
forall a. Semigroup a => a -> a -> a
<> Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"reason_class" (ReasonClass -> Text
forall b a. (Show a, IsString b) => a -> b
show (DenialAudit -> ReasonClass
daReasonClass DenialAudit
da) :: Text)
        SimpleLogPayload -> SimpleLogPayload -> SimpleLogPayload
forall a. Semigroup a => a -> a -> a
<> case [Text] -> [Text]
forall a. Ord a => [a] -> [a]
ordNub ((Reason -> [Text]) -> [Reason] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Reason -> [Text]
reasonAdvisories (DenialAudit -> [Reason]
daReasons DenialAudit
da)) of
            [] -> SimpleLogPayload
forall a. Monoid a => a
mempty
            [Text]
ids -> Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"cve" (Text -> [Text] -> Text
T.intercalate Text
", " [Text]
ids)

-- The fields every per-version audit line carries, so the denial and the skipped-check lines
-- are queried by the same names.
versionAuditPayload :: PackageName -> Text -> Maybe DbEtag -> SimpleLogPayload
versionAuditPayload :: PackageName -> Text -> Maybe DbEtag -> SimpleLogPayload
versionAuditPayload PackageName
pkg Text
version Maybe DbEtag
etag =
    Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"module" Text
pipelineInternalModule
        SimpleLogPayload -> SimpleLogPayload -> SimpleLogPayload
forall a. Semigroup a => a -> a -> a
<> Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"package" (PackageName -> Text
renderPackageName PackageName
pkg)
        SimpleLogPayload -> SimpleLogPayload -> SimpleLogPayload
forall a. Semigroup a => a -> a -> a
<> Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"version" Text
version
        SimpleLogPayload -> SimpleLogPayload -> SimpleLogPayload
forall a. Semigroup a => a -> a -> a
<> SimpleLogPayload
-> (DbEtag -> SimpleLogPayload) -> Maybe DbEtag -> SimpleLogPayload
forall b a. b -> (a -> b) -> Maybe a -> b
maybe SimpleLogPayload
forall a. Monoid a => a
mempty (\(DbEtag Text
e) -> Text -> Text -> SimpleLogPayload
forall a. ToJSON a => Text -> a -> SimpleLogPayload
sl Text
"active_advisory_db_etag" Text
e) Maybe DbEtag
etag

-- | Emit debug details per denied version. 'recordDenials' counts them at every log level.
logDenials :: (KatipContext m) => PackageName -> Maybe DbEtag -> [VersionVerdict] -> m ()
logDenials :: forall (m :: * -> *).
KatipContext m =>
PackageName -> Maybe DbEtag -> [VersionVerdict] -> m ()
logDenials PackageName
pkg Maybe DbEtag
etag = (VersionVerdict -> m ()) -> [VersionVerdict] -> m ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ VersionVerdict -> m ()
forall {f :: * -> *}. KatipContext f => VersionVerdict -> f ()
logOne
  where
    logOne :: VersionVerdict -> f ()
logOne VersionVerdict
vv = case VersionVerdict -> ServeDecision
vvDecision VersionVerdict
vv of
        ServeDecision
Admit -> f ()
forall (f :: * -> *). Applicative f => f ()
pass
        Reject (Rejection RejectReason
reason Text
_) ->
            let (Maybe Text
rule, ReasonClass
reasonClass) = RejectReason -> (Maybe Text, ReasonClass)
denialLabels RejectReason
reason
                audit :: DenialAudit
audit = PackageName
-> Text
-> Maybe Text
-> ReasonClass
-> Maybe DbEtag
-> [Reason]
-> DenialAudit
DenialAudit PackageName
pkg (VersionVerdict -> Text
vvVersion VersionVerdict
vv) Maybe Text
rule ReasonClass
reasonClass Maybe DbEtag
etag (RejectReason -> [Reason]
policyReasons RejectReason
reason)
             in SimpleLogPayload -> f () -> f ()
forall i (m :: * -> *) a.
(LogItem i, KatipContext m) =>
i -> m a -> m a
katipAddContext (DenialAudit -> SimpleLogPayload
denialAuditPayload DenialAudit
audit) (f () -> f ()) -> f () -> f ()
forall a b. (a -> b) -> a -> b
$
                    Severity -> LogStr -> f ()
forall (m :: * -> *).
(Applicative m, KatipContext m) =>
Severity -> LogStr -> m ()
logFM Severity
DebugS (Text -> LogStr
forall a. StringConv a Text => a -> LogStr
ls (Text
"denied" :: Text))

policyReasons :: RejectReason -> [Reason]
policyReasons :: RejectReason -> [Reason]
policyReasons = \case
    ByPolicy RuleName
_ [Reason]
reasons -> [Reason]
reasons
    Unavailable{} -> []
    RejectReason
MissingIntegrity -> []
    RejectReason
BelowIntegrityFloor -> []
    RejectReason
UpstreamInvalid -> []

-- | 'logSkippedChecks' once per package, version and skipped rule set for the outage, so a public serve that admits again repeats no line.
logSkippedChecksOnce :: (KatipContext m) => (AdmissionIdentity -> IO Bool) -> PackageName -> Text -> Maybe DbEtag -> [SkippedCheck] -> m ()
logSkippedChecksOnce :: forall (m :: * -> *).
KatipContext m =>
(AdmissionIdentity -> IO Bool)
-> PackageName -> Text -> Maybe DbEtag -> [SkippedCheck] -> m ()
logSkippedChecksOnce AdmissionIdentity -> IO Bool
note PackageName
pkg Text
version Maybe DbEtag
etag [SkippedCheck]
skipped =
    Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Set Text -> Bool
forall a. Set a -> Bool
Set.null Set Text
rules) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ do
        logIt <- IO Bool -> m Bool
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (AdmissionIdentity -> IO Bool
note (Text -> Text -> Set Text -> AdmissionIdentity
AdmissionIdentity (PackageName -> Text
renderPackageName PackageName
pkg) Text
version Set Text
rules))
        when logIt (logSkippedChecks pkg version etag skipped)
  where
    rules :: Set Text
rules = [Text] -> Set Text
forall a. Ord a => [a] -> Set a
Set.fromList [Text
rule | SkippedUnavailable Text
rule Inability
_ <- [SkippedCheck]
skipped]

-- | One audit line per check skipped for unavailability. An unreached check gets none. A trusted serve runs no rules, so it never reaches here.
logSkippedChecks :: (KatipContext m) => PackageName -> Text -> Maybe DbEtag -> [SkippedCheck] -> m ()
logSkippedChecks :: forall (m :: * -> *).
KatipContext m =>
PackageName -> Text -> Maybe DbEtag -> [SkippedCheck] -> m ()
logSkippedChecks PackageName
pkg Text
version Maybe DbEtag
etag = SimpleLogPayload -> [SkippedCheck] -> m ()
forall (m :: * -> *).
KatipContext m =>
SimpleLogPayload -> [SkippedCheck] -> m ()
logSkippedCheckEvidence (PackageName -> Text -> Maybe DbEtag -> SimpleLogPayload
versionAuditPayload PackageName
pkg Text
version Maybe DbEtag
etag)