on d462530 help sign in
383 lines 13 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 -- * Use a socket
36 withSocket
37 , withSocketS
39 -- * Read from connection
40 , read
41 -- , readUtf8
42 -- , readLines
43 -- , readFrames
44 -- , readByChunks
46 -- -- * Array Read
47 -- , readArrayUpto
48 -- , readArrayOf
50 -- , readArraysUpto
51 -- , readArraysOf
52 , readArrays
54 -- * Write to connection
55 , write
56 -- , writeUtf8
57 -- , writeUtf8ByLines
58 -- , writeByFrames
59 , writeByChunks
61 -- -- * Array Write
62 , writeArray
63 , writeArrays
65 -- reading/writing datagrams
66 )
67where
69import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
70import Control.Monad.Catch (MonadCatch, onException)
71import Control.Monad.IO.Class (MonadIO(..))
72import Control.Monad (when)
73import Data.Word (Word8)
74import Foreign.ForeignPtr (withForeignPtr)
75import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
76import Foreign.Ptr (minusPtr, plusPtr, Ptr, castPtr)
77import Foreign.Storable (Storable(..))
78import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
79import Network.Socket (Socket, sendBuf, recvBuf)
80#if MIN_VERSION_network(3,1,0)
81import Network.Socket (withFdSocket)
82#else
83import Network.Socket (fdSocket)
84#endif
85import Prelude hiding (read)
87import qualified Network.Socket as Net
89import Streamly.Mem.Array.Types (Array(..))
90import Streamly.Streams.Serial (SerialT)
91import Streamly.Streams.StreamK.Type (IsStream, mkStream)
92-- import Streamly.Fold (Fold)
93-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
95import qualified Streamly.Mem.Array as A
96import qualified Streamly.Mem.Array.Stream as AS
97import qualified Streamly.Mem.Array.Types as A hiding (flattenArrays)
98import qualified Streamly.Prelude as S
100-- | @'withSocket' socket act@ runs the monadic computation @act@ passing the
101-- socket handle to it. The handle will be closed on exit from 'withSocket',
102-- whether by normal termination or by raising an exception. If closing the
103-- handle raises an exception, then this exception will be raised by
104-- 'withSocket' rather than any exception raised by 'act'.
105--
106-- @since 0.7.0
107{-# INLINE withSocket #-}
108withSocket :: (MonadCatch m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
109withSocket sk f = do
110 f sk `onException` liftIO (Net.close sk)
111 liftIO (Net.close sk)
113-- XXX bracket performs 2x better than 'finally'. That's perhaps because of
114-- better fusion of "A.flattenArrays . readArrays"?
115--
116-- withSocketS :: (IsStream t, MonadCatch m, MonadIO m) => Socket -> t m Word8
117-- withSocketS sk = A.flattenArrays $
118-- S.finally (liftIO (Net.close sk)) (readArrays sk)
120-- | Like 'withSocket' but runs a streaming computation instead of a monadic
121-- computation.
122--
123-- @since 0.7.0
124{-# INLINE withSocketS #-}
125withSocketS :: (IsStream t, MonadCatch m, MonadIO m)
126 => Socket -> (Socket -> t m a) -> t m a
127withSocketS sk = S.bracket (return sk) (liftIO . Net.close)
129-------------------------------------------------------------------------------
130-- Array IO (Input)
131-------------------------------------------------------------------------------
133{-# INLINABLE readArrayUptoWith #-}
134readArrayUptoWith
135 :: (h -> Ptr Word8 -> Int -> IO Int)
136 -> Int
137 -> h
138 -> IO (Array Word8)
139readArrayUptoWith f size h = do
140 ptr <- mallocPlainForeignPtrBytes size
141 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
142 withForeignPtr ptr $ \p -> do
143 n <- f h p size
144 let v = Array
145 { aStart = ptr
146 , aEnd = p `plusPtr` n
147 , aBound = p `plusPtr` size
148 }
149 -- XXX shrink only if the diff is significant
150 -- A.shrinkToFit v
151 return v
153-- | Read a 'ByteArray' from a file handle. If no data is available on the
154-- handle it blocks until some data becomes available. If data is available
155-- then it immediately returns that data without blocking. It reads a maximum
156-- of up to the size requested.
157{-# INLINABLE readArrayUpto #-}
158readArrayUpto :: Int -> Socket -> IO (Array Word8)
159readArrayUpto = readArrayUptoWith recvBuf
161-------------------------------------------------------------------------------
162-- Array IO (output)
163-------------------------------------------------------------------------------
165waitWhen0 :: Int -> Socket -> IO ()
166waitWhen0 0 s = when rtsSupportsBoundThreads $
167#if MIN_VERSION_network(3,1,0)
168 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
169#else
170 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
171#endif
172waitWhen0 _ _ = return ()
174sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
175sendAll _ _ len | len <= 0 = return ()
176sendAll s p len = do
177 sent <- sendBuf s p len
178 waitWhen0 sent s
179 -- assert (sent <= len)
180 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
182{-# INLINABLE writeArrayWith #-}
183writeArrayWith :: Storable a
184 => (h -> Ptr Word8 -> Int -> IO ())
185 -> h
186 -> Array a
187 -> IO ()
188writeArrayWith _ _ arr | A.length arr == 0 = return ()
189writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
190 f h (castPtr p) aLen
191 where
192 aLen =
193 let p = unsafeForeignPtrToPtr aStart
194 in aEnd `minusPtr` p
196-- | Write an Array to a file handle.
197--
198-- @since 0.7.0
199{-# INLINABLE writeArray #-}
200writeArray :: Storable a => Socket -> Array a -> IO ()
201writeArray = writeArrayWith sendAll
203-------------------------------------------------------------------------------
204-- Stream of Arrays IO
205-------------------------------------------------------------------------------
207{-# INLINABLE readArraysUptoWith #-}
208readArraysUptoWith :: (IsStream t, MonadIO m)
209 => (Int -> h -> IO (Array Word8))
210 -> Int -> h -> t m (Array Word8)
211readArraysUptoWith f size h = go
212 where
213 -- XXX use cons/nil instead
214 go = mkStream $ \_ yld _ stp -> do
215 arr <- liftIO $ f size h
216 if A.length arr == 0
217 then stp
218 else yld arr go
220-- | @readArraysUpto size h@ reads a stream of arrays from file handle @h@.
221-- The maximum size of a single array is limited to @size@.
222-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
223-- on the 'Handle'.
224{-# INLINABLE readArraysUpto #-}
225readArraysUpto :: (IsStream t, MonadIO m)
226 => Int -> Socket -> t m (Array Word8)
227readArraysUpto = readArraysUptoWith readArrayUpto
229-- XXX read 'Array a' instead of Word8
230--
231-- | @readArrays h@ reads a stream of arrays from file handle @h@.
232-- The maximum size of a single array is limited to @defaultChunkSize@.
233-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
234-- on the 'Handle'.
235--
236-- @since 0.7.0
237{-# INLINE readArrays #-}
238readArrays :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
239readArrays = readArraysUpto A.defaultChunkSize
241-------------------------------------------------------------------------------
242-- Read File to Stream
243-------------------------------------------------------------------------------
245-- TODO for concurrent streams implement readahead IO. We can send multiple
246-- read requests at the same time. For serial case we can use async IO. We can
247-- also control the read throughput in mbps or IOPS.
249{-
250-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file
251-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
252-- as soon as EOF is encountered.
253--
254{-# INLINE readByChunksUpto #-}
255readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
256readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
257-}
259-- TODO
260-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
261--
262-- > read = 'readByChunks' A.defaultChunkSize
263-- | Generate a stream of elements of the given type from a file 'Handle'. The
264-- stream ends when EOF is encountered.
265--
266-- @since 0.7.0
267{-# INLINE read #-}
268read :: (IsStream t, MonadIO m) => Socket -> t m Word8
269read = AS.flatten . readArrays
271-------------------------------------------------------------------------------
272-- Writing
273-------------------------------------------------------------------------------
275-- | Write a stream of arrays to a handle.
276--
277-- @since 0.7.0
278{-# INLINE writeArrays #-}
279writeArrays :: (MonadIO m, Storable a) => Socket -> SerialT m (Array a) -> m ()
280writeArrays h m = S.mapM_ (liftIO . writeArray h) m
282-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
283--
284-- XXX test this
285-- Note that if you use a chunk size less than 8K (GHC's default buffer
286-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
287-- do not want buffering to occur at GHC level as well. Same thing applies to
288-- writes as well.
290-- | Like 'write' but provides control over the write buffer. Output will
291-- be written to the IO device as soon as we collect the specified number of
292-- input elements.
293--
294-- @since 0.7.0
295{-# INLINE writeByChunks #-}
296writeByChunks :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
297writeByChunks n h m = writeArrays h $ AS.arraysOf n m
299-- > write = 'writeByChunks' A.defaultChunkSize
300--
301-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
302-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
303-- depends on the 'IOMode' and the current seek position of the handle.
304--
305-- @since 0.7.0
306{-# INLINE write #-}
307write :: MonadIO m => Socket -> SerialT m Word8 -> m ()
308write = writeByChunks A.defaultChunkSize
310{-
311{-# INLINE write #-}
312write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
313write = toHandleWith A.defaultChunkSize
314-}
316-------------------------------------------------------------------------------
317-- IO with encoding/decoding Unicode characters
318-------------------------------------------------------------------------------
320{-
321-- |
322-- > readUtf8 = decodeUtf8 . read
323--
324-- Read a UTF8 encoded stream of unicode characters from a file handle.
325--
326-- @since 0.7.0
327{-# INLINE readUtf8 #-}
328readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
329readUtf8 = decodeUtf8 . read
331-- |
332-- > writeUtf8 h s = write h $ encodeUtf8 s
333--
334-- Encode a stream of unicode characters to UTF8 and write it to the given file
335-- handle. Default block buffering applies to the writes.
336--
337-- @since 0.7.0
338{-# INLINE writeUtf8 #-}
339writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
340writeUtf8 h s = write h $ encodeUtf8 s
342-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
343-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
344-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
345-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
346-- option.
347--
348-- @since 0.7.0
349{-# INLINE writeUtf8ByLines #-}
350writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
351writeUtf8ByLines = undefined
353-- | Read UTF-8 lines from a file handle and apply the specified fold to each
354-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
355--
356-- @since 0.7.0
357{-# INLINE readLines #-}
358readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
359readLines h f = foldLines (readUtf8 h) f
361-------------------------------------------------------------------------------
362-- Framing on a sequence
363-------------------------------------------------------------------------------
365-- | Read a stream from a file handle and split it into frames delimited by
366-- the specified sequence of elements. The supplied fold is applied on each
367-- frame.
368--
369-- @since 0.7.0
370{-# INLINE readFrames #-}
371readFrames :: (IsStream t, MonadIO m, Storable a)
372 => Array a -> Handle -> Fold m a b -> t m b
373readFrames = undefined -- foldFrames . read
375-- | Write a stream to the given file handle buffering up to frames separated
376-- by the given sequence or up to a maximum of @defaultChunkSize@.
377--
378-- @since 0.7.0
379{-# INLINE writeByFrames #-}
380writeByFrames :: (IsStream t, MonadIO m, Storable a)
381 => Array a -> Handle -> t m a -> m ()
382writeByFrames = undefined
383-}