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

{- | Deadlines that one sweeper thread checks every 100 ms, so arming one never waits on another
thread. GHC's timers share one process-wide queue, and every arm and disarm edits it in turn. Here
arming adds to a list owned by the arming thread's capability, and a deadline fires about one tick
late. A due check is thrown from a forked thread, as 'System.Timeout.timeout' does, so a disarm can
stop a throw still in flight. A flag scope raises a 'TVar' instead, for a transaction that waits.
-}
module Ecluse.Core.Deadline (
    -- * The sweeper
    Deadlines,
    newDeadlines,
    sweepTick,

    -- * Armed scopes
    Check,
    withDeadline,
    withEndableDeadline,
    withDeadlineFlag,
    timeout,
    inspectionDeadline,
) where

import Control.Exception (asyncExceptionFromException, asyncExceptionToException, handleJust, throwTo)
import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray, smallArrayFromList)
import GHC.Clock (getMonotonicTimeNSec)
import GHC.Conc (getNumCapabilities, threadCapability)
import GHC.IORef qualified as IORef
import Text.Show (showString, showsPrec)
import UnliftIO.Concurrent (ThreadId, forkIOWithUnmask, killThread, myThreadId, threadDelay)
import UnliftIO.Exception (bracket, onException, uninterruptibleMask_)
import UnliftIO.MVar (isEmptyMVar)

import Ecluse.Core.Security.Limits (requestTimeoutSeconds)

-- | The process's armed checks, one list for each capability.
newtype Deadlines = Deadlines (SmallArray (IORef [Armed]))

{- | Asked at each sweep with the monotonic time in nanoseconds. A 'Just' is raised in the armed
thread, and ends the check.
-}
type Check = Word64 -> IO (Maybe SomeException)

-- The lock is empty while the scope is open. Disarming fills it with 'Nothing', and a thrower with its own id.
data Armed = Armed ThreadId (MVar (Maybe ThreadId)) Check

-- | One list for each capability the process runs now. Create it once the capability count is final.
newDeadlines :: IO Deadlines
newDeadlines :: IO Deadlines
newDeadlines = do
    count <- IO Int
getNumCapabilities
    Deadlines . smallArrayFromList <$> replicateM (max 1 count) (newIORef [])

-- | Wait one tick, then raise every due check. The composition root repeats it under supervision.
sweepTick :: Deadlines -> IO ()
sweepTick :: Deadlines -> IO ()
sweepTick (Deadlines SmallArray (IORef [Armed])
cells) = do
    Int -> IO ()
forall (m :: * -> *). MonadIO m => Int -> m ()
threadDelay Int
tickMicros
    now <- IO Word64
getMonotonicTimeNSec
    traverse_ (sweepCell now) cells

tickMicros :: Int
tickMicros :: Int
tickMicros = Int
100_000

-- A fault part way through puts every entry back. One that fired already leaves at the next sweep.
sweepCell :: Word64 -> IORef [Armed] -> IO ()
sweepCell :: Word64 -> IORef [Armed] -> IO ()
sweepCell Word64
now IORef [Armed]
cell = do
    entries <- IORef [Armed] -> [Armed] -> IO [Armed]
forall a. IORef a -> a -> IO a
IORef.atomicSwapIORef IORef [Armed]
cell []
    kept <- filterM (stillArmed now) entries `onException` putBack entries
    unless (null kept) (putBack kept)
  where
    -- Consing never forces the list underneath, so an arming thread never waits on the sweeper.
    putBack :: [Armed] -> IO ()
putBack [Armed]
entries = IO ([Armed], [Armed]) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IORef [Armed] -> ([Armed] -> [Armed]) -> IO ([Armed], [Armed])
forall a. IORef a -> (a -> a) -> IO (a, a)
IORef.atomicModifyIORef'_ IORef [Armed]
cell ([Armed]
entries [Armed] -> [Armed] -> [Armed]
forall a. Semigroup a => a -> a -> a
<>))

stillArmed :: Word64 -> Armed -> IO Bool
stillArmed :: Word64 -> Armed -> IO Bool
stillArmed Word64
now (Armed ThreadId
owner MVar (Maybe ThreadId)
lock Check
check) =
    MVar (Maybe ThreadId) -> IO Bool
forall (m :: * -> *) a. MonadIO m => MVar a -> m Bool
isEmptyMVar MVar (Maybe ThreadId)
lock IO Bool -> (Bool -> IO Bool) -> IO Bool
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Bool
False -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False
        Bool
True ->
            Check
check Word64
now IO (Maybe SomeException)
-> (Maybe SomeException -> IO Bool) -> IO Bool
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                Maybe SomeException
Nothing -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
                Just SomeException
failure -> Bool
False Bool -> IO ThreadId -> IO Bool
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId
forall (m :: * -> *).
MonadUnliftIO m =>
((forall a. m a -> m a) -> m ()) -> m ThreadId
forkIOWithUnmask (\forall a. IO a -> IO a
unmask -> IO () -> IO ()
forall a. IO a -> IO a
unmask (ThreadId -> MVar (Maybe ThreadId) -> SomeException -> IO ()
throwOnce ThreadId
owner MVar (Maybe ThreadId)
lock SomeException
failure))

