packages feed

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

-- | Tools for connecting communicating sequential processes (threads)
-- with endless channels.
--
-- Many useful programs have no end to their input—they run in a steady state until killed.
-- This module provides the same utilities as "Control.Concurrent.Channel",
-- but for standard STM types we know and love.
module Control.Concurrent.Channel.Endless(
    Channel (..),
    evalWriteChannel,
    evalOverwriteChannel,
    consumeChannel,
    consumeChannelBatches,
    consumeChannelBatches',
    stateConsumeChannel,
    stateConsumeChannelBatches,
    stateConsumeChannelBatches',
    feedChannel,
    evalFeedChannel,
    pipeline,
    pipeline_
) where

import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Exception
import Control.DeepSeq
import Control.Monad

class Channel c where
    -- | Reads the next value, blocking if empty.
    readChannel :: c a -> STM a

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

    -- | Writes the next value, blocking if full.
    writeChannel :: c a -> a -> STM ()

    -- | Writes the next value, returning the oldest if the channel was full.
    overwriteChannel :: c a -> a -> STM (Maybe a)

instance Channel TBQueue where
    readChannel = readTBQueue

    drainChannel c = do
        vs <- flushTBQueue c
        when (null vs) retry
        pure vs

    writeChannel = writeTBQueue

    overwriteChannel c v = do
        wasFull <- isFullTBQueue c
        if wasFull
            then do
                o <- readTBQueue c
                writeTBQueue c v
                pure $ Just o
            else do
                writeTBQueue c v
                pure Nothing

instance Channel TMVar where
    readChannel = takeTMVar

    drainChannel = fmap (: []) <$> takeTMVar

    writeChannel = putTMVar

    overwriteChannel c v = do
        o <- tryTakeTMVar c
        putTMVar c v
        pure o

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

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 #-}

consumeChannel :: (Channel c) => c a -> (a -> IO ()) -> IO ()
consumeChannel c f = forever $ atomically (readChannel c) >>= f

-- | Consume the given channel, 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 = forever $ atomically (drainChannel c) >>= f

-- | `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

stateConsumeChannel :: (Channel c) => c a -> s -> (s -> a -> IO s) -> IO ()
stateConsumeChannel c !state f = do
    v <- atomically (readChannel c)
    next <- f state v
    stateConsumeChannel c next f

-- | `consumeChannelBatches`, but with each action updating some state.
stateConsumeChannelBatches :: (Channel c) => c a -> s -> (s -> [a] -> IO s) -> IO ()
stateConsumeChannelBatches c !state f = do
    vs <- atomically (drainChannel c)
    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 ()
stateConsumeChannelBatches' c state f = stateConsumeChannelBatches c state $ foldM (\ !s v -> f s v)

feedChannel :: (Channel c) => c a -> IO a -> IO ()
feedChannel c f = forever $ f >>= atomically . writeChannel c

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

-- There's not much to these when you don't ever close, but for completeness:

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

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