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

{- | Whether Pilot may replace the stored advisory artifact with a new compile.

Pilot writes only over the object revision it observed. It orders OSV and EPSS separately, each
by source identity, @Last-Modified@, and complete-stream digest, so an older run cannot replace
newer data. A new artifact may shrink only a bounded share below the durable size baseline, so a
damaged feed cannot replace good coverage. An operator's direct write bypasses these checks and
is the rollback authority. "Ecluse.Core.Osv.Publication.Envelope" carries the stored state.
-}
module Ecluse.Core.Osv.Publication (
    -- * The vocabulary
    module Ecluse.Core.Osv.Publication.Types,

    -- * The decision
    PublicationRequest (..),
    Precondition (..),
    PublicationPlan (..),
    SourceOrder (..),
    renderSourceOrder,
    OrderRefusal (..),
    ShrinkReading (..),
    PublicationRefusal (..),
    planPublication,
    renderPublicationRefusal,
) where

import Data.Text qualified as T
import Data.Time (UTCTime)

import Ecluse.Core.Osv.Provenance (ProvenanceSource (EpssFeed, OsvExport))
import Ecluse.Core.Osv.Publication.Types
import Ecluse.Core.Osv.Schema (EpssStatus (EnrichmentAvailable, EnrichmentUnavailable), osvSchemaEpoch)
import Ecluse.Core.Text.Iso8601 (renderIso8601Utc)

-- | One publication attempt: the compile's facts, the artifact's size, and its nonce.
data PublicationRequest = PublicationRequest
    { PublicationRequest -> CandidateFacts
prFacts :: CandidateFacts
    , PublicationRequest -> Integer
prBytes :: Integer
    , PublicationRequest -> PublicationNonce
prNonce :: PublicationNonce
    , PublicationRequest -> Maybe Rebaseline
prRebaseline :: Maybe Rebaseline
    }
    deriving stock (PublicationRequest -> PublicationRequest -> Bool
(PublicationRequest -> PublicationRequest -> Bool)
-> (PublicationRequest -> PublicationRequest -> Bool)
-> Eq PublicationRequest
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PublicationRequest -> PublicationRequest -> Bool
== :: PublicationRequest -> PublicationRequest -> Bool
$c/= :: PublicationRequest -> PublicationRequest -> Bool
/= :: PublicationRequest -> PublicationRequest -> Bool
Eq, Int -> PublicationRequest -> ShowS
[PublicationRequest] -> ShowS
PublicationRequest -> String
(Int -> PublicationRequest -> ShowS)
-> (PublicationRequest -> String)
-> ([PublicationRequest] -> ShowS)
-> Show PublicationRequest
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PublicationRequest -> ShowS
showsPrec :: Int -> PublicationRequest -> ShowS
$cshow :: PublicationRequest -> String
show :: PublicationRequest -> String
$cshowList :: [PublicationRequest] -> ShowS
showList :: [PublicationRequest] -> ShowS
Show)

-- | The condition the store must hold for the write to land.
data Precondition
    = -- | Write only if no object holds the key.
      CreateOnly
    | -- | Write only over this exact revision.
      ReplaceRevision ObjectRevision
    deriving stock (Precondition -> Precondition -> Bool
(Precondition -> Precondition -> Bool)
-> (Precondition -> Precondition -> Bool) -> Eq Precondition
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Precondition -> Precondition -> Bool
== :: Precondition -> Precondition -> Bool
$c/= :: Precondition -> Precondition -> Bool
/= :: Precondition -> Precondition -> Bool
Eq, Int -> Precondition -> ShowS
[Precondition] -> ShowS
Precondition -> String
(Int -> Precondition -> ShowS)
-> (Precondition -> String)
-> ([Precondition] -> ShowS)
-> Show Precondition
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Precondition -> ShowS
showsPrec :: Int -> Precondition -> ShowS
$cshow :: Precondition -> String
show :: Precondition -> String
$cshowList :: [Precondition] -> ShowS
showList :: [Precondition] -> ShowS
Show)

