on 523f606 help sign in
405 lines 14 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.Network.Socket
12-- Copyright : (c) 2018 Harendra Kumar
13--
14-- License : BSD3
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
17-- Portability : GHC
18--
19-- Read and write streams and arrays to and from network sockets. Socket IO
20-- APIs are quite similar to "Streamly.Mem.Array" read write APIs and almost
21-- identical to the sequential streaming APIs in "Streamly.FileSystem.File".
22--
23-- Read IO requests to the socket are performed in chunks of 32KiB, this is
24-- referred to as @defaultChunkSize@ in the documentation. One IO request may
25-- or may not read the full chunk. Unless specified otherwise in the API,
26-- writes are collected into chunks of @defaultChunkSize@ before they are
27-- written to the socket. APIs are provided to control the chunking and
28-- framing behavior.
29--
30-- > import qualified Streamly.Network.Socket as SK
31--
33module Streamly.Network.Socket
34 (
35 -- ** Listen for Connections
36 ServerSpec(..)
37 , recvConnectionsWith
38 , recvConnectionsOn
40 -- ** Read a stream from a connection
41 , read
42 -- , readUtf8
43 -- , readLines
44 -- , readFrames
45 -- , readByChunks
47 -- -- * Array Read
48 -- , readArrayUpto
49 -- , readArrayOf
51 -- , readArraysUpto
52 -- , readArraysOf
53 , readArrays
55 -- ** Write a stream to a connection
56 , write
57 -- , writeUtf8
58 -- , writeUtf8ByLines
59 -- , writeByFrames
60 , writeByChunks
62 -- -- * Array Write
63 , writeArray
64 , writeArrays
65 )
66where
68import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
69import Control.Monad.IO.Class (MonadIO(..))
70import Control.Monad (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, PortNumber, SocketOption(..), Family(..),
79 SockAddr(..), withSocketsDo, SocketType(..), socket, accept, bind,
80 defaultProtocol, setSocketOption, maxListenQueue, 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 (MonadAsync)
91import Streamly.Mem.Array.Types (Array(..))
92import Streamly.Streams.Serial (SerialT)
93import Streamly.Streams.StreamK.Type (IsStream, mkStream)
94-- import Streamly.Fold (Fold)
95-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
97import qualified Streamly.Mem.Array as A
98import qualified Streamly.Mem.Array.Types as A hiding (flattenArrays)
99import qualified Streamly.Prelude as S
101-------------------------------------------------------------------------------
102-- Listen
103-------------------------------------------------------------------------------
105-- | Specify the configuration of a server.
106data ServerSpec = ServerSpec
107 {
108 serverAddressFamily :: !Family
109 , serverAddress :: !SockAddr
110 , serverSockOpts :: ![(SocketOption, Int)]
111 }
113initListener :: Int -> ServerSpec -> IO Socket
114initListener tcpListenQ ServerSpec{..} =
115 withSocketsDo $ do
116 sock <- socket serverAddressFamily Stream defaultProtocol
117 mapM_ (\(opt, val) -> setSocketOption sock opt val) serverSockOpts
118 bind sock serverAddress
119 Net.listen sock tcpListenQ
120 return sock
122-- | Start a TCP stream server. The server listens for connections on the
123-- supplied address (address family, local interface IP address and port) and
124-- generates a stream of connected sockets and the endpoint they are connected
125-- to. The first argument is the maximum number of pending connections in the
126-- backlog.
127{-# INLINE recvConnectionsWith #-}
128recvConnectionsWith :: MonadAsync m => Int -> ServerSpec -> SerialT m (Socket, SockAddr)
129recvConnectionsWith tcpListenQ opts = S.unfoldrM step Nothing
130 where
131 step Nothing = do
132 listener <- liftIO $ initListener tcpListenQ opts
133 r <- liftIO $ accept listener
134 -- XXX error handling
135 return $ Just (r, Just listener)
137 step (Just listener) = do
138 r <- liftIO $ accept listener
139 -- XXX error handling
140 return $ Just (r, Just listener)
142{-# INLINE recvConnectionsOn #-}
143recvConnectionsOn :: MonadAsync m => PortNumber -> SerialT m (Socket, SockAddr)
144recvConnectionsOn port =
145 recvConnectionsWith maxListenQueue ServerSpec
146 { serverAddressFamily = AF_INET
147 , serverAddress = SockAddrInet port 0
148 , serverSockOpts = [(NoDelay,1), (ReuseAddr,1)]
149 }
151-------------------------------------------------------------------------------
152-- Array IO (Input)
153-------------------------------------------------------------------------------
155{-# INLINABLE readArrayUptoWith #-}
156readArrayUptoWith
157 :: (h -> Ptr Word8 -> Int -> IO Int)
158 -> Int
159 -> h
160 -> IO (Array Word8)
161readArrayUptoWith f size h = do
162 ptr <- mallocPlainForeignPtrBytes size
163 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
164 withForeignPtr ptr $ \p -> do
165 n <- f h p size
166 let v = Array
167 { aStart = ptr
168 , aEnd = p `plusPtr` n
169 , aBound = p `plusPtr` size
170 }
171 -- XXX shrink only if the diff is significant
172 -- A.shrinkToFit v
173 return v
175-- | Read a 'ByteArray' from a file handle. If no data is available on the
176-- handle it blocks until some data becomes available. If data is available
177-- then it immediately returns that data without blocking. It reads a maximum
178-- of up to the size requested.
179{-# INLINABLE readArrayUpto #-}
180readArrayUpto :: Int -> Socket -> IO (Array Word8)
181readArrayUpto = readArrayUptoWith recvBuf
183-------------------------------------------------------------------------------
184-- Array IO (output)
185-------------------------------------------------------------------------------
187waitWhen0 :: Int -> Socket -> IO ()
188waitWhen0 0 s = when rtsSupportsBoundThreads $
189#if MIN_VERSION_network(3,1,0)
190 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
191#else
192 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
193#endif
194waitWhen0 _ _ = return ()
196sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
197sendAll _ _ len | len <= 0 = return ()
198sendAll s p len = do
199 sent <- sendBuf s p len
200 waitWhen0 sent s
201 -- assert (sent <= len)
202 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
204{-# INLINABLE writeArrayWith #-}
205writeArrayWith :: Storable a
206 => (h -> Ptr Word8 -> Int -> IO ())
207 -> h
208 -> Array a
209 -> IO ()
210writeArrayWith _ _ arr | A.length arr == 0 = return ()
211writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
212 f h (castPtr p) aLen
213 where
214 aLen =
215 let p = unsafeForeignPtrToPtr aStart
216 in aEnd `minusPtr` p
218-- | Write an Array to a file handle.
219--
220-- @since 0.7.0
221{-# INLINABLE writeArray #-}
222writeArray :: Storable a => Socket -> Array a -> IO ()
223writeArray = writeArrayWith sendAll
225-------------------------------------------------------------------------------
226-- Stream of Arrays IO
227-------------------------------------------------------------------------------
229{-# INLINABLE readArraysUptoWith #-}
230readArraysUptoWith :: (IsStream t, MonadIO m)
231 => (Int -> h -> IO (Array Word8))
232 -> Int -> h -> t m (Array Word8)
233readArraysUptoWith f size h = go
234 where
235 -- XXX use cons/nil instead
236 go = mkStream $ \_ yld _ stp -> do
237 arr <- liftIO $ f size h
238 if A.length arr == 0
239 then stp
240 else yld arr go
242-- | @readArraysUpto size h@ reads a stream of arrays from file handle @h@.
243-- The maximum size of a single array is limited to @size@.
244-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
245-- on the 'Handle'.
246{-# INLINABLE readArraysUpto #-}
247readArraysUpto :: (IsStream t, MonadIO m)
248 => Int -> Socket -> t m (Array Word8)
249readArraysUpto = readArraysUptoWith readArrayUpto
251-- XXX read 'Array a' instead of Word8
252--
253-- | @readArrays h@ reads a stream of arrays from file handle @h@.
254-- The maximum size of a single array is limited to @defaultChunkSize@.
255-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
256-- on the 'Handle'.
257--
258-- @since 0.7.0
259{-# INLINE readArrays #-}
260readArrays :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
261readArrays = readArraysUpto A.defaultChunkSize
263-------------------------------------------------------------------------------
264-- Read File to Stream
265-------------------------------------------------------------------------------
267-- TODO for concurrent streams implement readahead IO. We can send multiple
268-- read requests at the same time. For serial case we can use async IO. We can
269-- also control the read throughput in mbps or IOPS.
271{-
272-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file
273-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
274-- as soon as EOF is encountered.
275--
276{-# INLINE readByChunksUpto #-}
277readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
278readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
279-}
281-- TODO
282-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
283--
284-- > read = 'readByChunks' A.defaultChunkSize
285-- | Generate a stream of elements of the given type from a file 'Handle'. The
286-- stream ends when EOF is encountered.
287--
288-- @since 0.7.0
289{-# INLINE read #-}
290read :: (IsStream t, MonadIO m) => Socket -> t m Word8
291read = A.flattenArrays . readArrays
293-------------------------------------------------------------------------------
294-- Writing
295-------------------------------------------------------------------------------
297-- | Write a stream of arrays to a handle.
298--
299-- @since 0.7.0
300{-# INLINE writeArrays #-}
301writeArrays :: (MonadIO m, Storable a) => Socket -> SerialT m (Array a) -> m ()
302writeArrays h m = S.mapM_ (liftIO . writeArray h) m
304-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
305--
306-- XXX test this
307-- Note that if you use a chunk size less than 8K (GHC's default buffer
308-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
309-- do not want buffering to occur at GHC level as well. Same thing applies to
310-- writes as well.
312-- | Like 'write' but provides control over the write buffer. Output will
313-- be written to the IO device as soon as we collect the specified number of
314-- input elements.
315--
316-- @since 0.7.0
317{-# INLINE writeByChunks #-}
318writeByChunks :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
319writeByChunks n h m = writeArrays h $ A.arraysOf n m
321-- > write = 'writeByChunks' A.defaultChunkSize
322--
323-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
324-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
325-- depends on the 'IOMode' and the current seek position of the handle.
326--
327-- @since 0.7.0
328{-# INLINE write #-}
329write :: MonadIO m => Socket -> SerialT m Word8 -> m ()
330write = writeByChunks A.defaultChunkSize
332{-
333{-# INLINE write #-}
334write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
335write = toHandleWith A.defaultChunkSize
336-}
338-------------------------------------------------------------------------------
339-- IO with encoding/decoding Unicode characters
340-------------------------------------------------------------------------------
342{-
343-- |
344-- > readUtf8 = decodeUtf8 . read
345--
346-- Read a UTF8 encoded stream of unicode characters from a file handle.
347--
348-- @since 0.7.0
349{-# INLINE readUtf8 #-}
350readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
351readUtf8 = decodeUtf8 . read
353-- |
354-- > writeUtf8 h s = write h $ encodeUtf8 s
355--
356-- Encode a stream of unicode characters to UTF8 and write it to the given file
357-- handle. Default block buffering applies to the writes.
358--
359-- @since 0.7.0
360{-# INLINE writeUtf8 #-}
361writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
362writeUtf8 h s = write h $ encodeUtf8 s
364-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
365-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
366-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
367-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
368-- option.
369--
370-- @since 0.7.0
371{-# INLINE writeUtf8ByLines #-}
372writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
373writeUtf8ByLines = undefined
375-- | Read UTF-8 lines from a file handle and apply the specified fold to each
376-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
377--
378-- @since 0.7.0
379{-# INLINE readLines #-}
380readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
381readLines h f = foldLines (readUtf8 h) f
383-------------------------------------------------------------------------------
384-- Framing on a sequence
385-------------------------------------------------------------------------------
387-- | Read a stream from a file handle and split it into frames delimited by
388-- the specified sequence of elements. The supplied fold is applied on each
389-- frame.
390--
391-- @since 0.7.0
392{-# INLINE readFrames #-}
393readFrames :: (IsStream t, MonadIO m, Storable a)
394 => Array a -> Handle -> Fold m a b -> t m b
395readFrames = undefined -- foldFrames . read
397-- | Write a stream to the given file handle buffering up to frames separated
398-- by the given sequence or up to a maximum of @defaultChunkSize@.
399--
400-- @since 0.7.0
401{-# INLINE writeByFrames #-}
402writeByFrames :: (IsStream t, MonadIO m, Storable a)
403 => Array a -> Handle -> t m a -> m ()
404writeByFrames = undefined
405-}