effectful-streamly-http (empty) → 0.1.0.0
raw patch · 6 files changed
+434/−0 lines, 6 filesdep +asyncdep +basedep +bytestring
Dependencies added: async, base, bytestring, effectful-core, effectful-streamly-http, network, streamly-bytestring, streamly-http, tasty, tasty-hunit, text
Files
- CHANGELOG.md +10/−0
- LICENSE +29/−0
- README.md +52/−0
- effectful-streamly-http.cabal +74/−0
- src/Effectful/HTTP.hs +124/−0
- test/Main.hs +145/−0
+ CHANGELOG.md view
@@ -0,0 +1,10 @@+# Revision history for effectful-streamly-http++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `Effectful.HTTP`: the `Http` effect and `fetch`; `runHttpClear` over+ streamly-http, within limits of time and size; `runHttpWith`, from a+ function.+* `runHttpClear` keeps its connections, for each server, as long as it+ runs.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,52 @@+# effectful-streamly-http++HTTP requests as an [Effectful](https://hackage.haskell.org/package/effectful)+effect: send a request, get the whole response. The interpreter of this+package runs over+[streamly-http](https://hackage.haskell.org/package/streamly-http), in+clear;+[effectful-streamly-http-tls](https://github.com/GuillaumedeVolpiano/effectful-streamly-http-tls)+adds `https`.++```haskell+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++import Effectful (runEff)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.HTTP (HttpFailure, Response (..), Scheme (Http), defaultLimits,+ fetch, get, runHttpClear)++main :: IO ()+main = do+ outcome <- runEff . runErrorNoCallStack @HttpFailure . runHttpClear defaultLimits $+ fetch Http (get "example.org" 80 "/")+ print (fmap (.status) outcome)+```++## What it gives++- `Http`, the effect, with one operation: `fetch`, for a request in clear+ (`Http`) or over TLS (`Https`).+- `runHttpClear`: connections over plain TCP, within `Limits` of time and+ size, kept from one request to the next for each server as long as the+ interpreter runs. A request over TLS fails with+ `TlsUnavailable`.+- `runHttpWith`: the effect answered from a function. Code written against+ the effect is tested without any server.+- `HttpFailure`: why an exchange gave no response. A status is never a+ failure.++## Limits of this version++- The whole response is read into memory: set `maxBodySize` when the+ server is not trusted. There is no streaming of a body.+- No redirect is followed.++## Building++To build against a copy of+[streamly-http](https://hackage.haskell.org/package/streamly-http) checked+out next to this repository, pass `--project-file=cabal.project.siblings`.++Tested with GHC 9.8.4, 9.10.3 and 9.12.4, and effectful 2.7.1.
+ effectful-streamly-http.cabal view
@@ -0,0 +1,74 @@+cabal-version: 3.12+name: effectful-streamly-http+version: 0.1.0.0+synopsis: HTTP requests as an Effectful effect+description:+ An HTTP effect for Effectful: send a request, get the whole response.+ The interpreter of this package runs over streamly-http, in clear;+ effectful-streamly-http-tls adds https. An interpreter from a function+ serves tests, which then need no server.++homepage: https://github.com/GuillaumedeVolpiano/effectful-streamly-http+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: Network, Web, Control+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/effectful-streamly-http.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ DuplicateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ NoFieldSelectors+ OverloadedRecordDot+ OverloadedStrings+ RoleAnnotations+ TypeFamilies++ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules: Effectful.HTTP+ build-depends:+ , base >=4.19 && <4.22+ , bytestring ^>=0.12+ , effectful-core ^>=2.7.1+ , streamly-bytestring ^>=0.2.3+ , streamly-http ^>=0.1+ , text ^>=2.1++test-suite effectful-streamly-http-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , async ^>=2.2+ , base+ , bytestring+ , effectful-core+ , effectful-streamly-http+ , network ^>=3.2+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10
+ src/Effectful/HTTP.hs view
@@ -0,0 +1,124 @@+-- |+-- Module : Effectful.HTTP+-- Description : HTTP requests as an effect+-- License : BSD-3-Clause+--+-- Sending a request and getting the whole response, as an effect. The+-- connections are opened by an interpreter: 'runHttpClear' here, for+-- @http@; the one of @effectful-streamly-http-tls@ for @https@ too; or+-- 'runHttpWith', which answers from a function, for tests.+--+-- > {-# LANGUAGE OverloadedRecordDot #-}+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Effectful (runEff)+-- > import Effectful.Error.Static (runErrorNoCallStack)+-- > import Effectful.HTTP (HttpFailure, Response (..), Scheme (Http), defaultLimits,+-- > fetch, get, runHttpClear)+-- >+-- > main :: IO ()+-- > main = do+-- > outcome <- runEff . runErrorNoCallStack @HttpFailure . runHttpClear defaultLimits $+-- > fetch Http (get "example.org" 80 "/")+-- > print (fmap (.status) outcome)+--+-- A status is never a failure: look at 'status'. The response is read+-- whole into memory: bound it with 'maxBodySize' when the server is not+-- trusted.+module Effectful.HTTP+ ( -- * Effect+ Http (..)+ , fetch++ -- * Requests and responses+ , Scheme (..)+ , Request (..)+ , RequestBody (..)+ , Header+ , get+ , withHeaders+ , withBody+ , Response (..)+ , header++ -- * Interpreters+ , runHttpClear+ , runHttpWith+ , Limits (..)+ , defaultLimits+ , noLimits++ -- * Failures+ , HttpFailure (..)+ , HttpError (..)+ ) where++import Control.Exception (IOException, displayException, try)+import Data.ByteString (ByteString)+import Data.Text (Text, pack)+import Effectful (Dispatch (Dynamic), DispatchOf, Eff, Effect, IOE,+ MonadIO (liftIO), UnliftStrategy (SeqUnlift), withEffToIO,+ type (:>))+import Effectful.Dispatch.Dynamic (interpret_, send)+import Effectful.Error.Static (Error, throwError)+import Streamly.External.ByteString (fromArray)+import Streamly.External.Network.HTTP (Client, Header, HttpError (..),+ Limits (..), Request (..),+ RequestBody (..), Response (..),+ defaultLimits, fetchFrom, get, header,+ noLimits, withBody, withClient,+ withHeaders)+import Streamly.External.Network.HTTP.URL (Scheme (..))++-- | Exchanges with HTTP servers.+data Http :: Effect where+ -- | One request to the host and the port it names, in clear or over+ -- TLS, and its whole response.+ Fetch :: Scheme -> Request -> Http m (Response ByteString)++type instance DispatchOf Http = Dynamic++-- | Send a request to the host and the port it names, in clear (@Http@)+-- or over TLS (@Https@), and get the whole response. No redirect is+-- followed.+fetch :: Http :> es => Scheme -> Request -> Eff es (Response ByteString)+fetch scheme request = send (Fetch scheme request)++-- | Why an exchange gave no response.+data HttpFailure+ = -- | The request could not be written, the response could not be read,+ -- or a limit of time or size was exceeded: which.+ RequestFailed HttpError+ | -- | The connection could not be opened, or broke. Carries the cause.+ ConnectFailed Text+ | -- | The TLS connection could not be set up, among others because the+ -- certificate of the server was not accepted. Carries the cause.+ TlsFailed Text+ | -- | A request over TLS given to an interpreter that only speaks in+ -- clear.+ TlsUnavailable+ deriving stock (Eq, Show)++-- | Interpret the effect over plain TCP connections, within limits of+-- time and size. The connections are kept from one request to the next+-- for each server, as long as the interpreter runs, and closed when it is+-- done. A request over TLS fails with 'TlsUnavailable': see+-- @effectful-streamly-http-tls@.+runHttpClear :: (IOE :> es, Error HttpFailure :> es) => Limits -> Eff (Http : es) a -> Eff es a+runHttpClear limits action =+ withEffToIO SeqUnlift $ \runInIO ->+ withClient limits (\client -> runInIO (throughClear client action))++throughClear :: (IOE :> es, Error HttpFailure :> es) => Client -> Eff (Http : es) a -> Eff es a+throughClear client = interpret_ $ \case+ Fetch Https _ -> throwError TlsUnavailable+ Fetch Http request ->+ liftIO (try (try (fetchFrom client Http request))) >>= \case+ Left (problem :: IOException) -> throwError (ConnectFailed (pack (displayException problem)))+ Right (Left (problem :: HttpError)) -> throwError (RequestFailed problem)+ Right (Right response) -> pure (fromArray <$> response)++-- | Interpret the effect with a function from a request to its response:+-- for tests, and for other ways to reach a server.+runHttpWith :: (Scheme -> Request -> Eff es (Response ByteString)) -> Eff (Http : es) a -> Eff es a+runHttpWith exchange = interpret_ $ \case+ Fetch scheme request -> exchange scheme request
+ test/Main.hs view
@@ -0,0 +1,145 @@+-- | The effect answered from a function, then over TCP against a server+-- on the loopback interface.+module Main (main) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (wait, withAsync)+import Control.Exception (bracket)+import Control.Monad (forever)+import Data.ByteString (ByteString, breakSubstring, isInfixOf, pack)+import Data.ByteString qualified as BS (drop, length, null, takeWhile)+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Effectful (Eff, IOE, runEff)+import Effectful.Error.Static (Error, runErrorNoCallStack)+import Effectful.HTTP (Http,+ HttpError (BodyTooLarge, InvalidRequest, MalformedResponse, ResponseTimedOut),+ HttpFailure (ConnectFailed, RequestFailed, TlsUnavailable),+ Limits (idleTimeout, maxBodySize),+ Request (method, target), RequestBody (BodyBytes),+ Response (Response, body, headers, reason, status),+ Scheme (Http, Https), defaultLimits, fetch, get, header,+ runHttpClear, runHttpWith, withBody, withHeaders)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+ SocketOption (ReuseAddr), SocketType (Stream), accept,+ bind, close, defaultProtocol, listen, setSocketOption,+ socketPort, tupleToHostAddress)+import Network.Socket qualified as N (socket)+import Network.Socket.ByteString (recv, sendAll)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++main :: IO ()+main = defaultMain tests++-- | Run a server that answers one connection: it reads the request head,+-- sends the answer, then holds the connection for a while or closes it.+-- Returns the request with the result.+withServer :: Bool -> [ByteString] -> (Int -> IO a) -> IO (ByteString, a)+withServer hold answer action =+ bracket open close $ \listener -> do+ port <- socketPort listener+ withAsync (serve listener) $ \server -> do+ result <- action (fromIntegral port)+ request <- if hold then pure "" else wait server+ pure (request, result)+ where+ open = do+ listener <- N.socket AF_INET Stream defaultProtocol+ setSocketOption listener ReuseAddr 1+ bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ listen listener 1+ pure listener+ serve listener =+ bracket (fst <$> accept listener) close $ \peer -> do+ request <- readHead peer ""+ mapM_ (sendAll peer) answer+ if hold then threadDelay 10_000_000 else pure ()+ pure request+ readHead peer seen+ | "\r\n\r\n" `isInfixOf` seen = pure seen+ | otherwise = do+ more <- recv peer 4096+ if BS.null more then pure seen else readHead peer (seen <> more)++clear :: Limits -> Eff '[Http, Error HttpFailure, IOE] a -> IO (Either HttpFailure a)+clear limits = runEff . runErrorNoCallStack . runHttpClear limits++tests :: TestTree+tests =+ localOption (mkTimeout 20_000_000) $+ testGroup+ "effectful-streamly-http"+ [ testCase "answered from a function, without any server" $ do+ let answer scheme request =+ pure Response {status = 200, reason = "OK", headers = [("x-scheme", if scheme == Https then "https" else "http")], body = request.method <> " " <> request.target}+ (first, second) <- runEff . runHttpWith answer $ do+ first <- fetch Http (get "example.org" 80 "/a")+ second <- fetch Https (withBody (BodyBytes "x") (get "example.org" 443 "/b") {method = "POST"})+ pure (first, second)+ (first.body, header "x-scheme" first) @?= ("GET /a", Just "http")+ (second.body, header "x-scheme" second) @?= ("POST /b", Just "https")+ , testCase "a request in clear goes over TCP, and its response comes back whole" $ do+ let content = pack (take 100_000 (cycle [0 .. 255]))+ answer = ["HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nTransfer-Encoding: chunked\r\n\r\n186a0\r\n", content, "\r\n0\r\n\r\n"]+ (request, outcome) <- withServer False answer $ \port ->+ clear defaultLimits (fetch Http (withHeaders [("Accept", "image/jpeg")] (get "127.0.0.1" port "/image?size=3")))+ BS.takeWhile (/= 13) request @?= "GET /image?size=3 HTTP/1.1"+ isInfixOf "\r\nAccept: image/jpeg\r\n" request @?= True+ fmap (\response -> (response.status, header "content-type" response, response.body)) outcome @?= Right (200, Just "image/jpeg", content)+ , testCase "the requests of one interpreter to a server share a connection" $ do+ connections <- newIORef (0 :: Int)+ bracket (N.socket AF_INET Stream defaultProtocol) close $ \listener -> do+ bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ listen listener 5+ port <- fromIntegral <$> socketPort listener+ let answerAll peer buffered = case breakSubstring "\r\n\r\n" buffered of+ (found, rest) | not (BS.null rest) -> do+ let target = BS.takeWhile (/= 32) (BS.drop 4 found)+ sendAll peer ("HTTP/1.1 200 OK\r\nContent-Length: " <> pack (map (fromIntegral . fromEnum) (show (BS.length target))) <> "\r\n\r\n" <> target)+ answerAll peer (BS.drop 4 rest)+ _ -> do+ more <- recv peer 4096+ if BS.null more then pure () else answerAll peer (buffered <> more)+ serve = forever . bracket (fst <$> accept listener) close $ \peer ->+ atomicModifyIORef' connections (\count -> (count + 1, ())) >> answerAll peer ""+ withAsync serve $ \_ -> do+ outcome <- clear defaultLimits (mapM (\target -> (.body) <$> fetch Http (get "127.0.0.1" port target)) ["/a", "/b", "/c"])+ outcome @?= Right ["/a", "/b", "/c"]+ readIORef connections >>= (@?= 1)+ -- Another interpreter has connections of its own.+ again <- clear defaultLimits ((.body) <$> fetch Http (get "127.0.0.1" port "/d"))+ again @?= Right "/d"+ readIORef connections >>= (@?= 2)+ , testCase "a status is not a failure" $ do+ (_, outcome) <- withServer False ["HTTP/1.1 404 Not Found\r\nContent-Length: 4\r\n\r\ngone"] $ \port ->+ clear defaultLimits (fetch Http (get "127.0.0.1" port "/"))+ fmap (\response -> (response.status, response.reason, response.body)) outcome @?= Right (404, "Not Found", "gone")+ , testCase "the limits of the interpreter apply" $ do+ (_, tooLarge) <- withServer False ["HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n0123456789"] $ \port ->+ clear defaultLimits {maxBodySize = Just 9} (fetch Http (get "127.0.0.1" port "/"))+ fmap (.status) tooLarge @?= Left (RequestFailed (BodyTooLarge 9))+ (_, silent) <- withServer True [] $ \port ->+ clear defaultLimits {idleTimeout = Just 150_000} (fetch Http (get "127.0.0.1" port "/"))+ fmap (.status) silent @?= Left (RequestFailed ResponseTimedOut)+ , testCase "what cannot be written or read is reported" $ do+ invalid <- clear defaultLimits (fetch Http (get "127.0.0.1" 1 "/a b"))+ case invalid of+ Left (RequestFailed (InvalidRequest _)) -> pure ()+ other -> assertFailure ("expected InvalidRequest, got " <> show (fmap (.status) other))+ (_, notHttp) <- withServer False ["MOO/1 COMPLETE Success\n\n"] $ \port ->+ clear defaultLimits (fetch Http (get "127.0.0.1" port "/"))+ case notHttp of+ Left (RequestFailed (MalformedResponse _)) -> pure ()+ other -> assertFailure ("expected MalformedResponse, got " <> show (fmap (.status) other))+ , testCase "a refused connection is reported" $ do+ port <- bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do+ bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ fromIntegral <$> socketPort socket+ outcome <- clear defaultLimits (fetch Http (get "127.0.0.1" port "/"))+ case outcome of+ Left (ConnectFailed _) -> pure ()+ other -> assertFailure ("expected ConnectFailed, got " <> show (fmap (.status) other))+ , testCase "TLS is not for the interpreter in clear" $ do+ outcome <- clear defaultLimits (fetch Https (get "example.org" 443 "/"))+ fmap (.status) outcome @?= Left TlsUnavailable+ ]