on 63c646a help sign in
568 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#elif MIN_VERSION_network(3,0,0)
248 fdSocket s >>= threadWaitWrite . fromIntegral
249#else
250 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
251#endif
252waitWhen0 _ _ = return ()
254sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
255sendAll _ _ len | len <= 0 = return ()
256sendAll s p len = do
257 sent <- sendBuf s p len
258 waitWhen0 sent s
259 -- assert (sent <= len)
260 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
262{-# INLINABLE writeArrayWith #-}
263writeArrayWith :: Storable a
264 => (h -> Ptr Word8 -> Int -> IO ())
265 -> h
266 -> Array a
267 -> IO ()
268writeArrayWith _ _ arr | A.length arr == 0 = return ()
269writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
270 f h (castPtr p) aLen
271 where
272 aLen =
273 let p = unsafeForeignPtrToPtr aStart
274 in aEnd `minusPtr` p
276-- | Write an Array to a file handle.
277--
278-- @since 0.7.0
279{-# INLINABLE writeChunk #-}
280writeChunk :: Storable a => Socket -> Array a -> IO ()
281writeChunk = writeArrayWith sendAll
283-------------------------------------------------------------------------------
284-- Stream of Arrays IO
285-------------------------------------------------------------------------------
287{-# INLINABLE _readChunksUptoWith #-}
288_readChunksUptoWith :: (IsStream t, MonadIO m)
289 => (Int -> h -> IO (Array Word8))
290 -> Int -> h -> t m (Array Word8)
291_readChunksUptoWith f size h = go
292 where
293 -- XXX use cons/nil instead
294 go = mkStream $ \_ yld _ stp -> do
295 arr <- liftIO $ f size h
296 if A.length arr == 0
297 then stp
298 else yld arr go
300-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
301-- The maximum size of a single array is limited to @size@.
302-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
303-- on the 'Handle'.
304{-# INLINE_NORMAL toChunksWithBufferOf #-}
305toChunksWithBufferOf :: (IsStream t, MonadIO m)
306 => Int -> Socket -> t m (Array Word8)
307-- toChunksWithBufferOf = _readChunksUptoWith readArrayOf
308toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
309 where
310 {-# INLINE_LATE step #-}
311 step _ _ = do
312 arr <- liftIO $ readArrayOf size h
313 return $
314 case A.length arr of
315 0 -> D.Stop
316 _ -> D.Yield arr ()
318-- XXX read 'Array a' instead of Word8
319--
320-- | @toChunks h@ reads a stream of arrays from socket handle @h@.
321-- The maximum size of a single array is limited to @defaultChunkSize@.
322--
323-- @since 0.7.0
324{-# INLINE toChunks #-}
325toChunks :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
326toChunks = toChunksWithBufferOf A.defaultChunkSize
328-- | Unfold the tuple @(bufsize, socket)@ into a stream of 'Word8' arrays.
329-- Read requests to the socket are performed using a buffer of size @bufsize@.
330-- The size of an array in the resulting stream is always less than or equal to
331-- @bufsize@.
332--
333-- @since 0.7.0
334{-# INLINE_NORMAL readChunksWithBufferOf #-}
335readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
336readChunksWithBufferOf = Unfold step return
337 where
338 {-# INLINE_LATE step #-}
339 step (size, h) = do
340 arr <- liftIO $ readArrayOf size h
341 return $
342 case A.length arr of
343 0 -> D.Stop
344 _ -> D.Yield arr (size, h)
346-- | Unfolds a socket into a stream of 'Word8' arrays. Requests to the socket
347-- are performed using a buffer of size
348-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. The
349-- size of arrays in the resulting stream are therefore less than or equal to
350-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
351--
352-- @since 0.7.0
353{-# INLINE readChunks #-}
354readChunks :: MonadIO m => Unfold m Socket (Array Word8)
355readChunks = UF.supplyFirst readChunksWithBufferOf A.defaultChunkSize
357-------------------------------------------------------------------------------
358-- Read File to Stream
359-------------------------------------------------------------------------------
361-- TODO for concurrent streams implement readahead IO. We can send multiple
362-- read requests at the same time. For serial case we can use async IO. We can
363-- also control the read throughput in mbps or IOPS.
365{-
366-- | @readWithBufferOf bufsize handle@ reads a byte stream from a file
367-- handle, reads are performed in chunks of up to @bufsize@. The stream ends
368-- as soon as EOF is encountered.
369--
370{-# INLINE readWithBufferOf #-}
371readWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
372readWithBufferOf chunkSize h = A.flattenArrays $ readChunksUpto chunkSize h
373-}
375-- TODO
376-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
377--
378-- > read = 'readByChunks' A.defaultChunkSize
379-- | Generate a stream of elements of the given type from a socket. The
380-- stream ends when EOF is encountered.
381--
382-- @since 0.7.0
383{-# INLINE toBytes #-}
384toBytes :: (IsStream t, MonadIO m) => Socket -> t m Word8
385toBytes = AS.concat . toChunks
387-- | Unfolds the tuple @(bufsize, socket)@ into a byte stream, read requests
388-- to the socket are performed using buffers of @bufsize@.
389--
390-- @since 0.7.0
391{-# INLINE readWithBufferOf #-}
392readWithBufferOf :: MonadIO m => Unfold m (Int, Socket) Word8
393readWithBufferOf = UF.concat readChunksWithBufferOf A.read
395-- | Unfolds a 'Socket' into a byte stream. IO requests to the socket are
396-- performed in sizes of
397-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
398--
399-- @since 0.7.0
400{-# INLINE read #-}
401read :: MonadIO m => Unfold m Socket Word8
402read = UF.supplyFirst readWithBufferOf A.defaultChunkSize
404-------------------------------------------------------------------------------
405-- Writing
406-------------------------------------------------------------------------------
408-- | Write a stream of arrays to a handle.
409--
410-- @since 0.7.0
411{-# INLINE fromChunks #-}
412fromChunks :: (MonadIO m, Storable a)
413 => Socket -> SerialT m (Array a) -> m ()
414fromChunks h = S.mapM_ (liftIO . writeChunk h)
416-- | Write a stream of arrays to a socket. Each array in the stream is written
417-- to the socket as a separate IO request.
418--
419-- @since 0.7.0
420{-# INLINE writeChunks #-}
421writeChunks :: (MonadIO m, Storable a) => Socket -> Fold m (Array a) ()
422writeChunks h = FL.drainBy (liftIO . writeChunk h)
424-- | @writeChunksWithBufferOf bufsize socket@ writes a stream of arrays
425-- to @socket@ after coalescing the adjacent arrays in chunks of @bufsize@.
426-- We never split an array, if a single array is bigger than the specified size
427-- it emitted as it is. Multiple arrays are coalesed as long as the total size
428-- remains below the specified size.
429--
430-- @since 0.7.0
431{-# INLINE writeChunksWithBufferOf #-}
432writeChunksWithBufferOf :: (MonadIO m, Storable a)
433 => Int -> Socket -> Fold m (Array a) ()
434writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
436-- | Write a stream of strings to a socket in Latin1 encoding. Output is
437-- flushed to the socket for each string.
438--
439-- /Internal/
440--
441{-# INLINE writeStrings #-}
442writeStrings :: MonadIO m
443 => (SerialT m Char -> SerialT m Word8) -> Socket -> Fold m String ()
444writeStrings encode h =
445 FL.lmapM (IA.fromStream . encode . S.fromList) (writeChunks h)
447-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
448--
449-- XXX test this
450-- Note that if you use a chunk size less than 8K (GHC's default buffer
451-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
452-- do not want buffering to occur at GHC level as well. Same thing applies to
453-- writes as well.
455-- | Like 'write' but provides control over the write buffer. Output will
456-- be written to the IO device as soon as we collect the specified number of
457-- input elements.
458--
459-- @since 0.7.0
460{-# INLINE fromBytesWithBufferOf #-}
461fromBytesWithBufferOf :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
462fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
464-- | Write a byte stream to a socket. Accumulates the input in chunks of
465-- specified number of bytes before writing.
466--
467-- @since 0.7.0
468{-# INLINE writeWithBufferOf #-}
469writeWithBufferOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
470writeWithBufferOf n h = FL.lchunksOf n (A.writeNUnsafe n) (writeChunks h)
472-- > write = 'writeWithBufferOf' A.defaultChunkSize
473--
474-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
475-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
476-- depends on the 'IOMode' and the current seek position of the handle.
477--
478-- @since 0.7.0
479{-# INLINE fromBytes #-}
480fromBytes :: MonadIO m => Socket -> SerialT m Word8 -> m ()
481fromBytes = fromBytesWithBufferOf A.defaultChunkSize
483-- | Write a byte stream to a socket. Accumulates the input in chunks of
484-- up to 'A.defaultChunkSize' bytes before writing.
485--
486-- @
487-- write = 'writeWithBufferOf' 'A.defaultChunkSize'
488-- @
489--
490-- @since 0.7.0
491{-# INLINE write #-}
492write :: MonadIO m => Socket -> Fold m Word8 ()
493write = writeWithBufferOf A.defaultChunkSize
495{-
496{-# INLINE write #-}
497write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
498write = toHandleWith A.defaultChunkSize
499-}
501-------------------------------------------------------------------------------
502-- IO with encoding/decoding Unicode characters
503-------------------------------------------------------------------------------
505{-
506-- |
507-- > readUtf8 = decodeUtf8 . read
508--
509-- Read a UTF8 encoded stream of unicode characters from a file handle.
510--
511-- @since 0.7.0
512{-# INLINE readUtf8 #-}
513readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
514readUtf8 = decodeUtf8 . read
516-- |
517-- > writeUtf8 h s = write h $ encodeUtf8 s
518--
519-- Encode a stream of unicode characters to UTF8 and write it to the given file
520-- handle. Default block buffering applies to the writes.
521--
522-- @since 0.7.0
523{-# INLINE writeUtf8 #-}
524writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
525writeUtf8 h s = write h $ encodeUtf8 s
527-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
528-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
529-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
530-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
531-- option.
532--
533-- @since 0.7.0
534{-# INLINE writeUtf8ByLines #-}
535writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
536writeUtf8ByLines = undefined
538-- | Read UTF-8 lines from a file handle and apply the specified fold to each
539-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
540--
541-- @since 0.7.0
542{-# INLINE readLines #-}
543readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
544readLines h f = foldLines (readUtf8 h) f
546-------------------------------------------------------------------------------
547-- Framing on a sequence
548-------------------------------------------------------------------------------
550-- | Read a stream from a file handle and split it into frames delimited by
551-- the specified sequence of elements. The supplied fold is applied on each
552-- frame.
553--
554-- @since 0.7.0
555{-# INLINE readFrames #-}
556readFrames :: (IsStream t, MonadIO m, Storable a)
557 => Array a -> Handle -> Fold m a b -> t m b
558readFrames = undefined -- foldFrames . read
560-- | Write a stream to the given file handle buffering up to frames separated
561-- by the given sequence or up to a maximum of @defaultChunkSize@.
562--
563-- @since 0.7.0
564{-# INLINE writeByFrames #-}
565writeByFrames :: (IsStream t, MonadIO m, Storable a)
566 => Array a -> Handle -> t m a -> m ()
567writeByFrames = undefined
568-}