packages feed

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

-- | Tools for connecting communicating sequential processes (threads)
-- with closeable channels.
module Control.Concurrent.Channel(
    Channel (..),
    OverwriteResult (..),
    writeChannel',
    evalWriteChannel,
    evalWriteChannel',
    overwriteChannel',
    evalOverwriteChannel,
    evalOverwriteChannel',
    consumeChannel,
    consumeChannelBatches,
    consumeChannelBatches',
    stateConsumeChannel,
    stateConsumeChannelBatches,
    stateConsumeChannelBatches',
    feedChannel,
    evalFeedChannel,
    pipeline,
    pipeline_
) where

import Control.Concurrent.Async
import Control.Concurrent.Channel.Overwrite
import Control.Concurrent.STM
import Control.Concurrent.TBCQueue
import Control.Concurrent.TCSlot
import Control.Exception (evaluate, finally)
import Control.DeepSeq
import Control.Monad
import Data.Function (fix)
import Data.Maybe (maybeToList)

class Channel c where
    -- | Reads from the channel, blocking if empty,
    -- and returning @Nothing@ once it is empty and closed.
    readChannel :: c a -> STM (Maybe a)

    -- | Drains the channel, blocking if it is empty.
    --   Returns @[]@ if the channel is empty and closed.
    --
    --   Useful for accumulating values to pass in bulk to an expensive operation,
    --   like a @send()@ syscall.
    drainChannel :: c a -> STM [a]

    -- | Writes the given value to the channel if it's still open, blocking if full.
    --
    -- Returns whether the channel is still open so producers know when consumers no longer care.
    writeChannel :: c a -> a -> STM Bool

    -- | Writes the given value to the channel if it's still open.
    --
    -- When the channel is full, removes and returns the oldest value.
    overwriteChannel :: c a -> a -> STM (OverwriteResult a)

    -- | Closes the channel so that future writes are no-ops and readers get @Nothing@
    -- after all values currently inside have been read.
    closeChannel :: c a -> STM ()

    isEmptyChannel :: c a -> STM Bool

    isClosedChannel :: c a -> STM Bool

    isFullChannel :: c a -> STM Bool

instance Channel TBCQueue where
    readChannel = readTBCQueue
    drainChannel = drainTBCQueue
    writeChannel = writeTBCQueue
    overwriteChannel = overwriteTBCQueue
    closeChannel = closeTBCQueue
    isEmptyChannel = isEmptyTBCQueue
    isClosedChannel = isClosedTBCQueue
    isFullChannel = isFullTBCQueue

instance Channel TCSlot where
    readChannel = readTCSlot
    drainChannel = fmap maybeToList <$> readTCSlot
    writeChannel = writeTCSlot
    overwriteChannel = overwriteTCSlot
    closeChannel = closeTCSlot
    isEmptyChannel = isEmptyTCSlot
    isClosedChannel = isClosedTCSlot
    isFullChannel = isFullTCSlot

