-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT
{-# LANGUAGE ImportQualifiedPost #-}

-- | Durable worker records and transient inventories use the same monotonic completion facts.
module Ecluse.Core.Worker.Managed (
    readMirrorRecord,
    persistInventory,
    persistVerified,
    retainCompanion,
    verifyCompanions,
    fragmentDocument,
) where

import Data.Map.Strict qualified as Map

import Ecluse.Core.Mirror.State
import Ecluse.Core.Mirror.State.Codec (projectRecordWorkWeight)
import Ecluse.Core.Mirror.State.Format (MirrorStateFormat)
import Ecluse.Core.Mirror.State.Internal (retainVerifiedIdentity)
import Ecluse.Core.Package (PackageName)
import Ecluse.Core.Registry.Metadata (VersionDoc (VersionDoc))
import Ecluse.Core.Registry.MirrorUpload
import Ecluse.Core.Security (Limits)
import Ecluse.Core.Version (Version)
import Ecluse.Core.Worker.Types (WorkerMirrorState (..), WorkerStateBudget (..))

-- | Read after the native inventory. Unchanged responses require a payload that this caller holds.
readMirrorRecord :: WorkerStateBudget -> WorkerMirrorState -> PackageName -> IO (Either MirrorStateFault (Maybe ProjectMirrorRecord))
readMirrorRecord :: WorkerStateBudget
-> WorkerMirrorState
-> PackageName
-> IO (Either MirrorStateFault (Maybe ProjectMirrorRecord))
readMirrorRecord WorkerStateBudget
charge WorkerMirrorState
binding PackageName
name = do
    result <- (Either MirrorStateFault StateRead
 -> Either MirrorStateFault (Maybe ProjectMirrorRecord))
-> IO (Either MirrorStateFault StateRead)
-> IO (Either MirrorStateFault (Maybe ProjectMirrorRecord))
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Either MirrorStateFault StateRead
-> (StateRead
    -> Either MirrorStateFault (Maybe ProjectMirrorRecord))
-> Either MirrorStateFault (Maybe ProjectMirrorRecord)
forall a b.
Either MirrorStateFault a
-> (a -> Either MirrorStateFault b) -> Either MirrorStateFault b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= StateRead -> Either MirrorStateFault (Maybe ProjectMirrorRecord)
resolve) (MirrorState
-> StateCharge
-> PackageName
-> Maybe StateRevision
-> IO (Either MirrorStateFault StateRead)
msReadProject (WorkerMirrorState -> MirrorState
wmsStore WorkerMirrorState
binding) (WorkerStateBudget -> StateCharge
wsbState WorkerStateBudget
charge) PackageName
name Maybe StateRevision
forall a. Maybe a
Nothing)
    case result of
        Right (Just ProjectMirrorRecord
record) -> (ProjectMirrorRecord -> Maybe ProjectMirrorRecord)
-> Either MirrorStateFault ProjectMirrorRecord
-> Either MirrorStateFault (Maybe ProjectMirrorRecord)
forall a b.
(a -> b) -> Either MirrorStateFault a -> Either MirrorStateFault b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ProjectMirrorRecord -> Maybe ProjectMirrorRecord
forall a. a -> Maybe a
Just (Either MirrorStateFault ProjectMirrorRecord
 -> Either MirrorStateFault (Maybe ProjectMirrorRecord))
-> IO (Either MirrorStateFault ProjectMirrorRecord)
-> IO (Either MirrorStateFault (Maybe ProjectMirrorRecord))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> WorkerStateBudget
-> Limits
-> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
chargeRecord WorkerStateBudget
charge (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
binding) (ProjectMirrorRecord -> Either MirrorStateFault ProjectMirrorRecord
forall a b. b -> Either a b
Right ProjectMirrorRecord
record)
        Either MirrorStateFault (Maybe ProjectMirrorRecord)
other -> Either MirrorStateFault (Maybe ProjectMirrorRecord)
-> IO (Either MirrorStateFault (Maybe ProjectMirrorRecord))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Either MirrorStateFault (Maybe ProjectMirrorRecord)
other
  where
    resolve :: StateRead -> Either MirrorStateFault (Maybe ProjectMirrorRecord)
resolve StateRead
StateAbsent = Maybe ProjectMirrorRecord
-> Either MirrorStateFault (Maybe ProjectMirrorRecord)
forall a b. b -> Either a b
Right Maybe ProjectMirrorRecord
forall a. Maybe a
Nothing
    resolve (StateUnchanged StateRevision
_) = MirrorStateFault
-> Either MirrorStateFault (Maybe ProjectMirrorRecord)
forall a b. a -> Either a b
Left MirrorStateFault
StateRevisionMismatch
    resolve (StateLoaded StateRevision
_ ProjectMirrorRecord
record)
        | ProjectMirrorRecord -> PackageName