-- | An accepted publication: the write's precondition, the state it records, and how it was ordered.
data PublicationPlan = PublicationPlan
    { PublicationPlan -> Precondition
plPrecondition :: Precondition
    , PublicationPlan -> PublishedState
plState :: PublishedState
    , PublicationPlan -> SourceOrder
plOsvOrder :: SourceOrder
    , PublicationPlan -> Maybe SourceOrder
plEpssOrder :: Maybe SourceOrder
    -- ^ 'Nothing' when optional enrichment was unavailable, so EPSS was not compared.
    }
    deriving stock (PublicationPlan -> PublicationPlan -> Bool
(PublicationPlan -> PublicationPlan -> Bool)
-> (PublicationPlan -> PublicationPlan -> Bool)
-> Eq PublicationPlan
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PublicationPlan -> PublicationPlan -> Bool
== :: PublicationPlan -> PublicationPlan -> Bool
$c/= :: PublicationPlan -> PublicationPlan -> Bool
/= :: PublicationPlan -> PublicationPlan -> Bool
Eq, Int -> PublicationPlan -> ShowS
[PublicationPlan] -> ShowS
PublicationPlan -> String
(Int -> PublicationPlan -> ShowS)
-> (PublicationPlan -> String)
-> ([PublicationPlan] -> ShowS)
-> Show PublicationPlan
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PublicationPlan -> ShowS
showsPrec :: Int -> PublicationPlan -> ShowS
$cshow :: PublicationPlan -> String
show :: PublicationPlan -> String
$cshowList :: [PublicationPlan] -> ShowS
showList :: [PublicationPlan] -> ShowS
Show)

-- | How one source's snapshot relates to the stored artifact's.
data SourceOrder
    = -- | No marker from this source identity was stored, so the snapshot starts its ordering.
      FreshScope
    | -- | The source declared a later @Last-Modified@.
      OrderedForward
    | -- | The same @Last-Modified@ and the same bytes, so the publication refreshes.
      EqualSnapshot
    | -- | The same bytes without comparable timestamps. The stored @Last-Modified@ carries forward.
      IdenticalBytes
    deriving stock (SourceOrder -> SourceOrder -> Bool
(SourceOrder -> SourceOrder -> Bool)
-> (SourceOrder -> SourceOrder -> Bool) -> Eq SourceOrder
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SourceOrder -> SourceOrder -> Bool
== :: SourceOrder -> SourceOrder -> Bool
$c/= :: SourceOrder -> SourceOrder -> Bool
/= :: SourceOrder -> SourceOrder -> Bool
Eq, Int -> SourceOrder -> ShowS
[SourceOrder] -> ShowS
SourceOrder -> String
(Int -> SourceOrder -> ShowS)
-> (SourceOrder -> String)
-> ([SourceOrder] -> ShowS)
-> Show SourceOrder
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SourceOrder -> ShowS
showsPrec :: Int -> SourceOrder -> ShowS
$cshow :: SourceOrder -> String
show :: SourceOrder -> String
$cshowList :: [SourceOrder] -> ShowS
showList :: [SourceOrder] -> ShowS
Show)

-- | The order as the publication log reads it.
renderSourceOrder :: SourceOrder -> Text
renderSourceOrder :: SourceOrder -> Text
renderSourceOrder = \case
    SourceOrder
FreshScope -> Text
"new source"
    SourceOrder
OrderedForward -> Text
"newer snapshot"
    SourceOrder
EqualSnapshot -> Text
"same snapshot"
    SourceOrder
IdenticalBytes -> Text
"identical bytes"

-- | Why one source's snapshot cannot replace the stored one.
data OrderRefusal
    = -- | The candidate's @Last-Modified@ is older than the stored one, both carried.
      OlderSnapshot UTCTime UTCTime
    | -- | The same @Last-Modified@ with different bytes, so nothing orders them.
      AmbiguousSnapshot UTCTime
    | -- | Different bytes with no timestamp pair to order them.
      UnorderedSnapshot
    deriving stock (OrderRefusal -> OrderRefusal -> Bool
(OrderRefusal -> OrderRefusal -> Bool)
-> (OrderRefusal -> OrderRefusal -> Bool) -> Eq OrderRefusal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: OrderRefusal -> OrderRefusal -> Bool
== :: OrderRefusal -> OrderRefusal -> Bool
$c/= :: OrderRefusal -> OrderRefusal -> Bool
/= :: OrderRefusal -> OrderRefusal -> Bool
Eq, Int -> OrderRefusal -> ShowS
[OrderRefusal] -> ShowS
OrderRefusal -> String
(Int -> OrderRefusal -> ShowS)
-> (OrderRefusal -> String)
-> ([OrderRefusal] -> ShowS)
-> Show OrderRefusal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> OrderRefusal -> ShowS
showsPrec :: Int -> OrderRefusal -> ShowS
$cshow :: OrderRefusal -> String
show :: OrderRefusal -> String
$cshowList :: [OrderRefusal] -> ShowS
showList :: [OrderRefusal] -> ShowS
Show)

