packages feed

hoare-0.2.0.0: lib/Control/Concurrent/Channel/Try.hs

module Control.Concurrent.Channel.Try where

import Control.Concurrent.STM
import System.Clock.Seconds

data Tried a = Done a | Blocked
    deriving stock (Show, Eq, Foldable, Functor, Traversable)

-- | Attempt any STM action, returning immediately with @Blocked@ if it retries.
try :: STM a -> STM (Tried a)
try s = fmap Done s `orElse` pure Blocked
{-# INLINE try #-}

-- | Run the STM action, and give the time that it blocked, if it blocked.
--
-- Transactions can't detect their own retry without unsafeIOToSTM horrors,
-- so blocked transactions need to run again after getting the time.
timedAtomically :: STM a -> IO (a, Maybe Seconds)
timedAtomically s = atomically (try s) >>= \case
    Done v -> pure (v, Nothing)
    Blocked -> do
        t1 <- getTime Monotonic
        v <- atomically s
        t2 <- getTime Monotonic
        pure (v, Just (t2 - t1))