recordPackage ProjectMirrorRecord
record PackageName -> PackageName -> Bool
forall a. Eq a => a -> a -> Bool
== PackageName
name Bool -> Bool -> Bool
&& ProjectMirrorRecord -> StateTarget
recordTarget ProjectMirrorRecord
record StateTarget -> StateTarget -> Bool
forall a. Eq a => a -> a -> Bool
== WorkerMirrorState -> StateTarget
wmsTarget WorkerMirrorState
binding = Maybe ProjectMirrorRecord
-> Either MirrorStateFault (Maybe ProjectMirrorRecord)
forall a b. b -> Either a b
Right (ProjectMirrorRecord -> Maybe ProjectMirrorRecord
forall a. a -> Maybe a
Just ProjectMirrorRecord
record)
        | Bool
otherwise = MirrorStateFault
-> Either MirrorStateFault (Maybe ProjectMirrorRecord)
forall a b. a -> Either a b
Left MirrorStateFault
StateIdentityMismatch

-- | A native upload follows this write, including pending companion declarations.
persistInventory :: WorkerStateBudget -> MirrorStateFormat -> Limits -> Maybe WorkerMirrorState -> MirrorInventory -> Maybe ProjectMirrorRecord -> IO (Either MirrorStateFault ProjectMirrorRecord)
persistInventory :: WorkerStateBudget
-> MirrorStateFormat
-> Limits
-> Maybe WorkerMirrorState
-> MirrorInventory
-> Maybe ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
persistInventory WorkerStateBudget
charge MirrorStateFormat
format Limits
limits Maybe WorkerMirrorState
binding MirrorInventory
inventory Maybe ProjectMirrorRecord
previous = case Maybe WorkerMirrorState
binding of
    Maybe WorkerMirrorState
Nothing -> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFormat
-> Limits
-> StateTarget
-> MirrorInventory
-> Maybe ProjectMirrorRecord
-> Either MirrorStateFault ProjectMirrorRecord
extendProjectRecord MirrorStateFormat
format Limits
limits (Text -> StateTarget
stateTarget Text
"transient worker") MirrorInventory
inventory Maybe ProjectMirrorRecord
previous)
    Just WorkerMirrorState
managed -> MirrorStateFormat
-> Limits
-> StateCharge
-> StateTarget
-> MirrorState
-> MirrorInventory
-> IO
     (Either MirrorStateFault (StateRevision, ProjectMirrorRecord))
recordExpectedInventory MirrorStateFormat
format (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
managed) (WorkerStateBudget -> StateCharge
wsbState WorkerStateBudget
charge) (WorkerMirrorState -> StateTarget
wmsTarget WorkerMirrorState
managed) (WorkerMirrorState -> MirrorState
wmsStore WorkerMirrorState
managed) MirrorInventory
inventory IO (Either MirrorStateFault (StateRevision, ProjectMirrorRecord))
-> (Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
    -> IO (Either MirrorStateFault ProjectMirrorRecord))
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= WorkerStateBudget
-> Limits
-> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
chargeRecord WorkerStateBudget
charge (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
managed) (Either MirrorStateFault ProjectMirrorRecord
 -> IO (Either MirrorStateFault ProjectMirrorRecord))
-> (Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
    -> Either MirrorStateFault ProjectMirrorRecord)
-> Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((StateRevision, ProjectMirrorRecord) -> ProjectMirrorRecord)
-> Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
-> Either MirrorStateFault ProjectMirrorRecord
forall a b.
(a -> b) -> Either MirrorStateFault a -> Either MirrorStateFault b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (StateRevision, ProjectMirrorRecord) -> ProjectMirrorRecord
forall a b. (a, b) -> b
snd

-- | Retain the bridge from a verified source digest to the digest the native target advertises.
persistVerified :: WorkerStateBudget -> Maybe WorkerMirrorState -> Version -> VerifiedArtifactBytes -> ProjectMirrorRecord -> IO (Either MirrorStateFault ProjectMirrorRecord)
persistVerified :: WorkerStateBudget
-> Maybe WorkerMirrorState
-> Version
-> VerifiedArtifactBytes
-> ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
persistVerified WorkerStateBudget
charge Maybe WorkerMirrorState
binding Version
version VerifiedArtifactBytes
verified ProjectMirrorRecord
record = case Maybe WorkerMirrorState
binding of
    Maybe WorkerMirrorState
