http-semantics 0.4.2 → 0.5.0
raw patch · 10 files changed
+308/−60 lines, 10 filesdep −time-managerdep ~network-byte-orderPVP ok
version bump matches the API change (PVP)
Dependencies removed: time-manager
Dependency ranges changed: network-byte-order
API changes (from Hackage documentation)
- Network.HTTP.Semantics.Server: auxTimeHandle :: Aux -> Handle
- Network.HTTP.Semantics.Server.Internal: [auxTimeHandle] :: Aux -> Handle
+ Network.HTTP.Semantics: StreamCancelled :: StreamTerminated
+ Network.HTTP.Semantics: StreamOutOfScope :: StreamTerminated
+ Network.HTTP.Semantics: StreamPushedFinal :: StreamTerminated
+ Network.HTTP.Semantics: [outObjGiveUp] :: OutObj -> STM ()
+ Network.HTTP.Semantics: data StreamTerminated
+ Network.HTTP.Semantics.Client: StreamCancelled :: StreamTerminated
+ Network.HTTP.Semantics.Client: StreamOutOfScope :: StreamTerminated
+ Network.HTTP.Semantics.Client: StreamPushedFinal :: StreamTerminated
+ Network.HTTP.Semantics.Client: data StreamTerminated
+ Network.HTTP.Semantics.Client: sendRequestWith :: SendRequest -> Request -> (Response -> IO r) -> STM g -> IO (Either g r)
+ Network.HTTP.Semantics.Client.Internal: RequestGivenUp :: RequestGivenUp
+ Network.HTTP.Semantics.Client.Internal: data RequestGivenUp
+ Network.HTTP.Semantics.Client.Internal: instance GHC.Exception.Type.Exception Network.HTTP.Semantics.Client.Internal.RequestGivenUp
+ Network.HTTP.Semantics.Client.Internal: instance GHC.Show.Show Network.HTTP.Semantics.Client.Internal.RequestGivenUp
+ Network.HTTP.Semantics.Client.Internal: setRequestGiveUp :: Request -> STM () -> Request
+ Network.HTTP.Semantics.Error: BadThingHappen :: SomeException -> HTTPError
+ Network.HTTP.Semantics.Error: Cancelled :: ErrorKind
+ Network.HTTP.Semantics.Error: CompressionFailure :: ErrorKind
+ Network.HTTP.Semantics.Error: ConnectFailure :: ErrorKind
+ Network.HTTP.Semantics.Error: ConnectionErrorIsReceived :: HTTPErrorCode -> ReasonPhrase -> HTTPError
+ Network.HTTP.Semantics.Error: ConnectionErrorIsSent :: HTTPErrorCode -> ReasonPhrase -> HTTPError
+ Network.HTTP.Semantics.Error: ConnectionIsClosed :: HTTPError
+ Network.HTTP.Semantics.Error: ConnectionIsReset :: HTTPError
+ Network.HTTP.Semantics.Error: ConnectionIsTimeout :: HTTPError
+ Network.HTTP.Semantics.Error: ExcessiveLoad :: ErrorKind
+ Network.HTTP.Semantics.Error: HTTP2 :: ErrorSpace
+ Network.HTTP.Semantics.Error: HTTP3 :: ErrorSpace
+ Network.HTTP.Semantics.Error: HTTPErrorCode :: ErrorKind -> ErrorSpace -> Word64 -> HTTPErrorCode
+ Network.HTTP.Semantics.Error: Incomplete :: ErrorKind
+ Network.HTTP.Semantics.Error: InternalFailure :: ErrorKind
+ Network.HTTP.Semantics.Error: MalformedMessage :: ErrorKind
+ Network.HTTP.Semantics.Error: NotAnError :: ErrorKind
+ Network.HTTP.Semantics.Error: ProtocolViolation :: ErrorKind
+ Network.HTTP.Semantics.Error: QUICTransport :: ErrorSpace
+ Network.HTTP.Semantics.Error: Refused :: ErrorKind
+ Network.HTTP.Semantics.Error: RequestIsUnprocessed :: Maybe StreamId -> HTTPError
+ Network.HTTP.Semantics.Error: SecurityFailure :: ErrorKind
+ Network.HTTP.Semantics.Error: StreamErrorIsReceived :: HTTPErrorCode -> StreamId -> HTTPError
+ Network.HTTP.Semantics.Error: StreamErrorIsSent :: HTTPErrorCode -> StreamId -> ReasonPhrase -> HTTPError
+ Network.HTTP.Semantics.Error: TransportFailure :: ErrorKind
+ Network.HTTP.Semantics.Error: UnknownCode :: ErrorKind
+ Network.HTTP.Semantics.Error: VersionFallback :: ErrorKind
+ Network.HTTP.Semantics.Error: [errorKind] :: HTTPErrorCode -> ErrorKind
+ Network.HTTP.Semantics.Error: [errorSpace] :: HTTPErrorCode -> ErrorSpace
+ Network.HTTP.Semantics.Error: [errorValue] :: HTTPErrorCode -> Word64
+ Network.HTTP.Semantics.Error: data ErrorKind
+ Network.HTTP.Semantics.Error: data ErrorSpace
+ Network.HTTP.Semantics.Error: data HTTPError
+ Network.HTTP.Semantics.Error: data HTTPErrorCode
+ Network.HTTP.Semantics.Error: http2ErrorCode :: Word64 -> HTTPErrorCode
+ Network.HTTP.Semantics.Error: http3ErrorCode :: Word64 -> HTTPErrorCode
+ Network.HTTP.Semantics.Error: instance GHC.Classes.Eq Network.HTTP.Semantics.Error.ErrorKind
+ Network.HTTP.Semantics.Error: instance GHC.Classes.Eq Network.HTTP.Semantics.Error.ErrorSpace
+ Network.HTTP.Semantics.Error: instance GHC.Classes.Eq Network.HTTP.Semantics.Error.HTTPErrorCode
+ Network.HTTP.Semantics.Error: instance GHC.Exception.Type.Exception Network.HTTP.Semantics.Error.HTTPError
+ Network.HTTP.Semantics.Error: instance GHC.Show.Show Network.HTTP.Semantics.Error.ErrorKind
+ Network.HTTP.Semantics.Error: instance GHC.Show.Show Network.HTTP.Semantics.Error.ErrorSpace
+ Network.HTTP.Semantics.Error: instance GHC.Show.Show Network.HTTP.Semantics.Error.HTTPError
+ Network.HTTP.Semantics.Error: instance GHC.Show.Show Network.HTTP.Semantics.Error.HTTPErrorCode
+ Network.HTTP.Semantics.Error: isRetryable :: HTTPError -> Bool
+ Network.HTTP.Semantics.Error: quicTransportErrorCode :: Word64 -> HTTPErrorCode
+ Network.HTTP.Semantics.Error: type ReasonPhrase = ShortByteString
+ Network.HTTP.Semantics.Error: type StreamId = Int64
+ Network.HTTP.Semantics.Server: StreamCancelled :: StreamTerminated
+ Network.HTTP.Semantics.Server: StreamOutOfScope :: StreamTerminated
+ Network.HTTP.Semantics.Server: StreamPushedFinal :: StreamTerminated
+ Network.HTTP.Semantics.Server: data StreamTerminated
- Network.HTTP.Semantics: OutObj :: [Header] -> OutBody -> TrailersMaker -> OutObj
+ Network.HTTP.Semantics: OutObj :: [Header] -> OutBody -> TrailersMaker -> STM () -> OutObj
- Network.HTTP.Semantics.Client: defaultReadNWith :: Socket -> IORef (Maybe ByteString) -> STM a -> ReadN
+ Network.HTTP.Semantics.Client: defaultReadNWith :: Socket -> IORef (Maybe ByteString) -> Int -> STM g -> IO (Either g ByteString)
- Network.HTTP.Semantics.IO: defaultReadNWith :: Socket -> IORef (Maybe ByteString) -> STM a -> ReadN
+ Network.HTTP.Semantics.IO: defaultReadNWith :: Socket -> IORef (Maybe ByteString) -> Int -> STM g -> IO (Either g ByteString)
- Network.HTTP.Semantics.Server: defaultReadNWith :: Socket -> IORef (Maybe ByteString) -> STM a -> ReadN
+ Network.HTTP.Semantics.Server: defaultReadNWith :: Socket -> IORef (Maybe ByteString) -> Int -> STM g -> IO (Either g ByteString)
- Network.HTTP.Semantics.Server.Internal: Aux :: Handle -> SockAddr -> SockAddr -> (Status -> ResponseHeaders -> IO ()) -> Aux
+ Network.HTTP.Semantics.Server.Internal: Aux :: SockAddr -> SockAddr -> (Status -> ResponseHeaders -> IO ()) -> Aux
Files
- ChangeLog.md +19/−0
- Network/HTTP/Semantics/Client.hs +38/−5
- Network/HTTP/Semantics/Client/Internal.hs +26/−0
- Network/HTTP/Semantics/Error.hs +151/−0
- Network/HTTP/Semantics/ReadN.hs +26/−34
- Network/HTTP/Semantics/Server.hs +15/−10
- Network/HTTP/Semantics/Server/Internal.hs +1/−4
- Network/HTTP/Semantics/Trailer.hs +5/−2
- Network/HTTP/Semantics/Types.hs +24/−2
- http-semantics.cabal +3/−3
ChangeLog.md view
@@ -1,5 +1,24 @@ # 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
Network/HTTP/Semantics/Client.hs view
@@ -18,6 +18,7 @@ -- ** Generalized streaming interface OutBodyIface (..),+ StreamTerminated (..), requestStreamingIface, -- ** Trailers maker@@ -26,6 +27,9 @@ defaultTrailersMaker, setRequestTrailersMaker, + -- ** Giving up+ sendRequestWith,+ -- * Response Response, @@ -55,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)@@ -78,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 @@ -101,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@@ -122,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@@ -132,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
@@ -3,8 +3,15 @@ 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.@@ -27,3 +34,22 @@ { 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/ReadN.hs view
@@ -9,6 +9,7 @@ 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 @@ -21,47 +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 s ref = defaultReadNWith s ref retry+defaultReadN s ref n = either absurd id <$> defaultReadNWith s ref n retry --- | 'defaultReadN' which the caller can give up on. The 'STM' action is--- waited for beside each receive; when it fires, the read answers with the--- empty string, which is how 'ReadN' already says that there is nothing more.------ /NOTE/: the bytes read so far are discarded, so this ends a connection--- rather than pausing one. The caller cannot tell a give-up from the peer--- hanging up; whoever fired the 'STM' action knows which it was.+-- | '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-defaultReadNWith :: Socket -> IORef (Maybe B.ByteString) -> STM a -> ReadN-defaultReadNWith _ _ _ 0 = return B.empty-defaultReadNWith s ref giveUp n = do+-- @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 <- recv1 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- recv1 n' = either (const B.empty) id <$> N.recvWith s n' giveUp loop bs = do- let n' = n - B.length bs- bs1 <- recv1 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
@@ -19,7 +19,6 @@ -- * Aux Aux, defaultAux,- auxTimeHandle, auxMySockAddr, auxPeerSockAddr, auxSendInformational,@@ -35,6 +34,7 @@ -- ** Generalized streaming interface OutBodyIface (..),+ StreamTerminated (..), responseStreamingIface, -- ** Accessing response@@ -61,13 +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 qualified System.TimeManager as T import Network.HTTP.Semantics import Network.HTTP.Semantics.File@@ -80,8 +80,7 @@ defaultAux :: Aux defaultAux = Aux- { auxTimeHandle = T.emptyHandle- , auxMySockAddr = SockAddrInet 0 0+ { auxMySockAddr = SockAddrInet 0 0 , auxPeerSockAddr = SockAddrInet 0 0 , auxSendInformational = \_ _ -> return () }@@ -161,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 @@ -183,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@@ -193,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
@@ -6,7 +6,6 @@ import qualified Network.HTTP.Types as H import Network.Socket (SockAddr)-import qualified System.TimeManager as T import Network.HTTP.Semantics.Types (InpObj (..), OutObj (..)) @@ -18,9 +17,7 @@ -- | 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'.
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,6 +62,21 @@ | 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 -- ^ Unmask exceptions in the thread spawned for the request body@@ -140,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,6 +1,6 @@ cabal-version: 3.0 name: http-semantics-version: 0.4.2+version: 0.5.0 license: BSD-3-Clause license-file: LICENSE maintainer: Kazu Yamamoto <kazu@iij.ad.jp>@@ -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@@ -45,7 +46,6 @@ case-insensitive, http-types >=0.12 && <0.13, network >=3.2.10,- network-byte-order,+ network-byte-order >=0.1.10, stm,- time-manager >= 0.2.4, utf8-string