-- | The size comparison a refused shrink failed, all in bytes.
data ShrinkReading = ShrinkReading
    { ShrinkReading -> Integer
srCandidateBytes :: Integer
    , ShrinkReading -> Integer
srMinimumBytes :: Integer
    , ShrinkReading -> Integer
srBaselineBytes :: Integer
    , ShrinkReading -> Integer
srCreditBytes :: Integer
    }
    deriving stock (ShrinkReading -> ShrinkReading -> Bool
(ShrinkReading -> ShrinkReading -> Bool)
-> (ShrinkReading -> ShrinkReading -> Bool) -> Eq ShrinkReading
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ShrinkReading -> ShrinkReading -> Bool
== :: ShrinkReading -> ShrinkReading -> Bool
$c/= :: ShrinkReading -> ShrinkReading -> Bool
/= :: ShrinkReading -> ShrinkReading -> Bool
Eq, Int -> ShrinkReading -> ShowS
[ShrinkReading] -> ShowS
ShrinkReading -> String
(Int -> ShrinkReading -> ShowS)
-> (ShrinkReading -> String)
-> ([ShrinkReading] -> ShowS)
-> Show ShrinkReading
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ShrinkReading -> ShowS
showsPrec :: Int -> ShrinkReading -> ShowS
$cshow :: ShrinkReading -> String
show :: ShrinkReading -> String
$cshowList :: [ShrinkReading] -> ShowS
showList :: [ShrinkReading] -> ShowS
Show)

-- | Why Pilot will not replace the stored artifact. Consumers keep the stored one.
data PublicationRefusal
    = -- | The stored object's publication metadata is missing or unreadable.
      PredecessorUnreadable EnvelopeFault
    | -- | The stored metadata names another ecosystem or schema epoch, both carried.
      PredecessorOutOfScope Text Int
    | -- | One source's snapshot is not ordered after the stored one.
      SourceOutOfOrder ProvenanceSource OrderRefusal
    | -- | The artifact shrank past the baseline's allowance.
      ShrinkPastBaseline ShrinkReading
    | -- | The rebaseline names a revision the store does not hold. 'Nothing' is an empty store.
      RebaselineMismatch ObjectRevision (Maybe ObjectRevision)
    deriving stock (PublicationRefusal -> PublicationRefusal -> Bool
(PublicationRefusal -> PublicationRefusal -> Bool)
-> (PublicationRefusal -> PublicationRefusal -> Bool)
-> Eq PublicationRefusal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PublicationRefusal -> PublicationRefusal -> Bool
== :: PublicationRefusal -> PublicationRefusal -> Bool
$c/= :: PublicationRefusal -> PublicationRefusal -> Bool
/= :: PublicationRefusal -> PublicationRefusal -> Bool
Eq, Int -> PublicationRefusal -> ShowS
[PublicationRefusal] -> ShowS
PublicationRefusal -> String
(Int -> PublicationRefusal -> ShowS)
-> (PublicationRefusal -> String)
-> ([PublicationRefusal] -> ShowS)
-> Show PublicationRefusal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PublicationRefusal -> ShowS
showsPrec :: Int -> PublicationRefusal -> ShowS
$cshow :: PublicationRefusal -> String
show :: PublicationRefusal -> String
$cshowList :: [PublicationRefusal] -> ShowS
showList :: [PublicationRefusal] -> ShowS
Show)

-- | Decide one attempt against one observation. A rebaseline replaces only the shrink allowance, never the ordering.
planPublication :: ShrinkPolicy -> BaselineCapability -> PublicationRequest -> StoreObservation -> Either PublicationRefusal PublicationPlan
planPublication :: ShrinkPolicy
-> BaselineCapability
-> PublicationRequest
-> StoreObservation
-> Either PublicationRefusal PublicationPlan
planPublication ShrinkPolicy
policy BaselineCapability
capability PublicationRequest
request = \case
    StoreObservation
StoreAbsent -> case PublicationRequest -> Maybe Rebaseline
prRebaseline PublicationRequest
request of
        Just Rebaseline