-- | Writes to the channel, asserting that it hasn't been closed.
--
-- Useful in situations where only the writer closes the channel (when finished).
writeChannel' :: (Channel c) => c a -> a -> STM ()
writeChannel' c v = do
    o <- writeChannel c v
    unless o $ error "absurd: writeChannel' on closed channel"
{-# INLINE writeChannel' #-}

-- | Force a value to normal form before writing it to the given channel.
--
-- One of the goals of CSP is to divide work into independent tasks.
-- Forcing values before passing them to the next actor can improve performance—it
-- keeps the last one in the chain from doing more than its share of evaluation.
evalWriteChannel :: (Channel c, NFData a) => c a -> a -> IO Bool
evalWriteChannel c v = do
    v' <- evaluate $ force v
    atomically $ writeChannel c v'
{-# INLINE evalWriteChannel #-}

-- | `writeChannel'` meets `evalWriteChannel`
evalWriteChannel' :: (Channel c, NFData a) => c a -> a -> IO ()
evalWriteChannel' c v = do
    v' <- evaluate $ force v
    atomically $ writeChannel' c v'
{-# INLINE evalWriteChannel' #-}

-- | Overwrites the channel, asserting that it hasn't been closed
-- and returning any overwritten value.
--
-- Useful in situations where only the writer closes the channel (when finished).
overwriteChannel' :: (Channel c) => c a -> a -> STM (Maybe a)
overwriteChannel' c v = overwriteChannel c v >>= \case
    Wrote -> pure Nothing
    Overwrote o -> pure $ Just o
    Closed -> error "absurd: overwriteChannel' on closed channel"

-- | Force a value to normal form before overwriting the given channel with it.
evalOverwriteChannel :: (Channel c, NFData a) => c a -> a -> IO (OverwriteResult a)
evalOverwriteChannel c v = do
    v' <- evaluate $ force v
    atomically $ overwriteChannel c v'
{-# INLINE evalOverwriteChannel #-}

-- | `overwriteChannel'` meets `evalOverwriteChannel`
evalOverwriteChannel' :: (Channel c, NFData a) => c a -> a -> IO (Maybe a)
evalOverwriteChannel' c v = do
    v' <- evaluate $ force v
    atomically $ overwriteChannel' c v'
{-# INLINE evalOverwriteChannel' #-}

-- | Consume the given channel until it closes, passing values to the given action.
--
-- See 'stateConsumeChannel' to accumulate state at each step.
consumeChannel :: (Channel c) => c a -> (a -> IO ()) -> IO ()
consumeChannel c f = fix $ \loop -> atomically (readChannel c) >>= \case
    Just v -> f v >> loop
    Nothing -> pure ()

-- | Consume the given channel until it closes, passing batches of values to the given action.
--
-- Each batch is all the values in the channel at the time of the read (see `drainChannel`).
-- When the consumer falls behind, this uses fewer STM transactions than `consumeChannel`
-- at the cost of weaker backpressure.
consumeChannelBatches :: (Channel c) => c a -> ([a] -> IO ()) -> IO ()
consumeChannelBatches c f = fix $ \loop -> atomically (drainChannel c) >>= \case
    [] -> pure ()
    vs -> f vs >> loop

-- | `consumeChannelBatches`, but with an action for each value instead of each batch.
--
-- This has the same interface as `consumeChannel`,
-- but uses fewer STM transactions when the consumer falls behind.
consumeChannelBatches' :: (Channel c) => c a -> (a -> IO ()) -> IO ()
consumeChannelBatches' c f = consumeChannelBatches c $ mapM_ f

-- | Consume the given channel until it closes,
-- with each action updating some state. Returns the final state.
stateConsumeChannel :: (Channel c) => c a -> s -> (s -> a -> IO s) -> IO s
stateConsumeChannel c !state f = atomically (readChannel c) >>= \case
    Just v -> do
        next <- f state v
        stateConsumeChannel c next f
    Nothing -> pure state

-- | `consumeChannelBatches`, but with each action updating some state.
-- Returns the final state.
stateConsumeChannelBatches :: (Channel c) => c a -> s -> (s -> [a] -> IO s) -> IO s
stateConsumeChannelBatches c !state f = atomically (drainChannel c) >>= \case
    [] -> pure state
    vs -> do
        next <- f state vs
        stateConsumeChannelBatches c next f

-- | `stateConsumeChannelBatches`, but with an action for each value instead of each batch.
--
-- This has the same interface as `stateConsumeChannel`,
-- but uses fewer STM transactions when the consumer falls behind.
stateConsumeChannelBatches' :: (Channel c) => c a -> s -> (s -> a -> IO s) -> IO s
stateConsumeChannelBatches' c state f = stateConsumeChannelBatches c state $ foldM (\ !s v -> f s v)

feedChannel' :: (Channel c) => c a -> IO (Maybe a) -> IO ()
feedChannel' c f = f >>= \case
    Just v -> do
        stillOpen <- atomically $ writeChannel c v
        when stillOpen $ feedChannel' c f
    Nothing -> atomically $ closeChannel c

-- | Produce values with the given IO action,
-- feeding them into the given channel until it closes or the action returns @Nothing@.
feedChannel :: (Channel c) => c a -> IO (Maybe a) -> IO ()
feedChannel c f = do
    -- Protect against an f that could block for a long time (e.g., a network socket),
    -- even after the consumer hangs up.
    let chanClosed = atomically $ isClosedChannel c >>= check
    race_ (feedChannel' c f) chanClosed

-- | `feedChannel`, but forces produced values.
--
-- See `evalWriteChannel` for the motivation.
evalFeedChannel :: (Channel c, NFData a) => c a -> IO (Maybe a) -> IO ()
evalFeedChannel c f = feedChannel c f' where
    f' = f >>= evaluate . force
{-# INLINE evalFeedChannel #-}

-- | Create a channel with the given action,
-- then wire it to the given producer and consumer.
pipeline :: (Channel c) => IO (c a) -> (c a -> IO x) -> (c a -> IO y) -> IO (x, y)
pipeline new producer consumer = do
    c <- new
    let producer' = producer c `finally` atomically (closeChannel c)
    let consumer' = consumer c `finally` atomically (closeChannel c)
    concurrently producer' consumer'

-- | `pipeline`, but ignore the results.
pipeline_ :: (Channel c) => IO (c a) -> (c a -> IO x) -> (c a -> IO y) -> IO ()
pipeline_ n p c = void $ pipeline n p c
{-# INLINE pipeline_ #-}