memcache-0.5.1.0: Database/Memcache/Timeout.hs
{-# LANGUAGE CPP #-}
{-|
Module : Database.Memcache.Timeout
Description : A timeout that its action can start again
Copyright : (c) David Terei, 2026
License : BSD
Maintainer : code@davidterei.com
Stability : internal
Portability : GHC
A timeout that the action it limits can start again, with which the batches of
"Database.Memcache.Cluster" give each reply a timeout of its own. Not exposed.
This module uses CPP, to leave out "GHC.Event" on Windows, and that is why it
is a module of its own: CPP joins each line that ends in a backslash to the
next, which breaks a string continued across lines with a string gap, as the
deprecation message in "Database.Memcache.Cluster" is.
-}
module Database.Memcache.Timeout (
timeoutRestartable
) where
import Control.Concurrent (forkIOWithUnmask, killThread, myThreadId, threadDelay, throwTo)
#if !defined(mingw32_HOST_OS)
import qualified Control.Concurrent as Concurrent
#endif
import Control.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar)
import qualified Control.Exception as E
import Control.Monad (unless, void, when)
import Data.IORef (atomicWriteIORef, newIORef, readIORef)
import Data.Unique (Unique, newUnique)
import GHC.Clock (getMonotonicTimeNSec)
#if !defined(mingw32_HOST_OS)
import qualified GHC.Event as Event
#endif
-- | Like 'System.Timeout.timeout', but the action is given an action that
-- starts its time again, from the moment it is run, by moving its deadline.
-- Once the time first runs out, a watchdog thread reads the deadline: if it
-- has passed, the watchdog throws the action an exception of its own, and
-- otherwise it sleeps until the deadline and reads it again. The watchdog is
-- stopped once the action has finished, so the exception never reaches the
-- caller (see 'withWatchdog'). As with 'System.Timeout.timeout', a time below
-- zero means none, and zero gives 'Nothing' without running the action.
timeoutRestartable :: Int -> (IO () -> IO a) -> IO (Maybe a)
timeoutRestartable usecs action
| usecs < 0 = Just <$> action (return ())
| usecs == 0 = return Nothing
| otherwise = do
worker <- myThreadId
expired <- TimedOut <$> newUnique
deadline <- newIORef =<< later
let restart = later >>= atomicWriteIORef deadline
-- Sleep at most 1,000 s at a time, which threadDelay takes on
-- any platform, and check again.
watch = do
now <- nanoseconds
end <- readIORef deadline
if now < end
then threadDelay (fromInteger (min 1000000000 ((end - now) `div` 1000 + 1))) >> watch
else throwTo worker expired
E.handleJust (\e -> if e == expired then Just () else Nothing) (const (return Nothing)) $
withWatchdog usecs watch (Just <$> action restart)
where
nanoseconds = toInteger <$> getMonotonicTimeNSec
later = (+ toInteger usecs * 1000) <$> nanoseconds
-- | Run an action with a watchdog thread, started once the given time has
-- passed, and stopped once the action has finished. The watchdog claims a
-- lock before it does anything else, and the cleanup either takes the lock
-- first, so that the watchdog, if it starts, does nothing, or kills the
-- watchdog that holds it, as 'System.Timeout.timeout' does. On the threaded
-- runtime, as in 'System.Timeout.timeout', the system's timer manager starts
-- the watchdog, so an action that finishes in time starts no thread.
-- Elsewhere there is no timer manager, and the watchdog starts at once, as the
-- thread of 'System.Timeout.timeout' does: the watch begins by sleeping until
-- the deadline.
withWatchdog :: Int -> IO () -> IO a -> IO a
withWatchdog usecs watch run = do
lock <- newEmptyMVar
let start = void $ forkIOWithUnmask $ \unmask -> unmask $ do
claimed <- tryPutMVar lock . Just =<< myThreadId
when claimed watch
-- True if the watchdog never claimed the lock.
stop = do
first <- tryPutMVar lock Nothing
unless first $ takeMVar lock >>= mapM_ killThread
return first
startAfter usecs start stop
where
#if !defined(mingw32_HOST_OS)
startAfter time start stop
| Concurrent.rtsSupportsBoundThreads = do
manager <- Event.getSystemTimerManager
E.bracket (Event.registerTimeout manager time start)
(\key -> E.uninterruptibleMask_ $ do
first <- stop
when first $ Event.unregisterTimeout manager key)
(const run)
#endif
startAfter _ start stop = E.bracket_ start (E.uninterruptibleMask_ stop) run
-- | Thrown by 'timeoutRestartable' to the action it runs, once the action's
-- time has run out. Each call makes its own, and catches only that one. Like
-- the exception of 'System.Timeout.timeout', it is asynchronous, so that
-- handlers for synchronous exceptions let it through.
newtype TimedOut = TimedOut Unique
deriving Eq
instance Show TimedOut where
show _ = "<<timeout>>"
instance E.Exception TimedOut where
toException = E.asyncExceptionToException
fromException = E.asyncExceptionFromException