papa-0.7.0: src/Papa/Async/Control/Concurrent/Async.hs
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}
-- | Structured concurrency ("Control.Concurrent.Async"): threads whose
-- lifetime is bounded by a scope, and whose results, or failures, are values.
--
-- == Which functions rethrow
--
-- An 'Async' is a thread that ends with a result or an exception. This module
-- returns that exception as a value ('waitCatch', 'waitExcept', 'poll', the
-- @…Catch@ functions), never rethrowing it into the waiting thread.
--
-- The combinators of a scope ('withAsync', 'concurrently', 'race',
-- 'mapConcurrently', …) run their actions in threads, and when an action
-- throws, cancel the other threads and throw its exception in the caller,
-- just as the action itself would have, had it run in the caller. They add no
-- failure: an action that does not throw, such as one of 'Papa.Base.System.IO.Except.IOExcept', which
-- returns its failure, does not make them throw. 'concurrentlyExcept' and
-- 'raceExcept' run actions of @'ExceptT' e 'IO'@, and the first failure
-- cancels the others.
--
-- The functions that rethrow a thread's exception in another thread are in
-- "Papa.Unsafe.Async": @wait@, @waitAny@, @waitEither@, @waitBoth@ (and their
-- @…STM@ and @…Cancel@ forms), which rethrow it in the waiting thread, and
-- @link@, @link2@, which throw it asynchronously into the linked thread.
--
-- 'waitAnyCatch', 'waitAnyCatchSTM' and 'waitAnyCatchCancel' take a
-- 'NonEmpty' list: at an empty list, "Control.Concurrent.Async"'s wait forever.
--
-- ==== __Examples__
--
-- >>> concurrently (pure 1) (pure 'a')
-- (1,'a')
--
-- >>> race (C.threadDelay 10000000) (pure 'a')
-- Right 'a'
--
-- >>> mapConcurrently (\x -> pure (x * 2)) [1, 2, 3]
-- [2,4,6]
--
-- >>> forConcurrently (Just 3) pure
-- Just 3
--
-- >>> replicateConcurrently 3 (pure 'x')
-- "xxx"
--
-- >>> runConcurrently ((,) <$> Concurrently (pure 1) <*> Concurrently (pure 2))
-- (1,2)
--
-- >>> concurrentlyE (pure (Right 1)) (pure (Left "b")) :: IO (Either String (Int, Int))
-- Left "b"
--
-- An action that throws, throws in the caller:
--
-- >>> E.try (concurrently (E.throwIO (userError "x")) (C.threadDelay 10000000)) :: IO (Either IOException ((), ()))
-- Left user error (x)
--
-- A thread that is cancelled ends with 'AsyncCancelled':
--
-- >>> do { a <- async (C.threadDelay 10000000); cancel a; r <- waitCatch a; pure (either (\e -> E.fromException e == Just AsyncCancelled) (const False) r) }
-- True
--
-- >>> withAsync (pure 'x') (\a -> waitCatch a *> poll a) >>= traverse (pure . preview _Right)
-- Just (Just 'x')
--
-- @since 0.7.0
module Papa.Async.Control.Concurrent.Async (
-- * Asynchronous actions
Async,
AsyncCancelled (AsyncCancelled),
asyncThreadId,
compareAsyncs,
-- * Scoped
withAsync,
withAsyncBound,
withAsyncOn,
withAsyncWithUnmask,
withAsyncOnWithUnmask,
-- * Unscoped
async,
asyncBound,
asyncOn,
asyncWithUnmask,
asyncOnWithUnmask,
-- * Results as values
waitCatch,
waitCatchSTM,
waitExcept,
poll,
pollSTM,
waitAnyCatch,
waitAnyCatchSTM,
waitAnyCatchCancel,
waitEitherCatch,
waitEitherCatchSTM,
waitEitherCatchCancel,
-- * Cancelling
cancel,
cancelWith,
uninterruptibleCancel,
-- * Combinators
concurrently,
concurrently_,
race,
race_,
mapConcurrently,
mapConcurrently_,
forConcurrently,
forConcurrently_,
replicateConcurrently,
replicateConcurrently_,
Concurrently (Concurrently, runConcurrently),
-- * Combinators of failures as values
concurrentlyE,
ConcurrentlyE (ConcurrentlyE, runConcurrentlyE),
concurrentlyExcept,
raceExcept,
) where
import Control.Category ((.))
import Control.Concurrent.Async (
Async,
AsyncCancelled (AsyncCancelled),
Concurrently (Concurrently, runConcurrently),
ConcurrentlyE (ConcurrentlyE, runConcurrentlyE),
async,
asyncBound,
asyncOn,
asyncOnWithUnmask,
asyncThreadId,
asyncWithUnmask,
cancel,
cancelWith,
compareAsyncs,
concurrently,
concurrentlyE,
concurrently_,
forConcurrently,
forConcurrently_,
mapConcurrently,
mapConcurrently_,
poll,
pollSTM,
race,
race_,
replicateConcurrently,
replicateConcurrently_,
uninterruptibleCancel,
waitCatch,
waitCatchSTM,
waitEitherCatch,
waitEitherCatchCancel,
waitEitherCatchSTM,
withAsync,
withAsyncBound,
withAsyncOn,
withAsyncOnWithUnmask,
withAsyncWithUnmask,
)
import qualified Control.Concurrent.Async as A
import Control.Concurrent.STM (STM)
import Control.Exception (SomeException)
import Control.Monad.Trans.Except (ExceptT (ExceptT), runExceptT)
import Data.Either (Either (Left, Right), either)
import Data.Foldable (toList)
import Data.Functor (fmap, (<$>))
import Data.List.NonEmpty (NonEmpty)
import System.IO (IO)
-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import qualified Control.Concurrent as C
-- >>> import qualified Control.Exception as E
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- | Wait for a thread, returning its exception, if it threw one, as a
-- 'Left'.
--
-- ==== __Examples__
--
-- >>> withAsync (pure 3) (runExceptT . waitExcept)
-- Right 3
--
-- >>> withAsync (E.throwIO (userError "x") :: IO ()) (fmap (either (const "threw") (const "returned")) . runExceptT . waitExcept)
-- "threw"
--
-- >>> check $ property $ do { n <- forAll (Gen.int (Range.linear 0 100)); r <- evalIO (withAsync (pure n) (runExceptT . waitExcept)); preview _Right r === Just n }
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
waitExcept :: Async a -> ExceptT SomeException IO a
waitExcept =
ExceptT . waitCatch
{-# INLINE waitExcept #-}
-- | Wait for the first of some threads to end, returning it and its result
-- or exception.
--
-- ==== __Examples__
--
-- >>> withAsync (C.threadDelay 1000000 *> pure 1) (\a -> withAsync (pure 2) (\b -> fmap (preview _Right . snd) (waitAnyCatch (a :| [b]))))
-- Just 2
--
-- @since 0.7.0
waitAnyCatch :: NonEmpty (Async a) -> IO (Async a, Either SomeException a)
waitAnyCatch =
A.waitAnyCatch . toList
{-# INLINE waitAnyCatch #-}
-- | 'waitAnyCatch' in 'STM'.
--
-- ==== __Examples__
--
-- >>> withAsync (pure 'x') (\a -> fmap (preview _Right . snd) (atomically (waitAnyCatchSTM (a :| []))))
-- Just 'x'
--
-- @since 0.7.0
waitAnyCatchSTM :: NonEmpty (Async a) -> STM (Async a, Either SomeException a)
waitAnyCatchSTM =
A.waitAnyCatchSTM . toList
{-# INLINE waitAnyCatchSTM #-}
-- | 'waitAnyCatch', and then cancel all of the threads.
--
-- ==== __Examples__
--
-- >>> do { a <- async (C.threadDelay 10000000); b <- async (pure ()); _ <- waitAnyCatchCancel (a :| [b]); fmap (fmap (either (const "cancelled") (const "ended"))) (poll a) }
-- Just "cancelled"
--
-- @since 0.7.0
waitAnyCatchCancel :: NonEmpty (Async a) -> IO (Async a, Either SomeException a)
waitAnyCatchCancel =
A.waitAnyCatchCancel . toList
{-# INLINE waitAnyCatchCancel #-}
-- | Run two actions of @'ExceptT' e 'IO'@ at once, and return both results.
-- The first failure cancels the other action, and is returned: when both
-- fail, it is the failure of whichever fails first.
--
-- An exception that an action throws is thrown in the caller, as in
-- 'concurrently'.
--
-- ==== __Examples__
--
-- >>> runExceptT (concurrentlyExcept (pure 1) (pure 'a') :: ExceptT () IO (Int, Char))
-- Right (1,'a')
--
-- >>> runExceptT (concurrentlyExcept (throwError "a") (ExceptT (C.threadDelay 10000000 *> pure (Right ()))) :: ExceptT String IO ((), ()))
-- Left "a"
--
-- >>> check $ property $ do { a <- forAll (Gen.either (Gen.int (Range.linear 0 9)) Gen.alpha); b <- forAll (Gen.either (Gen.int (Range.linear 0 9)) Gen.alpha); r <- evalIO (runExceptT (concurrentlyExcept (ExceptT (pure a)) (ExceptT (pure b)))); r === ((,) <$> a <*> b) }
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
concurrentlyExcept :: ExceptT e IO a -> ExceptT e IO b -> ExceptT e IO (a, b)
concurrentlyExcept a b =
ExceptT (concurrentlyE (runExceptT a) (runExceptT b))
{-# INLINE concurrentlyExcept #-}
-- | Run two actions of @'ExceptT' e 'IO'@ at once, and return the result or
-- failure of the first to end. It cancels the other.
--
-- An exception that an action throws is thrown in the caller, as in 'race'.
--
-- ==== __Examples__
--
-- >>> runExceptT (raceExcept (pure 1) (ExceptT (C.threadDelay 10000000 *> pure (Right 'a'))) :: ExceptT () IO (Either Int Char))
-- Right (Left 1)
--
-- >>> runExceptT (raceExcept (ExceptT (C.threadDelay 10000000 *> pure (Right ()))) (throwError "b") :: ExceptT String IO (Either () ()))
-- Left "b"
--
-- @since 0.7.0
raceExcept :: ExceptT e IO a -> ExceptT e IO b -> ExceptT e IO (Either a b)
raceExcept a b =
ExceptT (either (fmap Left) (fmap Right) <$> race (runExceptT a) (runExceptT b))
{-# INLINE raceExcept #-}