-- Base 'throwTo' delivers the exception as given. UnliftIO's would wrap a synchronous one as asynchronous.
throwOnce :: ThreadId -> MVar (Maybe ThreadId) -> SomeException -> IO ()
throwOnce :: ThreadId -> MVar (Maybe ThreadId) -> SomeException -> IO ()
throwOnce ThreadId
owner MVar (Maybe ThreadId)
lock SomeException
failure = do
    self <- IO ThreadId
forall (m :: * -> *). MonadIO m => m ThreadId
myThreadId
    claimed <- tryPutMVar lock (Just self)
    when claimed (throwTo owner failure)

{- | Run an action under a check the sweeper asks every tick. A failure it returns is raised in this
thread while the action runs, and never after it ends.
-}
withDeadline :: Deadlines -> Check -> IO a -> IO a
withDeadline :: forall a. Deadlines -> Check -> IO a -> IO a
withDeadline Deadlines
deadlines Check
check = Deadlines -> Check -> (IO () -> IO a) -> IO a
forall a. Deadlines -> Check -> (IO () -> IO a) -> IO a
withEndableDeadline Deadlines
deadlines Check
check ((IO () -> IO a) -> IO a)
-> (IO a -> IO () -> IO a) -> IO a -> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO a -> IO () -> IO a
forall a b. a -> b -> a
const

-- | 'withDeadline' whose action can end the check early. Once the end returns, nothing the check raised lands.
withEndableDeadline :: Deadlines -> Check -> (IO () -> IO a) -> IO a
withEndableDeadline :: forall a. Deadlines -> Check -> (IO () -> IO a) -> IO a
withEndableDeadline Deadlines
deadlines Check
check IO () -> IO a
action = IO (MVar (Maybe ThreadId))
-> (MVar (Maybe ThreadId) -> IO ())
-> (MVar (Maybe ThreadId) -> IO a)
-> IO a
forall (m :: * -> *) a b c.
MonadUnliftIO m =>
m a -> (a -> m b) -> (a -> m c) -> m c
bracket (Deadlines -> Check -> IO (MVar (Maybe ThreadId))
arm Deadlines
deadlines Check
check) MVar (Maybe ThreadId) -> IO ()
disarm (IO () -> IO a
action (IO () -> IO a)
-> (MVar (Maybe ThreadId) -> IO ())
-> MVar (Maybe ThreadId)
-> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MVar (Maybe ThreadId) -> IO ()
disarm)

arm :: Deadlines -> Check -> IO (MVar (Maybe ThreadId))
arm :: Deadlines -> Check -> IO (MVar (Maybe ThreadId))
arm (Deadlines SmallArray (IORef [Armed])
cells) Check
check = do
    owner <- IO ThreadId
