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

-- | Advisory download, verification, and ownership transfer into the live slot.
module Ecluse.Runtime.Cve.Sync.Step (
    CveFetch (..),
    FetchedObject (..),
    DbEtag (..),
    OsvDbFetchFault (..),
    SyncEnv (..),
    SyncOutcome (..),
    syncStep,
    publishVerified,
) where

import Data.Time (UTCTime)
import System.Directory (removeFile, renameFile)
import UnliftIO.Exception (catchAny, mask, onException)

import Ecluse.Core.Cve (CveDb (cveDbClose, cveDbMeta), CveDbRejected)
import Ecluse.Core.Cve.Internal (transferCveDb)
import Ecluse.Core.Cve.Slot (CveSlot, observeAdvisoryPublication, swapIn)
import Ecluse.Core.Cve.Types (DbEtag (..), OsvDbFetchFault (..))
import Ecluse.Core.Ecosystem (Ecosystem)
import Ecluse.Core.Osv.Schema (EpssRequirement)

-- | The advisory transport supplied to one sync cycle.
data CveFetch = CveFetch
    { CveFetch -> IO (Either OsvDbFetchFault (Maybe FetchedObject))
fetchHead :: IO (Either OsvDbFetchFault (Maybe FetchedObject))
    -- ^ The object's ETag and publication time. @Right Nothing@ means it does not exist, and a fetch failure is a 'Left'.
    , CveFetch -> FilePath -> IO (Either OsvDbFetchFault FetchedObject)
fetchDownload :: FilePath -> IO (Either OsvDbFetchFault FetchedObject)
    -- ^ Download the artifact, byte-bounded, with the download's own ETag, so a racing publish reads true. A 'Left' may leave a partial file.
    }

-- | Metadata from one HEAD or GET response. A download carries its own, so a publication racing HEAD cannot mislabel the bytes.
data FetchedObject = FetchedObject
    { FetchedObject -> DbEtag
foEtag :: DbEtag
    , FetchedObject -> Maybe UTCTime
foPushedAt :: Maybe UTCTime
    -- ^ The object's own timestamp, 'Nothing' when the store reported none.
    }
    deriving stock (FetchedObject -> FetchedObject -> Bool
(FetchedObject -> FetchedObject -> Bool)
-> (FetchedObject -> FetchedObject -> Bool) -> Eq FetchedObject
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FetchedObject -> FetchedObject -> Bool
== :: FetchedObject -> FetchedObject -> Bool
$c/= :: FetchedObject -> FetchedObject -> Bool
/= :: FetchedObject -> FetchedObject -> Bool
Eq, Int -> FetchedObject -> ShowS
[FetchedObject] -> ShowS
FetchedObject -> FilePath
(Int -> FetchedObject -> ShowS)
-> (FetchedObject -> FilePath)
-> ([FetchedObject] -> ShowS)
-> Show FetchedObject
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FetchedObject -> ShowS
showsPrec :: Int -> FetchedObject -> ShowS
$cshow :: FetchedObject -> FilePath
show :: FetchedObject -> FilePath
$cshowList :: [FetchedObject] -> ShowS
showList :: [FetchedObject] -> ShowS
Show)

-- | Everything one ecosystem's sync task operates on.
data SyncEnv = SyncEnv
    { SyncEnv -> CveFetch
syncFetch :: CveFetch
    -- ^ The transport for this ecosystem's object key.
    , SyncEnv -> Ecosystem
syncEcosystem :: Ecosystem
    -- ^ The ecosystem the artifact must verify as.
    , SyncEnv -> EpssRequirement
syncEpssRequirement :: EpssRequirement
    -- ^ Whether this ecosystem requires successful EPSS enrichment.
    , SyncEnv -> FilePath
syncDbPath :: FilePath
    -- ^ The canonical on-disk artifact path (the stable per-ecosystem name).
    , SyncEnv -> CveSlot
syncSlot :: CveSlot
    -- ^ The slot this task's swaps publish to.
    , SyncEnv -> Text
syncStoreRef :: Text
    -- ^ How the configured store reads back, for the reports that name where an artifact belongs.
    }

