packages feed

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

-- | Locate an OKF computation definition without reading or running it.
module Okf.Computation
  ( LocatedComputation (..),
    ComputationIssue (..),
    locateComputation,
    missingContractParts,
  )
where

import Data.List (find)
import Data.Text qualified as Text
import Okf.Bundle
import Okf.Document
import Okf.Index (VersionDeclaration, frontmatterReferenceContext)
import Okf.Path (PathResolution (..), resolveFileReference)
import Okf.Prelude

data LocatedComputation
  = InlineComputation !Text
  | FileComputation !FilePath
  deriving stock (Eq, Show)

data ComputationIssue
  = NoComputationFence
  | InvalidComputationReference !Value
  | UnusableComputationFile !Text !PathResolution
  deriving stock (Eq, Show)

-- | A nonempty declaration selects the file even if a fence is also present.
-- The inventory predicate admits files only and already excludes unsafe paths.
locateComputation :: VersionDeclaration -> BundleInventory -> Concept -> Either ComputationIssue LocatedComputation
locateComputation declaration inventory concept =
  case optionalFieldValue "computation" (frontmatter (conceptDocument concept)) of
    Nothing ->
      case find isInline (conceptComputationSources concept) of
        Just (ComputationInline code) -> Right (InlineComputation code)
        _ -> Left NoComputationFence
    Just (String raw) ->
      case resolveFileReference (flip bundleInventoryMember inventory) (frontmatterReferenceContext declaration) (conceptSourcePath concept) raw of
        ResolvedInBundle path -> Right (FileComputation path)
        resolution -> Left (UnusableComputationFile raw resolution)
    Just raw -> Left (InvalidComputationReference raw)
  where
    isInline (ComputationInline _) = True
    isInline _ = False

-- | Structural inputs required to be eligible for attestation. A complete
-- definition still needs a verdict from the consumer for each executed run.
missingContractParts :: Concept -> Either ComputationIssue LocatedComputation -> [Text]
missingContractParts concept location =
  ["runtime" | not (hasText (conceptRuntime concept))]
    <> ["attester" | not (hasText (conceptAttester concept >>= attesterResource))]
    <> ["computation" | either (const True) (const False) location]
  where
    hasText = maybe False (not . Text.null . Text.strip)