Nothing -> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Version
-> VerifiedArtifactBytes
-> ProjectMirrorRecord
-> Either MirrorStateFault ProjectMirrorRecord
retainVerifiedIdentity Version
version VerifiedArtifactBytes
verified ProjectMirrorRecord
record)
    Just WorkerMirrorState
managed -> Limits
-> StateCharge
-> MirrorState
-> PackageName
-> Version
-> VerifiedArtifactBytes
-> IO
     (Either MirrorStateFault (StateRevision, ProjectMirrorRecord))
recordVerifiedArtifact (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
managed) (WorkerStateBudget -> StateCharge
wsbState WorkerStateBudget
charge) (WorkerMirrorState -> MirrorState
wmsStore WorkerMirrorState
managed) (ProjectMirrorRecord -> PackageName
recordPackage ProjectMirrorRecord
record) Version
version VerifiedArtifactBytes
verified IO (Either MirrorStateFault (StateRevision, ProjectMirrorRecord))
-> (Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
    -> IO (Either MirrorStateFault ProjectMirrorRecord))
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= WorkerStateBudget
-> Limits
-> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
chargeRecord WorkerStateBudget
charge (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
managed) (Either MirrorStateFault ProjectMirrorRecord
 -> IO (Either MirrorStateFault ProjectMirrorRecord))
-> (Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
    -> Either MirrorStateFault ProjectMirrorRecord)
-> Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((StateRevision, ProjectMirrorRecord) -> ProjectMirrorRecord)
-> Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
-> Either MirrorStateFault ProjectMirrorRecord
forall a b.
(a -> b) -> Either MirrorStateFault a -> Either MirrorStateFault b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (StateRevision, ProjectMirrorRecord) -> ProjectMirrorRecord
forall a b. (a, b) -> b
snd

-- | Companion objects become durable before the project points at them.
retainCompanion :: WorkerStateBudget -> WorkerMirrorState -> Version -> VerifiedCompanionBytes -> ProjectMirrorRecord -> IO (Either MirrorStateFault ProjectMirrorRecord)
retainCompanion :: WorkerStateBudget
-> WorkerMirrorState
-> Version
-> VerifiedCompanionBytes
-> ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
retainCompanion WorkerStateBudget
charge WorkerMirrorState
managed Version
version VerifiedCompanionBytes
bytes ProjectMirrorRecord
record =
    Limits
-> StateCharge
-> MirrorState
-> PackageName
-> Version
-> VerifiedCompanionBytes
-> IO
     (Either MirrorStateFault (StateRevision, ProjectMirrorRecord))
retainProjectCompanion (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
managed) (WorkerStateBudget -> StateCharge
wsbState WorkerStateBudget
charge) (WorkerMirrorState -> MirrorState
wmsStore WorkerMirrorState
managed) (ProjectMirrorRecord -> PackageName
recordPackage ProjectMirrorRecord
record) Version
version VerifiedCompanionBytes
bytes IO (Either MirrorStateFault (StateRevision, ProjectMirrorRecord))
-> (Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
    -> IO (Either MirrorStateFault ProjectMirrorRecord))
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= WorkerStateBudget
-> Limits
-> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
chargeRecord WorkerStateBudget
charge (WorkerMirrorState -> Limits
wmsLimits WorkerMirrorState
managed) (Either MirrorStateFault ProjectMirrorRecord
 -> IO (Either MirrorStateFault ProjectMirrorRecord))
-> (Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
    -> Either MirrorStateFault ProjectMirrorRecord)
-> Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((StateRevision, ProjectMirrorRecord) -> ProjectMirrorRecord)
-> Either MirrorStateFault (StateRevision, ProjectMirrorRecord)
-> Either MirrorStateFault ProjectMirrorRecord
forall a b.
(a -> b) -> Either MirrorStateFault a -> Either MirrorStateFault b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (StateRevision, ProjectMirrorRecord) -> ProjectMirrorRecord
forall a b. (a, b) -> b
snd

-- | Revalidate immutable objects before acknowledgement, including retries after a lost response.
verifyCompanions :: WorkerStateBudget -> IO () -> Maybe WorkerMirrorState -> MirrorVersion -> IO (Either MirrorStateFault ())
verifyCompanions :: WorkerStateBudget
-> IO ()
-> Maybe WorkerMirrorState
-> MirrorVersion
-> IO (Either MirrorStateFault ())
verifyCompanions WorkerStateBudget
charge IO ()
progress Maybe WorkerMirrorState
binding MirrorVersion
version = [CompanionState] -> IO (Either MirrorStateFault ())
go (Map Text CompanionState -> [CompanionState]
forall k a. Map k a -> [a]
Map.elems (MirrorVersion -> Map Text CompanionState
versionCompanions MirrorVersion
version))
  where
    go :: [CompanionState] -> IO (Either MirrorStateFault ())