approval -> PublicationRefusal -> Either PublicationRefusal PublicationPlan
forall a b. a -> Either a b
Left (ObjectRevision -> Maybe ObjectRevision -> PublicationRefusal
RebaselineMismatch (Rebaseline -> ObjectRevision
rbExpected Rebaseline
approval) Maybe ObjectRevision
forall a. Maybe a
Nothing)
        Maybe Rebaseline
Nothing -> PublicationPlan -> Either PublicationRefusal PublicationPlan
forall a b. b -> Either a b
Right (PublicationRequest -> PublicationPlan
initialPlan PublicationRequest
request)
    StorePresent ObjectRevision
revision Integer
previousBytes Either EnvelopeFault PublishedState
stored -> do
        Maybe Rebaseline
-> (Rebaseline -> Either PublicationRefusal ())
-> Either PublicationRefusal ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ (PublicationRequest -> Maybe Rebaseline
prRebaseline PublicationRequest
request) (ObjectRevision -> Rebaseline -> Either PublicationRefusal ()
approvedFor ObjectRevision
revision)
        previous <- (EnvelopeFault -> PublicationRefusal)
-> Either EnvelopeFault PublishedState
-> Either PublicationRefusal PublishedState
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 EnvelopeFault -> PublicationRefusal
PredecessorUnreadable Either EnvelopeFault PublishedState
stored
        inScope facts previous
        osvOrder <- first (SourceOutOfOrder OsvExport) (orderSource (Just (psOsv previous)) (cfOsv facts))
        epssOrder <- first (SourceOutOfOrder EpssFeed) (traverse (orderSource (psLastEpss previous)) (cfEpss facts))
        sized <- first ShrinkPastBaseline (sizeAgainst policy capability request previous previousBytes)
        pure
            PublicationPlan
                { plPrecondition = ReplaceRevision revision
                , plState = recordedState request (snd osvOrder) (maybe (psLastEpss previous) (Just . snd) epssOrder) sized
                , plOsvOrder = fst osvOrder
                , plEpssOrder = fst <$> epssOrder
                }
  where
    facts :: CandidateFacts
facts = PublicationRequest -> CandidateFacts
prFacts PublicationRequest
request

initialPlan :: PublicationRequest -> PublicationPlan
initialPlan :: PublicationRequest -> PublicationPlan
initialPlan PublicationRequest
request =
    PublicationPlan
        { plPrecondition :: Precondition
plPrecondition = Precondition
CreateOnly
        , plState :: PublishedState
plState = PublicationRequest
-> SourceMarker -> Maybe SourceMarker -> Sized -> PublishedState
recordedState PublicationRequest
request (CandidateFacts -> SourceMarker
cfOsv CandidateFacts
facts) (CandidateFacts -> Maybe SourceMarker
cfEpss CandidateFacts
facts) (Integer -> Integer -> Adjustment -> Sized
Sized (PublicationRequest -> Integer
prBytes PublicationRequest
request) Integer
0 Adjustment
InitialBaseline)
        , plOsvOrder :: SourceOrder
plOsvOrder = SourceOrder
FreshScope
        , plEpssOrder :: Maybe SourceOrder
plEpssOrder = SourceOrder
FreshScope SourceOrder -> Maybe SourceMarker -> Maybe SourceOrder
forall a b. a -> Maybe b -> Maybe a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ CandidateFacts -> Maybe SourceMarker
cfEpss CandidateFacts
facts
        }
  where
    facts :: CandidateFacts
facts = PublicationRequest -> CandidateFacts
prFacts PublicationRequest
request

-- The ETag S3 reports is quoted, and an operator may copy it with or without the quotes.
approvedFor :: ObjectRevision -> Rebaseline -> Either PublicationRefusal ()
approvedFor :: ObjectRevision -> Rebaseline -> Either PublicationRefusal ()
approvedFor ObjectRevision
observed Rebaseline
approval
    | ObjectRevision -> Text
unquoted ObjectRevision
observed Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== ObjectRevision -> Text
unquoted (Rebaseline -> ObjectRevision
rbExpected Rebaseline
approval) = () -> Either PublicationRefusal ()
forall a b. b -> Either a b
Right ()
    | Bool
