packages feed

http-semantics 0.2.1 → 0.5.0

raw patch · 11 files changed

Files

ChangeLog.md view
@@ -1,5 +1,52 @@ # ChangeLog for http-semantics +## 0.5.0++* Let a client give up on a request+  [#20](https://github.com/kazu-yamamoto/http-semantics/pull/20)+* Keep the streaming request and response makers from inlining+  [#21](https://github.com/kazu-yamamoto/http-semantics/pull/21)+* Drop auxTimeHandle and the time-manager dependency+  [#22](https://github.com/kazu-yamamoto/http-semantics/pull/22)+* Share the errors of HTTP/2 and HTTP/3, and give up on a request with a result+  [#23](https://github.com/kazu-yamamoto/http-semantics/pull/23)+* Let defaultReadNWith take the STM action last and give up with Left+  [#24](https://github.com/kazu-yamamoto/http-semantics/pull/24)+* Let RequestIsUnprocessed carry Maybe StreamId, for a request with no stream yet+  [#25](https://github.com/kazu-yamamoto/http-semantics/pull/25)+* Use unsafeBufferIO instead of deprecated bufferIO+  [#26](https://github.com/kazu-yamamoto/http-semantics/pull/26)+* Take the STM give-up last in sendRequestWith+  [#27](https://github.com/kazu-yamamoto/http-semantics/pull/27)++## 0.4.2++* `defaultReadNWith` is `defaultReadN` with an `STM` action beside each+  receive.  When it fires the read answers with the empty string, which is+  what `ReadN` already means by end of input, so a reader blocked in it can+  be given up on without closing the socket under it or throwing into it --+  neither of which works everywhere.++## 0.4.1++* Add `auxSendInformational` to the server `Aux` for sending 1xx informational+  responses (e.g. 103 Early Hints) ahead of the final response.++## 0.4.0++* This version is idential to v0.3.1 which includes breaking changes+  and thus is deprecated.++## 0.3.1++* Adding defaultAux and auxSendPing for client.+* Adding defaultAux for server.++## 0.3.0++* Breaking change: fillFileBodyGetNext takes Sentinel instead of+  IO () to close files on time.+ ## 0.2.1  * Add outBodyCancel to OutBodyIface
Network/HTTP/Semantics/Client.hs view
@@ -17,7 +17,8 @@     requestBuilder,      -- ** Generalized streaming interface-    OutBodyIface(..),+    OutBodyIface (..),+    StreamTerminated (..),     requestStreamingIface,      -- ** Trailers maker@@ -26,6 +27,9 @@     defaultTrailersMaker,     setRequestTrailersMaker, +    -- ** Giving up+    sendRequestWith,+     -- * Response     Response, @@ -39,7 +43,9 @@      -- * Aux     Aux,+    defaultAux,     auxPossibleClientStreams,+    auxSendPing,      -- * Types     Scheme,@@ -53,6 +59,9 @@     module Network.HTTP.Semantics.File, ) where +import Control.Concurrent.STM (STM, atomically, orElse, retry)+import Control.Monad (void)+import qualified Control.Exception as E import Data.ByteString (ByteString) import Data.ByteString.Builder (Builder) import Data.IORef (readIORef)@@ -76,19 +85,19 @@  -- | Creating request without body. requestNoBody :: Method -> Path -> RequestHeaders -> Request-requestNoBody m p hdr = Request $ OutObj hdr' OutBodyNone defaultTrailersMaker+requestNoBody m p hdr = Request $ OutObj hdr' OutBodyNone defaultTrailersMaker retry   where     hdr' = addHeaders m p hdr  -- | Creating request with file. requestFile :: Method -> Path -> RequestHeaders -> FileSpec -> Request-requestFile m p hdr fileSpec = Request $ OutObj hdr' (OutBodyFile fileSpec) defaultTrailersMaker+requestFile m p hdr fileSpec = Request $ OutObj hdr' (OutBodyFile fileSpec) defaultTrailersMaker retry   where     hdr' = addHeaders m p hdr  -- | Creating request with builder. requestBuilder :: Method -> Path -> RequestHeaders -> Builder -> Request-requestBuilder m p hdr builder = Request $ OutObj hdr' (OutBodyBuilder builder) defaultTrailersMaker+requestBuilder m p hdr builder = Request $ OutObj hdr' (OutBodyBuilder builder) defaultTrailersMaker retry   where     hdr' = addHeaders m p hdr @@ -99,9 +108,12 @@     -> RequestHeaders     -> ((Builder -> IO ()) -> IO () -> IO ())     -> Request-requestStreaming m p hdr strmbdy = Request $ OutObj hdr' (OutBodyStreaming strmbdy) defaultTrailersMaker+requestStreaming m p hdr strmbdy = Request $ OutObj hdr' (OutBodyStreaming strmbdy) defaultTrailersMaker retry   where     hdr' = addHeaders m p hdr+-- Not inlined: GHC 9.12.4 and 9.14.1 may store a never-returning body+-- unevaluated in the strict field, read as the first constructor (ghc#27857).+{-# NOINLINE requestStreaming #-}  -- | Like 'requestStreaming', but run the action with exceptions masked requestStreamingUnmask@@ -120,9 +132,12 @@     -> RequestHeaders     -> (OutBodyIface -> IO ())     -> Request-requestStreamingIface m p hdr strmbdy = Request $ OutObj hdr' (OutBodyStreamingIface strmbdy) defaultTrailersMaker+requestStreamingIface m p hdr strmbdy = Request $ OutObj hdr' (OutBodyStreamingIface strmbdy) defaultTrailersMaker retry   where     hdr' = addHeaders m p hdr+-- Not inlined: GHC 9.12.4 and 9.14.1 may store a never-returning body+-- unevaluated in the strict field, read as the first constructor (ghc#27857).+{-# NOINLINE requestStreamingIface #-}  addHeaders :: Method -> Path -> RequestHeaders -> RequestHeaders addHeaders m p hdr = (":method", m) : (":path", p) : hdr@@ -130,6 +145,26 @@ -- | Setting 'TrailersMaker' to 'Response'. setRequestTrailersMaker :: Request -> TrailersMaker -> Request setRequestTrailersMaker (Request req) tm = Request req{outObjTrailers = tm}++-- | Sending a request and handling its response as 'SendRequest' does,+--   giving up on it once the 'STM' action, the last argument,+--   succeeds: while its stream is opened, while it is sent,+--   while the response is waited for, and while the handler reads the+--   body.  The stream is reset and what the action gave is returned as+--   'Left'.  A request already done by then is not given up on.  The+--   action is run wherever the request waits, and once more for what it+--   gave: it should go on succeeding once it has, as a deadline does.+--+-- @since 0.5.0+sendRequestWith+    :: SendRequest -> Request -> (Response -> IO r) -> STM g -> IO (Either g r)+sendRequestWith send req handler giveUp = do+    r <- E.try $ send (setRequestGiveUp req $ void giveUp) handler+    case r of+        Right x -> return $ Right x+        Left RequestGivenUp -> do+            mg <- atomically $ (Just <$> giveUp) `orElse` return Nothing+            maybe (E.throwIO RequestGivenUp) (return . Left) mg  ---------------------------------------------------------------- 
Network/HTTP/Semantics/Client/Internal.hs view
@@ -2,8 +2,16 @@     Request (..),     Response (..),     Aux (..),+    defaultAux,++    -- * Giving up+    setRequestGiveUp,+    RequestGivenUp (..), ) where +import Control.Concurrent.STM (STM)+import Control.Exception (Exception)+ import Network.HTTP.Semantics.Types (InpObj (..), OutObj (..))  -- | Request from client.@@ -16,4 +24,32 @@ data Aux = Aux     { auxPossibleClientStreams :: IO Int     -- ^ How many streams can be created without blocking.+    , auxSendPing :: IO ()+    -- ^ Sending a ping.     }++defaultAux :: Aux+defaultAux =+    Aux+        { auxPossibleClientStreams = return 0+        , auxSendPing = return ()+        }++-- | Giving up on the request once the STM action succeeds: the stream is+--   reset, and the wait for its response, or for its body, throws+--   'RequestGivenUp'.  'Network.HTTP.Semantics.Client.sendRequestWith'+--   is how a user gives up.+--+-- @since 0.5.0+setRequestGiveUp :: Request -> STM () -> Request+setRequestGiveUp (Request req) giveUp = Request req{outObjGiveUp = giveUp}++-- | What a library throws where it gave up on a request, for+--   'Network.HTTP.Semantics.Client.sendRequestWith' to turn into a+--   result.+--+-- @since 0.5.0+data RequestGivenUp = RequestGivenUp+    deriving (Show)++instance Exception RequestGivenUp
+ Network/HTTP/Semantics/Error.hs view
@@ -0,0 +1,151 @@+-- | Errors which end an HTTP connection or stream abnormally, the same+--   over HTTP\/2 and HTTP\/3.+--+--   Only what ended abnormally is here.  A connection closed with no+--   error, stopped, or given up on by the user is a normal end: it is+--   returned, not thrown.+--+--   @since 0.5.0+module Network.HTTP.Semantics.Error (+    -- * Errors+    HTTPError (..),+    StreamId,+    ReasonPhrase,+    isRetryable,++    -- * Error codes+    HTTPErrorCode (..),+    ErrorKind (..),+    ErrorSpace (..),+    http2ErrorCode,+    http3ErrorCode,+    quicTransportErrorCode,+) where++import qualified Control.Exception as E+import Data.ByteString.Short (ShortByteString)+import Data.Int (Int64)+import Data.Word (Word64)++-- | A stream identifier, of HTTP\/2 or of QUIC.+type StreamId = Int64++-- | Why, in words, for the peer or a log.+type ReasonPhrase = ShortByteString++-- | An HTTP connection or stream which ended abnormally.+data HTTPError+    = -- | The peer is gone, or does not send what it owes.+      ConnectionIsTimeout+    | -- | The transport broke: TCP reset, or a QUIC stateless reset.+      ConnectionIsReset+    | -- | The connection closed normally while this was waiting.+      ConnectionIsClosed+    | -- | The peer will not process this request, after its GOAWAY: it+      --   may be sent again.  The stream, if the request had got one.+      RequestIsUnprocessed (Maybe StreamId)+    | ConnectionErrorIsReceived HTTPErrorCode ReasonPhrase+    | ConnectionErrorIsSent HTTPErrorCode ReasonPhrase+    | StreamErrorIsReceived HTTPErrorCode StreamId+    | StreamErrorIsSent HTTPErrorCode StreamId ReasonPhrase+    | BadThingHappen E.SomeException+    deriving (Show)++instance E.Exception HTTPError++-- | Whether the request was not processed by the peer, and may be sent+--   again (RFC 9113, section 8.7; RFC 9114, section 4.1.1).+isRetryable :: HTTPError -> Bool+isRetryable (RequestIsUnprocessed _) = True+isRetryable (StreamErrorIsReceived code _) = errorKind code == Refused+isRetryable _ = False++-- | An error code of HTTP\/2, of HTTP\/3 or of QUIC, with what it means.+data HTTPErrorCode = HTTPErrorCode+    { errorKind :: ErrorKind+    , errorSpace :: ErrorSpace+    , errorValue :: Word64+    -- ^ The code itself, for a log.+    }+    deriving (Eq, Show)++-- | What an error code means, after RFC 9114, appendix A.4.1.+data ErrorKind+    = NotAnError+    | ProtocolViolation+    | CompressionFailure+    | InternalFailure+    | -- | Not processed: the request may be sent again.+      Refused+    | Cancelled+    | Incomplete+    | MalformedMessage+    | ConnectFailure+    | ExcessiveLoad+    | VersionFallback+    | SecurityFailure+    | TransportFailure+    | UnknownCode+    deriving (Eq, Show)++-- | Whose code it is: they overlap.+data ErrorSpace = HTTP2 | HTTP3 | QUICTransport+    deriving (Eq, Show)++-- | An HTTP\/2 error code (RFC 9113, section 7).+http2ErrorCode :: Word64 -> HTTPErrorCode+http2ErrorCode w = HTTPErrorCode kind HTTP2 w+  where+    kind = case w of+        0x0 -> NotAnError+        0x1 -> ProtocolViolation+        0x2 -> InternalFailure+        0x3 -> ProtocolViolation -- FLOW_CONTROL_ERROR+        0x4 -> ProtocolViolation -- SETTINGS_TIMEOUT+        0x5 -> ProtocolViolation -- STREAM_CLOSED+        0x6 -> ProtocolViolation -- FRAME_SIZE_ERROR+        0x7 -> Refused+        0x8 -> Cancelled+        0x9 -> CompressionFailure+        0xa -> ConnectFailure+        0xb -> ExcessiveLoad -- ENHANCE_YOUR_CALM+        0xc -> SecurityFailure+        0xd -> VersionFallback -- HTTP_1_1_REQUIRED+        _ -> UnknownCode++-- | An HTTP\/3 or QPACK error code (RFC 9114, section 8.1; RFC 9204,+--   section 6).+http3ErrorCode :: Word64 -> HTTPErrorCode+http3ErrorCode w = HTTPErrorCode kind HTTP3 w+  where+    kind = case w of+        0x100 -> NotAnError+        0x101 -> ProtocolViolation+        0x102 -> InternalFailure+        0x103 -> ProtocolViolation -- H3_STREAM_CREATION_ERROR+        0x104 -> ProtocolViolation -- H3_CLOSED_CRITICAL_STREAM+        0x105 -> ProtocolViolation -- H3_FRAME_UNEXPECTED+        0x106 -> ProtocolViolation -- H3_FRAME_ERROR+        0x107 -> ExcessiveLoad+        0x108 -> ProtocolViolation -- H3_ID_ERROR+        0x109 -> ProtocolViolation -- H3_SETTINGS_ERROR+        0x10a -> ProtocolViolation -- H3_MISSING_SETTINGS+        0x10b -> Refused -- H3_REQUEST_REJECTED+        0x10c -> Cancelled+        0x10d -> Incomplete+        0x10e -> MalformedMessage+        0x10f -> ConnectFailure+        0x110 -> VersionFallback+        0x200 -> CompressionFailure -- QPACK_DECOMPRESSION_FAILED+        0x201 -> CompressionFailure -- QPACK_ENCODER_STREAM_ERROR+        0x202 -> CompressionFailure -- QPACK_DECODER_STREAM_ERROR+        _ -> UnknownCode++-- | A QUIC transport error code (RFC 9000, section 20.1): the+--   connection failed below HTTP.+quicTransportErrorCode :: Word64 -> HTTPErrorCode+quicTransportErrorCode w = HTTPErrorCode kind QUICTransport w+  where+    kind+        | w == 0 = NotAnError+        | otherwise = TransportFailure
Network/HTTP/Semantics/FillBuf.hs view
@@ -1,6 +1,3 @@-{-# LANGUAGE NamedFieldPuns #-}-{-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-}  module Network.HTTP.Semantics.FillBuf (@@ -25,7 +22,7 @@ import Data.Int (Int64) import Data.Maybe import Foreign.Ptr (plusPtr)-import Network.ByteOrder+import Network.ByteOrder hiding (start) import Network.HTTP.Semantics.Client  ----------------------------------------------------------------@@ -35,7 +32,7 @@ -- In @http2@ this will be used to construct a single HTTP2 @DATA@ frame -- (see discussion of the maximum number of bytes, below). type DynaNext =-       Buffer+    Buffer     -- ^ Write buffer     -> Int     -- ^ Maximum number of bytes we are allowed to write@@ -76,15 +73,14 @@ -- | Action to run prior to terminating the stream type CleanupStream = IO () -data IsEndOfStream =-    -- | The stream is not yet terminated-    NotEndOfStream--    -- | The stream is terminated-    ---    -- In addition to indicating that the stream is terminated, we can also-    -- specify an optional `Cleanup` handler to be run.-  | EndOfStream (Maybe CleanupStream)+data IsEndOfStream+    = -- | The stream is not yet terminated+      NotEndOfStream+    | -- | The stream is terminated+      --+      -- In addition to indicating that the stream is terminated, we can also+      -- specify an optional `Cleanup` handler to be run.+      EndOfStream (Maybe CleanupStream)  ---------------------------------------------------------------- @@ -94,11 +90,11 @@     return $ nextForBuilder len signal  fillFileBodyGetNext-    :: PositionRead -> FileOffset -> ByteCount -> IO () -> DynaNext-fillFileBodyGetNext pread start bytecount refresh buf room = do+    :: PositionRead -> FileOffset -> ByteCount -> Sentinel -> DynaNext+fillFileBodyGetNext pread start bytecount sentinel buf room = do     len <- pread start (mini room bytecount) buf     let len' = fromIntegral len-    return $ nextForFile len' pread (start + len) (bytecount - len) refresh+    nextForFile len' pread (start + len) (bytecount - len) sentinel  fillStreamBodyGetNext :: IO (Maybe StreamingChunk) -> DynaNext fillStreamBodyGetNext takeQ = loop 0@@ -116,10 +112,10 @@ fillBufBuilderOne minReq writer buf0 room = do     if room >= minReq         then do-          (len, signal) <- writer buf0 room-          return $ nextForBuilder len signal+            (len, signal) <- writer buf0 room+            return $ nextForBuilder len signal         else do-          return $ Next 0 True (Just $ fillBufBuilderOne minReq writer)+            return $ Next 0 True (Just $ fillBufBuilderOne minReq writer)  fillBufBuilderTwo :: ByteString -> B.BufferWriter -> DynaNext fillBufBuilderTwo bs writer buf0 room@@ -202,10 +198,10 @@         let enoughRoom = maybe True (room >=) mMinReq         if enoughRoom             then do-              writeResult <- writer buf room-              ranWriter writeResult total buf room+                writeResult <- writer buf room+                ranWriter writeResult total buf room             else do-              return $ Next total True (Just $ goMore mMinReq writer 0)+                return $ Next total True (Just $ goMore mMinReq writer 0)      goChunk :: ByteString -> B.BufferWriter -> NextWithTotal     goChunk bs writer = \total buf room ->@@ -221,19 +217,25 @@  ---------------------------------------------------------------- -fillBufFile :: PositionRead -> FileOffset -> ByteCount -> IO () -> DynaNext-fillBufFile pread start bytes refresh buf room = do+fillBufFile :: PositionRead -> FileOffset -> ByteCount -> Sentinel -> DynaNext+fillBufFile pread start bytes sentinel buf room = do     len <- pread start (mini room bytes) buf-    refresh+    case sentinel of+        Refresher refresh -> refresh+        _ -> return ()     let len' = fromIntegral len-    return $ nextForFile len' pread (start + len) (bytes - len) refresh+    nextForFile len' pread (start + len) (bytes - len) sentinel  nextForFile-    :: BytesFilled -> PositionRead -> FileOffset -> ByteCount -> IO () -> Next-nextForFile 0 _ _ _ _ = Next 0 True Nothing -- let's flush-nextForFile len _ _ 0 _ = Next len False Nothing+    :: BytesFilled -> PositionRead -> FileOffset -> ByteCount -> Sentinel -> IO Next+nextForFile 0 _ _ _ _ = return $ Next 0 True Nothing -- let's flush+nextForFile len _ _ 0 sentinel = do+    case sentinel of+        Closer close -> close+        _ -> return ()+    return $ Next len False Nothing nextForFile len pread start bytes refresh =-    Next len False $ Just $ fillBufFile pread start bytes refresh+    return $ Next len False $ Just $ fillBufFile pread start bytes refresh  {-# INLINE mini #-} mini :: Int -> Int64 -> Int64
Network/HTTP/Semantics/ReadN.hs view
@@ -2,11 +2,14 @@     -- * Reading n bytes     ReadN,     defaultReadN,+    defaultReadNWith, ) where +import Control.Concurrent.STM import qualified Data.ByteString as B import Data.IORef+import Data.Void (absurd) import Network.Socket import qualified Network.Socket.ByteString as N @@ -19,34 +22,38 @@ -- (It is probably quite rare anyway to want concurrent reads from the /same/ -- network socket.) defaultReadN :: Socket -> IORef (Maybe B.ByteString) -> ReadN-defaultReadN _ _ 0 = return B.empty-defaultReadN s ref n = do+defaultReadN s ref n = either absurd id <$> defaultReadNWith s ref n retry++-- | 'defaultReadN' which the caller can give up on: 'Left' when the 'STM'+-- action fires before @n@ bytes have come.  The bytes read so far are kept+-- for the next read.  'Right' with the empty string is the end of input.+--+-- @since 0.4.2 (this type since 0.5.0)+defaultReadNWith+    :: Socket -> IORef (Maybe B.ByteString) -> Int -> STM g -> IO (Either g B.ByteString)+defaultReadNWith _ _ 0 _ = return $ Right B.empty+defaultReadNWith s ref n giveUp = do     mbs <- readIORef ref     writeIORef ref Nothing     case mbs of-        Nothing -> do-            bs <- N.recv s n-            if B.null bs-                then return B.empty-                else-                    if B.length bs == n-                        then return bs-                        else loop bs+        Nothing -> loop B.empty         Just bs-            | B.length bs == n -> return bs-            | B.length bs > n -> do+            | B.length bs >= n -> do                 let (bs0, bs1) = B.splitAt n bs-                writeIORef ref (Just bs1)-                return bs0+                writeIORef ref $ if B.null bs1 then Nothing else Just bs1+                return $ Right bs0             | otherwise -> loop bs   where     loop bs = do-        let n' = n - B.length bs-        bs1 <- N.recv s n'-        if B.null bs1-            then return B.empty-            else do-                let bs2 = bs `B.append` bs1-                if B.length bs2 == n-                    then return bs2-                    else loop bs2+        r <- N.recvWith s (n - B.length bs) giveUp+        case r of+            Left g -> do+                writeIORef ref $ if B.null bs then Nothing else Just bs+                return $ Left g+            Right bs1+                | B.null bs1 -> return $ Right B.empty+                | otherwise -> do+                    let bs2 = bs `B.append` bs1+                    if B.length bs2 == n+                        then return $ Right bs2+                        else loop bs2
Network/HTTP/Semantics/Server.hs view
@@ -1,5 +1,3 @@-{-# LANGUAGE OverloadedStrings #-}- module Network.HTTP.Semantics.Server (     -- * HTTP server     Server,@@ -20,9 +18,10 @@      -- * Aux     Aux,-    auxTimeHandle,+    defaultAux,     auxMySockAddr,     auxPeerSockAddr,+    auxSendInformational,      -- * Response     Response,@@ -34,7 +33,8 @@     responseBuilder,      -- ** Generalized streaming interface-    OutBodyIface(..),+    OutBodyIface (..),+    StreamTerminated (..),     responseStreamingIface,      -- ** Accessing response@@ -61,11 +61,13 @@     module Network.HTTP.Semantics.File, ) where +import Control.Concurrent.STM (retry) import Data.ByteString (ByteString) import Data.ByteString.Builder (Builder) import qualified Data.ByteString.UTF8 as UTF8 import Data.IORef import qualified Network.HTTP.Types as H+import Network.Socket  import Network.HTTP.Semantics import Network.HTTP.Semantics.File@@ -75,6 +77,16 @@  ---------------------------------------------------------------- +defaultAux :: Aux+defaultAux =+    Aux+        { auxMySockAddr = SockAddrInet 0 0+        , auxPeerSockAddr = SockAddrInet 0 0+        , auxSendInformational = \_ _ -> return ()+        }++----------------------------------------------------------------+ -- | Server type. Server takes a HTTP request, should --   generate a HTTP response and push promises, then --   should give them to the sending function.@@ -148,19 +160,19 @@  -- | Creating response without body. responseNoBody :: H.Status -> H.ResponseHeaders -> Response-responseNoBody st hdr = Response $ OutObj hdr' OutBodyNone defaultTrailersMaker+responseNoBody st hdr = Response $ OutObj hdr' OutBodyNone defaultTrailersMaker retry   where     hdr' = setStatus st hdr  -- | Creating response with file. responseFile :: H.Status -> H.ResponseHeaders -> FileSpec -> Response-responseFile st hdr fileSpec = Response $ OutObj hdr' (OutBodyFile fileSpec) defaultTrailersMaker+responseFile st hdr fileSpec = Response $ OutObj hdr' (OutBodyFile fileSpec) defaultTrailersMaker retry   where     hdr' = setStatus st hdr  -- | Creating response with builder. responseBuilder :: H.Status -> H.ResponseHeaders -> Builder -> Response-responseBuilder st hdr builder = Response $ OutObj hdr' (OutBodyBuilder builder) defaultTrailersMaker+responseBuilder st hdr builder = Response $ OutObj hdr' (OutBodyBuilder builder) defaultTrailersMaker retry   where     hdr' = setStatus st hdr @@ -170,9 +182,12 @@     -> H.ResponseHeaders     -> ((Builder -> IO ()) -> IO () -> IO ())     -> Response-responseStreaming st hdr strmbdy = Response $ OutObj hdr' (OutBodyStreaming strmbdy) defaultTrailersMaker+responseStreaming st hdr strmbdy = Response $ OutObj hdr' (OutBodyStreaming strmbdy) defaultTrailersMaker retry   where     hdr' = setStatus st hdr+-- Not inlined: GHC 9.12.4 and 9.14.1 may store a never-returning body+-- unevaluated in the strict field, read as the first constructor (ghc#27857).+{-# NOINLINE responseStreaming #-}  -- | Generalization of 'responseStreaming'. responseStreamingIface@@ -180,15 +195,18 @@     -> H.ResponseHeaders     -> (OutBodyIface -> IO ())     -> Response-responseStreamingIface st hdr strmbdy = Response $ OutObj hdr' (OutBodyStreamingIface strmbdy) defaultTrailersMaker+responseStreamingIface st hdr strmbdy = Response $ OutObj hdr' (OutBodyStreamingIface strmbdy) defaultTrailersMaker retry   where     hdr' = setStatus st hdr+-- Not inlined: GHC 9.12.4 and 9.14.1 may store a never-returning body+-- unevaluated in the strict field, read as the first constructor (ghc#27857).+{-# NOINLINE responseStreamingIface #-}  ----------------------------------------------------------------  -- | Getter for response body size. This value is available for file body. responseBodySize :: Response -> Maybe Int-responseBodySize (Response (OutObj _ (OutBodyFile (FileSpec _ _ len)) _)) = Just (fromIntegral len)+responseBodySize (Response (OutObj _ (OutBodyFile (FileSpec _ _ len)) _ _)) = Just (fromIntegral len) responseBodySize _ = Nothing  -- | Setting 'TrailersMaker' to 'Response'.
Network/HTTP/Semantics/Server/Internal.hs view
@@ -4,8 +4,8 @@     Aux (..), ) where +import qualified Network.HTTP.Types as H import Network.Socket (SockAddr)-import qualified System.TimeManager as T  import Network.HTTP.Semantics.Types (InpObj (..), OutObj (..)) @@ -17,10 +17,14 @@  -- | Additional information. data Aux = Aux-    { auxTimeHandle :: T.Handle-    -- ^ Time handle for the worker processing this request and response.-    , auxMySockAddr :: SockAddr+    { auxMySockAddr :: SockAddr     -- ^ Local socket address copied from 'Config'.     , auxPeerSockAddr :: SockAddr     -- ^ Remove socket address copied from 'Config'.+    , auxSendInformational :: H.Status -> H.ResponseHeaders -> IO ()+    -- ^ Send an informational (1xx) response, e.g. 103 Early Hints, on this+    --   request's stream before the final response. May be called multiple+    --   times. A no-op in 'defaultAux'.+    --+    --   @since 0.4.1     }
Network/HTTP/Semantics/Trailer.hs view
@@ -6,6 +6,9 @@ -- | Trailers maker. A chunks of the response body is passed --   with 'Just'. The maker should update internal state --   with the 'ByteString' and return the next trailers maker.+--   The 'ByteString' may share the sender's buffer and is valid+--   only during the call. Consume it strictly or copy it with+--   'Data.ByteString.copy', and never keep it in a lazy state. --   When response body reaches its end, --   'Nothing' is passed and the maker should generate --   trailers. An example:@@ -46,6 +49,6 @@  -- | Running trailers-maker. ----- > bufferIO buf siz $ \bs -> tlrmkr (Just bs)+-- > unsafeBufferIO buf siz $ \bs -> tlrmkr (Just bs) runTrailersMaker :: TrailersMaker -> Buffer -> Int -> IO NextTrailersMaker-runTrailersMaker tlrmkr buf siz = bufferIO buf siz $ \bs -> tlrmkr (Just bs)+runTrailersMaker tlrmkr buf siz = unsafeBufferIO buf siz $ \bs -> tlrmkr (Just bs)
Network/HTTP/Semantics/Types.hs view
@@ -9,6 +9,7 @@     OutObj (..),     OutBody (..),     OutBodyIface (..),+    StreamTerminated (..),      -- * Trailers maker     TrailersMaker,@@ -26,7 +27,8 @@     Path, ) where -import Control.Exception (SomeException)+import Control.Concurrent.STM (STM)+import Control.Exception (Exception, SomeException) import Data.ByteString.Builder (Builder) import Data.IORef import Data.Int (Int64)@@ -60,8 +62,23 @@     | OutBodyBuilder Builder     | OutBodyFile FileSpec +-- | Thrown by 'outBodyPush', 'outBodyPushFinal' and 'outBodyFlush'+--   once the body has ended or been cancelled.+--+--   @since 0.5.0+data StreamTerminated+    = -- | 'outBodyPushFinal' has been called.+      StreamPushedFinal+    | -- | 'outBodyCancel' has been called.+      StreamCancelled+    | -- | The body has returned.+      StreamOutOfScope+    deriving (Eq, Show)++instance Exception StreamTerminated+ data OutBodyIface = OutBodyIface-    { outBodyUnmask :: (forall x. IO x -> IO x)+    { outBodyUnmask :: forall x. IO x -> IO x     -- ^ Unmask exceptions in the thread spawned for the request body     --     -- This is used in the client: we spawn the new thread for the request body@@ -86,16 +103,20 @@     -- Using this function instead of 'outBodyPush' can be used to guarantee     -- that the final HTTP2 DATA frame is marked end-of-stream; with     -- 'outBodyPush' it may happen that an additional empty DATA frame is used-    -- for this purpose. Additionally, after calling this function,-    -- 'outBodyCancel' will be a no-op.+    -- for this purpose.     , outBodyCancel :: Maybe SomeException -> IO ()     -- ^ Cancel the stream     ---    -- Sends a @RST_STREAM@ to the peer. If cancelling as the result of an-    -- exception, a 'Just' should be provided which specifies the exception-    -- which will be stored locally as the reason for cancelling the stream; in-    -- this case, the error code sent with the @RST_STREAM@ will be-    -- @INTERNAL_ERROR@ (see+    -- Cancelling a streams sends a @RST_STREAM@ to the network peer, which+    -- tells them that they should stop sending us messages. As such, it may+    -- still be necessary to call 'outBodyCancel' after 'outBodyPushFinal',+    -- which merely tells the peer that /we/ will no longer send /them/ any more+    -- messages.+    --+    -- If cancelling as the result of an exception, a 'Just' should be provided+    -- which specifies the exception, which will be stored locally as the reason+    -- for cancelling the stream; in this case, the error code sent with the+    -- @RST_STREAM@ will be @INTERNAL_ERROR@ (see     -- <https://datatracker.ietf.org/doc/html/rfc7540#section-7>). If 'Nothing'     -- is given, the error code will be @CANCEL@.     --@@ -136,10 +157,15 @@     -- ^ Accessor for outObj body.     , outObjTrailers :: TrailersMaker     -- ^ Accessor for trailers maker.+    , outObjGiveUp :: STM ()+    -- ^ Once this succeeds, the library gives up on the object.+    --   'Control.Concurrent.STM.retry' gives up never.+    --+    --   @since 0.5.0     }  instance Show OutObj where-    show (OutObj hdr _ _) = show hdr+    show (OutObj hdr _ _ _) = show hdr  ---------------------------------------------------------------- 
http-semantics.cabal view
@@ -1,12 +1,12 @@ cabal-version:   3.0 name:            http-semantics-version:         0.2.1+version:         0.5.0 license:         BSD-3-Clause license-file:    LICENSE maintainer:      Kazu Yamamoto <kazu@iij.ad.jp> author:          Kazu Yamamoto <kazu@iij.ad.jp> homepage:        https://github.com/kazu-yamamoto/http-semantics-synopsis:        HTTP senmatics libarry+synopsis:        HTTP semantics library description:     Version-independent common parts of HTTP category:        Network build-type:      Simple@@ -21,6 +21,7 @@         Network.HTTP.Semantics         Network.HTTP.Semantics.Client         Network.HTTP.Semantics.Client.Internal+        Network.HTTP.Semantics.Error         Network.HTTP.Semantics.IO         Network.HTTP.Semantics.Server         Network.HTTP.Semantics.Server.Internal@@ -44,7 +45,7 @@         bytestring >=0.10,         case-insensitive,         http-types >=0.12 && <0.13,-        network,-        network-byte-order,-        time-manager,+        network >=3.2.10,+        network-byte-order >=0.1.10,+        stm,         utf8-string