effectful-websockets (empty) → 0.1.0.0
raw patch · 7 files changed
+668/−0 lines, 7 filesdep +asyncdep +basedep +bytestring
Dependencies added: async, base, bytestring, effectful, effectful-core, effectful-websockets, network, stm, streamly-core, streamly-http, streamly-websockets, tasty, tasty-hunit, text
Files
- CHANGELOG.md +13/−0
- LICENSE +29/−0
- README.md +64/−0
- effectful-websockets.cabal +83/−0
- src/Effectful/WebSocket.hs +104/−0
- src/Effectful/WebSocket/Client.hs +224/−0
- test/Main.hs +151/−0
+ CHANGELOG.md view
@@ -0,0 +1,13 @@+# Revision history for effectful-websockets++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `Effectful.WebSocket`: the `WebSocket` effect, with text and binary+ messages, a stream of received messages, and an interpreter from two+ actions; `traced`, to observe the messages of a connection.+* `Effectful.WebSocket.Client`: a client over streamly-websockets, with+ configurable pings, that keeps the action in the calling thread and+ waits for the server to answer the closing of the connection.+* `runWebSocketOver` and `connectionConfig`, for interpreters that open+ the connection another way, as effectful-websockets-tls does.
+ 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,64 @@+# effectful-websockets++A WebSocket connection as an [Effectful](https://hackage.haskell.org/package/effectful)+effect.++- `Effectful.WebSocket`: the `WebSocket` effect. Send and receive whole+ text or binary messages, one at a time or as a+ [Streamly](https://hackage.haskell.org/package/streamly-core) stream+ (`messages`). `runWebSocketWith` interprets it with two actions, for+ tests; `traced` reports every message to an observer, whatever the+ interpreter.+- `Effectful.WebSocket.Client`: `runWebSocketClient` opens a connection+ with the+ [streamly-websockets](https://hackage.haskell.org/package/streamly-websockets)+ package and runs an action over it.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Effectful (Eff, IOE, (:>))+import Effectful.Error.Static (Error)+import Effectful.WebSocket (Message, receiveMessage, sendText)+import Effectful.WebSocket.Client (WebSocketError, clientConfig,+ runWebSocketClient)++hello :: (IOE :> es, Error WebSocketError :> es) => Eff es (Maybe Message)+hello = runWebSocketClient (clientConfig "127.0.0.1" 8080 "/") $ do+ _ <- sendText "hello"+ receiveMessage+```++## Behaviour++- The action runs in the calling thread, so effects with thread-local+ state keep its changes. The pings are sent by a watchdog thread.+- The server is pinged every ten seconds by default, with twenty seconds to+ answer; `NoPong` reports a silent server. Pongs are only seen while the+ action receives messages.+- Sending from several threads at once is safe: each message goes out+ whole.+- A connection closed by the server is not an error: receiving returns+ `Nothing`, and sending then returns `False`.+- When the action is done, the client closes the WebSocket and waits for the+ server to answer (one second by default) before the TCP connection goes,+ so that the server reads all that was sent.+- Plain TCP only. Secure WebSockets (`wss://`) are in+ [effectful-websockets-tls](https://github.com/GuillaumedeVolpiano/effectful-websockets-tls),+ a package apart, so that this one does not need a TLS stack.++A server that breaks the protocol, or sends a message larger than+`maxMessageSize`, ends the connection like a server that closes it.++To build against copies of+[streamly-websockets](https://hackage.haskell.org/package/streamly-websockets)+and [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, against the+server of streamly-websockets.++## License++BSD-3-Clause. See [LICENSE](LICENSE).
+ effectful-websockets.cabal view
@@ -0,0 +1,83 @@+cabal-version: 3.12+name: effectful-websockets+version: 0.1.0.0+synopsis: WebSocket connections as an Effectful effect+description:+ A WebSocket effect for Effectful: send and receive whole text or binary+ messages, as single actions or as a Streamly stream. The client+ interpreter runs over the streamly-websockets package, keeps the action+ in the calling thread, and watches the connection with pings.++homepage: https://github.com/GuillaumedeVolpiano/effectful-websockets+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-websockets.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ 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.WebSocket+ Effectful.WebSocket.Client++ build-depends:+ , async ^>=2.2+ , base >=4.19 && <4.22+ , bytestring ^>=0.12+ , effectful-core ^>=2.7.1+ , stm ^>=2.5+ , streamly-core ^>=0.3.3+ , streamly-http ^>=0.1+ , streamly-websockets ^>=0.1+ , text ^>=2.1++test-suite effectful-websockets-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , async+ , base+ , bytestring+ , effectful ^>=2.7+ , effectful-core+ , effectful-websockets+ , network ^>=3.2+ , stm+ , streamly-core+ , streamly-websockets+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10
+ src/Effectful/WebSocket.hs view
@@ -0,0 +1,104 @@+-- |+-- Module : Effectful.WebSocket+-- Description : A WebSocket connection as an effect+-- License : BSD-3-Clause+--+-- Sending and receiving whole messages over an open WebSocket. The+-- connection itself is opened by an interpreter, such as+-- 'Effectful.WebSocket.Client.runWebSocketClient', or simulated by+-- 'runWebSocketWith' in tests.+--+-- Sending is safe from several threads at once: each message goes out+-- whole.+module Effectful.WebSocket+ ( -- * Effect+ WebSocket (..)+ , Message (..)+ , sendMessage+ , sendText+ , sendBinary+ , receiveMessage+ , messages++ -- * Interpreters+ , runWebSocketWith++ -- * Observing the traffic+ , Traffic (..)+ , traced+ ) where++import Data.ByteString (ByteString)+import Data.Text (Text)+import Effectful (Dispatch (Dynamic), DispatchOf, Eff, Effect, type (:>))+import Effectful.Dispatch.Dynamic (interpose_, interpret_, send)+import Streamly.Data.Stream (Stream, unfoldrM)++-- | A whole WebSocket message.+data Message+ = TextMessage Text+ | BinaryMessage ByteString+ deriving stock (Eq, Show)++-- | Exchange messages over an open WebSocket.+data WebSocket :: Effect where+ SendMessage :: Message -> WebSocket m Bool+ ReceiveMessage :: WebSocket m (Maybe Message)++type instance DispatchOf WebSocket = Dynamic++-- | Send a message. 'False' means the connection is closed and the+-- message was not sent.+sendMessage :: WebSocket :> es => Message -> Eff es Bool+sendMessage = send . SendMessage++-- | Send a text message, like 'sendMessage'.+sendText :: WebSocket :> es => Text -> Eff es Bool+sendText = sendMessage . TextMessage++-- | Send a binary message, like 'sendMessage'.+sendBinary :: WebSocket :> es => ByteString -> Eff es Bool+sendBinary = sendMessage . BinaryMessage++-- | Wait for the next message. 'Nothing' means the connection is closed.+receiveMessage :: WebSocket :> es => Eff es (Maybe Message)+receiveMessage = send ReceiveMessage++-- | The messages received until the connection closes.+messages :: WebSocket :> es => Stream (Eff es) Message+messages = unfoldrM (const (fmap (,()) <$> receiveMessage)) ()++-- | Interpret the effect with two actions: for tests, or for another+-- transport.+runWebSocketWith+ :: (Message -> Eff es Bool)+ -- ^ Send a message; 'False' when the connection is closed.+ -> Eff es (Maybe Message)+ -- ^ Receive a message; 'Nothing' when the connection is closed.+ -> Eff (WebSocket : es) a+ -> Eff es a+runWebSocketWith sendAction receiveAction = interpret_ $ \case+ SendMessage message -> sendAction message+ ReceiveMessage -> receiveAction++-- | A message that went through the connection.+data Traffic+ = -- | A message sent, and whether it went out.+ Sent Message Bool+ | -- | A message received; 'Nothing' when the connection closed.+ Received (Maybe Message)+ deriving stock (Eq, Show)++-- | Report every message of an action to an observer, whatever interprets+-- the effect, and leave the messages as they are. The observer runs in the+-- thread that sends or receives.+traced :: WebSocket :> es => (Traffic -> Eff es ()) -> Eff es a -> Eff es a+traced observe = interpose_ $ \case+ SendMessage message -> do+ sent <- sendMessage message+ observe (Sent message sent)+ pure sent+ ReceiveMessage -> do+ received <- receiveMessage+ observe (Received received)+ pure received
+ src/Effectful/WebSocket/Client.hs view
@@ -0,0 +1,224 @@+-- |+-- Module : Effectful.WebSocket.Client+-- Description : Opening a WebSocket to a server+-- License : BSD-3-Clause+--+-- A client over the @streamly-websockets@ package, on plain TCP (no TLS).+--+-- The action runs in the thread of the caller, so that effects with+-- thread-local state, such as a local @State@, keep the changes it makes.+-- The pings are sent by a watchdog thread.+module Effectful.WebSocket.Client+ ( -- * Configuration+ ClientConfig (..)+ , clientConfig+ , PingPong (..)+ , defaultPingPong++ -- * Errors+ , WebSocketError (..)++ -- * Interpreter+ , runWebSocketClient++ -- * Other ways to open the connection+ , runWebSocketOver+ , connectionConfig+ ) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (ExceptionInLinkedThread (..), link, withAsync)+import Control.Concurrent.STM (atomically, check, readTVar, registerDelay)+import Control.Exception (Exception, IOException, SomeException, catch,+ displayException, fromException, throwIO, try)+import Control.Monad (forever, unless)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as BS8 (pack)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Text (Text)+import Data.Text qualified as T (pack)+import Effectful (Eff, IOE, MonadIO (liftIO), UnliftStrategy (SeqUnlift),+ withEffToIO, type (:>))+import Effectful.Error.Static (Error, throwError)+import Effectful.WebSocket (Message (..), WebSocket, runWebSocketWith)+import Streamly.External.Network.HTTP (HttpError)+import Streamly.External.Network.WebSocket (Connection, ping, pongCount,+ receive, send, withConnection)+import Streamly.External.Network.WebSocket qualified as WS (Config (closeTimeout, headers, maxMessageSize),+ Message (BinaryMessage, TextMessage),+ WebSocketError,+ config)++-- | Where to connect, and how.+data ClientConfig = ClientConfig+ { host :: String+ , port :: Int+ , path :: String+ -- ^ Such as @\/api@.+ , headers :: [(ByteString, ByteString)]+ -- ^ Extra headers for the opening handshake: names and values.+ , maxMessageSize :: Int+ -- ^ The largest message accepted, in bytes. A larger one ends the+ -- connection.+ , pingPong :: Maybe PingPong+ -- ^ 'Nothing' sends no ping.+ , closeTimeout :: Int+ -- ^ Microseconds to wait, once the action is done, for the server to+ -- answer the closing of the connection.+ }++-- | A configuration with no extra header, messages of at most 64 MiB,+-- 'defaultPingPong', and one second to close.+clientConfig :: String -> Int -> String -> ClientConfig+clientConfig host port path =+ ClientConfig+ { host+ , port+ , path+ , headers = []+ , maxMessageSize = 64 * 1024 * 1024+ , pingPong = Just defaultPingPong+ , closeTimeout = 1_000_000+ }++-- | Keeping the connection alive, and noticing when the server is gone.+data PingPong = PingPong+ { interval :: Int+ -- ^ Seconds between two pings.+ , timeout :: Int+ -- ^ Seconds without a pong before the connection counts as lost.+ }+ deriving stock (Eq, Show)++-- | A ping every ten seconds, twenty seconds to answer.+defaultPingPong :: PingPong+defaultPingPong = PingPong {interval = 10, timeout = 20}++-- | Why a connection could not be used.+data WebSocketError+ = -- | The connection could not be opened. Carries the cause.+ ConnectFailed Text+ | -- | The server did not answer the pings in time.+ NoPong+ deriving stock (Eq, Show)++-- | Thrown by the watchdog when a ping gets no pong in time.+data PongTimeout = PongTimeout+ deriving stock (Show)++instance Exception PongTimeout++-- | Open a connection and run an action over it. The connection is closed+-- when the action returns.+--+-- Pongs are only seen while the action receives messages: an action that+-- stops receiving for longer than the timeout loses the connection.+--+-- Throws 'ConnectFailed' if the connection cannot be opened, and 'NoPong'+-- if the server stops answering pings. A connection closed by the server+-- is not an error: receiving returns 'Nothing' and sending 'False'. So+-- does a server that breaks the protocol or sends too large a message.+runWebSocketClient+ :: (IOE :> es, Error WebSocketError :> es)+ => ClientConfig+ -> Eff (WebSocket : es) a+ -> Eff es a+runWebSocketClient config = runWebSocketOver (withConnection (connectionConfig config)) config.pingPong++-- | The configuration of @streamly-websockets@ that a t'ClientConfig'+-- stands for, without its pings.+connectionConfig :: ClientConfig -> WS.Config+connectionConfig config =+ (WS.config config.host config.port (BS8.pack config.path))+ { WS.headers = config.headers+ , WS.maxMessageSize = config.maxMessageSize+ , WS.closeTimeout = config.closeTimeout+ }++-- | Like 'runWebSocketClient', with the way to open the connection left+-- to a function, such as @withConnection@ of @streamly-websockets@ over+-- another transport: @effectful-websockets-tls@ uses it for secure+-- WebSockets. The pings are given apart.+--+-- What the function throws before it has a connection is reported as+-- 'ConnectFailed' when it is an 'IOError', an error of+-- @streamly-websockets@ or one of @streamly-http@; anything else passes.+runWebSocketOver+ :: (IOE :> es, Error WebSocketError :> es)+ => (forall x. (Connection -> IO x) -> IO x)+ -> Maybe PingPong+ -> Eff (WebSocket : es) a+ -> Eff es a+runWebSocketOver open pings action = do+ outcome <- withEffToIO SeqUnlift $ \runInIO -> do+ connected <- newIORef False+ attempt <- try . open $ \connection -> do+ writeIORef connected True+ closed <- newIORef False+ let run = runInIO (runWebSocketWith (liftIO . sendTo closed connection) (liftIO (receiveFrom closed connection)) action)+ case pings of+ Nothing -> run+ Just pingPong -> withAsync (watch pingPong connection) $ \watchdog -> link watchdog >> run+ wasConnected <- readIORef connected+ case attempt of+ Right value -> pure (Right value)+ Left (err :: SomeException)+ | not wasConnected, openingFailure err -> pure (Left (ConnectFailed (T.pack (displayException err))))+ | Just (ExceptionInLinkedThread _ cause) <- fromException err+ , Just PongTimeout <- fromException cause ->+ pure (Left NoPong)+ | otherwise -> throwIO err+ either throwError pure outcome+ where+ -- What opening a connection throws: the TCP connection, the request,+ -- the answer of the server.+ openingFailure err =+ or+ [ maybe False (\(_ :: IOException) -> True) (fromException err)+ , maybe False (\(_ :: WS.WebSocketError) -> True) (fromException err)+ , maybe False (\(_ :: HttpError) -> True) (fromException err)+ ]++-- | Ping at each interval, and fail when the pong does not come in time.+-- Stops quietly once nothing can be sent: the connection is then closed,+-- which the action sees for itself.+watch :: PingPong -> Connection -> IO ()+watch pingPong connection = loop `catch` (\(_ :: WS.WebSocketError) -> pure ()) `catch` (\(_ :: IOException) -> pure ())+ where+ loop = forever $ do+ threadDelay (pingPong.interval * 1_000_000)+ before <- atomically (pongCount connection)+ ping connection ""+ expired <- registerDelay (pingPong.timeout * 1_000_000)+ answered <- atomically $ do+ count <- pongCount connection+ late <- readTVar expired+ check (count > before || late)+ pure (count > before)+ unless answered (throwIO PongTimeout)++-- | Once the connection is known to be closed, nothing is sent.+sendTo :: IORef Bool -> Connection -> Message -> IO Bool+sendTo closed connection message =+ readIORef closed >>= \case+ True -> pure False+ False ->+ ( True <$ send connection (case message of+ TextMessage text -> WS.TextMessage text+ BinaryMessage bytes -> WS.BinaryMessage bytes)+ )+ `catch` (\(_ :: WS.WebSocketError) -> lost)+ `catch` (\(_ :: IOException) -> lost)+ where+ lost = False <$ writeIORef closed True++receiveFrom :: IORef Bool -> Connection -> IO (Maybe Message)+receiveFrom closed connection =+ (receive connection >>= maybe lost (pure . Just . fromMessage))+ `catch` (\(_ :: WS.WebSocketError) -> lost)+ `catch` (\(_ :: IOException) -> lost)+ where+ lost = Nothing <$ writeIORef closed True+ fromMessage = \case+ WS.TextMessage text -> TextMessage text+ WS.BinaryMessage bytes -> BinaryMessage bytes
+ test/Main.hs view
@@ -0,0 +1,151 @@+-- | The client against a server of streamly-websockets on the loopback+-- interface.+module Main (main) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (withAsync)+import Control.Concurrent.STM (atomically, newTQueueIO, readTQueue, writeTQueue)+import Control.Exception (bracket)+import Control.Monad (forM_, forever, replicateM)+import Data.ByteString (pack)+import Data.ByteString qualified as BS (replicate)+import Data.IORef (atomicModifyIORef', modifyIORef', newIORef, readIORef)+import Data.List (sort)+import Effectful (Eff, IOE, MonadIO (liftIO), runEff)+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Concurrent.Async (forConcurrently_)+import Effectful.Error.Static (Error, runErrorNoCallStack)+import Effectful.State.Static.Local (execState, modify)+import Effectful.WebSocket (Message (BinaryMessage, TextMessage),+ Traffic (Received, Sent), WebSocket, messages,+ receiveMessage, runWebSocketWith, sendBinary,+ sendText, traced)+import Effectful.WebSocket.Client (ClientConfig (pingPong),+ PingPong (PingPong, interval, timeout),+ WebSocketError (..), clientConfig,+ runWebSocketClient)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+ SocketType (Stream), bind, defaultProtocol, socketPort,+ tupleToHostAddress)+import Network.Socket qualified as N (close, socket)+import Streamly.Data.Fold (drainMapM, toList)+import Streamly.Data.Fold qualified as F (drain)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.WebSocket.Server (Connection,+ defaultServerOptions, listen,+ send, serveSocket)+import Streamly.External.Network.WebSocket.Server qualified as WSS (Message (BinaryMessage, TextMessage),+ close,+ messages)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+ localOption (mkTimeout 20_000_000) $+ testGroup+ "effectful-websockets"+ [ testCase "echoes text and binary messages" $ do+ outcome <- withServer echo $ \config -> client config $ do+ _ <- sendText "héllo"+ _ <- sendBinary (pack [0, 1, 255])+ replicateM 2 receiveMessage+ outcome @?= Right [Just (TextMessage "héllo"), Just (BinaryMessage (pack [0, 1, 255]))]+ , testCase "carries a message larger than one packet" $ do+ let large = BS.replicate 300_000 42+ outcome <- withServer echo $ \config -> client config (sendBinary large >> receiveMessage)+ outcome @?= Right (Just (BinaryMessage large))+ , testCase "streams messages until the server closes" $ do+ let server connection = forM_ ["a", "b", "c"] (send connection . WSS.TextMessage) >> WSS.close connection >> drain connection+ outcome <- withServer server $ \config -> client config (fold toList messages)+ outcome @?= Right [TextMessage "a", TextMessage "b", TextMessage "c"]+ , testCase "sending after the server closed fails" $ do+ let server connection = WSS.close connection >> drain connection+ outcome <- withServer server $ \config -> client config $ do+ _ <- receiveMessage+ liftIO (threadDelay 100_000)+ sendText "late"+ outcome @?= Right False+ , testCase "reports a refused connection" $ do+ port <- freePort+ outcome <- client (clientConfig "127.0.0.1" port "/") (pure ())+ case outcome of+ Left (ConnectFailed _) -> pure ()+ other -> fail ("unexpected outcome: " <> show other)+ , testCase "reports a server that stops answering pings" $ do+ -- This server never reads, so it never answers a ping.+ let server _ = forever (threadDelay 1_000_000)+ outcome <- withServer server $ \config ->+ client config {pingPong = Just PingPong {interval = 1, timeout = 2}} receiveMessage+ outcome @?= Left NoPong+ , testCase "keeps the local state of the action" $ do+ outcome <- withServer echo $ \config ->+ client config . execState (0 :: Int) $ do+ modify @Int (+ 1)+ _ <- sendText "x" >> receiveMessage+ modify @Int (+ 1)+ outcome @?= Right 2+ , testCase "traced reports the traffic of an in-memory connection" $ do+ (log', inbox) <- (,) <$> newIORef [] <*> newIORef [Just (TextMessage "one"), Nothing]+ let receive = liftIO (atomicModifyIORef' inbox (\case (x : rest) -> (rest, x); [] -> ([], Nothing)))+ observe traffic = liftIO (modifyIORef' log' (traffic :))+ received <- runEff . runWebSocketWith (\_ -> pure True) receive . traced observe $+ sendText "hello" >> (,) <$> receiveMessage <*> receiveMessage+ received @?= (Just (TextMessage "one"), Nothing)+ reverse <$> readIORef log' >>= (@?= [Sent (TextMessage "hello") True, Received (Just (TextMessage "one")), Received Nothing])+ , testCase "traced reports the traffic of a real connection" $ do+ log' <- newIORef []+ outcome <- withServer echo $ \config ->+ client config . traced (\traffic -> liftIO (modifyIORef' log' (traffic :))) $+ sendBinary (pack [1, 2]) >> receiveMessage+ outcome @?= Right (Just (BinaryMessage (pack [1, 2])))+ reverse <$> readIORef log' >>= (@?= [Sent (BinaryMessage (pack [1, 2])) True, Received (Just (BinaryMessage (pack [1, 2])))])+ , testCase "sends from several threads without mixing messages" $ do+ let payloads = [BS.replicate 50_000 (fromIntegral n) | n <- [1 .. 20 :: Int]]+ received <- newTQueueIO+ let keep = \case+ WSS.BinaryMessage bytes -> atomically (writeTQueue received bytes)+ WSS.TextMessage _ -> pure ()+ server connection = fold (drainMapM keep) (WSS.messages connection)+ outcome <- withServer server $ \config ->+ client config (forConcurrently_ payloads sendBinary)+ outcome @?= Right ()+ messagesReceived <- replicateM 20 (atomically (readTQueue received))+ sort messagesReceived @?= sort payloads+ ]++-- | Echo every message.+echo :: Connection -> IO ()+echo connection = fold (drainMapM (send connection)) (WSS.messages connection)++-- | Read until the client closes.+drain :: Connection -> IO ()+drain connection = fold F.drain (WSS.messages connection)++client+ :: ClientConfig+ -> Eff '[WebSocket, Error WebSocketError, Concurrent, IOE] a+ -> IO (Either WebSocketError a)+client config = runEff . runConcurrent . runErrorNoCallStack . runWebSocketClient config++-- | Serve each connection with a handler, on a free loopback port, while+-- the client runs.+withServer+ :: (Connection -> IO ())+ -> (ClientConfig -> IO (Either WebSocketError a))+ -> IO (Either WebSocketError a)+withServer handler run =+ bracket (listen "127.0.0.1" 0) N.close $ \listener -> do+ port <- socketPort listener+ withAsync (serveSocket listener defaultServerOptions (const handler)) $ \_ ->+ run (clientConfig "127.0.0.1" (fromIntegral port) "/")++-- | A port that was free a moment ago.+freePort :: IO Int+freePort =+ bracket (N.socket AF_INET Stream defaultProtocol) N.close $ \socket -> do+ bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ fromIntegral <$> socketPort socket