1{-# OPTIONS_HADDOCK hide #-}
3{-# LANGUAGE BangPatterns #-}
4{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE MagicHash #-}
6{-# LANGUAGE RecordWildCards #-}
7{-# LANGUAGE UnboxedTuples #-}
12-- Module : Streamly.Internal.Network.Socket
13-- Copyright : (c) 2018 Composewell Technologies
16-- Maintainer : streamly@composewell.com
17-- Stability : experimental
20module Streamly.Internal.Network.Socket
27 -- * Accept connections
31 -- * Read from connection
44 , readChunksWithBufferOf
47 , toChunksWithBufferOf
51 -- * Write to connection
59 , fromBytesWithBufferOf
67 -- reading/writing datagrams
71import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
72import Control.Monad.Catch (MonadCatch, finally, MonadMask)
73import Control.Monad.IO.Class (MonadIO(..))
74import Control.Monad (when)
75import Data.Word (Word8)
76import Foreign.ForeignPtr (withForeignPtr)
77import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
78import Foreign.Ptr (minusPtr, plusPtr, Ptr, castPtr)
79import Foreign.Storable (Storable(..))
80import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
81import Network.Socket (sendBuf, recvBuf)
83 (Socket, SocketOption(..), Family(..), SockAddr(..),
84 ProtocolNumber, withSocketsDo, SocketType(..), socket, bind,
86#if MIN_VERSION_network(3,1,0)
87import Network.Socket (withFdSocket)
89import Network.Socket (fdSocket)
91import Prelude hiding (read)
93import qualified Network.Socket as Net
95import Streamly (MonadAsync)
96import Streamly.Internal.Data.Unfold.Types (Unfold(..))
97import Streamly.Internal.Memory.Array.Types (Array(..))
98import Streamly.Streams.Serial (SerialT)
99import Streamly.Streams.StreamK.Type (IsStream, mkStream)
100import Streamly.Data.Fold (Fold)
101-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
103import qualified Streamly.Data.Fold as FL
104import qualified Streamly.Data.Unicode.Stream as U
105import qualified Streamly.Internal.Data.Fold.Types as FL
106import qualified Streamly.Internal.Data.Unfold as UF
107import qualified Streamly.Internal.Memory.Array as IA
108import qualified Streamly.Memory.Array as A
109import qualified Streamly.Internal.Memory.ArrayStream as AS
110import qualified Streamly.Internal.Memory.Array.Types as A
111import qualified Streamly.Prelude as S
112import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
114-- | @'useSocketM' socket act@ runs the monadic computation @act@ passing the
115-- socket handle to it. The handle will be closed on exit from 'useSocketM',
116-- whether by normal termination or by raising an exception. If closing the
117-- handle raises an exception, then this exception will be raised by
118-- 'useSocketM' rather than any exception raised by 'act'.
121{-# INLINE useSocketM #-}
122useSocketM :: (MonadMask m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
123useSocketM sk f = finally (f sk) (liftIO (Net.close sk))
125-- | Like 'useSocketM' but runs a streaming computation instead of a monadic
129{-# INLINE useSocket #-}
130useSocket :: (IsStream t, MonadCatch m, MonadIO m)
131 => Socket -> (Socket -> t m a) -> t m a
132useSocket sk f = S.finally (liftIO $ Net.close sk) (f sk)
134-------------------------------------------------------------------------------
136-------------------------------------------------------------------------------
138-- XXX Protocol specific socket options should be separated from socket level
141-- | Specify the socket protocol details.
142data SockSpec = SockSpec
144 sockFamily :: !Family
145 , sockType :: !SocketType
146 , sockProto :: !ProtocolNumber
147 , sockOpts :: ![(SocketOption, Int)]
150initListener :: Int -> SockSpec -> SockAddr -> IO Socket
151initListener listenQLen SockSpec{..} addr =
153 sock <- socket sockFamily sockType sockProto
154 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
156 Net.listen sock listenQLen
159{-# INLINE listenTuples #-}
160listenTuples :: MonadIO m
161 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
162listenTuples = Unfold step inject
164 inject (listenQLen, spec, addr) = do
165 listener <- liftIO $ initListener listenQLen spec addr
169 r <- liftIO $ Net.accept listener
170 -- XXX error handling
171 return $ D.Yield r listener
173-- | Unfold a three tuple @(listenQLen, spec, addr)@ into a stream of connected
174-- protocol sockets corresponding to incoming connections. @listenQLen@ is the
175-- maximum number of pending connections in the backlog. @spec@ is the socket
176-- protocol and options specification and @addr@ is the protocol address where
177-- the server listens for incoming connections.
181accept :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
182accept = UF.map fst listenTuples
184-------------------------------------------------------------------------------
186-------------------------------------------------------------------------------
188{-# INLINE recvConnectionTuplesWith #-}
189recvConnectionTuplesWith :: MonadAsync m
190 => Int -> SockSpec -> SockAddr -> SerialT m (Socket, SockAddr)
191recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
194 listener <- liftIO $ initListener tcpListenQ spec addr
195 r <- liftIO $ Net.accept listener
196 -- XXX error handling
197 return $ Just (r, Just listener)
199 step (Just listener) = do
200 r <- liftIO $ Net.accept listener
201 -- XXX error handling
202 return $ Just (r, Just listener)
204-- | Start a TCP stream server that listens for connections on the supplied
205-- server address specification (address family, local interface IP address and
206-- port). The server generates a stream of connected sockets. The first
207-- argument is the maximum number of pending connections in the backlog.
210{-# INLINE connections #-}
211connections :: MonadAsync m => Int -> SockSpec -> SockAddr -> SerialT m Socket
212connections tcpListenQ spec addr = fmap fst $
213 recvConnectionTuplesWith tcpListenQ spec addr
215-------------------------------------------------------------------------------
217-------------------------------------------------------------------------------
219{-# INLINABLE readArrayUptoWith #-}
221 :: (h -> Ptr Word8 -> Int -> IO Int)
225readArrayUptoWith f size h = do
226 ptr <- mallocPlainForeignPtrBytes size
227 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
228 withForeignPtr ptr $ \p -> do
232 , aEnd = p `plusPtr` n
233 , aBound = p `plusPtr` size
235 -- XXX shrink only if the diff is significant
239-- | Read a 'ByteArray' from a file handle. If no data is available on the
240-- handle it blocks until some data becomes available. If data is available
241-- then it immediately returns that data without blocking. It reads a maximum
242-- of up to the size requested.
243{-# INLINABLE readArrayOf #-}
244readArrayOf :: Int -> Socket -> IO (Array Word8)
245readArrayOf = readArrayUptoWith recvBuf
247-------------------------------------------------------------------------------
249-------------------------------------------------------------------------------
251waitWhen0 :: Int -> Socket -> IO ()
252waitWhen0 0 s = when rtsSupportsBoundThreads $
253#if MIN_VERSION_network(3,1,0)
254 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
256 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
258waitWhen0 _ _ = return ()
260sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
261sendAll _ _ len | len <= 0 = return ()
263 sent <- sendBuf s p len
265 -- assert (sent <= len)
266 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
268{-# INLINABLE writeArrayWith #-}
269writeArrayWith :: Storable a
270 => (h -> Ptr Word8 -> Int -> IO ())
274writeArrayWith _ _ arr | A.length arr == 0 = return ()
275writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
279 let p = unsafeForeignPtrToPtr aStart
282-- | Write an Array to a file handle.
285{-# INLINABLE writeArray #-}
286writeArray :: Storable a => Socket -> Array a -> IO ()
287writeArray = writeArrayWith sendAll
289-------------------------------------------------------------------------------
290-- Stream of Arrays IO
291-------------------------------------------------------------------------------
293{-# INLINABLE readChunksUptoWith #-}
294readChunksUptoWith :: (IsStream t, MonadIO m)
295 => (Int -> h -> IO (Array Word8))
296 -> Int -> h -> t m (Array Word8)
297readChunksUptoWith f size h = go
299 -- XXX use cons/nil instead
300 go = mkStream $ \_ yld _ stp -> do
301 arr <- liftIO $ f size h
306-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
307-- The maximum size of a single array is limited to @size@.
308-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
310{-# INLINABLE toChunksWithBufferOf #-}
311toChunksWithBufferOf :: (IsStream t, MonadIO m)
312 => Int -> Socket -> t m (Array Word8)
313toChunksWithBufferOf = readChunksUptoWith readArrayOf
315-- XXX read 'Array a' instead of Word8
317-- | @toChunks h@ reads a stream of arrays from socket handle @h@.
318-- The maximum size of a single array is limited to @defaultChunkSize@.
321{-# INLINE toChunks #-}
322toChunks :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
323toChunks = toChunksWithBufferOf A.defaultChunkSize
325-- | Unfold the tuple @(bufsize, socket)@ into a stream of 'Word8' arrays.
326-- Read requests to the socket are performed using a buffer of size @bufsize@.
327-- The size of an array in the resulting stream is always less than or equal to
331{-# INLINE_NORMAL readChunksWithBufferOf #-}
332readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
333readChunksWithBufferOf = Unfold step return
335 {-# INLINE_LATE step #-}
337 arr <- liftIO $ readArrayOf size h
341 _ -> D.Yield arr (size, h)
343-- | Unfolds a socket into a stream of 'Word8' arrays. Requests to the socket
344-- are performed using a buffer of size
345-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. The
346-- size of arrays in the resulting stream are therefore less than or equal to
347-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
350{-# INLINE readChunks #-}
351readChunks :: MonadIO m => Unfold m Socket (Array Word8)
352readChunks = UF.supplyFirst readChunksWithBufferOf A.defaultChunkSize
354-------------------------------------------------------------------------------
355-- Read File to Stream
356-------------------------------------------------------------------------------
358-- TODO for concurrent streams implement readahead IO. We can send multiple
359-- read requests at the same time. For serial case we can use async IO. We can
360-- also control the read throughput in mbps or IOPS.
363-- | @readWithBufferOf bufsize handle@ reads a byte stream from a file
364-- handle, reads are performed in chunks of up to @bufsize@. The stream ends
365-- as soon as EOF is encountered.
367{-# INLINE readWithBufferOf #-}
368readWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
369readWithBufferOf chunkSize h = A.flattenArrays $ readChunksUpto chunkSize h
373-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
375-- > read = 'readByChunks' A.defaultChunkSize
376-- | Generate a stream of elements of the given type from a socket. The
377-- stream ends when EOF is encountered.
380{-# INLINE toBytes #-}
381toBytes :: (IsStream t, MonadIO m) => Socket -> t m Word8
382toBytes = AS.concat . toChunks
384-- | Unfolds the tuple @(bufsize, socket)@ into a byte stream, read requests
385-- to the socket are performed using buffers of @bufsize@.
388{-# INLINE readWithBufferOf #-}
389readWithBufferOf :: MonadIO m => Unfold m (Int, Socket) Word8
390readWithBufferOf = UF.concat readChunksWithBufferOf A.read
392-- | Unfolds a 'Socket' into a byte stream. IO requests to the socket are
393-- performed in sizes of
394-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
398read :: MonadIO m => Unfold m Socket Word8
399read = UF.supplyFirst readWithBufferOf A.defaultChunkSize
401-------------------------------------------------------------------------------
403-------------------------------------------------------------------------------
405-- | Write a stream of arrays to a handle.
408{-# INLINE fromChunks #-}
409fromChunks :: (MonadIO m, Storable a)
410 => Socket -> SerialT m (Array a) -> m ()
411fromChunks h m = S.mapM_ (liftIO . writeArray h) m
413-- | Write a stream of arrays to a socket. Each array in the stream is written
414-- to the socket as a separate IO request.
417{-# INLINE writeChunks #-}
418writeChunks :: (MonadIO m, Storable a) => Socket -> Fold m (Array a) ()
419writeChunks h = FL.drainBy (liftIO . writeArray h)
421-- | Write a stream of strings to a socket in Latin1 encoding.
425{-# INLINE writeStrings #-}
426writeStrings :: MonadIO m => Socket -> Fold m String ()
428 FL.lmapM (IA.fromStream . U.encodeLatin1 . S.fromList) (writeChunks h)
430-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
433-- Note that if you use a chunk size less than 8K (GHC's default buffer
434-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
435-- do not want buffering to occur at GHC level as well. Same thing applies to
438-- | Like 'write' but provides control over the write buffer. Output will
439-- be written to the IO device as soon as we collect the specified number of
443{-# INLINE fromBytesWithBufferOf #-}
444fromBytesWithBufferOf :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
445fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
447-- | Write a byte stream to a socket. Accumulates the input in chunks of
448-- specified number of bytes before writing.
451{-# INLINE writeWithBufferOf #-}
452writeWithBufferOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
453writeWithBufferOf n h = FL.lchunksOf n (A.writeNUnsafe n) (writeChunks h)
455-- > write = 'writeWithBufferOf' A.defaultChunkSize
457-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
458-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
459-- depends on the 'IOMode' and the current seek position of the handle.
462{-# INLINE fromBytes #-}
463fromBytes :: MonadIO m => Socket -> SerialT m Word8 -> m ()
464fromBytes = fromBytesWithBufferOf A.defaultChunkSize
466-- | Write a byte stream to a socket. Accumulates the input in chunks of
467-- up to 'A.defaultChunkSize' bytes before writing.
470-- write = 'writeWithBufferOf' 'A.defaultChunkSize'
475write :: MonadIO m => Socket -> Fold m Word8 ()
476write = writeWithBufferOf A.defaultChunkSize
480write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
481write = toHandleWith A.defaultChunkSize
484-------------------------------------------------------------------------------
485-- IO with encoding/decoding Unicode characters
486-------------------------------------------------------------------------------
490-- > readUtf8 = decodeUtf8 . read
492-- Read a UTF8 encoded stream of unicode characters from a file handle.
495{-# INLINE readUtf8 #-}
496readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
497readUtf8 = decodeUtf8 . read
500-- > writeUtf8 h s = write h $ encodeUtf8 s
502-- Encode a stream of unicode characters to UTF8 and write it to the given file
503-- handle. Default block buffering applies to the writes.
506{-# INLINE writeUtf8 #-}
507writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
508writeUtf8 h s = write h $ encodeUtf8 s
510-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
511-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
512-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
513-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
517{-# INLINE writeUtf8ByLines #-}
518writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
519writeUtf8ByLines = undefined
521-- | Read UTF-8 lines from a file handle and apply the specified fold to each
522-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
525{-# INLINE readLines #-}
526readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
527readLines h f = foldLines (readUtf8 h) f
529-------------------------------------------------------------------------------
530-- Framing on a sequence
531-------------------------------------------------------------------------------
533-- | Read a stream from a file handle and split it into frames delimited by
534-- the specified sequence of elements. The supplied fold is applied on each
538{-# INLINE readFrames #-}
539readFrames :: (IsStream t, MonadIO m, Storable a)
540 => Array a -> Handle -> Fold m a b -> t m b
541readFrames = undefined -- foldFrames . read
543-- | Write a stream to the given file handle buffering up to frames separated
544-- by the given sequence or up to a maximum of @defaultChunkSize@.
547{-# INLINE writeByFrames #-}
548writeByFrames :: (IsStream t, MonadIO m, Storable a)
549 => Array a -> Handle -> t m a -> m ()
550writeByFrames = undefined
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list