2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
11-- Module : Streamly.Network.Socket
12-- Copyright : (c) 2018 Harendra Kumar
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
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".
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
30-- > import qualified Streamly.Network.Socket as SK
33module Streamly.Network.Socket
39 -- * Read from connection
54 -- * Write to connection
65 -- reading/writing datagrams
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)
83import Network.Socket (fdSocket)
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'.
108{-# INLINE withSocket #-}
109withSocket :: (MonadCatch m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
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"?
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
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-------------------------------------------------------------------------------
132-------------------------------------------------------------------------------
134{-# INLINABLE readArrayUptoWith #-}
136 :: (h -> Ptr Word8 -> Int -> IO Int)
140readArrayUptoWith f size h = do
141 ptr <- mallocPlainForeignPtrBytes size
142 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
143 withForeignPtr ptr $ \p -> do
147 , aEnd = p `plusPtr` n
148 , aBound = p `plusPtr` size
150 -- XXX shrink only if the diff is significant
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-------------------------------------------------------------------------------
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
171 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
173waitWhen0 _ _ = return ()
175sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
176sendAll _ _ len | len <= 0 = return ()
178 sent <- sendBuf s p len
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 ())
189writeArrayWith _ _ arr | A.length arr == 0 = return ()
190writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
194 let p = unsafeForeignPtrToPtr aStart
197-- | Write an Array to a file handle.
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
214 -- XXX use cons/nil instead
215 go = mkStream $ \_ yld _ stp -> do
216 arr <- liftIO $ f size h
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'
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
232-- | @readArrays h@ reads a stream of arrays from socket handle @h@.
233-- The maximum size of a single array is limited to @defaultChunkSize@.
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.
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.
253{-# INLINE readInChunksOf #-}
254readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
255readInChunksOf chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
259-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
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.
267read :: (IsStream t, MonadIO m) => Socket -> t m Word8
268read = A.concat . readArrays
270-------------------------------------------------------------------------------
272-------------------------------------------------------------------------------
274-- | Write a stream of arrays to a handle.
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.
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.
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
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
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.
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
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.
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.
329-- write = 'writeInChunksOf' 'A.defaultChunkSize'
334write :: MonadIO m => Socket -> Fold m Word8 ()
335write = writeInChunksOf A.defaultChunkSize
339write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
340write = toHandleWith A.defaultChunkSize
343-------------------------------------------------------------------------------
344-- IO with encoding/decoding Unicode characters
345-------------------------------------------------------------------------------
349-- > readUtf8 = decodeUtf8 . read
351-- Read a UTF8 encoded stream of unicode characters from a file handle.
354{-# INLINE readUtf8 #-}
355readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
356readUtf8 = decodeUtf8 . read
359-- > writeUtf8 h s = write h $ encodeUtf8 s
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.
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'
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.
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
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@.
406{-# INLINE writeByFrames #-}
407writeByFrames :: (IsStream t, MonadIO m, Storable a)
408 => Array a -> Handle -> t m a -> m ()
409writeByFrames = undefined
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list