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