otherwise = PublicationRefusal -> Either PublicationRefusal ()
forall a b. a -> Either a b
Left (ObjectRevision -> Maybe ObjectRevision -> PublicationRefusal
RebaselineMismatch (Rebaseline -> ObjectRevision
rbExpected Rebaseline
approval) (ObjectRevision -> Maybe ObjectRevision
forall a. a -> Maybe a
Just ObjectRevision
observed))
  where
    unquoted :: ObjectRevision -> Text
unquoted (ObjectRevision Text
tag) = (Char -> Bool) -> Text -> Text
T.dropAround (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'"') (Text -> Text
T.strip Text
tag)

inScope :: CandidateFacts -> PublishedState -> Either PublicationRefusal ()
inScope :: CandidateFacts -> PublishedState -> Either PublicationRefusal ()
inScope CandidateFacts
facts PublishedState
previous
    | PublishedState -> Text
psEcosystem PublishedState
previous Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== CandidateFacts -> Text
cfEcosystem CandidateFacts
facts Bool -> Bool -> Bool
&& PublishedState -> Int
psSchemaEpoch PublishedState
previous Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
osvSchemaEpoch = () -> Either PublicationRefusal ()
forall a b. b -> Either a b
Right ()
    | Bool
otherwise = PublicationRefusal -> Either PublicationRefusal ()
forall a b. a -> Either a b
Left (Text -> Int -> PublicationRefusal
PredecessorOutOfScope (PublishedState -> Text
psEcosystem PublishedState
previous) (PublishedState -> Int
psSchemaEpoch PublishedState
previous))

-- A changed identity starts a fresh scope. Identical bytes keep the stored timestamp when the
-- candidate lacks one, so a later change is still ordered against it.
orderSource :: Maybe SourceMarker -> SourceMarker -> Either OrderRefusal (SourceOrder, SourceMarker)
orderSource :: Maybe SourceMarker
-> SourceMarker -> Either OrderRefusal (SourceOrder, SourceMarker)
orderSource Maybe SourceMarker
Nothing SourceMarker
candidate = (SourceOrder, SourceMarker)
-> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. b -> Either a b
Right (SourceOrder
FreshScope, SourceMarker
candidate)
orderSource (Just SourceMarker
stored) SourceMarker
candidate
    | SourceMarker -> SourceIdentity
smIdentity SourceMarker
stored SourceIdentity -> SourceIdentity -> Bool
forall a. Eq a => a -> a -> Bool
/= SourceMarker -> SourceIdentity
smIdentity SourceMarker
candidate = (SourceOrder, SourceMarker)
-> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. b -> Either a b
Right (SourceOrder
FreshScope, SourceMarker
candidate)
    | Bool
otherwise = case (SourceMarker -> Maybe UTCTime
smLastModified SourceMarker
candidate, SourceMarker -> Maybe UTCTime
smLastModified SourceMarker
stored) of
        (Just UTCTime
new, Just UTCTime
old)
            | UTCTime
new UTCTime -> UTCTime -> Bool
forall a. Ord a => a -> a -> Bool
> UTCTime
old -> (SourceOrder, SourceMarker)
-> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. b -> Either a b
Right (SourceOrder
OrderedForward, SourceMarker
candidate)
            | UTCTime
new UTCTime -> UTCTime -> Bool
forall a. Ord a => a -> a -> Bool
< UTCTime
old -> OrderRefusal -> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. a -> Either a b
Left (UTCTime -> UTCTime -> OrderRefusal
OlderSnapshot UTCTime
new UTCTime
old)
            | Bool
sameBytes -> (SourceOrder, SourceMarker)
-> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. b -> Either a b
Right (SourceOrder
EqualSnapshot, SourceMarker
candidate)
            | Bool
otherwise -> OrderRefusal -> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. a -> Either a b
Left (UTCTime -> OrderRefusal
AmbiguousSnapshot UTCTime
new)
        (Maybe UTCTime
new, Maybe UTCTime
old)
            | Bool
sameBytes -> (SourceOrder, SourceMarker)
-> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. b -> Either a b
Right (SourceOrder
IdenticalBytes, SourceMarker
candidate{smLastModified = new <|> old})
            | Bool
otherwise -> OrderRefusal -> Either OrderRefusal (SourceOrder, SourceMarker)
forall a b. a -> Either a b
Left OrderRefusal
UnorderedSnapshot
  where
    sameBytes :: Bool
