packages feed

streamly-network-tcp (empty) → 0.1.0.0

raw patch · 6 files changed

+385/−0 lines, 6 filesdep +asyncdep +basedep +bytestring

Dependencies added: async, base, bytestring, network, streamly, streamly-bytestring, streamly-core, streamly-network-tcp, tasty, tasty-hunit

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Revision history for streamly-network-tcp++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `Transport`, `socketTransport`, `opened`.+* `connect`, `connectWithin`.+* `listen`, `serveConnections`.
+ 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,39 @@+# streamly-network-tcp++TCP connections for [Streamly](https://streamly.composewell.com/), for+clients and for servers, over the+[network](https://hackage.haskell.org/package/network) package. It is the+ground under the network libraries of this family+([streamly-http](https://github.com/GuillaumedeVolpiano/streamly-http),+[streamly-websockets](https://github.com/GuillaumedeVolpiano/streamly-websockets),+[streamly-network-tls](https://github.com/GuillaumedeVolpiano/streamly-network-tls)).++```haskell+{-# LANGUAGE OverloadedRecordDot #-}++import Control.Exception (bracket)+import Network.Socket (close)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.TCP (Transport (..), listen, serveConnections,+                                      socketTransport)++-- Send back to each client what it sends.+main :: IO ()+main = bracket (listen "127.0.0.1" 7000) close $ \listener ->+  serveConnections listener $ \peer ->+    let transport = socketTransport peer+     in fold (drainMapM transport.send) transport.receive+```++## What it gives++- `Transport`: a way to send byte arrays and the stream of those received.+  Protocols written against it run over plain TCP (`socketTransport`),+  over TLS, or over anything else that gives the two.+- `connect` and `connectWithin`: a connection to a host by its name, to+  the first of its addresses that accepts it, within a time if asked.+- `listen` and `serveConnections`: a listening socket, and each client+  served in a thread of its own.+- `opened`: a connected socket as a transport and what closes it, for the+  connections that outlive a function.
+ src/Streamly/External/Network/TCP.hs view
@@ -0,0 +1,132 @@+-- |+-- Module      : Streamly.External.Network.TCP+-- Description : TCP connections, for clients and servers, and transports+-- License     : BSD-3-Clause+--+-- What the network libraries of this family share: opening a TCP+-- connection to a host by its name, listening and serving, and the+-- t'Transport' that protocols are written against.+--+-- > {-# LANGUAGE OverloadedRecordDot #-}+-- > import Control.Exception (bracket)+-- > import Network.Socket (close)+-- > import Streamly.Data.Fold (drainMapM)+-- > import Streamly.Data.Stream (fold)+-- > import Streamly.External.Network.TCP (Transport (..), listen, serveConnections,+-- >                                       socketTransport)+-- >+-- > -- Send back to each client what it sends.+-- > main :: IO ()+-- > main = bracket (listen "127.0.0.1" 7000) close $ \listener ->+-- >   serveConnections listener $ \peer ->+-- >     let transport = socketTransport peer+-- >      in fold (drainMapM transport.send) transport.receive+module Streamly.External.Network.TCP+  ( -- * Transports+    Transport (..)+  , socketTransport+  , opened++    -- * Clients+  , connect+  , connectWithin++    -- * Servers+  , listen+  , serveConnections+  ) where++import Control.Concurrent (forkIOWithUnmask)+import Control.Exception (IOException, SomeException, bracketOnError, finally,+                          mask_, throwIO, try)+import Control.Monad (forever, void)+import Data.Word (Word8)+import Network.Socket (AddrInfo (addrAddress, addrFlags, addrSocketType),+                       AddrInfoFlag (AI_PASSIVE), Socket,+                       SocketOption (NoDelay, ReuseAddr), SocketType (Stream),+                       accept, bind, close, defaultHints, getAddrInfo,+                       openSocket, setSocketOption)+import Network.Socket qualified as N (connect, listen)+import Streamly.Data.Array (Array)+import Streamly.Data.Stream (Stream)+import Streamly.Network.Socket (putChunk, readChunks)+import System.Timeout (timeout)++-- | A connection that is open, as the two things a protocol needs from+-- it. A protocol written against a transport runs over plain TCP, over+-- TLS, or over anything else that gives these two.+data Transport = Transport+  { send :: Array Word8 -> IO ()+  -- ^ Send bytes.+  , receive :: Stream IO (Array Word8)+  -- ^ The bytes received, until the other side ends the connection.+  }++-- | A TCP socket as a transport.+socketTransport :: Socket -> Transport+socketTransport socket = Transport {send = putChunk socket, receive = readChunks socket}++-- | A connected socket as a transport and what closes it, for the+-- connections that outlive a function. Small writes are not held back+-- (@TCP_NODELAY@): on a connection that carries several exchanges, a+-- request that waits for the last answer to be acknowledged costs tens of+-- milliseconds each time.+opened :: Socket -> IO (Transport, IO ())+opened socket = do+  setSocketOption socket NoDelay 1+  pure (socketTransport socket, close socket)++-- | Open a TCP connection to a host and a port: to the first address of+-- the host that accepts it. Throws 'IOError', that of the last address+-- tried.+connect :: String -> Int -> IO Socket+connect host port = do+  addresses <- getAddrInfo (Just hints) (Just host) (Just (show port))+  attempt addresses+  where+    hints = defaultHints {addrSocketType = Stream}+    attempt [] = throwIO (userError ("no address for " <> host))+    attempt (address : others) = do+      outcome <- try (to address)+      case (outcome, others) of+        (Right socket, _) -> pure socket+        (Left (problem :: IOException), []) -> throwIO problem+        (Left _, _) -> attempt others+    to address =+      bracketOnError (openSocket address) close $ \socket -> do+        N.connect socket (addrAddress address)+        pure socket++-- | Like 'connect', within a number of microseconds for the whole of it,+-- name resolution included; 'Nothing' as the limit waits without end.+-- Gives 'Nothing' when the time is exceeded: what was opened is closed.+-- Call it unmasked, or the limit cannot stop it.+connectWithin :: Maybe Int -> String -> Int -> IO (Maybe Socket)+connectWithin limit host port = case limit of+  Nothing -> Just <$> connect host port+  Just microseconds -> timeout microseconds (connect host port)++-- | A TCP socket that listens on an address and a port; 0 lets the system+-- choose the port, which 'Network.Socket.socketPort' then tells.+listen :: String -> Int -> IO Socket+listen host port = do+  addresses <- getAddrInfo (Just hints) (Just host) (Just (show port))+  case addresses of+    [] -> throwIO (userError ("no address for " <> host))+    address : _ ->+      bracketOnError (openSocket address) close $ \listener -> do+        setSocketOption listener ReuseAddr 1+        bind listener (addrAddress address)+        N.listen listener 128+        pure listener+  where+    hints = defaultHints {addrSocketType = Stream, addrFlags = [AI_PASSIVE]}++-- | Serve every client that connects to a listening socket with a+-- function, each in a thread of its own, without end. The connection of a+-- client is closed when the function returns or throws; what it throws+-- ends that client only and is not reported.+serveConnections :: Socket -> (Socket -> IO ()) -> IO ()+serveConnections listener client = forever . mask_ $ do+  (peer, _) <- accept listener+  void (forkIOWithUnmask (\unmask -> void (try @SomeException (unmask (client peer))) `finally` close peer))
+ streamly-network-tcp.cabal view
@@ -0,0 +1,73 @@+cabal-version:   3.12+name:            streamly-network-tcp+version:         0.1.0.0+synopsis:        TCP connections as Streamly streams, for clients and servers+description:+  The ground under the Streamly network libraries of this family: opening+  a TCP connection to a host by its name, listening, serving each client+  in a thread of its own, and a transport, the pair of a way to send byte+  arrays and a stream of those received, that protocols are written+  against so that they run over TCP, TLS or anything else.++homepage:        https://github.com/GuillaumedeVolpiano/streamly-network-tcp+license:         BSD-3-Clause+license-file:    LICENSE+author:          Xavier Dectot+maintainer:      Xavier Dectot <xavier@wheredoibegin.fr>+category:        Network, Streamly+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/streamly-network-tcp.git++common shared+  default-language:   GHC2021+  default-extensions:+    DataKinds+    DerivingStrategies+    DisambiguateRecordFields+    DuplicateRecordFields+    ExplicitNamespaces+    GADTs+    LambdaCase+    MonoLocalBinds+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    RoleAnnotations++  ghc-options:+    -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+    -Wunused-packages++library+  import:          shared+  hs-source-dirs:  src+  exposed-modules: Streamly.External.Network.TCP+  build-depends:+    , base           >=4.19 && <4.22+    , network        ^>=3.2+    , streamly       ^>=0.11.1+    , streamly-core  ^>=0.3.3++test-suite streamly-network-tcp-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           ^>=0.12+    , network+    , streamly-bytestring  ^>=0.2.3+    , streamly-core+    , streamly-network-tcp+    , tasty                ^>=1.5+    , tasty-hunit          ^>=0.10
+ test/Main.hs view
@@ -0,0 +1,104 @@+-- | Clients and servers on the loopback interface.+module Main (main) where++import Control.Concurrent.Async (mapConcurrently, withAsync)+import Control.Exception (bracket, try)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS (concat, pack)+import Data.ByteString.Char8 qualified as BS8 (pack)+import GHC.Clock (getMonotonicTime)+import Network.Socket (ShutdownCmd (ShutdownSend), Socket, shutdown, socketPort)+import Network.Socket qualified as N (close)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold, toList)+import Streamly.Data.Stream qualified as S (take)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.Network.TCP (Transport (receive, send), connect,+                                      connectWithin, listen, opened,+                                      serveConnections, socketTransport)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++main :: IO ()+main = defaultMain tests++-- | Serve with a function on a free port of the loopback interface, and+-- run something against the port.+withServer :: (Socket -> IO ()) -> (Int -> IO a) -> IO a+withServer client run =+  bracket (listen "127.0.0.1" 0) N.close $ \listener -> do+    port <- socketPort listener+    withAsync (serveConnections listener client) $ \_ -> run (fromIntegral port)++-- | Send back what comes.+echo :: Socket -> IO ()+echo peer = let transport = socketTransport peer in fold (drainMapM transport.send) transport.receive++-- | Send bytes, say that nothing more comes, and read everything back.+exchange :: Int -> ByteString -> IO ByteString+exchange port bytes = bracket (connect "localhost" port) N.close $ \socket -> do+  let transport = socketTransport socket+  transport.send (toArray bytes)+  shutdown socket ShutdownSend+  BS.concat . map fromArray <$> toList transport.receive++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "streamly-network-tcp"+      [ testCase "bytes go to a server and come back, megabytes of them" $ do+          let payload = BS.pack (take 3_000_000 (cycle [0 .. 250]))+          echoed <- withServer echo (\port -> exchange port payload)+          echoed @?= payload+      , testCase "each client is served in a thread of its own" $ do+          answers <- withServer echo $ \port ->+            mapConcurrently (\index -> exchange port (BS8.pack (show index))) [1 .. 30 :: Int]+          answers @?= map (BS8.pack . show) [1 .. 30 :: Int]+      , testCase "a client whose function fails does not stop the server" $ do+          let fragile peer = do+                let transport = socketTransport peer+                first <- toList (S.take 1 transport.receive)+                if map fromArray first == ["fail"] then ioError (userError "on purpose") else transport.send (toArray "served")+          answers <- withServer fragile (\port -> mapM (exchange port) ["fail", "work", "fail", "work"])+          answers @?= ["", "served", "", "served"]+      , testCase "the receiving of a transport ends when the other side is done" $ do+          answer <- withServer (\peer -> (socketTransport peer).send (toArray "bye")) (\port -> exchange port "")+          answer @?= "bye"+      , testCase "an opened socket gives its transport and what closes it" $ do+          answer <- withServer echo $ \port -> do+            (transport, close) <- connect "127.0.0.1" port >>= opened+            transport.send (toArray "ping")+            first <- toList (S.take 1 transport.receive)+            close+            pure (BS.concat (map fromArray first))+          answer @?= "ping"+      , testCase "nothing listening is an IOError, with a time limit or without" $ do+          port <- bracket (listen "127.0.0.1" 0) N.close (fmap fromIntegral . socketPort)+          try (connect "127.0.0.1" port) >>= \case+            Left (_ :: IOError) -> pure ()+            Right socket -> N.close socket >> assertFailure "connected to nothing"+          try (connectWithin (Just 2_000_000) "127.0.0.1" port) >>= \case+            Left (_ :: IOError) -> pure ()+            Right _ -> assertFailure "connected to nothing"+      , testCase "connecting gives up in time" $ do+          -- An address that answers nothing where it is routed, and is+          -- refused at once where it is not: either way the wait is+          -- bounded.+          before <- getMonotonicTime+          outcome <- try (connectWithin (Just 200_000) "10.255.255.1" 81)+          after <- getMonotonicTime+          case outcome of+            Left (_ :: IOError) -> pure ()+            Right Nothing -> pure ()+            Right (Just socket) -> N.close socket+          assertBool ("waited " <> show (after - before) <> " s") (after - before < 2)+      , testCase "connecting without a limit reaches a server" $ do+          answer <- withServer echo $ \port ->+            connectWithin Nothing "127.0.0.1" port >>= \case+              Nothing -> assertFailure "no connection" >> pure ""+              Just socket -> bracket (pure socket) N.close $ \_ -> do+                (socketTransport socket).send (toArray "x")+                BS.concat . map fromArray <$> toList (S.take 1 (socketTransport socket).receive)+          answer @?= "x"+      ]