packages feed

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

-- | Actor identities shared by generation, verification and provenance.
module Okf.Actor
  ( Actor (..),
    parseActor,
    renderActor,
    isHumanActor,
    isValidActor,
  )
where

import Data.Char (isAsciiLower, isAsciiUpper, isDigit)
import Data.Text qualified as Text
import Okf.Prelude

data Actor
  = HumanActor !Text
  | ProcessActor !Text
  | TeamActor !Text
  | SchemeActor !Text !Text
  | ProducerActor !Text !Text
  | UnclassifiedActor !Text
  deriving stock (Generic, Eq, Ord, Show)

-- | Read a scheme before examining any slash in its opaque identifier.
-- Unclassified text remains round-trippable for diagnostics and editing.
parseActor :: Text -> Actor
parseActor raw
  | (scheme, suffix) <- Text.breakOn ":" raw,
    Just actorId <- Text.stripPrefix ":" suffix,
    validScheme scheme =
      if Text.null actorId then UnclassifiedActor raw else withScheme scheme actorId
  | (producer, suffix) <- Text.breakOn "/" raw,
    Just version <- Text.stripPrefix "/" suffix,
    not (Text.null producer || Text.null version) =
      ProducerActor producer version
  | otherwise = UnclassifiedActor raw
  where
    withScheme "human" = HumanActor
    withScheme "process" = ProcessActor
    withScheme "team" = TeamActor
    withScheme scheme = SchemeActor scheme
    validScheme scheme = case Text.uncons scheme of
      Just (firstCharacter, rest) ->
        asciiLetter firstCharacter && Text.all (\c -> asciiLetter c || isDigit c || c `elem` ("+.-" :: String)) rest
      Nothing -> False
    asciiLetter c = isAsciiLower c || isAsciiUpper c

renderActor :: Actor -> Text
renderActor = \case
  HumanActor actorId -> "human:" <> actorId
  ProcessActor actorId -> "process:" <> actorId
  TeamActor actorId -> "team:" <> actorId
  SchemeActor scheme actorId -> scheme <> ":" <> actorId
  ProducerActor producer version -> producer <> "/" <> version
  UnclassifiedActor raw -> raw

isHumanActor :: Actor -> Bool
isHumanActor (HumanActor _) = True
isHumanActor _ = False

isValidActor :: Actor -> Bool
isValidActor (UnclassifiedActor _) = False
isValidActor _ = True