{-# LANGUAGE RecordWildCards #-}

module Network.HTTP2.Arch.Queue where

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

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 = IO () -> (() -> IO ()) -> (() -> IO ()) -> IO ()
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket IO ()
setup () -> IO ()
forall p. p -> IO ()
teardown ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ ->
    IO ThreadId -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ThreadId -> IO ()) -> (IO () -> IO ThreadId) -> IO () -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO () -> IO ThreadId
forkIO (IO () -> IO ()) -> IO () -> IO ()
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 = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TQueue (Output Stream) -> Output Stream -> STM ()
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 = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TQueue Control -> Control -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue TQueue Control
ctlQ Control
ctl

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