sameBytes = SourceMarker -> SourceDigest
smDigest SourceMarker
stored SourceDigest -> SourceDigest -> Bool
forall a. Eq a => a -> a -> Bool
== SourceMarker -> SourceDigest
smDigest SourceMarker
candidate

-- The baseline and credit an accepted size records, and how it set them.
data Sized = Sized Integer Integer Adjustment

-- The effective baseline is the baseline less any EPSS outage credit. A durable baseline keeps the
-- larger of itself and the accepted size, so neither small shrinks nor an overstated credit move it.
sizeAgainst :: ShrinkPolicy -> BaselineCapability -> PublicationRequest -> PublishedState -> Integer -> Either ShrinkReading Sized
sizeAgainst :: ShrinkPolicy
-> BaselineCapability
-> PublicationRequest
-> PublishedState
-> Integer
-> Either ShrinkReading Sized
sizeAgainst ShrinkPolicy
policy BaselineCapability
capability PublicationRequest
request PublishedState
previous Integer
previousBytes = case BaselineCapability
capability of
    BaselineCapability
NoBaseline -> Sized -> Either ShrinkReading Sized
forall a b. b -> Either a b
Right (Integer -> Integer -> Adjustment -> Sized
Sized Integer
candidate Integer
0 Adjustment
OrdinaryBaseline)
    BaselineCapability
_
        | Integer
candidate Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
minimumBytes -> ShrinkReading -> Either ShrinkReading Sized
forall a b. a -> Either a b
Left (Integer -> Integer -> Integer -> Integer -> ShrinkReading
ShrinkReading Integer
candidate Integer
minimumBytes Integer
baseline Integer
credit)
        | Maybe Rebaseline -> Bool
forall a. Maybe a -> Bool
isJust (PublicationRequest -> Maybe Rebaseline
prRebaseline PublicationRequest
request) -> Sized -> Either ShrinkReading Sized
forall a b. b -> Either a b
Right (Integer -> Integer -> Adjustment -> Sized
Sized Integer
candidate Integer
0 Adjustment
OperatorRebaseline)
        | BaselineCapability
capability BaselineCapability -> BaselineCapability -> Bool
forall a. Eq a => a -> a -> Bool
== BaselineCapability
DurableBaseline -> Sized -> Either ShrinkReading Sized
forall a b. b -> Either a b
Right (Integer -> Integer -> Adjustment -> Sized
Sized (Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
max Integer
baseline Integer
candidate) Integer
credit (Integer -> Adjustment
forall {a}. (Ord a, Num a) => a -> Adjustment
creditAdjustment Integer
credit))
        | Bool
otherwise -> Sized -> Either ShrinkReading Sized
forall a b. b -> Either a b
Right (Integer -> Integer -> Adjustment -> Sized
Sized Integer
candidate Integer
credit (Integer -> Adjustment
forall {a}. (Ord a, Num a) => a -> Adjustment
creditAdjustment Integer
credit))
  where
    candidate :: Integer
candidate = PublicationRequest -> Integer
prBytes PublicationRequest
request
    baseline :: Integer
baseline = if BaselineCapability
capability BaselineCapability -> BaselineCapability -> Bool
forall a. Eq a => a -> a -> Bool
== BaselineCapability
DurableBaseline then PublishedState -> Integer
psBaselineBytes PublishedState
previous else Integer
previousBytes
    credit :: Integer
credit = ShrinkPolicy
-> BaselineCapability
-> PublishedState
-> Integer
-> Maybe SourceMarker
-> Integer
epssCredit ShrinkPolicy
policy BaselineCapability
capability PublishedState
previous Integer
previousBytes (CandidateFacts -> Maybe SourceMarker
cfEpss (PublicationRequest -> CandidateFacts
prFacts PublicationRequest
request))
    allowance :: Percent
allowance = Percent -> (Rebaseline -> Percent) -> Maybe Rebaseline -> Percent
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ShrinkPolicy -> Percent
spMaxShrink ShrinkPolicy
policy) Rebaseline -> Percent
rbMaxShrink (PublicationRequest -> Maybe Rebaseline
prRebaseline PublicationRequest
request)
    minimumBytes :: Integer
minimumBytes = Integer -> Percent -> Integer
keptShare (Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
max Integer
0 (Integer
baseline Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
credit)) Percent
allowance
    creditAdjustment :: a -> Adjustment