forall (m :: * -> *). MonadIO m => m ThreadId
myThreadId
    lock <- newEmptyMVar
    (capability, _) <- threadCapability owner
    let cell = SmallArray (IORef [Armed]) -> Int -> IORef [Armed]
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray (IORef [Armed])
cells (Int
capability Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` SmallArray (IORef [Armed]) -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray (IORef [Armed])
cells)
    void (IORef.atomicModifyIORef'_ cell (Armed owner lock check :))
    pure lock

-- A thrower that claimed the lock first dies before its throw lands, as this thread is uninterruptible here. A second disarm does nothing.
disarm :: MVar (Maybe ThreadId) -> IO ()
disarm :: MVar (Maybe ThreadId) -> IO ()
disarm MVar (Maybe ThreadId)
lock = IO () -> IO ()
forall (m :: * -> *) a. MonadUnliftIO m => m a -> m a
uninterruptibleMask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    disarmed <- MVar (Maybe ThreadId) -> Maybe ThreadId -> IO Bool
forall (m :: * -> *) a. MonadIO m => MVar a -> a -> m Bool
tryPutMVar MVar (Maybe ThreadId)
lock Maybe ThreadId
forall a. Maybe a
Nothing
    unless disarmed (readMVar lock >>= traverse_ killThread)

{- | Run an action with a flag the first sweep after the microseconds raises, so a transaction can wait
for the deadline without a GHC timer. A bound of zero or less starts raised and needs no sweep.
-}
withDeadlineFlag :: Deadlines -> Int -> (TVar Bool -> IO a) -> IO a
withDeadlineFlag :: forall a. Deadlines -> Int -> (TVar Bool -> IO a) -> IO a
withDeadlineFlag Deadlines
deadlines Int
micros TVar Bool -> IO a
action
    | Int
micros Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = Bool -> IO (TVar Bool)
forall (m :: * -> *) a. MonadIO m => a -> m (TVar a)
newTVarIO Bool
True IO (TVar Bool) -> (TVar Bool -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= TVar Bool -> IO a
action
    | Bool
otherwise = do
        flag <- Bool -> IO (TVar Bool)
forall (m :: * -> *) a. MonadIO m => a -> m (TVar a)
newTVarIO Bool
False
        limit <- (`nanosAfter` micros) <$> getMonotonicTimeNSec
        withDeadline deadlines (raiseFrom limit flag) (action flag)

-- Raising throws nothing, so the check stays until its scope ends, and it writes the flag once.
raiseFrom :: Word64 -> TVar Bool -> Check
raiseFrom :: Word64 -> TVar Bool -> Check
raiseFrom Word64
limit TVar Bool
flag Word64
now = Maybe SomeException
forall a. Maybe a
Nothing Maybe SomeException -> IO () -> IO (Maybe SomeException)
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
limit) (STM () -> IO ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar TVar Bool
flag STM Bool -> (Bool -> STM ()) -> STM ()
forall a b. STM a -> (a -> STM b) -> STM b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Bool
raised -> Bool -> STM () -> STM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
raised (TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar Bool
flag Bool
True)))

{- | 'System.Timeout.timeout' on the sweeper: 'Nothing' once the action outlives the microseconds,
about a tick late. A negative bound never fires, and zero fires at once.
-}
timeout :: Deadlines -> Int -> IO a -> IO (Maybe a)
timeout :: forall a. Deadlines -> Int -> IO a -> IO (Maybe a)
timeout Deadlines
deadlines Int
micros IO a
action
    | Int
micros Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = a -> Maybe a
forall a. a -> Maybe a
Just (a -> Maybe a) -> IO a -> IO (Maybe a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO a
action
    | Int
micros Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 = Maybe a -> IO (Maybe a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe a
forall a. Maybe a
Nothing
    | Bool
otherwise = do
        expiry <- IORef () -> Expired
Expired (IORef () -> Expired) -> IO (IORef ()) -> IO Expired
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> () -> IO (IORef ())
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef ()
        limit <- (`nanosAfter` micros) <$> getMonotonicTimeNSec
        let due Word64
now = Maybe SomeException -> f (Maybe SomeException)
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (if Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
limit then SomeException -> Maybe SomeException
forall a. a -> Maybe a
Just (Expired -> SomeException
forall e. Exception e => e -> SomeException
toException Expired
expiry) else Maybe SomeException
forall a. Maybe a
Nothing)
        -- Base 'handleJust', because the unliftio one never catches an asynchronous exception.
        handleJust (\Expired
caught -> if Expired
caught Expired -> Expired -> Bool
forall a. Eq a => a -> a -> Bool
== Expired
expiry then () -> Maybe ()
forall a. a -> Maybe a
Just () else Maybe ()
forall a. Maybe a
Nothing) (\() -> Maybe a -> IO (Maybe a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe a
forall a. Maybe a
Nothing) $
            Just <$> withDeadline deadlines due action

-- | Return the refusal once an archive or metadata inspection outlives the request timeout, on the sweeper.
inspectionDeadline :: Deadlines -> e -> IO (Either e a) -> IO (Either e a)
inspectionDeadline :: forall e a. Deadlines -> e -> IO (Either e a) -> IO (Either e a)
inspectionDeadline Deadlines
deadlines e
refusal IO (Either e a)
action = Either e a -> Maybe (Either e a) -> Either e a
forall a. a -> Maybe a -> a
fromMaybe (e -> Either e a
forall a b. a -> Either a b
Left e
refusal) (Maybe (Either e a) -> Either e a)
-> IO (Maybe (Either e a)) -> IO (Either e a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Deadlines -> Int -> IO (Either e a) -> IO (Maybe (Either e a))
forall a. Deadlines -> Int -> IO a -> IO (Maybe a)
timeout Deadlines
deadlines (Int
requestTimeoutSeconds Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1_000_000) IO (Either e a)
action

-- The monotonic nanoseconds this many microseconds after an instant, saturating rather than wrapping.
nanosAfter :: Word64 -> Int -> Word64
nanosAfter :: Word64 -> Int -> Word64
nanosAfter Word64
start Int
micros = Integer -> Word64
forall a. Num a => Integer -> a
fromInteger (Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64
forall a. Bounded a => a
maxBound :: Word64)) (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
start Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
micros Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
1_000))

-- Asynchronous, as 'System.Timeout.timeout''s own is, so a synchronous catch inside the action passes it on.
-- Each scope's reference is its identity, so a nested scope never takes another's.
newtype Expired = Expired (IORef ())
    deriving newtype (Expired -> Expired -> Bool
(Expired -> Expired -> Bool)
-> (Expired -> Expired -> Bool) -> Eq Expired
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Expired -> Expired -> Bool
== :: Expired -> Expired -> Bool
$c/= :: Expired -> Expired -> Bool
/= :: Expired -> Expired -> Bool
Eq)

-- Shown as 'System.Timeout.timeout''s own, which a client span may record.
instance Show Expired where
    showsPrec :: Int -> Expired -> ShowS
showsPrec Int
_ Expired
_ = String -> ShowS
showString String
"<<timeout>>"

instance Exception Expired where
    toException :: Expired -> SomeException
toException = Expired -> SomeException
forall e. Exception e => e -> SomeException
asyncExceptionToException
    fromException :: SomeException -> Maybe Expired
fromException = SomeException -> Maybe Expired
forall e. Exception e => SomeException -> Maybe e
asyncExceptionFromException