diff --git a/benchmark/Streamly/Benchmark/Data/Stream/Prelude/Exceptions.hs b/benchmark/Streamly/Benchmark/Data/Stream/Prelude/Exceptions.hs index fd343f5fbe..373da080a0 100644 --- a/benchmark/Streamly/Benchmark/Data/Stream/Prelude/Exceptions.hs +++ b/benchmark/Streamly/Benchmark/Data/Stream/Prelude/Exceptions.hs @@ -238,6 +238,10 @@ takeInterval i value = withStream value $ drain . Stream.takeInterval i -- inspect $ 'takeInterval `hasNoType` ''D.Step #endif +{-# NOINLINE takeInterval_ #-} +takeInterval_ :: Double -> Int -> IO () +takeInterval_ i value = withStream value $ drain . Stream.takeInterval_ i + {-# NOINLINE dropInterval #-} dropInterval :: Double -> Int -> IO () dropInterval i value = withStream value $ drain . Stream.dropInterval i @@ -258,6 +262,7 @@ timeBenchmarks :: BenchEnv -> Int -> [Benchmark] timeBenchmarks _env size = [ benchIO "parTapCount 1 second" (pollCounts size) , benchIO "takeInterval-all" (takeInterval 10000 size) + , benchIO "takeInterval_-all" (takeInterval_ 10000 size) , benchIO "dropInterval-all" (dropInterval 10000 size) ] diff --git a/src/Streamly/Internal/Data/Stream/Time.hs b/src/Streamly/Internal/Data/Stream/Time.hs index 4ed318ff01..baeaf72242 100644 --- a/src/Streamly/Internal/Data/Stream/Time.hs +++ b/src/Streamly/Internal/Data/Stream/Time.hs @@ -19,6 +19,7 @@ module Streamly.Internal.Data.Stream.Time -- * Trimming , takeInterval + , takeInterval_ , takeLastInterval , dropInterval , dropLastInterval @@ -59,14 +60,19 @@ where #include "inline.hs" -import Control.Exception (assert) +import Control.Concurrent (ThreadId, forkIOWithUnmask, killThread, yield) +import Control.Exception (assert, mask_) +import Control.Monad (when) import Control.Monad.IO.Class (MonadIO(..)) import Data.Heap (Entry(..)) import Data.Int (Int64) +import Data.IORef (IORef, mkWeakIORef, newIORef, readIORef, writeIORef) import Data.Kind (Type) import Data.Map (Map) import Data.Maybe (isJust, isNothing) import Data.Proxy (Proxy(..)) +import Fusion.Plugin.Types (Fuse(..)) +import System.Mem.Weak (deRefWeak) import Streamly.Data.Fold (Fold) import Streamly.Data.Array (Unbox) import Streamly.Internal.Data.Array (Array) @@ -203,6 +209,75 @@ takeInterval d xs , Stream.fromEffect (Stream.sleep d >> return Nothing) ] +{-# ANN type TakeIntervalState Fuse #-} +data TakeIntervalState s + = TakeIntervalInit s + | TakeIntervalRun !Int !(IORef Bool) !ThreadId s + +-- | Like 'takeInterval' but faster, with a weaker guarantee about the time at +-- which the stream ends, and without requiring 'MonadAsync'. +-- +-- An element is yielded if the evaluation generating it starts before the end +-- of the interval, whenever it finishes. The evaluation of the stream is not +-- interrupted at the end of the interval: if it blocks, the stream does not +-- end until it returns. +-- +-- The stream is evaluated in the thread of the consumer. Another thread is +-- forked only to keep the time. It ends at the end of the interval, or when +-- the stream ends if that happens earlier. If the stream is abandoned before +-- it ends, the thread is killed when the stream is garbage collected. +-- +-- /Pre-release/ +{-# INLINE takeInterval_ #-} +takeInterval_ :: MonadIO m => Double -> Stream m a -> Stream m a +takeInterval_ d (Stream.Stream step state) = + Stream.Stream step1 (TakeIntervalInit state) + + where + + -- The timer thread gets to run only when the thread evaluating the stream + -- yields the CPU, which a fused loop that does not allocate never does on + -- its own. So we yield explicitly, once in this many steps. + yieldCount :: Int + yieldCount = 1000 + + -- A one-shot timer thread sets a flag at the end of the interval, reading + -- the flag is cheaper than reading the clock for each element. + -- + -- The timer thread holds only a weak reference to the flag, so that the + -- flag becomes unreachable when the stream is abandoned, and its finalizer + -- kills the thread. Asynchronous exceptions are masked until the finalizer + -- is installed, otherwise the thread could be left without one. + startTimer = mask_ $ do + ref <- newIORef False + weak <- mkWeakIORef ref (return ()) + tid <- forkIOWithUnmask $ \unmask -> unmask $ do + Stream.sleep d + deRefWeak weak >>= mapM_ (`writeIORef` True) + _ <- mkWeakIORef ref (killThread tid) + return (ref, tid) + + {-# INLINE_LATE step1 #-} + step1 _ (TakeIntervalInit st) + | not (d > 0) = return Stop + | otherwise = do + (ref, tid) <- liftIO startTimer + -- Let the timer thread start, the interval begins now. + liftIO yield + return $ Skip $ TakeIntervalRun yieldCount ref tid st + step1 gst (TakeIntervalRun n ref tid st) = do + when (n <= 0) $ liftIO yield + expired <- liftIO $ readIORef ref + if expired + then return Stop + else do + let n1 = if n <= 0 then yieldCount else n - 1 + r <- step gst st + case r of + Yield x s -> return $ Yield x (TakeIntervalRun n1 ref tid s) + Skip s -> return $ Skip (TakeIntervalRun n1 ref tid s) + Stop -> liftIO (killThread tid) >> return Stop + -- | Take time interval @i@ seconds at the end of the stream. -- -- O(n) space, where n is the number elements taken. diff --git a/test/Streamly/Test/Data/Stream/Prelude/Time.hs b/test/Streamly/Test/Data/Stream/Prelude/Time.hs index fb7e1298e9..b1f39bc5c6 100644 --- a/test/Streamly/Test/Data/Stream/Prelude/Time.hs +++ b/test/Streamly/Test/Data/Stream/Prelude/Time.hs @@ -136,6 +136,43 @@ dropIntervalHuge d = $ Stream.dropInterval d $ Stream.fromList [1..10] +takeInterval_Of :: Double -> IO [Int] +takeInterval_Of d = + Stream.fold Fold.toList + $ Stream.takeInterval_ d + $ Stream.fromList [1..10] + +takeInterval_Prefix :: IO Bool +takeInterval_Prefix = do + xs <- + Stream.fold Fold.toList + $ Stream.takeInterval_ shortInterval slowEnumeration + return $ not (null xs) && xs == [1..length xs] + +-- The second element is generated after the end of the interval, by an action +-- started before it. takeInterval_ does not interrupt the action, and yields +-- the element. No action is started after the end of the interval. +takeInterval_Blocked :: IO [Int] +takeInterval_Blocked = + Stream.fold Fold.toList + $ Stream.takeInterval_ shortInterval + $ Stream.mapM (\x -> when (x > 1) (threadDelay 300000) >> return x) + $ Stream.fromList [1..10] + +-- The loop does not allocate, so the timer thread of takeInterval_ runs only if +-- the loop yields the CPU. A loop that never yields cannot be interrupted, so +-- the stream is finite: if the timer thread does not run, the loop ends by +-- itself after several seconds, having taken all the elements. The number of +-- elements must fit in an Int of 32 bits, for the JavaScript backend. +takeInterval_Spin :: IO Bool +takeInterval_Spin = do + let total = 2000000000 :: Int + n <- + Stream.fold Fold.length + $ Stream.takeInterval_ shortInterval + $ Stream.enumerateFromTo 1 total + return $ n < total + -- The stream is endless, so this returns only if takeInterval ends it. The -- elements taken must be the beginning of the stream. takeIntervalPrefix :: IO Bool @@ -191,6 +228,22 @@ main = hspec (takeIntervalOf nan `shouldReturn` []) it "takeInterval ends a blocked stream after the interval" (takeIntervalBlocked `shouldReturn` Just [1]) + it "takeInterval_ takes all the elements within the interval" + (takeInterval_Of longInterval `shouldReturn` [1..10]) + it "takeInterval_ takes all the elements if the interval is infinite" + (takeInterval_Of (1/0) `shouldReturn` [1..10]) + it "takeInterval_ ends the stream after the interval" + (takeInterval_Prefix `shouldReturn` True) + it "takeInterval_ takes nothing if the interval is zero" + (takeInterval_Of 0 `shouldReturn` []) + it "takeInterval_ takes nothing if the interval is negative" + (takeInterval_Of (-1) `shouldReturn` []) + it "takeInterval_ takes nothing if the interval is NaN" + (takeInterval_Of nan `shouldReturn` []) + it "takeInterval_ yields the element of an action in progress" + (takeInterval_Blocked `shouldReturn` [1,2]) + it "takeInterval_ ends a loop that never yields the CPU" + (takeInterval_Spin `shouldReturn` True) it "dropInterval drops nothing if the interval is zero" (dropIntervalOf 0 `shouldReturn` [1..10]) it "dropInterval drops nothing if the interval is negative"