-- |
-- Module : Effectful.Streamly
-- Description : Running concurrent Streamly streams in Eff
-- License : BSD-3-Clause
--
-- Streamly evaluates concurrent streams in worker threads. It reaches the
-- base monad through 'Control.Monad.Trans.Control.MonadBaseControl', which
-- 'Eff' implements with the unlifting strategy of its 'IOE' context. The
-- default strategy, 'Effectful.SeqUnlift', refuses to run in another thread, so a
-- concurrent stream in 'Eff' fails unless that strategy is changed.
--
-- 'concurrently' changes it for the evaluation of one stream, whatever the
-- strategy of the code that consumes it. "Effectful.Streamly.Stream" applies
-- it to every concurrent combinator of streamly.
--
-- Effects behave in worker threads as in any thread that Effectful forks:
-- each worker gets its own copy of the environment. Static effects with
-- local state, such as "Effectful.State.Static.Local", are therefore not
-- shared: a change made by a worker stays in that worker. Use a shared
-- effect, such as "Effectful.State.Static.Shared", for state that workers
-- and the consumer must see. Errors from "Effectful.Error.Static" thrown in
-- a worker reach the handler of the consumer.
module Effectful.Streamly
( concurrently
, concurrentlyWith
, concurrentUnlift
) where
import Effectful (Eff, IOE, Limit (Unlimited), Persistence (Ephemeral),
UnliftStrategy (ConcUnlift), withUnliftStrategy, type (:>))
import Streamly.Data.Stream (Stream, morphInner)
-- | The strategy 'concurrently' uses: every worker thread gets its own
-- copy of the environment, with no limit on the number of threads.
concurrentUnlift :: UnliftStrategy
concurrentUnlift = ConcUnlift Ephemeral Unlimited
-- | Evaluate a stream with 'concurrentUnlift', so that the concurrent
-- combinators of streamly it is made of can run their workers. Apply it to
-- the result of the combinator; the strategy then holds for the worker
-- threads that the combinator starts.
concurrently :: IOE :> es => Stream (Eff es) a -> Stream (Eff es) a
concurrently = concurrentlyWith concurrentUnlift
-- | 'concurrently' with another strategy, such as a limited number of
-- persistent copies of the environment.
concurrentlyWith :: IOE :> es => UnliftStrategy -> Stream (Eff es) a -> Stream (Eff es) a
concurrentlyWith strategy = morphInner (withUnliftStrategy strategy)