-- | The result of one sync cycle, for scheduling and observation.
data SyncOutcome
    = -- | Verification accepted a new artifact and it is now live (its ETag and provenance carried).
      SyncSwapped DbEtag [(Text, Text)]
    | -- | No database replacement, though an accepted republication can advance publication time.
      SyncUnchanged
    | -- | The object does not exist in the bucket (not yet published).
      SyncAbsent
    | -- | The artifact downloaded, and verification __refused__ it. The last-good generation serves on, and the sync remembers the ETag.
      SyncRejected DbEtag CveDbRejected
    | -- | The fetch itself failed (carried). The step learned nothing, so the last seen ETag stands and the schedule retries.
      SyncFetchFaulted OsvDbFetchFault
    deriving stock (Int -> SyncOutcome -> ShowS
[SyncOutcome] -> ShowS
SyncOutcome -> FilePath
(Int -> SyncOutcome -> ShowS)
-> (SyncOutcome -> FilePath)
-> ([SyncOutcome] -> ShowS)
-> Show SyncOutcome
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SyncOutcome -> ShowS
showsPrec :: Int -> SyncOutcome -> ShowS
$cshow :: SyncOutcome -> FilePath
show :: SyncOutcome -> FilePath
$cshowList :: [SyncOutcome] -> ShowS
showList :: [SyncOutcome] -> ShowS
Show)

-- | One detect-download-verify-swap cycle against the last seen ETag. A failed fetch and a refused artifact are outcomes, not exceptions.
syncStep :: SyncEnv -> Maybe DbEtag -> IO SyncOutcome
syncStep :: SyncEnv -> Maybe DbEtag -> IO SyncOutcome
syncStep SyncEnv
env Maybe DbEtag
lastSeen =
    CveFetch -> IO (Either OsvDbFetchFault (Maybe FetchedObject))
fetchHead (SyncEnv -> CveFetch
syncFetch SyncEnv
env) IO (Either OsvDbFetchFault (Maybe FetchedObject))
-> (Either OsvDbFetchFault (Maybe FetchedObject) -> IO SyncOutcome)
-> IO SyncOutcome
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Left OsvDbFetchFault
fault -> SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (OsvDbFetchFault -> SyncOutcome
SyncFetchFaulted OsvDbFetchFault
fault)
        Right Maybe FetchedObject
Nothing -> SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SyncOutcome
SyncAbsent
        Right (Just FetchedObject
remote)
            | DbEtag -> Maybe DbEtag
forall a. a -> Maybe a
Just (FetchedObject -> DbEtag
foEtag FetchedObject
remote) Maybe DbEtag -> Maybe DbEtag -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe DbEtag
lastSeen -> do
                CveSlot -> DbEtag -> Maybe UTCTime -> IO ()
observeAdvisoryPublication (SyncEnv -> CveSlot
syncSlot SyncEnv
env) (FetchedObject -> DbEtag
foEtag FetchedObject
remote) (FetchedObject -> Maybe UTCTime
foPushedAt FetchedObject
remote)
                SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SyncOutcome
SyncUnchanged
            | Bool
otherwise -> SyncEnv -> IO SyncOutcome
syncNewArtifact SyncEnv
env

syncNewArtifact :: SyncEnv -> IO SyncOutcome
syncNewArtifact :: SyncEnv -> IO SyncOutcome
syncNewArtifact SyncEnv
env = ((forall a. IO a -> IO a) -> IO SyncOutcome) -> IO SyncOutcome
forall (m :: * -> *) b.
MonadUnliftIO m =>
((forall a. m a -> m a) -> m b) -> m b
mask (((forall a. IO a -> IO a) -> IO SyncOutcome) -> IO SyncOutcome)
-> ((forall a. IO a -> IO a) -> IO SyncOutcome) -> IO SyncOutcome
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
    let temp :: FilePath
temp = SyncEnv -> FilePath
syncDbPath SyncEnv
env FilePath -> ShowS
forall a. Semigroup a => a -> a -> a
<> FilePath
".tmp"
    downloaded <- IO (Either OsvDbFetchFault FetchedObject)