go [] = Either MirrorStateFault () -> IO (Either MirrorStateFault ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either MirrorStateFault ()
forall a b. b -> Either a b
Right ())
    go (CompanionState
CompanionPending : [CompanionState]
_) = Either MirrorStateFault () -> IO (Either MirrorStateFault ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFault -> Either MirrorStateFault ()
forall a b. a -> Either a b
Left MirrorStateFault
StateMissingCompanion)
    go (CompanionRetained CompanionRef
reference : [CompanionState]
rest) = case Maybe WorkerMirrorState
binding of
        Maybe WorkerMirrorState
Nothing -> Either MirrorStateFault () -> IO (Either MirrorStateFault ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFault -> Either MirrorStateFault ()
forall a b. a -> Either a b
Left MirrorStateFault
StateMissingCompanion)
        Just WorkerMirrorState
managed ->
            MirrorState
-> StateCharge
-> CompanionRef
-> IO (Either MirrorStateFault ByteString)
msReadCompanion (WorkerMirrorState -> MirrorState
wmsStore WorkerMirrorState
managed) (WorkerStateBudget -> StateCharge
wsbState WorkerStateBudget
charge) CompanionRef
reference IO (Either MirrorStateFault ByteString)
-> (Either MirrorStateFault ByteString
    -> IO (Either MirrorStateFault ()))
-> IO (Either MirrorStateFault ())
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 MirrorStateFault
fault -> Either MirrorStateFault () -> IO (Either MirrorStateFault ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFault -> Either MirrorStateFault ()
forall a b. a -> Either a b
Left MirrorStateFault
fault)
                Right ByteString
bytes -> case CompanionRef -> ByteString -> Either MirrorStateFault ByteString
verifyRetainedCompanion CompanionRef
reference ByteString
bytes of
                    Left MirrorStateFault
fault -> Either MirrorStateFault () -> IO (Either MirrorStateFault ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFault -> Either MirrorStateFault ()
forall a b. a -> Either a b
Left MirrorStateFault
fault)
                    Right ByteString
_ -> IO ()
progress IO ()
-> IO (Either MirrorStateFault ())
-> IO (Either MirrorStateFault ())
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [CompanionState] -> IO (Either MirrorStateFault ())
go [CompanionState]
rest

-- The initial, copied, and latest records can coexist during final validation.
chargeRecord :: WorkerStateBudget -> Limits -> Either MirrorStateFault ProjectMirrorRecord -> IO (Either MirrorStateFault ProjectMirrorRecord)
chargeRecord :: WorkerStateBudget
-> Limits
-> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
chargeRecord WorkerStateBudget
budget Limits
limits Either MirrorStateFault ProjectMirrorRecord
result = case Either MirrorStateFault ProjectMirrorRecord
result of
    Left MirrorStateFault
fault -> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFault -> Either MirrorStateFault ProjectMirrorRecord
forall a b. a -> Either a b
Left MirrorStateFault
fault)
    Right ProjectMirrorRecord
record -> case Limits -> ProjectMirrorRecord -> Either MirrorStateFault Int
projectRecordWorkWeight Limits
limits ProjectMirrorRecord
record of
        Left MirrorStateFault
fault -> Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorStateFault -> Either MirrorStateFault ProjectMirrorRecord
forall a b. a -> Either a b
Left MirrorStateFault
fault)
        Right Int
bytes -> do
            WorkerStateBudget -> StateCharge
wsbRecords WorkerStateBudget
budget (Integer -> Int
forall a. Num a => Integer -> a
fromInteger (Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int)) (Integer
3 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
bytes)))
            Either MirrorStateFault ProjectMirrorRecord
-> IO (Either MirrorStateFault ProjectMirrorRecord)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ProjectMirrorRecord -> Either MirrorStateFault ProjectMirrorRecord
forall a b. b -> Either a b
Right ProjectMirrorRecord
record)

-- | Restore the original admitted source fields for a missing historic file.
fragmentDocument :: StoredMirrorFragment -> VersionDoc
fragmentDocument :: StoredMirrorFragment -> VersionDoc
fragmentDocument StoredMirrorFragment
fragment = PackageDetails -> Maybe CachedDoc -> VersionDoc
VersionDoc (StoredMirrorFragment -> PackageDetails
fragmentDetails StoredMirrorFragment
fragment) (CachedDoc -> Maybe CachedDoc
forall a. a -> Maybe a
Just (MirrorReadData -> CachedDoc
mirrorReadDocument (StoredMirrorFragment -> MirrorReadData
fragmentReadData StoredMirrorFragment
fragment)))