4-- Module : Streamly.Internal.Network.Socket
5-- Copyright : (c) 2018 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
12module Streamly.Internal.Network.Socket
19 -- * Accept connections
25 -- * Read from connection
38 , readChunksWithBufferOf
41 , toChunksWithBufferOf
45 -- * Write to connection
53 , fromBytesWithBufferOf
59 , writeChunksWithBufferOf
62 -- reading/writing datagrams
66import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
67import Control.Exception (onException)
68import Control.Monad.Catch (MonadCatch, finally, MonadMask)
69import Control.Monad.IO.Class (MonadIO(..))
70import Control.Monad (forM_, when)
71import Data.Word (Word8)
72import Foreign.ForeignPtr (withForeignPtr)
73import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
74import Foreign.Ptr (minusPtr, plusPtr, Ptr, castPtr)
75import Foreign.Storable (Storable(..))
76import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
78 (Socket, SocketOption(..), Family(..), SockAddr(..),
79 ProtocolNumber, withSocketsDo, SocketType(..), socket, bind,
80 setSocketOption, sendBuf, recvBuf)
81#if MIN_VERSION_network(3,1,0)
82import Network.Socket (withFdSocket)
84import Network.Socket (fdSocket)
86import Prelude hiding (read)
88import qualified Network.Socket as Net
90import Streamly.Prelude (MonadAsync)
91import Streamly.Internal.Data.Unfold.Types (Unfold(..))
92import Streamly.Internal.Data.Array.Storable.Foreign.Types (Array(..), lpackArraysChunksOf)
93import Streamly.Internal.Data.Array.Storable.Foreign.Mut.Types (mutableArray)
94import Streamly.Internal.Data.Stream.Serial (SerialT)
95import Streamly.Internal.Data.Stream.StreamK.Type (IsStream, mkStream)
96import Streamly.Data.Fold (Fold)
97-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
99import qualified Streamly.Data.Fold as FL
100import qualified Streamly.Internal.Data.Fold.Types as FL
101import qualified Streamly.Internal.Data.Unfold as UF
102import qualified Streamly.Internal.Data.Array.Storable.Foreign as IA
103import qualified Streamly.Data.Array.Storable.Foreign as A
104import qualified Streamly.Internal.Memory.ArrayStream as AS
105import qualified Streamly.Internal.Data.Array.Storable.Foreign.Types as A
106import qualified Streamly.Prelude as S
107import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
109-- | @'handleWithM' socket act@ runs the monadic computation @act@ passing the
110-- socket handle to it. The handle will be closed on exit from 'handleWithM',
111-- whether by normal termination or by raising an exception. If closing the
112-- handle raises an exception, then this exception will be raised by
113-- 'handleWithM' rather than any exception raised by 'act'.
116{-# INLINE handleWithM #-}
117handleWithM :: (MonadMask m, MonadIO m) => (Socket -> m ()) -> Socket -> m ()
118handleWithM f sk = finally (f sk) (liftIO (Net.close sk))
120-- | Like 'handleWithM' but runs a streaming computation instead of a monadic
124{-# INLINE handleWith #-}
125handleWith :: (IsStream t, MonadAsync m, MonadCatch m)
126 => Socket -> (Socket -> t m a) -> t m a
127handleWith sk f = S.finally (liftIO $ Net.close sk) (f sk)
129-------------------------------------------------------------------------------
131-------------------------------------------------------------------------------
133-- XXX Protocol specific socket options should be separated from socket level
136-- | Specify the socket protocol details.
137data SockSpec = SockSpec
139 sockFamily :: !Family
140 , sockType :: !SocketType
141 , sockProto :: !ProtocolNumber
142 , sockOpts :: ![(SocketOption, Int)]
145initListener :: Int -> SockSpec -> SockAddr -> IO Socket
146initListener listenQLen SockSpec{..} addr =
148 sock <- socket sockFamily sockType sockProto
149 use sock `onException` Net.close sock
155 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
157 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) =
165 liftIO $ initListener listenQLen spec addr
168 r <- liftIO (Net.accept listener `onException` Net.close listener)
169 return $ D.Yield r listener
171-- | Unfold a three tuple @(listenQLen, spec, addr)@ into a stream of connected
172-- protocol sockets corresponding to incoming connections. @listenQLen@ is the
173-- maximum number of pending connections in the backlog. @spec@ is the socket
174-- protocol and options specification and @addr@ is the protocol address where
175-- the server listens for incoming connections.
179accept :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
180accept = UF.map fst listenTuples
182{-# INLINE connectCommon #-}
183connectCommon :: SockSpec -> Maybe SockAddr -> SockAddr -> IO Socket
184connectCommon SockSpec{..} local remote = withSocketsDo $ do
185 sock <- socket sockFamily sockType sockProto
186 use sock `onException` Net.close sock
192 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
193 forM_ local (bind sock)
194 Net.connect sock remote
196-- | Connect to a remote host using the given socket specification and remote
197-- address. Returns a connected socket or throws an exception.
201{-# INLINE connect #-}
202connect :: SockSpec -> SockAddr -> IO Socket
203connect spec = connectCommon spec Nothing
205-- | Connect to a remote host using the given socket specification, a local
206-- address to bind to and a remote address to connect to. Returns a connected
207-- socket or throws an exception.
211{-# INLINE connectFrom #-}
212connectFrom :: SockSpec -> SockAddr -> SockAddr -> IO Socket
213connectFrom spec local = connectCommon spec (Just local)
215-------------------------------------------------------------------------------
217-------------------------------------------------------------------------------
219{-# INLINE recvConnectionTuplesWith #-}
220recvConnectionTuplesWith :: MonadAsync m
221 => Int -> SockSpec -> SockAddr -> SerialT m (Socket, SockAddr)
222recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
225 listener <- liftIO $ initListener tcpListenQ spec addr
226 r <- liftIO (Net.accept listener `onException` Net.close listener)
227 return $ Just (r, Just listener)
229 step (Just listener) = do
230 r <- liftIO (Net.accept listener `onException` Net.close listener)
231 return $ Just (r, Just listener)
233-- | Start a TCP stream server that listens for connections on the supplied
234-- server address specification (address family, local interface IP address and
235-- port). The server generates a stream of connected sockets. The first
236-- argument is the maximum number of pending connections in the backlog.
239{-# INLINE connections #-}
240connections :: MonadAsync m => Int -> SockSpec -> SockAddr -> SerialT m Socket
241connections tcpListenQ spec addr =
242 fst <$> recvConnectionTuplesWith tcpListenQ spec addr
244-------------------------------------------------------------------------------
246-------------------------------------------------------------------------------
248{-# INLINABLE readArrayUptoWith #-}
250 :: (h -> Ptr Word8 -> Int -> IO Int)
254readArrayUptoWith f size h = do
255 ptr <- mallocPlainForeignPtrBytes size
256 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
257 withForeignPtr ptr $ \p -> do
259 let v = A.unsafeFreeze
260 $ mutableArray ptr (p `plusPtr` n) (p `plusPtr` size)
262 -- XXX shrink only if the diff is significant
266-- | Read a 'ByteArray' from a file handle. If no data is available on the
267-- handle it blocks until some data becomes available. If data is available
268-- then it immediately returns that data without blocking. It reads a maximum
269-- of up to the size requested.
270{-# INLINABLE readArrayOf #-}
271readArrayOf :: Int -> Socket -> IO (Array Word8)
272readArrayOf = readArrayUptoWith recvBuf
274-------------------------------------------------------------------------------
276-------------------------------------------------------------------------------
278waitWhen0 :: Int -> Socket -> IO ()
279waitWhen0 0 s = when rtsSupportsBoundThreads $
280#if MIN_VERSION_network(3,1,0)
281 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
282#elif MIN_VERSION_network(3,0,0)
283 fdSocket s >>= threadWaitWrite . fromIntegral
285 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
287waitWhen0 _ _ = return ()
289sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
290sendAll _ _ len | len <= 0 = return ()
292 sent <- sendBuf s p len
294 -- assert (sent <= len)
295 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
297{-# INLINABLE writeArrayWith #-}
298writeArrayWith :: Storable a
299 => (h -> Ptr Word8 -> Int -> IO ())
303writeArrayWith _ _ arr | A.length arr == 0 = return ()
304writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
308 let p = unsafeForeignPtrToPtr aStart
311-- | Write an Array to a file handle.
314{-# INLINABLE writeChunk #-}
315writeChunk :: Storable a => Socket -> Array a -> IO ()
316writeChunk = writeArrayWith sendAll
318-------------------------------------------------------------------------------
319-- Stream of Arrays IO
320-------------------------------------------------------------------------------
322{-# INLINABLE _readChunksUptoWith #-}
323_readChunksUptoWith :: (IsStream t, MonadIO m)
324 => (Int -> h -> IO (Array Word8))
325 -> Int -> h -> t m (Array Word8)
326_readChunksUptoWith f size h = go
328 -- XXX use cons/nil instead
329 go = mkStream $ \_ yld _ stp -> do
330 arr <- liftIO $ f size h
335-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
336-- The maximum size of a single array is limited to @size@.
337-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
339{-# INLINE_NORMAL toChunksWithBufferOf #-}
340toChunksWithBufferOf :: (IsStream t, MonadIO m)
341 => Int -> Socket -> t m (Array Word8)
342-- toChunksWithBufferOf = _readChunksUptoWith readArrayOf
343toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
345 {-# INLINE_LATE step #-}
347 arr <- liftIO $ readArrayOf size h
353-- XXX read 'Array a' instead of Word8
355-- | @toChunks h@ reads a stream of arrays from socket handle @h@.
356-- The maximum size of a single array is limited to @defaultChunkSize@.
359{-# INLINE toChunks #-}
360toChunks :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
361toChunks = toChunksWithBufferOf A.defaultChunkSize
363-- | Unfold the tuple @(bufsize, socket)@ into a stream of 'Word8' arrays.
364-- Read requests to the socket are performed using a buffer of size @bufsize@.
365-- The size of an array in the resulting stream is always less than or equal to
369{-# INLINE_NORMAL readChunksWithBufferOf #-}
370readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
371readChunksWithBufferOf = Unfold step return
373 {-# INLINE_LATE step #-}
375 arr <- liftIO $ readArrayOf size h
379 _ -> D.Yield arr (size, h)
381-- | Unfolds a socket into a stream of 'Word8' arrays. Requests to the socket
382-- are performed using a buffer of size
383-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize'. The
384-- size of arrays in the resulting stream are therefore less than or equal to
385-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize'.
388{-# INLINE readChunks #-}
389readChunks :: MonadIO m => Unfold m Socket (Array Word8)
390readChunks = UF.supplyFirst readChunksWithBufferOf A.defaultChunkSize
392-------------------------------------------------------------------------------
393-- Read File to Stream
394-------------------------------------------------------------------------------
396-- TODO for concurrent streams implement readahead IO. We can send multiple
397-- read requests at the same time. For serial case we can use async IO. We can
398-- also control the read throughput in mbps or IOPS.
401-- | @readWithBufferOf bufsize handle@ reads a byte stream from a file
402-- handle, reads are performed in chunks of up to @bufsize@. The stream ends
403-- as soon as EOF is encountered.
405{-# INLINE readWithBufferOf #-}
406readWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
407readWithBufferOf chunkSize h = A.flattenArrays $ readChunksUpto chunkSize h
411-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
413-- > read = 'readByChunks' A.defaultChunkSize
414-- | Generate a stream of elements of the given type from a socket. The
415-- stream ends when EOF is encountered.
418{-# INLINE toBytes #-}
419toBytes :: (IsStream t, MonadIO m) => Socket -> t m Word8
420toBytes = AS.concat . toChunks
422-- | Unfolds the tuple @(bufsize, socket)@ into a byte stream, read requests
423-- to the socket are performed using buffers of @bufsize@.
426{-# INLINE readWithBufferOf #-}
427readWithBufferOf :: MonadIO m => Unfold m (Int, Socket) Word8
428readWithBufferOf = UF.concat readChunksWithBufferOf A.read
430-- | Unfolds a 'Socket' into a byte stream. IO requests to the socket are
431-- performed in sizes of
432-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize'.
436read :: MonadIO m => Unfold m Socket Word8
437read = UF.supplyFirst readWithBufferOf A.defaultChunkSize
439-------------------------------------------------------------------------------
441-------------------------------------------------------------------------------
443-- | Write a stream of arrays to a handle.
446{-# INLINE fromChunks #-}
447fromChunks :: (MonadIO m, Storable a)
448 => Socket -> SerialT m (Array a) -> m ()
449fromChunks h = S.mapM_ (liftIO . writeChunk h)
451-- | Write a stream of arrays to a socket. Each array in the stream is written
452-- to the socket as a separate IO request.
455{-# INLINE writeChunks #-}
456writeChunks :: (MonadIO m, Storable a) => Socket -> Fold m (Array a) ()
457writeChunks h = FL.drainBy (liftIO . writeChunk h)
459-- | @writeChunksWithBufferOf bufsize socket@ writes a stream of arrays
460-- to @socket@ after coalescing the adjacent arrays in chunks of @bufsize@.
461-- We never split an array, if a single array is bigger than the specified size
462-- it emitted as it is. Multiple arrays are coalesed as long as the total size
463-- remains below the specified size.
466{-# INLINE writeChunksWithBufferOf #-}
467writeChunksWithBufferOf :: (MonadIO m, Storable a)
468 => Int -> Socket -> Fold m (Array a) ()
469writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
472-- | Write a stream of strings to a socket in Latin1 encoding. Output is
473-- flushed to the socket for each string.
477{-# INLINE writeStrings #-}
478writeStrings :: MonadIO m
479 => (SerialT m Char -> SerialT m Word8) -> Socket -> Fold m String ()
480writeStrings encode h =
481 FL.lmapM (IA.fromStream . encode . S.fromList) (writeChunks h)
483-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
486-- Note that if you use a chunk size less than 8K (GHC's default buffer
487-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
488-- do not want buffering to occur at GHC level as well. Same thing applies to
491-- | Like 'write' but provides control over the write buffer. Output will
492-- be written to the IO device as soon as we collect the specified number of
496{-# INLINE fromBytesWithBufferOf #-}
497fromBytesWithBufferOf :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
498fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
500-- | Write a byte stream to a socket. Accumulates the input in chunks of
501-- specified number of bytes before writing.
504{-# INLINE writeWithBufferOf #-}
505writeWithBufferOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
506writeWithBufferOf n h = FL.chunksOf n (A.writeNUnsafe n) (writeChunks h)
508-- > write = 'writeWithBufferOf' A.defaultChunkSize
510-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
511-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
512-- depends on the 'IOMode' and the current seek position of the handle.
515{-# INLINE fromBytes #-}
516fromBytes :: MonadIO m => Socket -> SerialT m Word8 -> m ()
517fromBytes = fromBytesWithBufferOf A.defaultChunkSize
519-- | Write a byte stream to a socket. Accumulates the input in chunks of
520-- up to 'A.defaultChunkSize' bytes before writing.
523-- write = 'writeWithBufferOf' 'A.defaultChunkSize'
528write :: MonadIO m => Socket -> Fold m Word8 ()
529write = writeWithBufferOf A.defaultChunkSize
533write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
534write = toHandleWith A.defaultChunkSize
537-------------------------------------------------------------------------------
538-- IO with encoding/decoding Unicode characters
539-------------------------------------------------------------------------------
543-- > readUtf8 = decodeUtf8 . read
545-- Read a UTF8 encoded stream of unicode characters from a file handle.
548{-# INLINE readUtf8 #-}
549readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
550readUtf8 = decodeUtf8 . read
553-- > writeUtf8 h s = write h $ encodeUtf8 s
555-- Encode a stream of unicode characters to UTF8 and write it to the given file
556-- handle. Default block buffering applies to the writes.
559{-# INLINE writeUtf8 #-}
560writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
561writeUtf8 h s = write h $ encodeUtf8 s
563-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
564-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
565-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
566-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
570{-# INLINE writeUtf8ByLines #-}
571writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
572writeUtf8ByLines = undefined
574-- | Read UTF-8 lines from a file handle and apply the specified fold to each
575-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
578{-# INLINE readLines #-}
579readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
580readLines h f = foldLines (readUtf8 h) f
582-------------------------------------------------------------------------------
583-- Framing on a sequence
584-------------------------------------------------------------------------------
586-- | Read a stream from a file handle and split it into frames delimited by
587-- the specified sequence of elements. The supplied fold is applied on each
591{-# INLINE readFrames #-}
592readFrames :: (IsStream t, MonadIO m, Storable a)
593 => Array a -> Handle -> Fold m a b -> t m b
594readFrames = undefined -- foldFrames . read
596-- | Write a stream to the given file handle buffering up to frames separated
597-- by the given sequence or up to a maximum of @defaultChunkSize@.
600{-# INLINE writeByFrames #-}
601writeByFrames :: (IsStream t, MonadIO m, Storable a)
602 => Array a -> Handle -> t m a -> m ()
603writeByFrames = 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