creditAdjustment a
held = if a
held a -> a -> Bool
forall a. Ord a => a -> a -> Bool
> a
0 then Adjustment
EpssOutageCredit else Adjustment
OrdinaryBaseline

-- Only a fall from available to unavailable enrichment grants a credit, from the stored scored-row
-- count, never the candidate's. A durable baseline carries it, unchanged, through the outage.
epssCredit :: ShrinkPolicy -> BaselineCapability -> PublishedState -> Integer -> Maybe SourceMarker -> Integer
epssCredit :: ShrinkPolicy
-> BaselineCapability
-> PublishedState
-> Integer
-> Maybe SourceMarker
-> Integer
epssCredit ShrinkPolicy
policy BaselineCapability
capability PublishedState
previous Integer
previousBytes Maybe SourceMarker
candidateEpss = case (PublishedState -> EpssStatus
psEpssStatus PublishedState
previous, Maybe SourceMarker
candidateEpss) of
    (EpssStatus
_, Just SourceMarker
_) -> Integer
0
    (EpssStatus
EnrichmentAvailable, Maybe SourceMarker
Nothing) -> Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min (Integer
epssBytesPerScoredRow Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* PublishedState -> Integer
psScoredRows PublishedState
previous) (Integer -> Percent -> Integer
floorShare Integer
previousBytes (ShrinkPolicy -> Percent
spEpssLossCap ShrinkPolicy
policy))
    (EpssStatus
EnrichmentUnavailable, Maybe SourceMarker
Nothing)
        | BaselineCapability
capability BaselineCapability -> BaselineCapability -> Bool
forall a. Eq a => a -> a -> Bool
== BaselineCapability
DurableBaseline -> PublishedState -> Integer
psEpssCreditBytes PublishedState
previous
        | Bool
otherwise -> Integer
0

-- The smallest size that keeps the share left after the allowance, rounded up.
keptShare :: Integer -> Percent -> Integer
keptShare :: Integer -> Percent -> Integer
keptShare Integer
bytes Percent
allowance = Rational -> Integer
forall b. Integral b => Rational -> b
forall a b. (RealFrac a, Integral b) => a -> b
ceiling (Integer -> Rational
forall a. Num a => Integer -> a
fromInteger Integer
bytes Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
* (Rational
100 Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
- Percent -> Rational
unPercent Percent
allowance) Rational -> Rational -> Rational
forall a. Fractional a => a -> a -> a
/ Rational
100)

floorShare :: Integer -> Percent -> Integer
floorShare :: Integer -> Percent -> Integer
floorShare Integer
bytes Percent
share = Rational -> Integer
forall b. Integral b => Rational -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor (Integer -> Rational
forall a. Num a => Integer -> a
fromInteger Integer
bytes Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
* Percent -> Rational
unPercent Percent
share Rational -> Rational -> Rational
forall a. Fractional a => a -> a -> a
/ Rational
100)

recordedState :: PublicationRequest -> SourceMarker -> Maybe SourceMarker -> Sized -> PublishedState
recordedState :: PublicationRequest
-> SourceMarker -> Maybe SourceMarker -> Sized -> PublishedState
recordedState PublicationRequest
request SourceMarker
osv Maybe SourceMarker
lastEpss (Sized Integer
baseline Integer
credit Adjustment
adjustment) =
    PublishedState
        { psEcosystem :: Text
psEcosystem = CandidateFacts -> Text
cfEcosystem CandidateFacts
facts
        , psSchemaEpoch :: Int
psSchemaEpoch = Int
osvSchemaEpoch
        , psOsv :: SourceMarker
psOsv = SourceMarker
osv
        , psEpssStatus :: EpssStatus
psEpssStatus = EpssStatus
-> (SourceMarker -> EpssStatus) -> Maybe SourceMarker -> EpssStatus
forall b a. b -> (a -> b) -> Maybe a -> b
maybe EpssStatus
EnrichmentUnavailable (EpssStatus -> SourceMarker -> EpssStatus
forall a b. a -> b -> a
const EpssStatus
EnrichmentAvailable) (CandidateFacts -> Maybe SourceMarker
cfEpss CandidateFacts
facts)
        , psLastEpss :: Maybe SourceMarker
psLastEpss = Maybe SourceMarker
lastEpss
        , psRelevantRows :: Integer
psRelevantRows = CandidateFacts -> Integer
cfRelevantRows CandidateFacts
facts
        , psScoredRows :: Integer
psScoredRows = CandidateFacts -> Integer
cfScoredRows CandidateFacts
facts
        , psBaselineBytes :: Integer
psBaselineBytes = Integer
baseline
        , psEpssCreditBytes :: Integer
psEpssCreditBytes = Integer
credit
        , psNonce :: PublicationNonce
psNonce = PublicationRequest -> PublicationNonce
prNonce PublicationRequest
request
        , psAdjustment :: Adjustment
psAdjustment = Adjustment
adjustment
        }
  where
    facts :: CandidateFacts
