{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Network.HTTP2.Client.Run where

import Control.Concurrent.STM (check)
import UnliftIO.Async
import UnliftIO.Concurrent
import qualified UnliftIO.Exception as E
import UnliftIO.STM

import Imports
import Network.HTTP2.Arch
import Network.HTTP2.Client.Types
import Network.HTTP2.Frame

-- | Client configuration
data ClientConfig = ClientConfig {
    ClientConfig -> Scheme
scheme     :: Scheme    -- ^ https or http
  , ClientConfig -> Scheme
authority  :: Authority -- ^ Server name
  , ClientConfig -> Int
cacheLimit :: Int       -- ^ How many pushed responses are contained in the cache
  }

-- | Running HTTP/2 client.
run :: ClientConfig -> Config -> Client a -> IO a
run :: forall a. ClientConfig -> Config -> Client a -> IO a
run ClientConfig{Int
Scheme
scheme :: ClientConfig -> Scheme
authority :: ClientConfig -> Scheme
cacheLimit :: ClientConfig -> Int
scheme :: Scheme
authority :: Scheme
cacheLimit :: Int
..} conf :: Config
conf@Config{Int
Buffer
Manager
Int -> IO Scheme
PositionReadMaker
Scheme -> IO ()
confWriteBuffer :: Buffer
confBufferSize :: Int
confSendAll :: Scheme -> IO ()
confReadN :: Int -> IO Scheme
confPositionReadMaker :: PositionReadMaker
confTimeoutManager :: Manager
confWriteBuffer :: Config -> Buffer
confBufferSize :: Config -> Int
confSendAll :: Config -> Scheme -> IO ()
confReadN :: Config -> Int -> IO Scheme
confPositionReadMaker :: Config -> PositionReadMaker
confTimeoutManager :: Config -> Manager
..} Client a
client = do
    RoleInfo
clientInfo <- Scheme -> Scheme -> Int -> IO RoleInfo
newClientInfo Scheme
scheme Scheme
authority Int
cacheLimit
    Context
ctx <- RoleInfo -> Int -> IO Context
newContext RoleInfo
clientInfo Int
confBufferSize
    Manager
mgr <- Manager -> IO Manager
start Manager
confTimeoutManager
    let runBackgroundThreads :: IO ()
runBackgroundThreads = do
            let runReceiver :: IO ()
runReceiver = Context -> Config -> IO ()
frameReceiver Context
ctx Config
conf
                runSender :: IO ()
runSender   = Context -> Config -> Manager -> IO ()
frameSender   Context
ctx Config
conf Manager
mgr
            IO () -> IO () -> IO ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m ()
concurrently_ IO ()
runReceiver IO ()
runSender
    Config -> Context -> IO ()
exchangeSettings Config
conf Context
ctx
    let runClient :: IO a
runClient = do
            a
x <- Client a
client Client a -> Client a
forall a b. (a -> b) -> a -> b
$ Context
-> Manager
-> Scheme
-> Scheme
-> Request
-> (Response -> IO a)
-> IO a
forall a.
Context
-> Manager
-> Scheme
-> Scheme
-> Request
-> (Response -> IO a)
-> IO a
sendRequest Context
ctx Manager
mgr Scheme
scheme Scheme
authority
            let frame :: Scheme
frame = Int -> ErrorCode -> Scheme -> Scheme
goawayFrame Int
0 ErrorCode
NoError Scheme
"graceful closing"
            TQueue Control -> Control -> IO ()
enqueueControl (Context -> TQueue Control
controlQ Context
ctx) (Control -> IO ()) -> Control -> IO ()
forall a b. (a -> b) -> a -> b
$ Maybe SettingsList -> [Scheme] -> Control
CFrames Maybe SettingsList
forall a. Maybe a
Nothing [Scheme
frame]
            a -> IO a
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x
    Either () a
ex <- IO () -> IO a -> IO (Either () a)
forall (m :: * -> *) a b.
MonadUnliftIO m =>
m a -> m b -> m (Either a b)
race IO ()
runBackgroundThreads IO a
runClient IO (Either () a) -> IO () -> IO (Either () a)
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`E.finally` Manager -> IO ()
stop Manager
mgr
    case Either () a
ex of
      Left () -> IO a
forall a. HasCallStack => a
undefined -- never reach
      Right a
x -> a -> IO a
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x

sendRequest :: Context -> Manager -> Scheme -> Authority -> Request -> (Response -> IO a) -> IO a
sendRequest :: forall a.
Context
-> Manager
-> Scheme
-> Scheme
-> Request
-> (Response -> IO a)
-> IO a
sendRequest ctx :: Context
ctx@Context{IORef Bool
IORef Int
IORef (Maybe Int)
IORef (Maybe SettingsList)
IORef Settings
DynamicTable
TVar Int
TQueue Control
TQueue (Output Stream)
Rate
StreamTable
RoleInfo
Role
controlQ :: Context -> TQueue Control
role :: Role
roleInfo :: RoleInfo
myFirstSettings :: IORef Bool
myPendingAlist :: IORef (Maybe SettingsList)
mySettings :: IORef Settings
peerSettings :: IORef Settings
streamTable :: StreamTable
concurrency :: IORef Int
continued :: IORef (Maybe Int)
myStreamId :: IORef Int
peerStreamId :: IORef Int
outputBufferLimit :: IORef Int
outputQ :: TQueue (Output Stream)
outputQStreamID :: TVar Int
controlQ :: TQueue Control
encodeDynamicTable :: DynamicTable
decodeDynamicTable :: DynamicTable
txConnectionWindow :: TVar Int
rxConnectionInc :: IORef Int
pingRate :: Rate
settingsRate :: Rate
emptyFrameRate :: Rate
role :: Context -> Role
roleInfo :: Context -> RoleInfo
myFirstSettings :: Context -> IORef Bool
myPendingAlist :: Context -> IORef (Maybe SettingsList)
mySettings :: Context -> IORef Settings
peerSettings :: Context -> IORef Settings
streamTable :: Context -> StreamTable
concurrency :: Context -> IORef Int
continued :: Context -> IORef (Maybe Int)
myStreamId :: Context -> IORef Int
peerStreamId :: Context -> IORef Int
outputBufferLimit :: Context -> IORef Int
outputQ :: Context -> TQueue (Output Stream)
outputQStreamID :: Context -> TVar Int
encodeDynamicTable :: Context -> DynamicTable
decodeDynamicTable :: Context -> DynamicTable
txConnectionWindow :: Context -> TVar Int
rxConnectionInc :: Context -> IORef Int
pingRate :: Context -> Rate
settingsRate :: Context -> Rate
emptyFrameRate :: Context -> Rate
..} Manager
mgr Scheme
scheme Scheme
auth (Request OutObj
req) Response -> IO a
processResponse = do
    -- Checking push promises
    let hdr0 :: [Header]
hdr0 = OutObj -> [Header]
outObjHeaders OutObj
req
        method :: Scheme
method = Scheme -> Maybe Scheme -> Scheme
forall a. a -> Maybe a -> a
fromMaybe ([Char] -> Scheme
forall a. HasCallStack => [Char] -> a
error [Char]
"sendRequest:method") (Maybe Scheme -> Scheme) -> Maybe Scheme -> Scheme
forall a b. (a -> b) -> a -> b
$ HeaderName -> [Header] -> Maybe Scheme
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
":method" [Header]
hdr0
        path :: Scheme
path   = Scheme -> Maybe Scheme -> Scheme
forall a. a -> Maybe a -> a
fromMaybe ([Char] -> Scheme
forall a. HasCallStack => [Char] -> a
error [Char]
"sendRequest:path") (Maybe Scheme -> Scheme) -> Maybe Scheme -> Scheme
forall a b. (a -> b) -> a -> b
$ HeaderName -> [Header] -> Maybe Scheme
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
":path" [Header]
hdr0
    Maybe Stream
mstrm0 <- Scheme -> Scheme -> RoleInfo -> IO (Maybe Stream)
lookupCache Scheme
method Scheme
path RoleInfo
roleInfo
    Stream
strm <- case Maybe Stream
mstrm0 of
      Maybe Stream
Nothing -> do
          -- Arch/Sender is originally implemented for servers where
          -- the ordering of responses can be out-of-order.
          -- But for clients, the ordering must be maintained.
          -- To implement this, 'outputQStreamID' is used.
          -- Also, for 'OutBodyStreaming', TBQ must not be empty
          -- when its 'Output' is enqueued into 'outputQ'.
          -- Otherwise, it would be re-enqueue because of empty
          -- resulting in out-of-order.
          -- To implement this, 'tbqNonMmpty' is used.
          let hdr1 :: [Header]
hdr1 | Scheme
scheme Scheme -> Scheme -> Bool
forall a. Eq a => a -> a -> Bool
/= Scheme
"" = (HeaderName
":scheme", Scheme
scheme) Header -> [Header] -> [Header]
forall a. a -> [a] -> [a]
: [Header]
hdr0
                   | Bool
otherwise    = [Header]
hdr0
              hdr2 :: [Header]
hdr2 | Scheme
auth Scheme -> Scheme -> Bool
forall a. Eq a => a -> a -> Bool
/= Scheme
"" = (HeaderName
":authority", Scheme
auth) Header -> [Header] -> [Header]
forall a. a -> [a] -> [a]
: [Header]
hdr1
                   | Bool
otherwise  = [Header]
hdr1
              req' :: OutObj
req' = OutObj
req { outObjHeaders :: [Header]
outObjHeaders = [Header]
hdr2 }
          Int
sid <- Context -> IO Int
getMyNewStreamId Context
ctx
          Stream
newstrm <- Context -> Int -> FrameType -> IO Stream
openStream Context
ctx Int
sid FrameType
FrameHeaders
          case OutObj -> OutBody
outObjBody OutObj
req of
            OutBodyStreaming (Builder -> IO ()) -> IO () -> IO ()
strmbdy -> do
                TBQueue StreamingChunk
tbq <- Natural -> IO (TBQueue StreamingChunk)
forall (m :: * -> *) a. MonadIO m => Natural -> m (TBQueue a)
newTBQueueIO Natural
10 -- fixme: hard coding: 10
                TVar Bool
tbqNonMmpty <- Bool -> IO (TVar Bool)
forall (m :: * -> *) a. MonadIO m => a -> m (TVar a)
newTVarIO Bool
False
                Manager -> IO () -> IO ()
forkManaged Manager
mgr (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
                    let push :: Builder -> m ()
push Builder
b = STM () -> m ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM () -> m ()) -> STM () -> m ()
forall a b. (a -> b) -> a -> b
$ do
                            TBQueue StreamingChunk -> StreamingChunk -> STM ()
forall a. TBQueue a -> a -> STM ()
writeTBQueue TBQueue StreamingChunk
tbq (Builder -> StreamingChunk
StreamingBuilder Builder
b)
                            TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar Bool
tbqNonMmpty Bool
True
                        flush :: IO ()
flush  = STM () -> IO ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TBQueue StreamingChunk -> StreamingChunk -> STM ()
forall a. TBQueue a -> a -> STM ()
writeTBQueue TBQueue StreamingChunk
tbq StreamingChunk
StreamingFlush
                    (Builder -> IO ()) -> IO () -> IO ()
strmbdy Builder -> IO ()
forall {m :: * -> *}. MonadIO m => Builder -> m ()
push IO ()
flush
                    STM () -> IO ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TBQueue StreamingChunk -> StreamingChunk -> STM ()
forall a. TBQueue a -> a -> STM ()
writeTBQueue TBQueue StreamingChunk
tbq StreamingChunk
StreamingFinished
                STM () -> IO ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
                    Int
sidOK <- TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar TVar Int
outputQStreamID
                    Bool
ready <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar TVar Bool
tbqNonMmpty
                    Bool -> STM ()
check (Int
sidOK Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
sid Bool -> Bool -> Bool
&& Bool
ready)
                    TVar Int -> Int -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar Int
outputQStreamID (Int
sid Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)
                    TQueue (Output Stream) -> Output Stream -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue TQueue (Output Stream)
outputQ (Output Stream -> STM ()) -> Output Stream -> STM ()
forall a b. (a -> b) -> a -> b
$ Stream
-> OutObj
-> OutputType
-> Maybe (TBQueue StreamingChunk)
-> IO ()
-> Output Stream
forall a.
a
-> OutObj
-> OutputType
-> Maybe (TBQueue StreamingChunk)
-> IO ()
-> Output a
Output Stream
newstrm OutObj
req' OutputType
OObj (TBQueue StreamingChunk -> Maybe (TBQueue StreamingChunk)
forall a. a -> Maybe a
Just TBQueue StreamingChunk
tbq) (() -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ())
            OutBody
_ -> STM () -> IO ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
                Int
sidOK <- TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar TVar Int
outputQStreamID
                Bool -> STM ()
check (Int
sidOK Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
sid)
                TVar Int -> Int -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar Int
outputQStreamID (Int
sid Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)
                TQueue (Output Stream) -> Output Stream -> STM ()
forall a. TQueue a -> a -> STM ()
writeTQueue TQueue (Output Stream)
outputQ (Output Stream -> STM ()) -> Output Stream -> STM ()
forall a b. (a -> b) -> a -> b
$ Stream
-> OutObj
-> OutputType
-> Maybe (TBQueue StreamingChunk)
-> IO ()
-> Output Stream
forall a.
a
-> OutObj
-> OutputType
-> Maybe (TBQueue StreamingChunk)
-> IO ()
-> Output a
Output Stream
newstrm OutObj
req' OutputType
OObj Maybe (TBQueue StreamingChunk)
forall a. Maybe a
Nothing (() -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ())
          Stream -> IO Stream
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Stream
newstrm
      Just Stream
strm0 -> Stream -> IO Stream
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Stream
strm0
    InpObj
rsp <- MVar InpObj -> IO InpObj
forall (m :: * -> *) a. MonadIO m => MVar a -> m a
takeMVar (MVar InpObj -> IO InpObj) -> MVar InpObj -> IO InpObj
forall a b. (a -> b) -> a -> b
$ Stream -> MVar InpObj
streamInput Stream
strm
    Response -> IO a
processResponse (Response -> IO a) -> Response -> IO a
forall a b. (a -> b) -> a -> b
$ InpObj -> Response
Response InpObj
rsp

exchangeSettings :: Config -> Context -> IO ()
exchangeSettings :: Config -> Context -> IO ()
exchangeSettings Config
conf ctx :: Context
ctx@Context{IORef Bool
IORef Int
IORef (Maybe Int)
IORef (Maybe SettingsList)
IORef Settings
DynamicTable
TVar Int
TQueue Control
TQueue (Output Stream)
Rate
StreamTable
RoleInfo
Role
controlQ :: Context -> TQueue Control
role :: Context -> Role
roleInfo :: Context -> RoleInfo
myFirstSettings :: Context -> IORef Bool
myPendingAlist :: Context -> IORef (Maybe SettingsList)
mySettings :: Context -> IORef Settings
peerSettings :: Context -> IORef Settings
streamTable :: Context -> StreamTable
concurrency :: Context -> IORef Int
continued :: Context -> IORef (Maybe Int)
myStreamId :: Context -> IORef Int
peerStreamId :: Context -> IORef Int
outputBufferLimit :: Context -> IORef Int
outputQ :: Context -> TQueue (Output Stream)
outputQStreamID :: Context -> TVar Int
encodeDynamicTable :: Context -> DynamicTable
decodeDynamicTable :: Context -> DynamicTable
txConnectionWindow :: Context -> TVar Int
rxConnectionInc :: Context -> IORef Int
pingRate :: Context -> Rate
settingsRate :: Context -> Rate
emptyFrameRate :: Context -> Rate
role :: Role
roleInfo :: RoleInfo
myFirstSettings :: IORef Bool
myPendingAlist :: IORef (Maybe SettingsList)
mySettings :: IORef Settings
peerSettings :: IORef Settings
streamTable :: StreamTable
concurrency :: IORef Int
continued :: IORef (Maybe Int)
myStreamId :: IORef Int
peerStreamId :: IORef Int
outputBufferLimit :: IORef Int
outputQ :: TQueue (Output Stream)
outputQStreamID :: TVar Int
controlQ :: TQueue Control
encodeDynamicTable :: DynamicTable
decodeDynamicTable :: DynamicTable
txConnectionWindow :: TVar Int
rxConnectionInc :: IORef Int
pingRate :: Rate
settingsRate :: Rate
emptyFrameRate :: Rate
..} = do
    [Scheme]
frames <- Config -> Context -> IO [Scheme]
updateMySettings Config
conf Context
ctx
    let setframe :: Control
setframe = Maybe SettingsList -> [Scheme] -> Control
CFrames Maybe SettingsList
forall a. Maybe a
Nothing (Scheme
connectionPrefaceScheme -> [Scheme] -> [Scheme]
forall a. a -> [a] -> [a]
:[Scheme]
frames)
    TQueue Control -> Control -> IO ()
enqueueControl TQueue Control
controlQ Control
setframe