effectful-streamly (empty) → 0.1.0.0
raw patch · 7 files changed
+661/−0 lines, 7 filesdep +basedep +effectful-coredep +effectful-streamly
Dependencies added: base, effectful-core, effectful-streamly, streamly, streamly-core, tasty, tasty-hunit
Files
- CHANGELOG.md +11/−0
- LICENSE +29/−0
- README.md +51/−0
- effectful-streamly.cabal +68/−0
- src/Effectful/Streamly.hs +48/−0
- src/Effectful/Streamly/Stream.hs +335/−0
- test/Main.hs +119/−0
+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Revision history for effectful-streamly++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `Effectful.Streamly`: `concurrently` and `concurrentlyWith`, which make a+ concurrent stream work in `Eff` whatever the unlifting strategy of its+ consumer.+* `Effectful.Streamly.Stream`: `Streamly.Data.Stream.Prelude` for `Eff`,+ with every concurrent combinator wrapped. Deprecated combinators are left+ out.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,51 @@+# effectful-streamly++Concurrent [Streamly](https://hackage.haskell.org/package/streamly) streams+in [Effectful](https://hackage.haskell.org/package/effectful).++Streamly evaluates concurrent streams in worker threads and reaches the+base monad through `MonadBaseControl`. `Eff` implements it with the+unlifting strategy of its `IOE` context, whose default refuses to run in+another thread: `parList`, `parMapM` and the other concurrent combinators+fail in `Eff` unless that strategy is changed.++This package changes it for you:++- `Effectful.Streamly.Stream` replaces `Streamly.Data.Stream.Prelude`.+ The serial API is re-exported as it is; every concurrent combinator works+ in `Eff`, whatever the strategy of the code that consumes the stream.+- `Effectful.Streamly` holds the wrapper it is built on, `concurrently`,+ for streams built some other way.++```haskell+import Effectful (Eff, IOE, liftIO, (:>))+import Effectful.Streamly.Stream (fromList, parMapM, toList)++lengths :: IOE :> es => [FilePath] -> Eff es [Int]+lengths paths = toList (parMapM id (fmap length . liftIO . readFile) (fromList paths))+```++## Effects in worker threads++Each worker gets its own copy of the environment, as in any thread that+Effectful forks:++- effects with local state, such as `Effectful.State.Static.Local`, are not+ shared: a change made by a worker stays in that worker;+- shared effects, such as `Effectful.State.Static.Shared`, are seen by+ everyone;+- an `Error` thrown in a worker reaches the handler of the consumer, and so+ does an exception.++## Known defects of streamly 0.11.1++`takeInterval` always yields an empty stream, and `dropInterval` drops+nothing when the stream yields at once+([streamly#3271](https://github.com/composewell/streamly/issues/3271)). The+wrappers keep that behaviour; a test records it.++Tested with GHC 9.8.4, 9.10.3 and 9.12.4, effectful 2.7.1, streamly 0.11.1.++## License++BSD-3-Clause. See [LICENSE](LICENSE).
+ effectful-streamly.cabal view
@@ -0,0 +1,68 @@+cabal-version: 3.12+name: effectful-streamly+version: 0.1.0.0+synopsis: Concurrent Streamly streams in Effectful+description:+ Streamly runs concurrent streams in worker threads, which the default+ unlifting strategy of Effectful refuses. This package makes the+ concurrent combinators of streamly work in Eff: a drop-in replacement+ for Streamly.Data.Stream.Prelude, and the wrapper it is built on.++homepage: https://github.com/GuillaumedeVolpiano/effectful-streamly+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: Control, Streaming, Concurrency+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/effectful-streamly.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ RoleAnnotations+ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ Effectful.Streamly+ Effectful.Streamly.Stream++ build-depends:+ , base >=4.19 && <4.22+ , effectful-core ^>=2.7.1+ , streamly ^>=0.11.1+ , streamly-core ^>=0.3.3++test-suite effectful-streamly-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , base+ , effectful-core+ , effectful-streamly+ , streamly+ , streamly-core+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10
+ src/Effectful/Streamly.hs view
@@ -0,0 +1,48 @@+-- |+-- 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)
+ src/Effectful/Streamly/Stream.hs view
@@ -0,0 +1,335 @@+-- |+-- Module : Effectful.Streamly.Stream+-- Description : Streamly.Data.Stream.Prelude, for Eff+-- License : BSD-3-Clause+--+-- A replacement for "Streamly.Data.Stream.Prelude" when the stream runs in+-- 'Eff'. The serial API and the configuration are re-exported as they+-- are. Every concurrent combinator is wrapped with+-- 'Effectful.Streamly.concurrently', so that it works whatever the+-- unlifting strategy of the consumer:+--+-- > import Effectful.Streamly.Stream (fold, parMapM)+-- > import Streamly.Data.Fold (toList)+-- >+-- > fold toList (parMapM id fetch names)+--+-- See "Effectful.Streamly" for how effects behave in worker threads.+-- The combinators that streamly deprecates are left out.+module Effectful.Streamly.Stream+ ( -- * Serial streams+ module Streamly.Data.Stream++ -- * Configuration+ , Config+ , maxThreads+ , maxBuffer+ , Rate (..)+ , rate+ , avgRate+ , minRate+ , maxRate+ , constRate+ , StopWhen (..)+ , stopWhen+ , eager+ , ordered+ , interleaved+ , useAcquire+ , clearAcquire+ , inspect++ -- * Evaluation+ , parBuffered+ , parRepeatM+ , parReplicateM+ , fromCallback++ -- * Mapping+ , parMapM+ , parSequence++ -- * Combining two streams+ , parZipWithM+ , parZipWith+ , parMergeByM+ , parMergeBy++ -- * Combining many streams+ , parList+ , parCrossApply+ , parConcat+ , parConcatMap+ , parConcatIterate++ -- * Observation+ , parTapCount++ -- * Time+ , interject+ , takeInterval+ , dropInterval+ , intervalsOf+ , sampleIntervalEnd+ , sampleIntervalStart+ , sampleBurstEnd+ , sampleBurstStart++ -- * Resources+ , after+ , bracket+ , finally+ ) where++import Effectful (Eff, IOE, type (:>))+import Effectful.Streamly (concurrently)+import Streamly.Data.Fold (Fold)+import Streamly.Data.Stream (Enumerable (..), Stream, afterIO, append, before,+ bfsUnfoldEach, bracketIO, bracketIO', bracketIO'',+ bracketIO3, catEithers, catLefts, catMaybes,+ catRights, chunksOf, cmpBy, concatEffect,+ concatFor, concatForM, concatMap, concatMapM, cons,+ consM, cross, crossWith, delay, drop, dropWhile,+ dropWhileM, enumerate, enumerateTo, eqBy,+ fairConcatFor, fairConcatForM, fairConcatMap,+ fairCross, fairUnfoldEach, filter, filterM,+ finallyIO, finallyIO', finallyIO'', fold,+ foldBreak, foldMany, foldr, foldrM, fromEffect,+ fromList, fromPure, groupsOf, handle, indexed,+ insertBy, intercalate, intercalateSuffix,+ interleave, intersperse, intersperseM,+ intersperseM_, isInfixOf, isPrefixOf,+ isSubsequenceOf, iterate, iterateM, liftInner,+ mapM, mapMaybe, mapMaybeM, mergeBy, mergeByM,+ morphInner, nil, nilM, onException, parse,+ parseBreak, parseBreakPos, parseMany, parsePos,+ postscan, postscanl, repeat, repeatM, replicate,+ replicateM, reverse, runReaderT, runStateT, scan,+ scanMaybe, scanl, sequence, splitEndBySeq,+ splitEndBySeq_, splitOn, splitSepBySeq_,+ splitSepBy_, stripPrefix, take, takeWhile,+ takeWhileM, tap, toList, trace, uncons, unfold,+ unfoldEach, unfoldEachEndBySeq, unfoldEachSepBySeq,+ unfoldMany, unfoldr, unfoldrM, unionBy, wordsBy,+ zipWith, zipWithM)+import Streamly.Data.Stream.Prelude (Config, Rate (..), StopWhen (..), avgRate,+ clearAcquire, constRate, eager, inspect,+ interleaved, maxBuffer, maxRate,+ maxThreads, minRate, ordered, rate,+ stopWhen, useAcquire)+import Streamly.Data.Stream.Prelude qualified as S (after, bracket,+ dropInterval, finally,+ fromCallback, interject,+ intervalsOf, parBuffered,+ parConcat, parConcatIterate,+ parConcatMap, parCrossApply,+ parList, parMapM,+ parMergeBy, parMergeByM,+ parRepeatM, parReplicateM,+ parSequence, parTapCount,+ parZipWith, parZipWithM,+ sampleBurstEnd,+ sampleBurstStart,+ sampleIntervalEnd,+ sampleIntervalStart,+ takeInterval)++-- Evaluation++-- | Evaluate the stream in a thread of its own, ahead of its consumer,+-- keeping the results in a buffer. The stream itself stays serial: its+-- actions do not run concurrently with each other.+parBuffered :: IOE :> es => (Config -> Config) -> Stream (Eff es) a -> Stream (Eff es) a+parBuffered cfg = concurrently . S.parBuffered cfg++-- | Run an action again and again, concurrently, as a stream of its+-- results.+parRepeatM :: IOE :> es => (Config -> Config) -> Eff es a -> Stream (Eff es) a+parRepeatM cfg = concurrently . S.parRepeatM cfg++-- | Run an action a number of times, concurrently, as a stream of its+-- results.+parReplicateM :: IOE :> es => (Config -> Config) -> Int -> Eff es a -> Stream (Eff es) a+parReplicateM cfg n = concurrently . S.parReplicateM cfg n++-- | The stream of the values given to a callback. The function receives+-- the callback and must hand it to a thread other than the one that+-- evaluates the stream, which calls it for as long as it runs.+fromCallback :: IOE :> es => ((a -> Eff es ()) -> Eff es ()) -> Stream (Eff es) a+fromCallback = concurrently . S.fromCallback++-- Mapping++-- | Map an action over the stream, several elements at a time.+parMapM :: IOE :> es => (Config -> Config) -> (a -> Eff es b) -> Stream (Eff es) a -> Stream (Eff es) b+parMapM cfg f = concurrently . S.parMapM cfg f++-- | Run the actions of a stream, several at a time.+parSequence :: IOE :> es => (Config -> Config) -> Stream (Eff es) (Eff es a) -> Stream (Eff es) a+parSequence cfg = concurrently . S.parSequence cfg++-- Combining two streams++-- | Evaluate two streams concurrently and combine their elements, pair+-- by pair, with an action.+parZipWithM+ :: IOE :> es+ => (Config -> Config)+ -> (a -> b -> Eff es c)+ -> Stream (Eff es) a+ -> Stream (Eff es) b+ -> Stream (Eff es) c+parZipWithM cfg f xs = concurrently . S.parZipWithM cfg f xs++-- | Evaluate two streams concurrently and combine their elements, pair+-- by pair.+parZipWith+ :: IOE :> es+ => (Config -> Config)+ -> (a -> b -> c)+ -> Stream (Eff es) a+ -> Stream (Eff es) b+ -> Stream (Eff es) c+parZipWith cfg f xs = concurrently . S.parZipWith cfg f xs++-- | Evaluate two streams concurrently and merge them, taking each time+-- the element the comparing action puts first.+parMergeByM+ :: IOE :> es+ => (Config -> Config)+ -> (a -> a -> Eff es Ordering)+ -> Stream (Eff es) a+ -> Stream (Eff es) a+ -> Stream (Eff es) a+parMergeByM cfg f xs = concurrently . S.parMergeByM cfg f xs++-- | Evaluate two streams concurrently and merge them, taking each time+-- the element the comparison puts first.+parMergeBy+ :: IOE :> es+ => (Config -> Config)+ -> (a -> a -> Ordering)+ -> Stream (Eff es) a+ -> Stream (Eff es) a+ -> Stream (Eff es) a+parMergeBy cfg f xs = concurrently . S.parMergeBy cfg f xs++-- Combining many streams++-- | Evaluate the streams of a list concurrently, as one stream of their+-- elements.+parList :: IOE :> es => (Config -> Config) -> [Stream (Eff es) a] -> Stream (Eff es) a+parList cfg = concurrently . S.parList cfg++-- | Apply every function of a stream to every value of another, the+-- two evaluated concurrently.+parCrossApply+ :: IOE :> es+ => (Config -> Config)+ -> Stream (Eff es) (a -> b)+ -> Stream (Eff es) a+ -> Stream (Eff es) b+parCrossApply cfg fs = concurrently . S.parCrossApply cfg fs++-- | Evaluate the streams of a stream concurrently, as one stream of+-- their elements.+parConcat :: IOE :> es => (Config -> Config) -> Stream (Eff es) (Stream (Eff es) a) -> Stream (Eff es) a+parConcat cfg = concurrently . S.parConcat cfg++-- | Map each element to a stream and evaluate these streams+-- concurrently, as one stream of their elements.+parConcatMap+ :: IOE :> es+ => (Config -> Config)+ -> (a -> Stream (Eff es) b)+ -> Stream (Eff es) a+ -> Stream (Eff es) b+parConcatMap cfg f = concurrently . S.parConcatMap cfg f++-- | Like 'parConcatMap', applied again to the elements it produces:+-- the concurrent traversal of a tree.+parConcatIterate+ :: IOE :> es+ => (Config -> Config)+ -> (a -> Stream (Eff es) a)+ -> Stream (Eff es) a+ -> Stream (Eff es) a+parConcatIterate cfg f = concurrently . S.parConcatIterate cfg f++-- Observation++-- | Count the elements that satisfy a predicate and give the stream of+-- the counts to a function, which runs in a thread of its own. The+-- elements pass unchanged.+parTapCount+ :: IOE :> es+ => (a -> Bool)+ -> (Stream (Eff es) Int -> Eff es b)+ -> Stream (Eff es) a+ -> Stream (Eff es) a+parTapCount p f = concurrently . S.parTapCount p f++-- Time++-- | Run an action every so many seconds and insert its results in the+-- stream.+interject :: IOE :> es => Eff es a -> Double -> Stream (Eff es) a -> Stream (Eff es) a+interject action seconds = concurrently . S.interject action seconds++-- | /Broken in streamly 0.11.1/: the stream ends at its first element, so+-- the result is always empty. Its definition keeps the elements while they+-- are @Nothing@ instead of while they are @Just@+-- (<https://github.com/composewell/streamly/issues/3271>). Kept for+-- compatibility.+takeInterval :: IOE :> es => Double -> Stream (Eff es) a -> Stream (Eff es) a+takeInterval seconds = concurrently . S.takeInterval seconds++-- | /Broken in streamly 0.11.1/, like 'takeInterval': nothing is dropped+-- when the stream yields at once.+dropInterval :: IOE :> es => Double -> Stream (Eff es) a -> Stream (Eff es) a+dropInterval seconds = concurrently . S.dropInterval seconds++-- | Fold the elements that arrive in each window of so many seconds;+-- the stream of the results. A fold that ends before its window does is+-- started again in the same window.+intervalsOf :: IOE :> es => Double -> Fold (Eff es) a b -> Stream (Eff es) a -> Stream (Eff es) b+intervalsOf seconds f = concurrently . S.intervalsOf seconds f++-- | The last element of each window of so many seconds. Known elsewhere+-- as throttling.+sampleIntervalEnd :: IOE :> es => Double -> Stream (Eff es) a -> Stream (Eff es) a+sampleIntervalEnd seconds = concurrently . S.sampleIntervalEnd seconds++-- | The first element of each window of so many seconds.+sampleIntervalStart :: IOE :> es => Double -> Stream (Eff es) a -> Stream (Eff es) a+sampleIntervalStart seconds = concurrently . S.sampleIntervalStart seconds++-- | The last element of each burst: a burst ends when nothing arrives+-- for so many seconds. Known elsewhere as debouncing.+sampleBurstEnd :: IOE :> es => Double -> Stream (Eff es) a -> Stream (Eff es) a+sampleBurstEnd seconds = concurrently . S.sampleBurstEnd seconds++-- | The first element of each burst: a burst ends when nothing arrives+-- for so many seconds.+sampleBurstStart :: IOE :> es => Double -> Stream (Eff es) a -> Stream (Eff es) a+sampleBurstStart seconds = concurrently . S.sampleBurstStart seconds++-- Resources++-- | Run an action when the stream stops, or when it is garbage collected+-- after a partial evaluation. The collection case runs the action in+-- another thread.+after :: IOE :> es => Eff es b -> Stream (Eff es) a -> Stream (Eff es) a+after action = concurrently . S.after action++-- | Acquire a resource, and release it when the stream stops, fails, or is+-- garbage collected after a partial evaluation. The collection case runs+-- the release in another thread.+bracket :: IOE :> es => Eff es b -> (b -> Eff es c) -> (b -> Stream (Eff es) a) -> Stream (Eff es) a+bracket acquire release = concurrently . S.bracket acquire release++-- | Run an action when the stream stops, fails, or is garbage collected+-- after a partial evaluation. The collection case runs the action in+-- another thread.+finally :: IOE :> es => Eff es b -> Stream (Eff es) a -> Stream (Eff es) a+finally action = concurrently . S.finally action
+ test/Main.hs view
@@ -0,0 +1,119 @@+-- | Every test runs with the default unlifting strategy of the caller,+-- 'SeqUnlift': the wrapped combinators must work without changing it.+module Main (main) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)+import Control.Exception (ErrorCall (..), SomeException, throwIO, try)+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.List (sort)+import Effectful (Eff, MonadIO (liftIO), runEff)+import Effectful.Error.Static (runErrorNoCallStack, throwError)+import Effectful.Reader.Static (ask, runReader)+import Effectful.State.Static.Local qualified as SL (modify, runState)+import Effectful.State.Static.Shared qualified as SS (modify, runState)+import Effectful.Streamly.Stream (Stream, bracket, fold, fromCallback,+ fromEffect, fromList, fromPure, interject,+ ordered, parConcatMap, parMapM, parReplicateM,+ parZipWith, repeatM, sampleIntervalEnd,+ takeInterval, toList)+import Effectful.Streamly.Stream qualified as ES (mapM, parList, take)+import Streamly.Data.Fold qualified as F (sum)+import Streamly.Data.Stream.Prelude qualified as S (parList)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+ localOption (mkTimeout 10_000_000) $+ testGroup+ "effectful-streamly"+ [ testCase "streamly alone fails in Eff" $ do+ outcome <- try @SomeException . runEff $ toList (S.parList id [one 1, one 2])+ case outcome of+ Left _ -> pure ()+ Right values -> assertFailure ("expected a failure, got " <> show values)+ , testGroup+ "combinators"+ [ testCase "parList" $ do+ values <- runEff $ toList (ES.parList id (map one [1 .. 50]))+ sort values @?= [1 .. 50]+ , testCase "parMapM" $ do+ values <- runEff $ toList (parMapM id (pure . (* 2)) (fromList [1 .. 20]))+ sort values @?= map (* 2) [1 .. 20 :: Int]+ , testCase "parMapM, ordered" $ do+ values <- runEff $ toList (parMapM (ordered True) (pure . (* 2)) (fromList [1 .. 20]))+ values @?= map (* 2) [1 .. 20 :: Int]+ , testCase "parConcatMap" $ do+ values <- runEff $ toList (parConcatMap id (\n -> fromList [n, n]) (fromList [1, 2, 3]))+ sort values @?= [1, 1, 2, 2, 3, 3 :: Int]+ , testCase "parZipWith" $ do+ values <- runEff $ toList (parZipWith id (+) (fromList [1, 2, 3]) (fromList [10, 20, 30]))+ values @?= [11, 22, 33 :: Int]+ , testCase "parReplicateM" $ do+ values <- runEff $ toList (parReplicateM id 5 (pure 'x'))+ values @?= "xxxxx"+ , testCase "fromCallback" $ do+ values <- runEff $ do+ let source = fromCallback (\push -> mapM_ push [1, 2, 3 :: Int])+ toList (ES.take 3 source)+ values @?= [1, 2, 3]+ , testCase "interject" $ do+ values <- runEff . toList . ES.take 3 $+ interject (pure 0) 0.01 (repeatM (liftIO (threadDelay 1_000_000) >> pure 1))+ values @?= [0, 0, 0 :: Int]+ , testCase "takeInterval yields nothing (streamly 0.11.1 defect)" $ do+ -- composewell/streamly#3271. When this fails, streamly has fixed+ -- takeInterval: update the documentation of the wrapper.+ values <- runEff $ toList (takeInterval 1 (fromList [1 .. 10 :: Int]))+ values @?= []+ , testCase "sampleIntervalEnd" $ do+ values <- runEff . toList . sampleIntervalEnd 0.05 $+ ES.mapM (\n -> liftIO (threadDelay 5_000) >> pure n) (fromList [1 .. 40 :: Int])+ last values @?= 40+ , testCase "bracket releases when the stream stops" $ do+ released <- newIORef (0 :: Int)+ values <- runEff . toList $+ bracket (pure ()) (\() -> liftIO (atomicModifyIORef' released (\n -> (n + 1, ())))) (\() -> fromList "ab")+ values @?= "ab"+ readIORef released >>= (@?= 1)+ ]+ , testGroup+ "effects in workers"+ [ testCase "the streams really run at the same time" $ do+ (left, right) <- (,) <$> newEmptyMVar <*> newEmptyMVar+ let ping = fromEffect (liftIO (putMVar left () >> takeMVar right) >> pure "ping")+ pong = fromEffect (liftIO (takeMVar left >> putMVar right ()) >> pure "pong")+ values <- runEff $ toList (ES.parList id [ping, pong])+ sort values @?= ["ping", "pong" :: String]+ , testCase "a Reader is seen" $ do+ values <- runEff . runReader (10 :: Int) $+ toList (parMapM id (\n -> (+ n) <$> ask @Int) (fromList [1, 2, 3]))+ sort values @?= [11, 12, 13]+ , testCase "local state stays in the worker" $ do+ (_, final) <- runEff . SL.runState (0 :: Int) $+ toList (ES.parList id (replicate 3 (fromEffect (SL.modify @Int (+ 1)))))+ final @?= 0+ , testCase "shared state reaches the consumer" $ do+ (_, final) <- runEff . SS.runState (0 :: Int) $+ toList (ES.parList id (replicate 3 (fromEffect (SS.modify @Int (+ 1)))))+ final @?= 3+ , testCase "an Error reaches the handler of the consumer" $ do+ outcome <- runEff . runErrorNoCallStack @String $+ toList (ES.parList id [one 1, fromEffect (throwError @String "boom"), one 3])+ outcome @?= Left "boom"+ , testCase "an exception reaches the consumer" $ do+ outcome <- try @ErrorCall . runEff $+ toList (ES.parList id [one 1, fromEffect (liftIO (throwIO (ErrorCall "boom")))])+ outcome @?= Left (ErrorCall "boom")+ , testCase "a fold over a concurrent stream" $ do+ total <- runEff $ fold F.sum (parMapM id pure (fromList [1 .. 100 :: Int]))+ total @?= 5050+ ]+ ]+ where+ one :: Int -> Stream (Eff es) Int+ one = fromPure