-> IO (Either OsvDbFetchFault FetchedObject)
forall a. IO a -> IO a
restore (CveFetch -> FilePath -> IO (Either OsvDbFetchFault FetchedObject)
fetchDownload (SyncEnv -> CveFetch
syncFetch SyncEnv
env) FilePath
temp) IO (Either OsvDbFetchFault FetchedObject)
-> IO () -> IO (Either OsvDbFetchFault FetchedObject)
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`onException` FilePath -> IO ()
discardTemp FilePath
temp
    case downloaded of
        Left OsvDbFetchFault
fault -> do
            FilePath -> IO ()
discardTemp FilePath
temp
            SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (OsvDbFetchFault -> SyncOutcome
SyncFetchFaulted OsvDbFetchFault
fault)
        Right FetchedObject
fetched -> do
            opened <-
                IO (Either CveDbRejected SyncOutcome)
-> IO (Either CveDbRejected SyncOutcome)
forall a. IO a -> IO a
restore (Ecosystem
-> EpssRequirement
-> FilePath
-> (CveDb -> IO SyncOutcome)
-> IO (Either CveDbRejected SyncOutcome)
forall a.
Ecosystem
-> EpssRequirement
-> FilePath
-> (CveDb -> IO a)
-> IO (Either CveDbRejected a)
transferCveDb (SyncEnv -> Ecosystem
syncEcosystem SyncEnv
env) (SyncEnv -> EpssRequirement
syncEpssRequirement SyncEnv
env) FilePath
temp (SyncEnv
-> IO () -> FilePath -> FetchedObject -> CveDb -> IO SyncOutcome
publishVerified SyncEnv
env (IO () -> IO ()
forall a. IO a -> IO a
restore (FilePath -> FilePath -> IO ()
renameFile FilePath
temp (SyncEnv -> FilePath
syncDbPath SyncEnv
env))) FilePath
temp FetchedObject
fetched))
                    IO (Either CveDbRejected SyncOutcome)
-> IO () -> IO (Either CveDbRejected SyncOutcome)
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`onException` FilePath -> IO ()
discardTemp FilePath
temp
            case opened of
                Left CveDbRejected
rejection -> do
                    FilePath -> IO ()
discardTemp FilePath
temp
                    SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DbEtag -> CveDbRejected -> SyncOutcome
SyncRejected (FetchedObject -> DbEtag
foEtag FetchedObject
fetched) CveDbRejected
rejection)
                Right SyncOutcome
outcome -> SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SyncOutcome
outcome

-- | Transfer under a mask, with a restored rename action. The slot owns the database from swap entry.
publishVerified :: SyncEnv -> IO () -> FilePath -> FetchedObject -> CveDb -> IO SyncOutcome
publishVerified :: SyncEnv
-> IO () -> FilePath -> FetchedObject -> CveDb -> IO SyncOutcome
publishVerified SyncEnv
env IO ()
rename FilePath
temp FetchedObject
fetched CveDb
db = do
    -- The transfer continuation owns the connection under a mask until 'swapIn' takes it.
    IO ()
rename IO () -> IO () -> IO ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`onException` (CveDb -> IO ()
cveDbClose CveDb
db IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> FilePath -> IO ()
discardTemp FilePath
temp)
    -- 'swapIn' owns the connection from entry, including cancellation during old-reader draining.
    CveSlot -> DbEtag -> Maybe UTCTime -> CveDb -> IO ()
swapIn (SyncEnv -> CveSlot
syncSlot SyncEnv
env) (FetchedObject -> DbEtag
foEtag FetchedObject
fetched) (FetchedObject -> Maybe UTCTime
foPushedAt FetchedObject
fetched) CveDb
db
    SyncOutcome -> IO SyncOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DbEtag -> [(Text, Text)] -> SyncOutcome
SyncSwapped (FetchedObject -> DbEtag
foEtag FetchedObject
fetched) (CveDb -> [(Text, Text)]
cveDbMeta CveDb
db))

-- Best-effort: the temp may already be renamed away or never created.
discardTemp :: FilePath -> IO ()
discardTemp :: FilePath -> IO ()
discardTemp FilePath
temp = FilePath -> IO ()
removeFile FilePath
temp IO () -> (SomeException -> IO ()) -> IO ()
forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> (SomeException -> m a) -> m a
`catchAny` IO () -> SomeException -> IO ()
forall a b. a -> b -> a
const IO ()
forall (f :: * -> *). Applicative f => f ()
pass