on fb39bc3 help sign in
410 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.Memory.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 , writeInChunksOf
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.Memory.Array.Types (Array(..))
90import Streamly.Streams.Serial (SerialT)
91import Streamly.Streams.StreamK.Type (IsStream, mkStream)
92import Streamly.Fold (Fold)
93-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
95import qualified Streamly.Fold as FL
96import qualified Streamly.Fold.Types as FL
97import qualified Streamly.Memory.Array as A
98import qualified Streamly.Memory.Array.Types as A
99import qualified Streamly.Prelude as S
101-- | @'withSocket' socket act@ runs the monadic computation @act@ passing the
102-- socket handle to it. The handle will be closed on exit from 'withSocket',
103-- whether by normal termination or by raising an exception. If closing the
104-- handle raises an exception, then this exception will be raised by
105-- 'withSocket' rather than any exception raised by 'act'.
106--
107-- @since 0.7.0
108{-# INLINE withSocket #-}
109withSocket :: (MonadCatch m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
110withSocket sk f = do
111 f sk `onException` liftIO (Net.close sk)
112 liftIO (Net.close sk)
114-- XXX bracket performs 2x better than 'finally'. That's perhaps because of
115-- better fusion of "A.flattenArrays . readArrays"?
116--
117-- withSocketS :: (IsStream t, MonadCatch m, MonadIO m) => Socket -> t m Word8
118-- withSocketS sk = A.flattenArrays $
119-- S.finally (liftIO (Net.close sk)) (readArrays sk)
121-- | Like 'withSocket' but runs a streaming computation instead of a monadic
122-- computation.
123--
124-- @since 0.7.0
125{-# INLINE withSocketS #-}
126withSocketS :: (IsStream t, MonadCatch m, MonadIO m)
127 => Socket -> (Socket -> t m a) -> t m a
128withSocketS sk = S.bracket (return sk) (liftIO . Net.close)
130-------------------------------------------------------------------------------
131-- Array IO (Input)
132-------------------------------------------------------------------------------
134{-# INLINABLE readArrayUptoWith #-}
135readArrayUptoWith
136 :: (h -> Ptr Word8 -> Int -> IO Int)
137 -> Int
138 -> h
139 -> IO (Array Word8)
140readArrayUptoWith f size h = do
141 ptr <- mallocPlainForeignPtrBytes size
142 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
143 withForeignPtr ptr $ \p -> do
144 n <- f h p size
145 let v = Array
146 { aStart = ptr
147 , aEnd = p `plusPtr` n
148 , aBound = p `plusPtr` size
149 }
150 -- XXX shrink only if the diff is significant
151 -- A.shrinkToFit v
152 return v
154-- | Read a 'ByteArray' from a file handle. If no data is available on the
155-- handle it blocks until some data becomes available. If data is available
156-- then it immediately returns that data without blocking. It reads a maximum
157-- of up to the size requested.
158{-# INLINABLE readArrayOf #-}
159readArrayOf :: Int -> Socket -> IO (Array Word8)
160readArrayOf = readArrayUptoWith recvBuf
162-------------------------------------------------------------------------------
163-- Array IO (output)
164-------------------------------------------------------------------------------
166waitWhen0 :: Int -> Socket -> IO ()
167waitWhen0 0 s = when rtsSupportsBoundThreads $
168#if MIN_VERSION_network(3,1,0)
169 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
170#else
171 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
172#endif
173waitWhen0 _ _ = return ()
175sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
176sendAll _ _ len | len <= 0 = return ()
177sendAll s p len = do
178 sent <- sendBuf s p len
179 waitWhen0 sent s
180 -- assert (sent <= len)
181 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
183{-# INLINABLE writeArrayWith #-}
184writeArrayWith :: Storable a
185 => (h -> Ptr Word8 -> Int -> IO ())
186 -> h
187 -> Array a
188 -> IO ()
189writeArrayWith _ _ arr | A.length arr == 0 = return ()
190writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
191 f h (castPtr p) aLen
192 where
193 aLen =
194 let p = unsafeForeignPtrToPtr aStart
195 in aEnd `minusPtr` p
197-- | Write an Array to a file handle.
198--
199-- @since 0.7.0
200{-# INLINABLE writeArray #-}
201writeArray :: Storable a => Socket -> Array a -> IO ()
202writeArray = writeArrayWith sendAll
204-------------------------------------------------------------------------------
205-- Stream of Arrays IO
206-------------------------------------------------------------------------------
208{-# INLINABLE readArraysUptoWith #-}
209readArraysUptoWith :: (IsStream t, MonadIO m)
210 => (Int -> h -> IO (Array Word8))
211 -> Int -> h -> t m (Array Word8)
212readArraysUptoWith f size h = go
213 where
214 -- XXX use cons/nil instead
215 go = mkStream $ \_ yld _ stp -> do
216 arr <- liftIO $ f size h
217 if A.length arr == 0
218 then stp
219 else yld arr go
221-- | @readArraysOf size h@ reads a stream of arrays from file handle @h@.
222-- The maximum size of a single array is limited to @size@.
223-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
224-- on the 'Handle'.
225{-# INLINABLE readArraysOf #-}
226readArraysOf :: (IsStream t, MonadIO m)
227 => Int -> Socket -> t m (Array Word8)
228readArraysOf = readArraysUptoWith readArrayOf
230-- XXX read 'Array a' instead of Word8
231--
232-- | @readArrays h@ reads a stream of arrays from socket handle @h@.
233-- The maximum size of a single array is limited to @defaultChunkSize@.
234--
235-- @since 0.7.0
236{-# INLINE readArrays #-}
237readArrays :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
238readArrays = readArraysOf A.defaultChunkSize
240-------------------------------------------------------------------------------
241-- Read File to Stream
242-------------------------------------------------------------------------------
244-- TODO for concurrent streams implement readahead IO. We can send multiple
245-- read requests at the same time. For serial case we can use async IO. We can
246-- also control the read throughput in mbps or IOPS.
248{-
249-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
250-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
251-- as soon as EOF is encountered.
252--
253{-# INLINE readInChunksOf #-}
254readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
255readInChunksOf chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
256-}
258-- TODO
259-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
260--
261-- > read = 'readByChunks' A.defaultChunkSize
262-- | Generate a stream of elements of the given type from a socket. The
263-- stream ends when EOF is encountered.
264--
265-- @since 0.7.0
266{-# INLINE read #-}
267read :: (IsStream t, MonadIO m) => Socket -> t m Word8
268read = A.concat . readArrays
270-------------------------------------------------------------------------------
271-- Writing
272-------------------------------------------------------------------------------
274-- | Write a stream of arrays to a handle.
275--
276-- @since 0.7.0
277{-# INLINE writeArraysS #-}
278writeArraysS :: (MonadIO m, Storable a)
279 => Socket -> SerialT m (Array a) -> m ()
280writeArraysS h m = S.mapM_ (liftIO . writeArray h) m
282-- | Write a stream of arrays to a socket.
283--
284-- @since 0.7.0
285{-# INLINE writeArrays #-}
286writeArrays :: (MonadIO m, Storable a) => Socket -> Fold m (Array a) ()
287writeArrays h = FL.drainBy (liftIO . writeArray h)
289-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
290--
291-- XXX test this
292-- Note that if you use a chunk size less than 8K (GHC's default buffer
293-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
294-- do not want buffering to occur at GHC level as well. Same thing applies to
295-- writes as well.
297-- | Like 'write' but provides control over the write buffer. Output will
298-- be written to the IO device as soon as we collect the specified number of
299-- input elements.
300--
301-- @since 0.7.0
302{-# INLINE writeInChunksOfS #-}
303writeInChunksOfS :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
304writeInChunksOfS n h m = writeArraysS h $ A.arraysOf n m
306-- | Write a byte stream to a socket. Accumulates the input in chunks of
307-- specified number of bytes before writing.
308--
309-- @since 0.7.0
310{-# INLINE writeInChunksOf #-}
311writeInChunksOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
312writeInChunksOf n h = FL.lchunksOf n (A.writeN n) (writeArrays h)
314-- > write = 'writeInChunksOf' A.defaultChunkSize
315--
316-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
317-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
318-- depends on the 'IOMode' and the current seek position of the handle.
319--
320-- @since 0.7.0
321{-# INLINE _writeS #-}
322_writeS :: MonadIO m => Socket -> SerialT m Word8 -> m ()
323_writeS = writeInChunksOfS A.defaultChunkSize
325-- | Write a byte stream to a socket. Accumulates the input in chunks of
326-- up to 'A.defaultChunkSize' bytes before writing.
327--
328-- @
329-- write = 'writeInChunksOf' 'A.defaultChunkSize'
330-- @
331--
332-- @since 0.7.0
333{-# INLINE write #-}
334write :: MonadIO m => Socket -> Fold m Word8 ()
335write = writeInChunksOf A.defaultChunkSize
337{-
338{-# INLINE write #-}
339write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
340write = toHandleWith A.defaultChunkSize
341-}
343-------------------------------------------------------------------------------
344-- IO with encoding/decoding Unicode characters
345-------------------------------------------------------------------------------
347{-
348-- |
349-- > readUtf8 = decodeUtf8 . read
350--
351-- Read a UTF8 encoded stream of unicode characters from a file handle.
352--
353-- @since 0.7.0
354{-# INLINE readUtf8 #-}
355readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
356readUtf8 = decodeUtf8 . read
358-- |
359-- > writeUtf8 h s = write h $ encodeUtf8 s
360--
361-- Encode a stream of unicode characters to UTF8 and write it to the given file
362-- handle. Default block buffering applies to the writes.
363--
364-- @since 0.7.0
365{-# INLINE writeUtf8 #-}
366writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
367writeUtf8 h s = write h $ encodeUtf8 s
369-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
370-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
371-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
372-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
373-- option.
374--
375-- @since 0.7.0
376{-# INLINE writeUtf8ByLines #-}
377writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
378writeUtf8ByLines = undefined
380-- | Read UTF-8 lines from a file handle and apply the specified fold to each
381-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
382--
383-- @since 0.7.0
384{-# INLINE readLines #-}
385readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
386readLines h f = foldLines (readUtf8 h) f
388-------------------------------------------------------------------------------
389-- Framing on a sequence
390-------------------------------------------------------------------------------
392-- | Read a stream from a file handle and split it into frames delimited by
393-- the specified sequence of elements. The supplied fold is applied on each
394-- frame.
395--
396-- @since 0.7.0
397{-# INLINE readFrames #-}
398readFrames :: (IsStream t, MonadIO m, Storable a)
399 => Array a -> Handle -> Fold m a b -> t m b
400readFrames = undefined -- foldFrames . read
402-- | Write a stream to the given file handle buffering up to frames separated
403-- by the given sequence or up to a maximum of @defaultChunkSize@.
404--
405-- @since 0.7.0
406{-# INLINE writeByFrames #-}
407writeByFrames :: (IsStream t, MonadIO m, Storable a)
408 => Array a -> Handle -> t m a -> m ()
409writeByFrames = undefined
410-}