packages feed

streamly-network-udp (empty) → 0.1.0.0

raw patch · 7 files changed

+482/−0 lines, 7 filesdep +basedep +bytestringdep +network

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

Files

+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Revision history for streamly-network-udp++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* UDP sockets bound to an address (`withSocket`), with the address reuse+  and broadcast options.+* Datagrams received as a stream with their senders (`datagrams`,+  `datagramsWith`, `datagramsWithin`), and sent one by one (`sendTo`) or+  through a fold (`write`, `writeTo`).+* IPv4 multicast: joining and leaving a group, hop limit and loopback.
+ 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-udp++UDP sockets for [Streamly](https://streamly.composewell.com/), over the+[network](https://hackage.haskell.org/package/network) package. The+datagrams received are a stream, each with the address of its sender;+datagrams are sent one by one or through a fold.++```haskell+import Network.Socket (SockAddr (SockAddrInet), tupleToHostAddress)+import Streamly.Data.Array (fromList)+import Streamly.Data.Stream (toList)+import Streamly.External.Network.UDP (anyAddress, datagramsWithin, sendTo,+                                      socketAt, withSocket)++-- Ask, and collect the answers that come within a second.+main :: IO ()+main = withSocket (socketAt anyAddress) $ \socket -> do+  sendTo socket (SockAddrInet 9003 (tupleToHostAddress (192, 0, 2, 1))) (fromList [1, 2, 3])+  answers <- toList (datagramsWithin 1000000 socket)+  print (map fst answers)+```++## What it gives++- `withSocket`: a socket bound to an address, with `reuseAddress` and+  `broadcast` as options.+- `datagrams`: the datagrams received, without end; `datagramsWith` to+  give each less room; `datagramsWithin` for those that come within a+  time.+- `sendTo`, and the folds `write` (one address) and `writeTo` (an address+  with each datagram).+- For IPv4 multicast: `joinGroup`, `leaveGroup`, `setMulticastTTL`,+  `setMulticastLoopback`.++## Limits of this version++- Unix only: the multicast options are set as Unix systems expect them.+- Multicast groups are IPv4 only. Sockets can be IPv6.+- No connected sockets: every datagram names its destination.
+ src/Streamly/External/Network/UDP.hs view
@@ -0,0 +1,190 @@+-- |+-- Module      : Streamly.External.Network.UDP+-- Description : UDP datagrams as streams+-- License     : BSD-3-Clause+--+-- UDP sockets for Streamly, over the @network@ package. The datagrams+-- received are a stream, each with the address of its sender; datagrams+-- are sent one by one or through a fold.+--+-- > import Network.Socket (SockAddr (SockAddrInet), tupleToHostAddress)+-- > import Streamly.Data.Array (fromList)+-- > import Streamly.Data.Stream (toList)+-- > import Streamly.External.Network.UDP (anyAddress, datagramsWithin, sendTo,+-- >                                       socketAt, withSocket)+-- >+-- > -- Ask, and collect the answers that come within a second.+-- > main :: IO ()+-- > main = withSocket (socketAt anyAddress) $ \socket -> do+-- >   sendTo socket (SockAddrInet 9003 (tupleToHostAddress (192, 0, 2, 1))) (fromList [1, 2, 3])+-- >   answers <- toList (datagramsWithin 1000000 socket)+-- >   print (map fst answers)+--+-- Unix only: the multicast options are set as Unix systems expect them.+module Streamly.External.Network.UDP+  ( -- * Sockets+    SocketConfig (..)+  , socketAt+  , anyAddress+  , withSocket++    -- * Receiving+  , datagrams+  , datagramsWith+  , datagramsWithin+  , maxDatagramSize++    -- * Sending+  , sendTo+  , write+  , writeTo++    -- * Broadcast and multicast+  , setBroadcast+  , joinGroup+  , leaveGroup+  , setMulticastTTL+  , setMulticastLoopback+  ) where++import Control.Exception (bracket)+import Control.Monad (void, when)+import Control.Monad.IO.Class (MonadIO (..))+import Data.Word (Word8)+import Foreign.C.Types (CInt)+import Foreign.Ptr (castPtr, plusPtr)+import Foreign.Storable (Storable (..))+import GHC.Clock (getMonotonicTimeNSec)+import Network.Socket (Family (AF_INET, AF_INET6, AF_UNIX), HostAddress,+                       SockAddr (..), Socket,+                       SocketOption (Broadcast, ReuseAddr, SockOpt),+                       SocketType (Datagram), bind, close, defaultProtocol,+                       setSockOpt, setSocketOption)+import Network.Socket qualified as N (socket)+import Network.Socket.ByteString (recvFrom)+import Network.Socket.ByteString qualified as NB (sendTo)+import Streamly.Data.Array (Array)+import Streamly.Data.Fold (Fold, drainMapM)+import Streamly.Data.Stream (Stream, repeatM, unfoldrM)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.Network.UDP.Constants (addMembership, dropMembership,+                                                ipProtocol, multicastLoop,+                                                multicastTtl)+import System.Timeout (timeout)++-- | How to open a socket.+data SocketConfig = SocketConfig+  { address :: SockAddr+  -- ^ The address and the port to bind to. Its family is that of the+  -- socket.+  , reuseAddress :: Bool+  -- ^ Let several sockets bind to this address, as the listeners of a+  -- multicast group do.+  , broadcast :: Bool+  -- ^ Allow sending to broadcast addresses.+  }+  deriving stock (Eq, Show)++-- | A socket bound to an address, alone on it and without broadcast.+socketAt :: SockAddr -> SocketConfig+socketAt address = SocketConfig {address, reuseAddress = False, broadcast = False}++-- | Every IPv4 interface, on a port chosen by the system: what a socket+-- that asks and listens to the answers needs.+anyAddress :: SockAddr+anyAddress = SockAddrInet 0 0++-- | Open a UDP socket, bind it, use it and close it.+withSocket :: SocketConfig -> (Socket -> IO a) -> IO a+withSocket settings use =+  bracket (N.socket family Datagram defaultProtocol) close $ \socket -> do+    when settings.reuseAddress (setSocketOption socket ReuseAddr 1)+    when settings.broadcast (setBroadcast socket True)+    bind socket settings.address+    use socket+  where+    family = case settings.address of+      SockAddrInet {} -> AF_INET+      SockAddrInet6 {} -> AF_INET6+      SockAddrUnix {} -> AF_UNIX++-- | The largest datagram UDP can carry over IPv4, headers included: no+-- datagram is cut when this much room is given to each.+maxDatagramSize :: Int+maxDatagramSize = 65535++-- | The datagrams received, each with the address of its sender, without+-- end. An empty datagram is an empty array.+datagrams :: MonadIO m => Socket -> Stream m (SockAddr, Array Word8)+datagrams = datagramsWith maxDatagramSize++-- | Like 'datagrams', with the room given to each datagram, in bytes: a+-- longer one is cut to it.+datagramsWith :: MonadIO m => Int -> Socket -> Stream m (SockAddr, Array Word8)+datagramsWith size socket = repeatM (liftIO (receiveFrom size socket))++-- | The datagrams received within a number of microseconds, counted from+-- the moment the stream starts.+datagramsWithin :: MonadIO m => Int -> Socket -> Stream m (SockAddr, Array Word8)+datagramsWithin microseconds socket = unfoldrM step Nothing+  where+    step started = liftIO $ do+      now <- getMonotonicTimeNSec+      let deadline = maybe (now + fromIntegral (max 0 microseconds) * 1000) id started+      if now >= deadline+        then pure Nothing+        else fmap (,Just deadline) <$> timeout (fromIntegral ((deadline - now + 999) `div` 1000)) (receiveFrom maxDatagramSize socket)++receiveFrom :: Int -> Socket -> IO (SockAddr, Array Word8)+receiveFrom size socket = do+  (bytes, sender) <- recvFrom socket size+  pure (sender, toArray bytes)++-- | Send one datagram to an address. An empty array is an empty datagram.+sendTo :: MonadIO m => Socket -> SockAddr -> Array Word8 -> m ()+sendTo socket destination datagram =+  -- One call: a datagram goes whole or not at all, and the sendAllTo of+  -- network sends nothing for an empty one.+  liftIO (void (NB.sendTo socket (fromArray datagram) destination))++-- | Send each array as a datagram to one address.+write :: MonadIO m => Socket -> SockAddr -> Fold m (Array Word8) ()+write socket destination = drainMapM (sendTo socket destination)++-- | Send each array as a datagram to the address that comes with it.+writeTo :: MonadIO m => Socket -> Fold m (SockAddr, Array Word8) ()+writeTo socket = drainMapM (uncurry (sendTo socket))++-- | Allow or forbid sending to broadcast addresses.+setBroadcast :: Socket -> Bool -> IO ()+setBroadcast socket allowed = setSocketOption socket Broadcast (if allowed then 1 else 0)++-- | A multicast group and the interface to reach it by, as the system+-- wants them (@struct ip_mreq@).+data Membership = Membership HostAddress HostAddress++instance Storable Membership where+  sizeOf _ = 8+  alignment _ = 4+  peek pointer = Membership <$> peek (castPtr pointer) <*> peek (castPtr pointer `plusPtr` 4)+  poke pointer (Membership group interface) = poke (castPtr pointer) group >> poke (castPtr pointer `plusPtr` 4) interface++-- | Join an IPv4 multicast group, on the interface that has an address, or+-- on the one the system chooses when the address is 0. The socket then+-- receives the datagrams sent to the group on the port it is bound to.+joinGroup :: Socket -> HostAddress -> HostAddress -> IO ()+joinGroup socket group interface = setSockOpt socket (SockOpt ipProtocol addMembership) (Membership group interface)++-- | Leave an IPv4 multicast group joined with 'joinGroup'.+leaveGroup :: Socket -> HostAddress -> HostAddress -> IO ()+leaveGroup socket group interface = setSockOpt socket (SockOpt ipProtocol dropMembership) (Membership group interface)++-- | How many routers the IPv4 multicast datagrams sent may cross. The+-- systems start at 1: the local network.+setMulticastTTL :: Socket -> Int -> IO ()+setMulticastTTL socket hops = setSockOpt socket (SockOpt ipProtocol multicastTtl) (fromIntegral hops :: CInt)++-- | Whether the IPv4 multicast datagrams sent come back to the sockets of+-- this machine that joined the group. The systems start with it on.+setMulticastLoopback :: Socket -> Bool -> IO ()+setMulticastLoopback socket enabled = setSockOpt socket (SockOpt ipProtocol multicastLoop) (if enabled then 1 else 0 :: CInt)
+ src/Streamly/External/Network/UDP/Constants.hsc view
@@ -0,0 +1,25 @@+-- |+-- Module      : Streamly.External.Network.UDP.Constants+-- Description : The numbers of the IPv4 multicast socket options+-- License     : BSD-3-Clause+--+-- These numbers differ from one system to another, and the network package+-- does not give them: they are read from the headers of the system.+module Streamly.External.Network.UDP.Constants+  ( ipProtocol+  , addMembership+  , dropMembership+  , multicastTtl+  , multicastLoop+  ) where++#include <netinet/in.h>++import Foreign.C.Types (CInt)++ipProtocol, addMembership, dropMembership, multicastTtl, multicastLoop :: CInt+ipProtocol = #const IPPROTO_IP+addMembership = #const IP_ADD_MEMBERSHIP+dropMembership = #const IP_DROP_MEMBERSHIP+multicastTtl = #const IP_MULTICAST_TTL+multicastLoop = #const IP_MULTICAST_LOOP
+ streamly-network-udp.cabal view
@@ -0,0 +1,72 @@+cabal-version:   3.12+name:            streamly-network-udp+version:         0.1.0.0+synopsis:        UDP datagrams as Streamly streams+description:+  UDP sockets for Streamly, over the network package: the datagrams+  received are a stream, each with its sender; datagrams are sent one by+  one or through a fold. With the broadcast option and, for IPv4, multicast+  groups.++homepage:        https://github.com/GuillaumedeVolpiano/streamly-network-udp+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-udp.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.UDP+  other-modules:   Streamly.External.Network.UDP.Constants+  build-depends:+    , base                 >=4.19 && <4.22+    , network              ^>=3.2+    , streamly-bytestring  ^>=0.2.3+    , streamly-core        ^>=0.3.3++test-suite streamly-network-udp-test+  import:         shared+  type:           exitcode-stdio-1.0+  hs-source-dirs: test+  main-is:        Main.hs+  ghc-options:    -threaded+  build-depends:+    , base+    , bytestring            ^>=0.12+    , network+    , streamly-bytestring+    , streamly-core+    , streamly-network-udp+    , tasty                 ^>=1.5+    , tasty-hunit           ^>=0.10
+ test/Main.hs view
@@ -0,0 +1,116 @@+-- | Datagrams between sockets of this machine.+module Main (main) where++import Control.Exception (try)+import Data.ByteString (ByteString, pack)+import GHC.Clock (getMonotonicTime)+import Network.Socket (SockAddr (SockAddrInet), Socket, getSocketName,+                       socketPort, tupleToHostAddress)+import Streamly.Data.Stream (fold, fromList, toList)+import Streamly.Data.Stream qualified as S (take)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.Network.UDP (SocketConfig (broadcast, reuseAddress),+                                      anyAddress, datagrams, datagramsWith,+                                      datagramsWithin, joinGroup, leaveGroup,+                                      sendTo, setMulticastLoopback,+                                      setMulticastTTL, socketAt, withSocket,+                                      write, writeTo)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++main :: IO ()+main = defaultMain tests++loopback :: SockAddr+loopback = SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1))++-- | Two sockets on the loopback interface, each with its address.+withPair :: ((Socket, SockAddr) -> (Socket, SockAddr) -> IO a) -> IO a+withPair use =+  withSocket (socketAt loopback) $ \one ->+    withSocket (socketAt loopback) $ \two -> do+      oneAddress <- getSocketName one+      twoAddress <- getSocketName two+      use (one, oneAddress) (two, twoAddress)++bytesOf :: [(SockAddr, a)] -> (a -> ByteString) -> [ByteString]+bytesOf received convert = map (convert . snd) received++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "streamly-network-udp"+      [ testCase "datagrams arrive whole, in order, with their sender" $+          withPair $ \(one, oneAddress) (two, twoAddress) -> do+            mapM_ (sendTo one twoAddress . toArray) ["first", "", "third"]+            received <- toList (S.take 3 (datagrams two))+            map fst received @?= replicate 3 oneAddress+            bytesOf received fromArray @?= ["first", "", "third"]+      , testCase "a large datagram is not cut, a small room cuts it" $+          withPair $ \(one, _) (two, twoAddress) -> do+            let large = pack (take 60_000 (cycle [0 .. 255]))+            sendTo one twoAddress (toArray large)+            whole <- toList (S.take 1 (datagrams two))+            bytesOf whole fromArray @?= [large]+            sendTo one twoAddress (toArray "0123456789")+            cut <- toList (S.take 1 (datagramsWith 4 two))+            bytesOf cut fromArray @?= ["0123"]+      , testCase "write sends each array to one address" $+          withPair $ \(one, _) (two, twoAddress) -> do+            fold (write one twoAddress) (fromList (map toArray ["a", "b"]))+            received <- toList (S.take 2 (datagrams two))+            bytesOf received fromArray @?= ["a", "b"]+      , testCase "writeTo sends each array to its own address" $+          withPair $ \(one, oneAddress) (two, twoAddress) -> do+            fold (writeTo one) (fromList [(twoAddress, toArray "to two"), (oneAddress, toArray "to one")])+            atTwo <- toList (S.take 1 (datagrams two))+            atOne <- toList (S.take 1 (datagrams one))+            (bytesOf atTwo fromArray, bytesOf atOne fromArray) @?= (["to two"], ["to one"])+      , testCase "datagramsWithin gives what came, then ends in time" $+          withPair $ \(one, _) (two, twoAddress) -> do+            mapM_ (sendTo one twoAddress . toArray) ["a", "b"]+            before <- getMonotonicTime+            received <- toList (datagramsWithin 200_000 two)+            after <- getMonotonicTime+            bytesOf received fromArray @?= ["a", "b"]+            assertBool ("waited " <> show (after - before) <> " s") (after - before >= 0.2 && after - before < 1)+      , testCase "datagramsWithin with no time left gives nothing" $+          withPair $ \(one, _) (two, twoAddress) -> do+            sendTo one twoAddress (toArray "ignored")+            received <- toList (datagramsWithin 0 two)+            length received @?= 0+      , testCase "broadcast needs the option" $ do+          let everyone = SockAddrInet 9 (tupleToHostAddress (255, 255, 255, 255))+          refused <- try (withSocket (socketAt anyAddress) (\socket -> sendTo socket everyone (toArray "x")))+          case refused of+            Left (_ :: IOError) -> pure ()+            Right () -> assertFailure "sent a broadcast without the option"+          withSocket (socketAt anyAddress) {broadcast = True} (\socket -> sendTo socket everyone (toArray "x"))+      , testCase "a socket that joined a group receives what is sent to it, until it leaves" $ do+          let group = tupleToHostAddress (239, 255, 77, 77)+              everywhere port = SockAddrInet port 0+          withSocket (socketAt (everywhere 0)) {reuseAddress = True} $ \listener -> do+            port <- socketPort listener+            joinGroup listener group 0+            withSocket (socketAt anyAddress) $ \sender -> do+              setMulticastTTL sender 1+              setMulticastLoopback sender True+              sendTo sender (SockAddrInet port group) (toArray "to the group")+              received <- toList (S.take 1 (datagramsWithin 2_000_000 listener))+              bytesOf received fromArray @?= ["to the group"]+              leaveGroup listener group 0+              sendTo sender (SockAddrInet port group) (toArray "to nobody")+              after <- toList (datagramsWithin 200_000 listener)+              length after @?= 0+      , testCase "two sockets share an address with reuseAddress, not without" $ do+          withSocket (socketAt loopback) {reuseAddress = True} $ \first -> do+            address <- getSocketName first+            withSocket (socketAt address) {reuseAddress = True} (\_ -> pure ())+          withSocket (socketAt loopback) $ \first -> do+            address <- getSocketName first+            taken <- try (withSocket (socketAt address) (\_ -> pure ()))+            case taken of+              Left (_ :: IOError) -> pure ()+              Right () -> assertFailure "bound twice to the same address"+      ]