2{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE RecordWildCards #-}
8-- Module : Streamly.Internal.Network.Socket
9-- Copyright : (c) 2018 Composewell Technologies
12-- Maintainer : streamly@composewell.com
13-- Stability : experimental
16module Streamly.Internal.Network.Socket
23 -- * Accept connections
27 -- * Read from connection
40 , readChunksWithBufferOf
43 , toChunksWithBufferOf
47 -- * Write to connection
55 , fromBytesWithBufferOf
61 , writeChunksWithBufferOf
64 -- reading/writing datagrams
68import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
69import Control.Monad.Catch (MonadCatch, finally, MonadMask)
70import Control.Monad.IO.Class (MonadIO(..))
71import Control.Monad (when)
72import Data.Word (Word8)
73import Foreign.ForeignPtr (withForeignPtr)
74import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
75import Foreign.Ptr (minusPtr, plusPtr, Ptr, castPtr)
76import Foreign.Storable (Storable(..))
77import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
79 (Socket, SocketOption(..), Family(..), SockAddr(..),
80 ProtocolNumber, withSocketsDo, SocketType(..), socket, bind,
81 setSocketOption, sendBuf, recvBuf)
82#if MIN_VERSION_network(3,1,0)
83import Network.Socket (withFdSocket)
85import Network.Socket (fdSocket)
87import Prelude hiding (read)
89import qualified Network.Socket as Net
91import Streamly (MonadAsync)
92import Streamly.Internal.Data.Unfold.Types (Unfold(..))
93import Streamly.Internal.Memory.Array.Types (Array(..), lpackArraysChunksOf)
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.Memory.Array as IA
103import qualified Streamly.Memory.Array as A
104import qualified Streamly.Internal.Memory.ArrayStream as AS
105import qualified Streamly.Internal.Memory.Array.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, MonadCatch m, MonadIO 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 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
151 Net.listen sock listenQLen
154{-# INLINE listenTuples #-}
155listenTuples :: MonadIO m
156 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
157listenTuples = Unfold step inject
159 inject (listenQLen, spec, addr) = liftIO $ initListener listenQLen spec addr
162 r <- liftIO $ Net.accept listener
163 -- XXX error handling
164 return $ D.Yield r listener
166-- | Unfold a three tuple @(listenQLen, spec, addr)@ into a stream of connected
167-- protocol sockets corresponding to incoming connections. @listenQLen@ is the
168-- maximum number of pending connections in the backlog. @spec@ is the socket
169-- protocol and options specification and @addr@ is the protocol address where
170-- the server listens for incoming connections.
174accept :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
175accept = UF.map fst listenTuples
177-------------------------------------------------------------------------------
179-------------------------------------------------------------------------------
181{-# INLINE recvConnectionTuplesWith #-}
182recvConnectionTuplesWith :: MonadAsync m
183 => Int -> SockSpec -> SockAddr -> SerialT m (Socket, SockAddr)
184recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
187 listener <- liftIO $ initListener tcpListenQ spec addr
188 r <- liftIO $ Net.accept listener
189 -- XXX error handling
190 return $ Just (r, Just listener)
192 step (Just listener) = do
193 r <- liftIO $ Net.accept listener
194 -- XXX error handling
195 return $ Just (r, Just listener)
197-- | Start a TCP stream server that listens for connections on the supplied
198-- server address specification (address family, local interface IP address and
199-- port). The server generates a stream of connected sockets. The first
200-- argument is the maximum number of pending connections in the backlog.
203{-# INLINE connections #-}
204connections :: MonadAsync m => Int -> SockSpec -> SockAddr -> SerialT m Socket
205connections tcpListenQ spec addr = fst <$> recvConnectionTuplesWith tcpListenQ spec addr
207-------------------------------------------------------------------------------
209-------------------------------------------------------------------------------
211{-# INLINABLE readArrayUptoWith #-}
213 :: (h -> Ptr Word8 -> Int -> IO Int)
217readArrayUptoWith f size h = do
218 ptr <- mallocPlainForeignPtrBytes size
219 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
220 withForeignPtr ptr $ \p -> do
224 , aEnd = p `plusPtr` n
225 , aBound = p `plusPtr` size
227 -- XXX shrink only if the diff is significant
231-- | Read a 'ByteArray' from a file handle. If no data is available on the
232-- handle it blocks until some data becomes available. If data is available
233-- then it immediately returns that data without blocking. It reads a maximum
234-- of up to the size requested.
235{-# INLINABLE readArrayOf #-}
236readArrayOf :: Int -> Socket -> IO (Array Word8)
237readArrayOf = readArrayUptoWith recvBuf
239-------------------------------------------------------------------------------
241-------------------------------------------------------------------------------
243waitWhen0 :: Int -> Socket -> IO ()
244waitWhen0 0 s = when rtsSupportsBoundThreads $
245#if MIN_VERSION_network(3,1,0)
246 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
248 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
250waitWhen0 _ _ = return ()
252sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
253sendAll _ _ len | len <= 0 = return ()
255 sent <- sendBuf s p len
257 -- assert (sent <= len)
258 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
260{-# INLINABLE writeArrayWith #-}
261writeArrayWith :: Storable a
262 => (h -> Ptr Word8 -> Int -> IO ())
266writeArrayWith _ _ arr | A.length arr == 0 = return ()
267writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
271 let p = unsafeForeignPtrToPtr aStart
274-- | Write an Array to a file handle.
277{-# INLINABLE writeChunk #-}
278writeChunk :: Storable a => Socket -> Array a -> IO ()
279writeChunk = writeArrayWith sendAll
281-------------------------------------------------------------------------------
282-- Stream of Arrays IO
283-------------------------------------------------------------------------------
285{-# INLINABLE _readChunksUptoWith #-}
286_readChunksUptoWith :: (IsStream t, MonadIO m)
287 => (Int -> h -> IO (Array Word8))
288 -> Int -> h -> t m (Array Word8)
289_readChunksUptoWith f size h = go
291 -- XXX use cons/nil instead
292 go = mkStream $ \_ yld _ stp -> do
293 arr <- liftIO $ f size h
298-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
299-- The maximum size of a single array is limited to @size@.
300-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
302{-# INLINE_NORMAL toChunksWithBufferOf #-}
303toChunksWithBufferOf :: (IsStream t, MonadIO m)
304 => Int -> Socket -> t m (Array Word8)
305-- toChunksWithBufferOf = _readChunksUptoWith readArrayOf
306toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
308 {-# INLINE_LATE step #-}
310 arr <- liftIO $ readArrayOf size h
316-- XXX read 'Array a' instead of Word8
318-- | @toChunks h@ reads a stream of arrays from socket handle @h@.
319-- The maximum size of a single array is limited to @defaultChunkSize@.
322{-# INLINE toChunks #-}
323toChunks :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
324toChunks = toChunksWithBufferOf A.defaultChunkSize
326-- | Unfold the tuple @(bufsize, socket)@ into a stream of 'Word8' arrays.
327-- Read requests to the socket are performed using a buffer of size @bufsize@.
328-- The size of an array in the resulting stream is always less than or equal to
332{-# INLINE_NORMAL readChunksWithBufferOf #-}
333readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
334readChunksWithBufferOf = Unfold step return
336 {-# INLINE_LATE step #-}
338 arr <- liftIO $ readArrayOf size h
342 _ -> D.Yield arr (size, h)
344-- | Unfolds a socket into a stream of 'Word8' arrays. Requests to the socket
345-- are performed using a buffer of size
346-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. The
347-- size of arrays in the resulting stream are therefore less than or equal to
348-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
351{-# INLINE readChunks #-}
352readChunks :: MonadIO m => Unfold m Socket (Array Word8)
353readChunks = UF.supplyFirst readChunksWithBufferOf A.defaultChunkSize
355-------------------------------------------------------------------------------
356-- Read File to Stream
357-------------------------------------------------------------------------------
359-- TODO for concurrent streams implement readahead IO. We can send multiple
360-- read requests at the same time. For serial case we can use async IO. We can
361-- also control the read throughput in mbps or IOPS.
364-- | @readWithBufferOf bufsize handle@ reads a byte stream from a file
365-- handle, reads are performed in chunks of up to @bufsize@. The stream ends
366-- as soon as EOF is encountered.
368{-# INLINE readWithBufferOf #-}
369readWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
370readWithBufferOf chunkSize h = A.flattenArrays $ readChunksUpto chunkSize h
374-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
376-- > read = 'readByChunks' A.defaultChunkSize
377-- | Generate a stream of elements of the given type from a socket. The
378-- stream ends when EOF is encountered.
381{-# INLINE toBytes #-}
382toBytes :: (IsStream t, MonadIO m) => Socket -> t m Word8
383toBytes = AS.concat . toChunks
385-- | Unfolds the tuple @(bufsize, socket)@ into a byte stream, read requests
386-- to the socket are performed using buffers of @bufsize@.
389{-# INLINE readWithBufferOf #-}
390readWithBufferOf :: MonadIO m => Unfold m (Int, Socket) Word8
391readWithBufferOf = UF.concat readChunksWithBufferOf A.read
393-- | Unfolds a 'Socket' into a byte stream. IO requests to the socket are
394-- performed in sizes of
395-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
399read :: MonadIO m => Unfold m Socket Word8
400read = UF.supplyFirst readWithBufferOf A.defaultChunkSize
402-------------------------------------------------------------------------------
404-------------------------------------------------------------------------------
406-- | Write a stream of arrays to a handle.
409{-# INLINE fromChunks #-}
410fromChunks :: (MonadIO m, Storable a)
411 => Socket -> SerialT m (Array a) -> m ()
412fromChunks h = S.mapM_ (liftIO . writeChunk h)
414-- | Write a stream of arrays to a socket. Each array in the stream is written
415-- to the socket as a separate IO request.
418{-# INLINE writeChunks #-}
419writeChunks :: (MonadIO m, Storable a) => Socket -> Fold m (Array a) ()
420writeChunks h = FL.drainBy (liftIO . writeChunk h)
422-- | @writeChunksWithBufferOf bufsize socket@ writes a stream of arrays
423-- to @socket@ after coalescing the adjacent arrays in chunks of @bufsize@.
424-- We never split an array, if a single array is bigger than the specified size
425-- it emitted as it is. Multiple arrays are coalesed as long as the total size
426-- remains below the specified size.
429{-# INLINE writeChunksWithBufferOf #-}
430writeChunksWithBufferOf :: (MonadIO m, Storable a)
431 => Int -> Socket -> Fold m (Array a) ()
432writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
434-- | Write a stream of strings to a socket in Latin1 encoding. Output is
435-- flushed to the socket for each string.
439{-# INLINE writeStrings #-}
440writeStrings :: MonadIO m
441 => (SerialT m Char -> SerialT m Word8) -> Socket -> Fold m String ()
442writeStrings encode h =
443 FL.lmapM (IA.fromStream . encode . S.fromList) (writeChunks h)
445-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
448-- Note that if you use a chunk size less than 8K (GHC's default buffer
449-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
450-- do not want buffering to occur at GHC level as well. Same thing applies to
453-- | Like 'write' but provides control over the write buffer. Output will
454-- be written to the IO device as soon as we collect the specified number of
458{-# INLINE fromBytesWithBufferOf #-}
459fromBytesWithBufferOf :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
460fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
462-- | Write a byte stream to a socket. Accumulates the input in chunks of
463-- specified number of bytes before writing.
466{-# INLINE writeWithBufferOf #-}
467writeWithBufferOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
468writeWithBufferOf n h = FL.lchunksOf n (A.writeNUnsafe n) (writeChunks h)
470-- > write = 'writeWithBufferOf' A.defaultChunkSize
472-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
473-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
474-- depends on the 'IOMode' and the current seek position of the handle.
477{-# INLINE fromBytes #-}
478fromBytes :: MonadIO m => Socket -> SerialT m Word8 -> m ()
479fromBytes = fromBytesWithBufferOf A.defaultChunkSize
481-- | Write a byte stream to a socket. Accumulates the input in chunks of
482-- up to 'A.defaultChunkSize' bytes before writing.
485-- write = 'writeWithBufferOf' 'A.defaultChunkSize'
490write :: MonadIO m => Socket -> Fold m Word8 ()
491write = writeWithBufferOf A.defaultChunkSize
495write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
496write = toHandleWith A.defaultChunkSize
499-------------------------------------------------------------------------------
500-- IO with encoding/decoding Unicode characters
501-------------------------------------------------------------------------------
505-- > readUtf8 = decodeUtf8 . read
507-- Read a UTF8 encoded stream of unicode characters from a file handle.
510{-# INLINE readUtf8 #-}
511readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
512readUtf8 = decodeUtf8 . read
515-- > writeUtf8 h s = write h $ encodeUtf8 s
517-- Encode a stream of unicode characters to UTF8 and write it to the given file
518-- handle. Default block buffering applies to the writes.
521{-# INLINE writeUtf8 #-}
522writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
523writeUtf8 h s = write h $ encodeUtf8 s
525-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
526-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
527-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
528-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
532{-# INLINE writeUtf8ByLines #-}
533writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
534writeUtf8ByLines = undefined
536-- | Read UTF-8 lines from a file handle and apply the specified fold to each
537-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
540{-# INLINE readLines #-}
541readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
542readLines h f = foldLines (readUtf8 h) f
544-------------------------------------------------------------------------------
545-- Framing on a sequence
546-------------------------------------------------------------------------------
548-- | Read a stream from a file handle and split it into frames delimited by
549-- the specified sequence of elements. The supplied fold is applied on each
553{-# INLINE readFrames #-}
554readFrames :: (IsStream t, MonadIO m, Storable a)
555 => Array a -> Handle -> Fold m a b -> t m b
556readFrames = undefined -- foldFrames . read
558-- | Write a stream to the given file handle buffering up to frames separated
559-- by the given sequence or up to a maximum of @defaultChunkSize@.
562{-# INLINE writeByFrames #-}
563writeByFrames :: (IsStream t, MonadIO m, Storable a)
564 => Array a -> Handle -> t m a -> m ()
565writeByFrames = 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