packages feed

okf-core-0.14.0.0: src/Okf/Trust.hs

-- | Trust and freshness derived from frontmatter and caller-supplied time.
module Okf.Trust
  ( TrustTier (..),
    trustTier,
    renderTrustTier,
    VerificationSummary (..),
    summarizeVerification,
    latestVerification,
    Staleness (..),
    staleness,
    stalenessAt,
    renderStaleness,
  )
where

import Data.List qualified as List
import Data.Ord (comparing)
import Data.Text qualified as Text
import Data.Time (Day, UTCTime (..), defaultTimeLocale, formatTime)
import Okf.Actor (isHumanActor, isValidActor)
import Okf.Document (Generated (..), Verification (..))
import Okf.Prelude
import Okf.Timestamp (parseTimestamp)

data TrustTier
  = Unverified
  | MachineConfirmed
  | HumanReviewed
  deriving stock (Generic, Eq, Ord, Show)

-- | Classify a list of current events. Use 'summarizeVerification' to find
-- which events cover a particular generation before deriving its tier.
trustTier :: [Verification] -> TrustTier
trustTier verifications = case usableEvents verifications of
  [] -> Unverified
  events
    | any (isHumanActor . verificationBy . snd) events -> HumanReviewed
    | otherwise -> MachineConfirmed

renderTrustTier :: TrustTier -> Text
renderTrustTier = \case
  Unverified -> "unverified"
  MachineConfirmed -> "machine-confirmed"
  HumanReviewed -> "human-reviewed"

data VerificationSummary = VerificationSummary
  { currentVerifications :: ![Verification],
    earlierVerifications :: ![Verification],
    comparisonTimeUnknown :: !Bool
  }
  deriving stock (Generic, Eq, Show)

-- | Compare real instants. A missing or ignored generation has no lower bound.
-- A recognized generator with an unknown change time cannot establish that an
-- event covers the current text.
summarizeVerification :: Maybe Generated -> [Verification] -> VerificationSummary
summarizeVerification generation verifications =
  case generation of
    Just Generated {generatedBy, generatedAt} | isValidActor generatedBy ->
      case generatedAt >>= parseTimestamp of
        Nothing -> VerificationSummary [] [] (not (null events))
        Just changed ->
          let (current, earlier) = List.partition ((>= changed) . fst) events
           in VerificationSummary (map snd current) (map snd earlier) False
    _ -> VerificationSummary (map snd events) [] False
  where
    events = usableEvents verifications

usableEvents :: [Verification] -> [(UTCTime, Verification)]
usableEvents events =
  [ (instant, verification)
  | verification@Verification {verificationBy, verificationAt} <- events,
    isValidActor verificationBy,
    Just instant <- [verificationAt >>= parseTimestamp]
  ]

-- | Return the original timestamp of the newest usable event.
latestVerification :: [Verification] -> Maybe Text
latestVerification verifications =
  case usableEvents verifications of
    [] -> Nothing
    events -> verificationAt (snd (List.maximumBy (comparing fst) events))

data Staleness
  = Fresh
  | Stale !Day
  | StaleAt !UTCTime
  | StaleAfterUnparseable !Text
  | NoStaleAfter
  deriving stock (Generic, Eq, Show)

-- | Compatibility entry point using midnight UTC for the supplied day.
staleness :: Day -> Maybe Text -> Staleness
staleness today = stalenessAt (UTCTime today 0)

-- | A deadline is inclusive. Text that cannot represent an instant remains
-- visible so it cannot be mistaken for a fresh status.
stalenessAt :: UTCTime -> Maybe Text -> Staleness
stalenessAt now = \case
  Nothing -> NoStaleAfter
  Just "" -> NoStaleAfter
  Just raw ->
    case parseTimestamp raw of
      Nothing -> StaleAfterUnparseable raw
      Just deadline
        | now < deadline -> Fresh
        | Text.length raw == 10 -> Stale (utctDay deadline)
        | otherwise -> StaleAt deadline

renderStaleness :: Staleness -> Text
renderStaleness = \case
  Fresh -> "ok"
  NoStaleAfter -> "no review deadline"
  Stale deadline -> "stale since " <> Text.pack (show deadline)
  StaleAt deadline -> "stale since " <> Text.pack (formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%QZ" deadline)
  StaleAfterUnparseable raw -> "unparseable stale_after " <> raw