2-- Module : Streamly.Internal.Data.Stream.StreamD.Exception
3-- Copyright : (c) 2020 Composewell Technologies and Contributors
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
9module Streamly.Internal.Data.Stream.StreamD.Exception
29import Control.Monad.IO.Class (MonadIO(..))
30import Control.Exception (Exception, SomeException, mask_)
31import Control.Monad.Catch (MonadCatch)
32import GHC.Exts (inline)
33import Streamly.Internal.Data.IOFinalizer
34 (newIOFinalizer, runIOFinalizer, clearingIOFinalizer)
36import qualified Control.Monad.Catch as MC
38import Streamly.Internal.Data.Stream.StreamD.Type
42-- >>> import qualified Streamly.Internal.Data.Stream as Stream
44data GbracketState s1 s2 v
47 | GBracketException s2
49-- | Like 'gbracket' but with following differences:
51-- * alloc action @m c@ runs with async exceptions enabled
52-- * cleanup action @c -> m d@ won't run if the stream is garbage collected
53-- after partial evaluation.
55-- /Inhibits stream fusion/
59{-# INLINE_NORMAL gbracket_ #-}
63 -> (c -> m d) -- ^ after, on normal stop
64 -> (c -> e -> Stream m b -> Stream m b) -- ^ on exception
65 -> (forall s. m s -> m (Either e s)) -- ^ try (exception handling)
66 -> (c -> Stream m b) -- ^ stream generator
68gbracket_ bef aft onExc ftry action =
69 Stream step GBracketInit
73 {-# INLINE_LATE step #-}
74 step _ GBracketInit = do
76 return $ Skip $ GBracketNormal (action r) r
78 step gst (GBracketNormal (UnStream step1 st) v) = do
79 res <- ftry $ step1 gst st
83 return $ Yield x (GBracketNormal (Stream step1 s) v)
84 Skip s -> return $ Skip (GBracketNormal (Stream step1 s) v)
85 Stop -> aft v >> return Stop
86 -- XXX Do not handle async exceptions, just rethrow them.
89 $ Skip (GBracketException (onExc v e (UnStream step1 st)))
90 step gst (GBracketException (UnStream step1 st)) = do
93 Yield x s -> return $ Yield x (GBracketException (Stream step1 s))
94 Skip s -> return $ Skip (GBracketException (Stream step1 s))
97data GbracketIOState s1 s2 v wref
99 | GBracketIONormal s1 v wref
100 | GBracketIOException s2
102-- | Run the alloc action @m c@ with async exceptions disabled but keeping
103-- blocking operations interruptible (see 'Control.Exception.mask'). Use the
104-- output @c@ as input to @c -> Stream m b@ to generate an output stream. When
105-- generating the stream use the supplied @try@ operation @forall s. m s -> m
106-- (Either e s)@ to catch synchronous exceptions. If an exception occurs run
107-- the exception handler @c -> e -> Stream m b -> m (Stream m b)@. Note that
108-- 'gbracket' does not rethrow the exception, it has to be done by the
109-- exception handler if desired.
111-- The cleanup action @c -> m d@, runs whenever the stream ends normally, due
112-- to a sync or async exception or if it gets garbage collected after a partial
113-- lazy evaluation. See 'bracket' for the semantics of the cleanup action.
115-- 'gbracket' can express all other exception handling combinators.
117-- /Inhibits stream fusion/
120{-# INLINE_NORMAL gbracket #-}
124 -> (c -> IO d1) -- ^ on normal stop
125 -> (c -> e -> Stream m b -> IO (Stream m b)) -- ^ on exception
126 -> (c -> IO d2) -- ^ on GC without normal stop or exception
127 -> (forall s. m s -> m (Either e s)) -- ^ try (exception handling)
128 -> (c -> Stream m b) -- ^ stream generator
130gbracket bef aft onExc onGC ftry action =
131 Stream step GBracketIOInit
135 -- If the stream is never evaluated the "aft" action will never be
136 -- called. For that to occur we will need the user of this API to pass a
137 -- weak pointer to us.
138 {-# INLINE_LATE step #-}
139 step _ GBracketIOInit = do
140 -- We mask asynchronous exceptions to make the execution
141 -- of 'bef' and the registration of 'aft' atomic.
142 -- A similar thing is done in the resourcet package: https://git.io/JvKV3
143 -- Tutorial: https://markkarpov.com/tutorial/exceptions.html
144 (r, ref) <- liftIO $ mask_ $ do
146 ref <- newIOFinalizer (onGC r)
148 return $ Skip $ GBracketIONormal (action r) r ref
150 step gst (GBracketIONormal (UnStream step1 st) v ref) = do
151 res <- ftry $ step1 gst st
155 return $ Yield x (GBracketIONormal (Stream step1 s) v ref)
157 return $ Skip (GBracketIONormal (Stream step1 s) v ref)
159 liftIO (clearingIOFinalizer ref (aft v)) >> return Stop
160 -- XXX Do not handle async exceptions, just rethrow them.
162 -- Clearing of finalizer and running of exception handler must
163 -- be atomic wrt async exceptions. Otherwise if we have cleared
164 -- the finalizer and have not run the exception handler then we
165 -- may leak the resource.
167 liftIO (clearingIOFinalizer ref (onExc v e (UnStream step1 st)))
168 return $ Skip (GBracketIOException stream)
169 step gst (GBracketIOException (UnStream step1 st)) = do
173 return $ Yield x (GBracketIOException (Stream step1 s))
174 Skip s -> return $ Skip (GBracketIOException (Stream step1 s))
177-- | Run the action @m b@ before the stream yields its first element.
179-- Same as the following but more efficient due to fusion:
181-- >>> before action xs = Stream.nilM action <> xs
182-- >>> before action xs = Stream.concatMap (const xs) (Stream.fromEffect action)
184{-# INLINE_NORMAL before #-}
185before :: Monad m => m b -> Stream m a -> Stream m a
186before action (Stream step state) = Stream step' Nothing
190 {-# INLINE_LATE step' #-}
191 step' _ Nothing = action >> return (Skip (Just state))
193 step' gst (Just st) = do
196 Yield x s -> return $ Yield x (Just s)
197 Skip s -> return $ Skip (Just s)
200-- | Like 'after', with following differences:
202-- * action @m b@ won't run if the stream is garbage collected
203-- after partial evaluation.
204-- * Monad @m@ does not require any other constraints.
205-- * has slightly better performance than 'after'.
207-- Same as the following, but with stream fusion:
209-- >>> afterUnsafe action xs = xs <> Stream.nilM action
213{-# INLINE_NORMAL afterUnsafe #-}
214afterUnsafe :: Monad m => m b -> Stream m a -> Stream m a
215afterUnsafe action (Stream step state) = Stream step' state
219 {-# INLINE_LATE step' #-}
223 Yield x s -> return $ Yield x s
224 Skip s -> return $ Skip s
225 Stop -> action >> return Stop
227-- | Run the action @IO b@ whenever the stream is evaluated to completion, or
228-- if it is garbage collected after a partial lazy evaluation.
230-- The semantics of the action @IO b@ are similar to the semantics of cleanup
231-- action in 'bracketIO'.
233-- /See also 'afterUnsafe'/
235{-# INLINE_NORMAL afterIO #-}
237 => IO b -> Stream m a -> Stream m a
238afterIO action (Stream step state) = Stream step' Nothing
242 {-# INLINE_LATE step' #-}
244 ref <- liftIO $ newIOFinalizer action
245 return $ Skip $ Just (state, ref)
246 step' gst (Just (st, ref)) = do
249 Yield x s -> return $ Yield x (Just (s, ref))
250 Skip s -> return $ Skip (Just (s, ref))
255-- XXX For high performance error checks in busy streams we may need another
256-- Error constructor in step.
258-- | Run the action @m b@ if the stream evaluation is aborted due to an
259-- exception. The exception is not caught, simply rethrown.
261-- /Inhibits stream fusion/
263{-# INLINE_NORMAL onException #-}
264onException :: MonadCatch m => m b -> Stream m a -> Stream m a
265onException action stream =
267 (return ()) -- before
269 (\_ (e :: MC.SomeException) _ -> nilM (action >> MC.throwM e))
273{-# INLINE_NORMAL _onException #-}
274_onException :: MonadCatch m => m b -> Stream m a -> Stream m a
275_onException action (Stream step state) = Stream step' state
279 {-# INLINE_LATE step' #-}
281 res <- step gst st `MC.onException` action
283 Yield x s -> return $ Yield x s
284 Skip s -> return $ Skip s
287-- | Like 'bracket' but with following differences:
289-- * alloc action @m b@ runs with async exceptions enabled
290-- * cleanup action @b -> m c@ won't run if the stream is garbage collected
291-- after partial evaluation.
292-- * has slightly better performance than 'bracketIO'.
294-- /Inhibits stream fusion/
298{-# INLINE_NORMAL bracketUnsafe #-}
299bracketUnsafe :: MonadCatch m
300 => m b -> (b -> m c) -> (b -> Stream m a) -> Stream m a
301bracketUnsafe bef aft =
305 (\a (e :: SomeException) _ -> nilM (aft a >> MC.throwM e))
308-- For a use case of this see the "streamly-process" package. It needs to kill
309-- the process in case of exception or garbage collection, but waits for the
310-- process to terminate in normal cases.
312-- | Like 'bracketIO' but can use 3 separate cleanup actions depending on the
313-- mode of termination:
315-- 1. When the stream stops normally
316-- 2. When the stream is garbage collected
317-- 3. When the stream encounters an exception
319-- @bracketIO3 before onStop onGC onException action@ runs @action@ using the
320-- result of @before@. If the stream stops, @onStop@ action is executed, if the
321-- stream is abandoned @onGC@ is executed, if the stream encounters an
322-- exception @onException@ is executed.
324-- /Inhibits stream fusion/
327{-# INLINE_NORMAL bracketIO3 #-}
328bracketIO3 :: (MonadIO m, MonadCatch m) =>
335bracketIO3 bef aft onExc onGC =
339 (\a (e :: SomeException) _ -> onExc a >> return (nilM (MC.throwM e)))
343-- | Run the alloc action @IO b@ with async exceptions disabled but keeping
344-- blocking operations interruptible (see 'Control.Exception.mask'). Use the
345-- output @b@ as input to @b -> Stream m a@ to generate an output stream.
347-- @b@ is usually a resource under the IO monad, e.g. a file handle, that
348-- requires a cleanup after use. The cleanup action @b -> IO c@, runs whenever
349-- the stream ends normally, due to a sync or async exception or if it gets
350-- garbage collected after a partial lazy evaluation.
352-- 'bracketIO' only guarantees that the cleanup action runs, and it runs with
353-- async exceptions enabled. The action must ensure that it can successfully
354-- cleanup the resource in the face of sync or async exceptions.
356-- When the stream ends normally or on a sync exception, cleanup action runs
357-- immediately in the current thread context, whereas in other cases it runs in
358-- the GC context, therefore, cleanup may be delayed until the GC gets to run.
360-- /See also: 'bracketUnsafe'/
362-- /Inhibits stream fusion/
364{-# INLINE bracketIO #-}
365bracketIO :: (MonadIO m, MonadCatch m)
366 => IO b -> (b -> IO c) -> (b -> Stream m a) -> Stream m a
367bracketIO bef aft = bracketIO3 bef aft aft aft
369data BracketState s v = BracketInit | BracketRun s v
371-- | Alternate (custom) implementation of 'bracket'.
373{-# INLINE_NORMAL _bracket #-}
374_bracket :: MonadCatch m
375 => m b -> (b -> m c) -> (b -> Stream m a) -> Stream m a
376_bracket bef aft bet = Stream step' BracketInit
380 {-# INLINE_LATE step' #-}
381 step' _ BracketInit = bef >>= \x -> return (Skip (BracketRun (bet x) x))
383 -- NOTE: It is important to use UnStream instead of the Stream pattern
384 -- here, otherwise we get huge perf degradation, see note in concatMap.
385 step' gst (BracketRun (UnStream step state) v) = do
386 -- res <- step gst state `MC.onException` aft v
387 res <- inline MC.try $ step gst state
389 Left (e :: SomeException) -> aft v >> MC.throwM e >> return Stop
391 Yield x s -> return $ Yield x (BracketRun (Stream step s) v)
392 Skip s -> return $ Skip (BracketRun (Stream step s) v)
393 Stop -> aft v >> return Stop
395-- | Like 'finally' with following differences:
397-- * action @m b@ won't run if the stream is garbage collected
398-- after partial evaluation.
399-- * has slightly better performance than 'finallyIO'.
401-- /Inhibits stream fusion/
405{-# INLINE finallyUnsafe #-}
406finallyUnsafe :: MonadCatch m => m b -> Stream m a -> Stream m a
407finallyUnsafe action xs = bracketUnsafe (return ()) (const action) (const xs)
409-- | Run the action @IO b@ whenever the stream stream stops normally, aborts
410-- due to an exception or if it is garbage collected after a partial lazy
413-- The semantics of running the action @IO b@ are similar to the cleanup action
414-- semantics described in 'bracketIO'.
416-- >>> finallyIO release = Stream.bracketIO (return ()) (const release)
418-- /See also 'finallyUnsafe'/
420-- /Inhibits stream fusion/
422{-# INLINE finallyIO #-}
423finallyIO :: (MonadIO m, MonadCatch m) => IO b -> Stream m a -> Stream m a
424finallyIO action xs = bracketIO3 (return ()) act act act (const xs)
427-- | Like 'handle' but the exception handler is also provided with the stream
428-- that generated the exception as input. The exception handler can thus
429-- re-evaluate the stream to retry the action that failed. The exception
430-- handler can again call 'ghandle' on it to retry the action multiple times.
432-- This is highly experimental. In a stream of actions we can map the stream
433-- with a retry combinator to retry each action on failure.
435-- /Inhibits stream fusion/
439{-# INLINE_NORMAL ghandle #-}
440ghandle :: (MonadCatch m, Exception e)
441 => (e -> Stream m a -> Stream m a) -> Stream m a -> Stream m a
443 gbracket_ (return ()) return (const f) (inline MC.try) (const stream)
445-- | When evaluating a stream if an exception occurs, stream evaluation aborts
446-- and the specified exception handler is run with the exception as argument.
448-- /Inhibits stream fusion/
450{-# INLINE_NORMAL handle #-}
451handle :: (MonadCatch m, Exception e)
452 => (e -> Stream m a) -> Stream m a -> Stream m a
454 gbracket_ (return ()) return (\_ e _ -> f e) (inline MC.try) (const stream)
456-- | Alternate (custom) implementation of 'handle'.
458{-# INLINE_NORMAL _handle #-}
459_handle :: (MonadCatch m, Exception e)
460 => (e -> Stream m a) -> Stream m a -> Stream m a
461_handle f (Stream step state) = Stream step' (Left state)
465 {-# INLINE_LATE step' #-}
466 step' gst (Left st) = do
467 res <- inline MC.try $ step gst st
469 Left e -> return $ Skip $ Right (f e)
471 Yield x s -> return $ Yield x (Left s)
472 Skip s -> return $ Skip (Left s)
475 step' gst (Right (UnStream step1 st)) = do
478 Yield x s -> return $ Yield x (Right (Stream step1 s))
479 Skip s -> return $ Skip (Right (Stream step1 s))
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list