on 9034b2d help sign in
566 lines 20 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE RecordWildCards #-}
5#include "inline.hs"
7-- |
8-- Module : Streamly.Internal.Network.Socket
9-- Copyright : (c) 2018 Composewell Technologies
10--
11-- License : BSD3
12-- Maintainer : streamly@composewell.com
13-- Stability : experimental
14-- Portability : GHC
15--
16module Streamly.Internal.Network.Socket
17 (
18 SockSpec (..)
19 -- * Use a socket
20 , handleWithM
21 , handleWith
23 -- * Accept connections
24 , accept
25 , connections
27 -- * Read from connection
28 , read
29 , readWithBufferOf
30 -- , readUtf8
31 -- , readLines
32 -- , readFrames
33 -- , readByChunks
35 -- -- * Array Read
36 -- , readArrayUpto
37 -- , readArrayOf
39 -- , readChunksUpto
40 , readChunksWithBufferOf
41 , readChunks
43 , toChunksWithBufferOf
44 , toChunks
45 , toBytes
47 -- * Write to connection
48 , write
49 -- , writeUtf8
50 -- , writeUtf8ByLines
51 -- , writeByFrames
52 , writeWithBufferOf
54 , fromChunks
55 , fromBytesWithBufferOf
56 , fromBytes
58 -- -- * Array Write
59 , writeChunk
60 , writeChunks
61 , writeChunksWithBufferOf
62 , writeStrings
64 -- reading/writing datagrams
65 )
66where
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)
78import Network.Socket
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)
84#else
85import Network.Socket (fdSocket)
86#endif
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'.
114--
115-- @since 0.7.0
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
121-- computation.
122--
123-- @since 0.7.0
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-------------------------------------------------------------------------------
130-- Accept (Unfolds)
131-------------------------------------------------------------------------------
133-- XXX Protocol specific socket options should be separated from socket level
134-- options.
135--
136-- | Specify the socket protocol details.
137data SockSpec = SockSpec
138 {
139 sockFamily :: !Family
140 , sockType :: !SocketType
141 , sockProto :: !ProtocolNumber
142 , sockOpts :: ![(SocketOption, Int)]
143 }
145initListener :: Int -> SockSpec -> SockAddr -> IO Socket
146initListener listenQLen SockSpec{..} addr =
147 withSocketsDo $ do
148 sock <- socket sockFamily sockType sockProto
149 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
150 bind sock addr
151 Net.listen sock listenQLen
152 return sock
154{-# INLINE listenTuples #-}
155listenTuples :: MonadIO m
156 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
157listenTuples = Unfold step inject
158 where
159 inject (listenQLen, spec, addr) = liftIO $ initListener listenQLen spec addr
161 step listener = do
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.
171--
172-- @since 0.7.0
173{-# INLINE accept #-}
174accept :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
175accept = UF.map fst listenTuples
177-------------------------------------------------------------------------------
178-- Listen (Streams)
179-------------------------------------------------------------------------------
181{-# INLINE recvConnectionTuplesWith #-}
182recvConnectionTuplesWith :: MonadAsync m
183 => Int -> SockSpec -> SockAddr -> SerialT m (Socket, SockAddr)
184recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
185 where
186 step Nothing = do
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.
201--
202-- /Internal/
203{-# INLINE connections #-}
204connections :: MonadAsync m => Int -> SockSpec -> SockAddr -> SerialT m Socket
205connections tcpListenQ spec addr = fst <$> recvConnectionTuplesWith tcpListenQ spec addr
207-------------------------------------------------------------------------------
208-- Array IO (Input)
209-------------------------------------------------------------------------------
211{-# INLINABLE readArrayUptoWith #-}
212readArrayUptoWith
213 :: (h -> Ptr Word8 -> Int -> IO Int)
214 -> Int
215 -> h
216 -> IO (Array Word8)
217readArrayUptoWith f size h = do
218 ptr <- mallocPlainForeignPtrBytes size
219 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
220 withForeignPtr ptr $ \p -> do
221 n <- f h p size
222 let v = Array
223 { aStart = ptr
224 , aEnd = p `plusPtr` n
225 , aBound = p `plusPtr` size
226 }
227 -- XXX shrink only if the diff is significant
228 -- A.shrinkToFit v
229 return v
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-------------------------------------------------------------------------------
240-- Array IO (output)
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
247#else
248 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
249#endif
250waitWhen0 _ _ = return ()
252sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
253sendAll _ _ len | len <= 0 = return ()
254sendAll s p len = do
255 sent <- sendBuf s p len
256 waitWhen0 sent s
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 ())
263 -> h
264 -> Array a
265 -> IO ()
266writeArrayWith _ _ arr | A.length arr == 0 = return ()
267writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
268 f h (castPtr p) aLen
269 where
270 aLen =
271 let p = unsafeForeignPtrToPtr aStart
272 in aEnd `minusPtr` p
274-- | Write an Array to a file handle.
275--
276-- @since 0.7.0
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
290 where
291 -- XXX use cons/nil instead
292 go = mkStream $ \_ yld _ stp -> do
293 arr <- liftIO $ f size h
294 if A.length arr == 0
295 then stp
296 else yld arr go
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'
301-- on the 'Handle'.
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 ())
307 where
308 {-# INLINE_LATE step #-}
309 step _ _ = do
310 arr <- liftIO $ readArrayOf size h
311 return $
312 case A.length arr of
313 0 -> D.Stop
314 _ -> D.Yield arr ()
316-- XXX read 'Array a' instead of Word8
317--
318-- | @toChunks h@ reads a stream of arrays from socket handle @h@.
319-- The maximum size of a single array is limited to @defaultChunkSize@.
320--
321-- @since 0.7.0
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
329-- @bufsize@.
330--
331-- @since 0.7.0
332{-# INLINE_NORMAL readChunksWithBufferOf #-}
333readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
334readChunksWithBufferOf = Unfold step return
335 where
336 {-# INLINE_LATE step #-}
337 step (size, h) = do
338 arr <- liftIO $ readArrayOf size h
339 return $
340 case A.length arr of
341 0 -> D.Stop
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'.
349--
350-- @since 0.7.0
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.
363{-
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.
367--
368{-# INLINE readWithBufferOf #-}
369readWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
370readWithBufferOf chunkSize h = A.flattenArrays $ readChunksUpto chunkSize h
371-}
373-- TODO
374-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
375--
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.
379--
380-- @since 0.7.0
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@.
387--
388-- @since 0.7.0
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'.
396--
397-- @since 0.7.0
398{-# INLINE read #-}
399read :: MonadIO m => Unfold m Socket Word8
400read = UF.supplyFirst readWithBufferOf A.defaultChunkSize
402-------------------------------------------------------------------------------
403-- Writing
404-------------------------------------------------------------------------------
406-- | Write a stream of arrays to a handle.
407--
408-- @since 0.7.0
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.
416--
417-- @since 0.7.0
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.
427--
428-- @since 0.7.0
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.
436--
437-- /Internal/
438--
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.
446--
447-- XXX test this
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
451-- writes as well.
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
455-- input elements.
456--
457-- @since 0.7.0
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.
464--
465-- @since 0.7.0
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
471--
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.
475--
476-- @since 0.7.0
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.
483--
484-- @
485-- write = 'writeWithBufferOf' 'A.defaultChunkSize'
486-- @
487--
488-- @since 0.7.0
489{-# INLINE write #-}
490write :: MonadIO m => Socket -> Fold m Word8 ()
491write = writeWithBufferOf A.defaultChunkSize
493{-
494{-# INLINE write #-}
495write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
496write = toHandleWith A.defaultChunkSize
497-}
499-------------------------------------------------------------------------------
500-- IO with encoding/decoding Unicode characters
501-------------------------------------------------------------------------------
503{-
504-- |
505-- > readUtf8 = decodeUtf8 . read
506--
507-- Read a UTF8 encoded stream of unicode characters from a file handle.
508--
509-- @since 0.7.0
510{-# INLINE readUtf8 #-}
511readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
512readUtf8 = decodeUtf8 . read
514-- |
515-- > writeUtf8 h s = write h $ encodeUtf8 s
516--
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.
519--
520-- @since 0.7.0
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'
529-- option.
530--
531-- @since 0.7.0
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.
538--
539-- @since 0.7.0
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
550-- frame.
551--
552-- @since 0.7.0
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@.
560--
561-- @since 0.7.0
562{-# INLINE writeByFrames #-}
563writeByFrames :: (IsStream t, MonadIO m, Storable a)
564 => Array a -> Handle -> t m a -> m ()
565writeByFrames = undefined
566-}