facts = PublicationRequest -> CandidateFacts
prFacts PublicationRequest
request

-- | The refusal as an operator reads it, ending with what stays in place.
renderPublicationRefusal :: PublicationRefusal -> Text
renderPublicationRefusal :: PublicationRefusal -> Text
renderPublicationRefusal PublicationRefusal
refusal = PublicationRefusal -> Text
reason PublicationRefusal
refusal Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", so the stored artifact stays in place"
  where
    reason :: PublicationRefusal -> Text
reason = \case
        PredecessorUnreadable EnvelopeFault
fault -> Text
"Pilot replaces only an object it can order against, and on the stored object " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> EnvelopeFault -> Text
renderEnvelopeFault EnvelopeFault
fault
        PredecessorOutOfScope Text
ecosystem Int
epoch -> Text
"the stored object's publication metadata names ecosystem " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ecosystem Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" at schema epoch " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show Int
epoch Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", not this artifact's"
        SourceOutOfOrder ProvenanceSource
source OrderRefusal
order -> ProvenanceSource -> Text
sourceName ProvenanceSource
source Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> OrderRefusal -> Text
renderOrderRefusal OrderRefusal
order
        ShrinkPastBaseline ShrinkReading
reading -> ShrinkReading -> Text
renderShrink ShrinkReading
reading
        RebaselineMismatch (ObjectRevision Text
expected) Maybe ObjectRevision
observed ->
            Text
"the rebaseline expects revision " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
expected Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", and the store holds " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> (ObjectRevision -> Text) -> Maybe ObjectRevision -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"no object" (\(ObjectRevision Text
tag) -> Text
"revision " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
tag) Maybe ObjectRevision
observed

renderOrderRefusal :: OrderRefusal -> Text
renderOrderRefusal :: OrderRefusal -> Text
renderOrderRefusal = \case
    OlderSnapshot UTCTime
new UTCTime
old -> Text
"answered Last-Modified " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> UTCTime -> Text
renderIso8601Utc UTCTime
new Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", older than the stored " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> UTCTime -> Text
renderIso8601Utc UTCTime
old
    AmbiguousSnapshot UTCTime
at -> Text
"answered the stored Last-Modified " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> UTCTime -> Text
renderIso8601Utc UTCTime
at Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" with different bytes, so nothing orders them"
    OrderRefusal
UnorderedSnapshot -> Text
"changed without a Last-Modified that orders it after the stored snapshot"

renderShrink :: ShrinkReading -> Text
renderShrink :: ShrinkReading -> Text
renderShrink ShrinkReading
reading =
    Text
"the artifact is "
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Integer -> Text
forall b a. (Show a, IsString b) => a -> b
show (ShrinkReading -> Integer
srCandidateBytes ShrinkReading
reading)
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" bytes, under the "
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Integer -> Text
forall b a. (Show a, IsString b) => a -> b
show (ShrinkReading -> Integer
srMinimumBytes ShrinkReading
reading)
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-byte minimum from a "
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Integer -> Text
forall b a. (Show a, IsString b) => a -> b
show (ShrinkReading -> Integer
srBaselineBytes ShrinkReading
reading)
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-byte baseline"
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
credit
  where
    credit :: Text
credit
        | ShrinkReading -> Integer
srCreditBytes ShrinkReading
reading Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
0 = Text
" less a " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Integer -> Text
forall b a. (Show a, IsString b) => a -> b
show (ShrinkReading -> Integer
srCreditBytes ShrinkReading
reading) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-byte EPSS outage credit"
        | Bool
otherwise = Text
""

sourceName :: ProvenanceSource -> Text
sourceName :: ProvenanceSource -> Text
sourceName = \case
    ProvenanceSource
OsvExport -> Text
"the OSV export"
    ProvenanceSource
EpssFeed -> Text
"the EPSS feed"