on da62ada help sign in
604 lines 21 kB history raw
1#include "inline.hs"
3-- |
4-- Module : Streamly.Internal.Network.Socket
5-- Copyright : (c) 2018 Composewell Technologies
6--
7-- License : BSD3
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
10-- Portability : GHC
11--
12module Streamly.Internal.Network.Socket
13 (
14 SockSpec (..)
15 -- * Use a socket
16 , handleWithM
17 , handleWith
19 -- * Accept connections
20 , accept
21 , connections
22 , connect
23 , connectFrom
25 -- * Read from connection
26 , read
27 , readWithBufferOf
28 -- , readUtf8
29 -- , readLines
30 -- , readFrames
31 -- , readByChunks
33 -- -- * Array Read
34 -- , readArrayUpto
35 -- , readArrayOf
37 -- , readChunksUpto
38 , readChunksWithBufferOf
39 , readChunks
41 , toChunksWithBufferOf
42 , toChunks
43 , toBytes
45 -- * Write to connection
46 , write
47 -- , writeUtf8
48 -- , writeUtf8ByLines
49 -- , writeByFrames
50 , writeWithBufferOf
52 , fromChunks
53 , fromBytesWithBufferOf
54 , fromBytes
56 -- -- * Array Write
57 , writeChunk
58 , writeChunks
59 , writeChunksWithBufferOf
60 , writeStrings
62 -- reading/writing datagrams
63 )
64where
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)
77import Network.Socket
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)
83#else
84import Network.Socket (fdSocket)
85#endif
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'.
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, 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-------------------------------------------------------------------------------
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 use sock `onException` Net.close sock
150 return sock
152 where
154 use sock = do
155 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
156 bind sock addr
157 Net.listen sock listenQLen
159{-# INLINE listenTuples #-}
160listenTuples :: MonadIO m
161 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
162listenTuples = Unfold step inject
163 where
164 inject (listenQLen, spec, addr) =
165 liftIO $ initListener listenQLen spec addr
167 step listener = do
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.
176--
177-- @since 0.7.0
178{-# INLINE accept #-}
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
187 return sock
189 where
191 use sock = do
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.
198--
199-- /Internal/
200--
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.
208--
209-- /Internal/
210--
211{-# INLINE connectFrom #-}
212connectFrom :: SockSpec -> SockAddr -> SockAddr -> IO Socket
213connectFrom spec local = connectCommon spec (Just local)
215-------------------------------------------------------------------------------
216-- Listen (Streams)
217-------------------------------------------------------------------------------
219{-# INLINE recvConnectionTuplesWith #-}
220recvConnectionTuplesWith :: MonadAsync m
221 => Int -> SockSpec -> SockAddr -> SerialT m (Socket, SockAddr)
222recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
223 where
224 step Nothing = do
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.
237--
238-- /Internal/
239{-# INLINE connections #-}
240connections :: MonadAsync m => Int -> SockSpec -> SockAddr -> SerialT m Socket
241connections tcpListenQ spec addr =
242 fst <$> recvConnectionTuplesWith tcpListenQ spec addr
244-------------------------------------------------------------------------------
245-- Array IO (Input)
246-------------------------------------------------------------------------------
248{-# INLINABLE readArrayUptoWith #-}
249readArrayUptoWith
250 :: (h -> Ptr Word8 -> Int -> IO Int)
251 -> Int
252 -> h
253 -> IO (Array Word8)
254readArrayUptoWith f size h = do
255 ptr <- mallocPlainForeignPtrBytes size
256 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
257 withForeignPtr ptr $ \p -> do
258 n <- f h p size
259 let v = A.unsafeFreeze
260 $ mutableArray ptr (p `plusPtr` n) (p `plusPtr` size)
262 -- XXX shrink only if the diff is significant
263 -- A.shrinkToFit v
264 return v
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-------------------------------------------------------------------------------
275-- Array IO (output)
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
284#else
285 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
286#endif
287waitWhen0 _ _ = return ()
289sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
290sendAll _ _ len | len <= 0 = return ()
291sendAll s p len = do
292 sent <- sendBuf s p len
293 waitWhen0 sent s
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 ())
300 -> h
301 -> Array a
302 -> IO ()
303writeArrayWith _ _ arr | A.length arr == 0 = return ()
304writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
305 f h (castPtr p) aLen
306 where
307 aLen =
308 let p = unsafeForeignPtrToPtr aStart
309 in aEnd `minusPtr` p
311-- | Write an Array to a file handle.
312--
313-- @since 0.7.0
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
327 where
328 -- XXX use cons/nil instead
329 go = mkStream $ \_ yld _ stp -> do
330 arr <- liftIO $ f size h
331 if A.length arr == 0
332 then stp
333 else yld arr go
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'
338-- on the 'Handle'.
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 ())
344 where
345 {-# INLINE_LATE step #-}
346 step _ _ = do
347 arr <- liftIO $ readArrayOf size h
348 return $
349 case A.length arr of
350 0 -> D.Stop
351 _ -> D.Yield arr ()
353-- XXX read 'Array a' instead of Word8
354--
355-- | @toChunks h@ reads a stream of arrays from socket handle @h@.
356-- The maximum size of a single array is limited to @defaultChunkSize@.
357--
358-- @since 0.7.0
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
366-- @bufsize@.
367--
368-- @since 0.7.0
369{-# INLINE_NORMAL readChunksWithBufferOf #-}
370readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
371readChunksWithBufferOf = Unfold step return
372 where
373 {-# INLINE_LATE step #-}
374 step (size, h) = do
375 arr <- liftIO $ readArrayOf size h
376 return $
377 case A.length arr of
378 0 -> D.Stop
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'.
386--
387-- @since 0.7.0
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.
400{-
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.
404--
405{-# INLINE readWithBufferOf #-}
406readWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
407readWithBufferOf chunkSize h = A.flattenArrays $ readChunksUpto chunkSize h
408-}
410-- TODO
411-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
412--
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.
416--
417-- @since 0.7.0
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@.
424--
425-- @since 0.7.0
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'.
433--
434-- @since 0.7.0
435{-# INLINE read #-}
436read :: MonadIO m => Unfold m Socket Word8
437read = UF.supplyFirst readWithBufferOf A.defaultChunkSize
439-------------------------------------------------------------------------------
440-- Writing
441-------------------------------------------------------------------------------
443-- | Write a stream of arrays to a handle.
444--
445-- @since 0.7.0
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.
453--
454-- @since 0.7.0
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.
464--
465-- @since 0.7.0
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.
474--
475-- /Internal/
476--
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.
484--
485-- XXX test this
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
489-- writes as well.
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
493-- input elements.
494--
495-- @since 0.7.0
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.
502--
503-- @since 0.7.0
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
509--
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.
513--
514-- @since 0.7.0
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.
521--
522-- @
523-- write = 'writeWithBufferOf' 'A.defaultChunkSize'
524-- @
525--
526-- @since 0.7.0
527{-# INLINE write #-}
528write :: MonadIO m => Socket -> Fold m Word8 ()
529write = writeWithBufferOf A.defaultChunkSize
531{-
532{-# INLINE write #-}
533write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
534write = toHandleWith A.defaultChunkSize
535-}
537-------------------------------------------------------------------------------
538-- IO with encoding/decoding Unicode characters
539-------------------------------------------------------------------------------
541{-
542-- |
543-- > readUtf8 = decodeUtf8 . read
544--
545-- Read a UTF8 encoded stream of unicode characters from a file handle.
546--
547-- @since 0.7.0
548{-# INLINE readUtf8 #-}
549readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
550readUtf8 = decodeUtf8 . read
552-- |
553-- > writeUtf8 h s = write h $ encodeUtf8 s
554--
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.
557--
558-- @since 0.7.0
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'
567-- option.
568--
569-- @since 0.7.0
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.
576--
577-- @since 0.7.0
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
588-- frame.
589--
590-- @since 0.7.0
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@.
598--
599-- @since 0.7.0
600{-# INLINE writeByFrames #-}
601writeByFrames :: (IsStream t, MonadIO m, Storable a)
602 => Array a -> Handle -> t m a -> m ()
603writeByFrames = undefined
604-}