on 10bb2fb help sign in
526 lines 18 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
8#include "inline.hs"
10-- |
11-- Module : Streamly.Internal.Network.Socket
12-- Copyright : (c) 2018 Composewell Technologies
13--
14-- License : BSD3
15-- Maintainer : streamly@composewell.com
16-- Stability : experimental
17-- Portability : GHC
18--
19module Streamly.Internal.Network.Socket
20 (
21 SockSpec (..)
22 -- * Use a socket
23 , useSocketM
24 , useSocket
26 -- * Accept connections
27 , accept
28 , connections
30 -- * Read from connection
31 , read
32 -- , readUtf8
33 -- , readLines
34 -- , readFrames
35 -- , readByChunks
36 , toStream
38 -- -- * Array Read
39 -- , readArrayUpto
40 -- , readArrayOf
42 -- , readArraysUpto
43 , readArraysOf
44 , readArrays
46 , toStreamArraysOf
47 , toStreamArrays
49 -- * Write to connection
50 , write
51 -- , writeUtf8
52 -- , writeUtf8ByLines
53 -- , writeByFrames
54 , writeInChunksOf
56 -- -- * Array Write
57 , writeArray
58 , writeArrays
60 -- reading/writing datagrams
61 )
62where
64import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
65import Control.Monad.Catch (MonadCatch, finally, MonadMask)
66import Control.Monad.IO.Class (MonadIO(..))
67import Control.Monad (when)
68import Data.Word (Word8)
69import Foreign.ForeignPtr (withForeignPtr)
70import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
71import Foreign.Ptr (minusPtr, plusPtr, Ptr, castPtr)
72import Foreign.Storable (Storable(..))
73import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
74import Network.Socket (sendBuf, recvBuf)
75import Network.Socket
76 (Socket, SocketOption(..), Family(..), SockAddr(..),
77 ProtocolNumber, withSocketsDo, SocketType(..), socket, bind,
78 setSocketOption)
79#if MIN_VERSION_network(3,1,0)
80import Network.Socket (withFdSocket)
81#else
82import Network.Socket (fdSocket)
83#endif
84import Prelude hiding (read)
86import qualified Network.Socket as Net
88import Streamly (MonadAsync)
89import Streamly.Internal.Data.Unfold.Types (Unfold(..))
90import Streamly.Internal.Memory.Array.Types (Array(..))
91import Streamly.Streams.Serial (SerialT)
92import Streamly.Streams.StreamK.Type (IsStream, mkStream)
93import Streamly.Data.Fold (Fold)
94-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
96import qualified Streamly.Data.Fold as FL
97import qualified Streamly.Internal.Data.Fold.Types as FL
98import qualified Streamly.Internal.Data.Unfold as UF
99import qualified Streamly.Memory.Array as A
100import qualified Streamly.Internal.Memory.ArrayStream as AS
101import qualified Streamly.Internal.Memory.Array.Types as A
102import qualified Streamly.Prelude as S
103import qualified Streamly.Streams.StreamD.Type as D
105-- | @'useSocketM' socket act@ runs the monadic computation @act@ passing the
106-- socket handle to it. The handle will be closed on exit from 'useSocketM',
107-- whether by normal termination or by raising an exception. If closing the
108-- handle raises an exception, then this exception will be raised by
109-- 'useSocketM' rather than any exception raised by 'act'.
110--
111-- @since 0.7.0
112{-# INLINE useSocketM #-}
113useSocketM :: (MonadMask m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
114useSocketM sk f = finally (liftIO (Net.close sk)) (f sk)
116-- | Like 'useSocketM' but runs a streaming computation instead of a monadic
117-- computation.
118--
119-- @since 0.7.0
120{-# INLINE useSocket #-}
121useSocket :: (IsStream t, MonadCatch m, MonadIO m)
122 => Socket -> (Socket -> t m a) -> t m a
123useSocket sk f = S.finally (liftIO $ Net.close sk) (f sk)
125-------------------------------------------------------------------------------
126-- Accept (Unfolds)
127-------------------------------------------------------------------------------
129-- XXX Protocol specific socket options should be separated from socket level
130-- options.
131--
132-- | Specify the socket protocol details.
133data SockSpec = SockSpec
134 {
135 sockFamily :: !Family
136 , sockType :: !SocketType
137 , sockProto :: !ProtocolNumber
138 , sockOpts :: ![(SocketOption, Int)]
139 }
141initListener :: Int -> SockSpec -> SockAddr -> IO Socket
142initListener listenQLen SockSpec{..} addr =
143 withSocketsDo $ do
144 sock <- socket sockFamily sockType sockProto
145 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
146 bind sock addr
147 Net.listen sock listenQLen
148 return sock
150{-# INLINE listenTuples #-}
151listenTuples :: MonadIO m
152 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
153listenTuples = Unfold step inject
154 where
155 inject (listenQLen, spec, addr) = do
156 listener <- liftIO $ initListener listenQLen spec addr
157 return listener
159 step listener = do
160 r <- liftIO $ Net.accept listener
161 -- XXX error handling
162 return $ D.Yield r listener
164-- | Unfold a three tuple @(listenQLen, spec, addr)@ into a stream of connected
165-- protocol sockets corresponding to incoming connections. @listenQLen@ is the
166-- maximum number of pending connections in the backlog. @spec@ is the socket
167-- protocol and options specification and @addr@ is the protocol address where
168-- the server listens for incoming connections.
169--
170-- @since 0.7.0
171{-# INLINE accept #-}
172accept :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
173accept = UF.map fst listenTuples
175-------------------------------------------------------------------------------
176-- Listen (Streams)
177-------------------------------------------------------------------------------
179{-# INLINE recvConnectionTuplesWith #-}
180recvConnectionTuplesWith :: MonadAsync m
181 => Int -> SockSpec -> SockAddr -> SerialT m (Socket, SockAddr)
182recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
183 where
184 step Nothing = do
185 listener <- liftIO $ initListener tcpListenQ spec addr
186 r <- liftIO $ Net.accept listener
187 -- XXX error handling
188 return $ Just (r, Just listener)
190 step (Just listener) = do
191 r <- liftIO $ Net.accept listener
192 -- XXX error handling
193 return $ Just (r, Just listener)
195-- | Start a TCP stream server that listens for connections on the supplied
196-- server address specification (address family, local interface IP address and
197-- port). The server generates a stream of connected sockets. The first
198-- argument is the maximum number of pending connections in the backlog.
199--
200-- /Internal/
201{-# INLINE connections #-}
202connections :: MonadAsync m => Int -> SockSpec -> SockAddr -> SerialT m Socket
203connections tcpListenQ spec addr = fmap fst $
204 recvConnectionTuplesWith tcpListenQ spec addr
206-------------------------------------------------------------------------------
207-- Array IO (Input)
208-------------------------------------------------------------------------------
210{-# INLINABLE readArrayUptoWith #-}
211readArrayUptoWith
212 :: (h -> Ptr Word8 -> Int -> IO Int)
213 -> Int
214 -> h
215 -> IO (Array Word8)
216readArrayUptoWith f size h = do
217 ptr <- mallocPlainForeignPtrBytes size
218 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
219 withForeignPtr ptr $ \p -> do
220 n <- f h p size
221 let v = Array
222 { aStart = ptr
223 , aEnd = p `plusPtr` n
224 , aBound = p `plusPtr` size
225 }
226 -- XXX shrink only if the diff is significant
227 -- A.shrinkToFit v
228 return v
230-- | Read a 'ByteArray' from a file handle. If no data is available on the
231-- handle it blocks until some data becomes available. If data is available
232-- then it immediately returns that data without blocking. It reads a maximum
233-- of up to the size requested.
234{-# INLINABLE readArrayOf #-}
235readArrayOf :: Int -> Socket -> IO (Array Word8)
236readArrayOf = readArrayUptoWith recvBuf
238-------------------------------------------------------------------------------
239-- Array IO (output)
240-------------------------------------------------------------------------------
242waitWhen0 :: Int -> Socket -> IO ()
243waitWhen0 0 s = when rtsSupportsBoundThreads $
244#if MIN_VERSION_network(3,1,0)
245 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
246#else
247 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
248#endif
249waitWhen0 _ _ = return ()
251sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
252sendAll _ _ len | len <= 0 = return ()
253sendAll s p len = do
254 sent <- sendBuf s p len
255 waitWhen0 sent s
256 -- assert (sent <= len)
257 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
259{-# INLINABLE writeArrayWith #-}
260writeArrayWith :: Storable a
261 => (h -> Ptr Word8 -> Int -> IO ())
262 -> h
263 -> Array a
264 -> IO ()
265writeArrayWith _ _ arr | A.length arr == 0 = return ()
266writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
267 f h (castPtr p) aLen
268 where
269 aLen =
270 let p = unsafeForeignPtrToPtr aStart
271 in aEnd `minusPtr` p
273-- | Write an Array to a file handle.
274--
275-- @since 0.7.0
276{-# INLINABLE writeArray #-}
277writeArray :: Storable a => Socket -> Array a -> IO ()
278writeArray = writeArrayWith sendAll
280-------------------------------------------------------------------------------
281-- Stream of Arrays IO
282-------------------------------------------------------------------------------
284{-# INLINABLE readArraysUptoWith #-}
285readArraysUptoWith :: (IsStream t, MonadIO m)
286 => (Int -> h -> IO (Array Word8))
287 -> Int -> h -> t m (Array Word8)
288readArraysUptoWith f size h = go
289 where
290 -- XXX use cons/nil instead
291 go = mkStream $ \_ yld _ stp -> do
292 arr <- liftIO $ f size h
293 if A.length arr == 0
294 then stp
295 else yld arr go
297-- | @toStreamArraysOf size h@ reads a stream of arrays from file handle @h@.
298-- The maximum size of a single array is limited to @size@.
299-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
300-- on the 'Handle'.
301{-# INLINABLE toStreamArraysOf #-}
302toStreamArraysOf :: (IsStream t, MonadIO m)
303 => Int -> Socket -> t m (Array Word8)
304toStreamArraysOf = readArraysUptoWith readArrayOf
306-- XXX read 'Array a' instead of Word8
307--
308-- | @toStreamArrays h@ reads a stream of arrays from socket handle @h@.
309-- The maximum size of a single array is limited to @defaultChunkSize@.
310--
311-- @since 0.7.0
312{-# INLINE toStreamArrays #-}
313toStreamArrays :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
314toStreamArrays = toStreamArraysOf A.defaultChunkSize
316-- | Unfold the tuple @(size, socket)@ into a stream of 'Word8' arrays. The
317-- stream consists of arrays representing chunks of data read from the socket.
318-- The maximum size of a single array is limited to @size@.
319--
320-- @since 0.7.0
321{-# INLINE_NORMAL readArraysOf #-}
322readArraysOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
323readArraysOf = Unfold step return
324 where
325 {-# INLINE_LATE step #-}
326 step (size, h) = do
327 arr <- liftIO $ readArrayOf size h
328 return $
329 case A.length arr of
330 0 -> D.Stop
331 _ -> D.Yield arr (size, h)
333-- | Unfolds a socket into a stream of 'Word8' arrays. The maximum size of a
334-- single array is limited to @defaultChunkSize@.
335--
336-- @since 0.7.0
337{-# INLINE readArrays #-}
338readArrays :: MonadIO m => Unfold m Socket (Array Word8)
339readArrays = UF.supplyFirst readArraysOf A.defaultChunkSize
341-------------------------------------------------------------------------------
342-- Read File to Stream
343-------------------------------------------------------------------------------
345-- TODO for concurrent streams implement readahead IO. We can send multiple
346-- read requests at the same time. For serial case we can use async IO. We can
347-- also control the read throughput in mbps or IOPS.
349{-
350-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
351-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
352-- as soon as EOF is encountered.
353--
354{-# INLINE readInChunksOf #-}
355readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
356readInChunksOf chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
357-}
359-- TODO
360-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
361--
362-- > read = 'readByChunks' A.defaultChunkSize
363-- | Generate a stream of elements of the given type from a socket. The
364-- stream ends when EOF is encountered.
365--
366-- @since 0.7.0
367{-# INLINE toStream #-}
368toStream :: (IsStream t, MonadIO m) => Socket -> t m Word8
369toStream = AS.concat . toStreamArrays
371-- | @readInChunksOf@ unfolds @(bufsize, socket)@ into a byte stream, reads
372-- are performed in buffers of up to @bufsize@.
373--
374-- @since 0.7.0
375{-# INLINE readInChunksOf #-}
376readInChunksOf :: MonadIO m => Unfold m (Int, Socket) Word8
377readInChunksOf = UF.concat readArraysOf A.read
379-- | Unfolds a 'Socket' into a byte stream.
380--
381-- @since 0.7.0
382{-# INLINE read #-}
383read :: MonadIO m => Unfold m Socket Word8
384read = UF.supplyFirst readInChunksOf A.defaultChunkSize
386-------------------------------------------------------------------------------
387-- Writing
388-------------------------------------------------------------------------------
390-- | Write a stream of arrays to a handle.
391--
392-- @since 0.7.0
393{-# INLINE writeArraysS #-}
394writeArraysS :: (MonadIO m, Storable a)
395 => Socket -> SerialT m (Array a) -> m ()
396writeArraysS h m = S.mapM_ (liftIO . writeArray h) m
398-- | Write a stream of arrays to a socket.
399--
400-- @since 0.7.0
401{-# INLINE writeArrays #-}
402writeArrays :: (MonadIO m, Storable a) => Socket -> Fold m (Array a) ()
403writeArrays h = FL.drainBy (liftIO . writeArray h)
405-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
406--
407-- XXX test this
408-- Note that if you use a chunk size less than 8K (GHC's default buffer
409-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
410-- do not want buffering to occur at GHC level as well. Same thing applies to
411-- writes as well.
413-- | Like 'write' but provides control over the write buffer. Output will
414-- be written to the IO device as soon as we collect the specified number of
415-- input elements.
416--
417-- @since 0.7.0
418{-# INLINE writeInChunksOfS #-}
419writeInChunksOfS :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
420writeInChunksOfS n h m = writeArraysS h $ AS.arraysOf n m
422-- | Write a byte stream to a socket. Accumulates the input in chunks of
423-- specified number of bytes before writing.
424--
425-- @since 0.7.0
426{-# INLINE writeInChunksOf #-}
427writeInChunksOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
428writeInChunksOf n h = FL.lchunksOf n (A.writeNUnsafe n) (writeArrays h)
430-- > write = 'writeInChunksOf' A.defaultChunkSize
431--
432-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
433-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
434-- depends on the 'IOMode' and the current seek position of the handle.
435--
436-- @since 0.7.0
437{-# INLINE _writeS #-}
438_writeS :: MonadIO m => Socket -> SerialT m Word8 -> m ()
439_writeS = writeInChunksOfS A.defaultChunkSize
441-- | Write a byte stream to a socket. Accumulates the input in chunks of
442-- up to 'A.defaultChunkSize' bytes before writing.
443--
444-- @
445-- write = 'writeInChunksOf' 'A.defaultChunkSize'
446-- @
447--
448-- @since 0.7.0
449{-# INLINE write #-}
450write :: MonadIO m => Socket -> Fold m Word8 ()
451write = writeInChunksOf A.defaultChunkSize
453{-
454{-# INLINE write #-}
455write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
456write = toHandleWith A.defaultChunkSize
457-}
459-------------------------------------------------------------------------------
460-- IO with encoding/decoding Unicode characters
461-------------------------------------------------------------------------------
463{-
464-- |
465-- > readUtf8 = decodeUtf8 . read
466--
467-- Read a UTF8 encoded stream of unicode characters from a file handle.
468--
469-- @since 0.7.0
470{-# INLINE readUtf8 #-}
471readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
472readUtf8 = decodeUtf8 . read
474-- |
475-- > writeUtf8 h s = write h $ encodeUtf8 s
476--
477-- Encode a stream of unicode characters to UTF8 and write it to the given file
478-- handle. Default block buffering applies to the writes.
479--
480-- @since 0.7.0
481{-# INLINE writeUtf8 #-}
482writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
483writeUtf8 h s = write h $ encodeUtf8 s
485-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
486-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
487-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
488-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
489-- option.
490--
491-- @since 0.7.0
492{-# INLINE writeUtf8ByLines #-}
493writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
494writeUtf8ByLines = undefined
496-- | Read UTF-8 lines from a file handle and apply the specified fold to each
497-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
498--
499-- @since 0.7.0
500{-# INLINE readLines #-}
501readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
502readLines h f = foldLines (readUtf8 h) f
504-------------------------------------------------------------------------------
505-- Framing on a sequence
506-------------------------------------------------------------------------------
508-- | Read a stream from a file handle and split it into frames delimited by
509-- the specified sequence of elements. The supplied fold is applied on each
510-- frame.
511--
512-- @since 0.7.0
513{-# INLINE readFrames #-}
514readFrames :: (IsStream t, MonadIO m, Storable a)
515 => Array a -> Handle -> Fold m a b -> t m b
516readFrames = undefined -- foldFrames . read
518-- | Write a stream to the given file handle buffering up to frames separated
519-- by the given sequence or up to a maximum of @defaultChunkSize@.
520--
521-- @since 0.7.0
522{-# INLINE writeByFrames #-}
523writeByFrames :: (IsStream t, MonadIO m, Storable a)
524 => Array a -> Handle -> t m a -> m ()
525writeByFrames = undefined
526-}