{-# LANGUAGE RecordWildCards #-}

module Network.HTTP2.Arch.Queue where

import UnliftIO.Concurrent (forkIO)
import UnliftIO.Exception (bracket)
import UnliftIO.STM

import Imports
import Network.HTTP2.Arch.Manager
import Network.HTTP2.Arch.Types

{-# INLINE forkAndEnqueueWhenReady #-}
forkAndEnqueueWhenReady :: IO () -> TQueue (Output Stream) -> Output Stream -> Manager -> IO ()
forkAndEnqueueWhenReady :: IO ()
-> TQueue (Output Stream) -> Output Stream -> Manager -> IO ()
forkAndEnqueueWhenReady IO ()
wait TQueue (Output Stream)
outQ Output Stream
out Manager
mgr = forall (m :: * -> *) a b c.
MonadUnliftIO m =>
m a -> (a -> m b) -> (a -> m c) -> m c
bracket IO ()
setup forall {p}. p -> IO ()
teardown forall a b. (a -> b) -> a -> b
$ \()
_ ->
    forall (f :: * -> *) a. Functor f => f a -> f ()
void forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *). MonadUnliftIO m => m () -> m ThreadId
forkIO forall a b. (a -> b) -> a -> b
$ do
        IO ()
wait
        TQueue (Output Stream) -> Output Stream -> IO ()
enqueueOutput TQueue (Output Stream)
outQ Output Stream
out
  where
    setup :: IO ()
setup = Manager -> IO ()
addMyId Manager
mgr
    teardown :: p -> IO ()
teardown p
_ = Manager -> IO ()
deleteMyId Manager
mgr

{-# INLINE enqueueOutput #-}
enqueueOutput :: TQueue (Output Stream) -> Output Stream -> IO ()
enqueueOutput :: TQueue (Output Stream) -> Output Stream -> IO ()
enqueueOutput TQueue (Output Stream)
outQ Output Stream
out = forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically forall a b. (a -> b) -> a -> b
$ forall a. TQueue a -> a -> STM ()
writeTQueue TQueue (Output Stream)
outQ Output Stream
out

{-# INLINE enqueueControl #-}
enqueueControl :: TQueue Control -> Control -> IO ()
enqueueControl :: TQueue Control -> Control -> IO ()
enqueueControl TQueue Control
ctlQ Control
ctl = forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically forall a b. (a -> b) -> a -> b
$ forall a. TQueue a -> a -> STM ()
writeTQueue TQueue Control
ctlQ Control
ctl

----------------------------------------------------------------