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.Mem.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.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.Types as A hiding (flattenArrays)
97import qualified Streamly.Prelude as S
99-- | @'withSocket' socket act@ runs the monadic computation @act@ passing the
100-- socket handle to it. The handle will be closed on exit from 'withSocket',
101-- whether by normal termination or by raising an exception. If closing the
102-- handle raises an exception, then this exception will be raised by
103-- 'withSocket' rather than any exception raised by 'act'.
106{-# INLINE withSocket #-}
107withSocket :: (MonadCatch m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
109 f sk `onException` liftIO (Net.close sk)
110 liftIO (Net.close sk)
112-- XXX bracket performs 2x better than 'finally'. That's perhaps because of
113-- better fusion of "A.flattenArrays . readArrays"?
115-- withSocketS :: (IsStream t, MonadCatch m, MonadIO m) => Socket -> t m Word8
116-- withSocketS sk = A.flattenArrays $
117-- S.finally (liftIO (Net.close sk)) (readArrays sk)
119-- | Like 'withSocket' but runs a streaming computation instead of a monadic
123{-# INLINE withSocketS #-}
124withSocketS :: (IsStream t, MonadCatch m, MonadIO m)
125 => Socket -> (Socket -> t m a) -> t m a
126withSocketS sk = S.bracket (return sk) (liftIO . Net.close)
128-------------------------------------------------------------------------------
130-------------------------------------------------------------------------------
132{-# INLINABLE readArrayUptoWith #-}
134 :: (h -> Ptr Word8 -> Int -> IO Int)
138readArrayUptoWith f size h = do
139 ptr <- mallocPlainForeignPtrBytes size
140 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
141 withForeignPtr ptr $ \p -> do
145 , aEnd = p `plusPtr` n
146 , aBound = p `plusPtr` size
148 -- XXX shrink only if the diff is significant
152-- | Read a 'ByteArray' from a file handle. If no data is available on the
153-- handle it blocks until some data becomes available. If data is available
154-- then it immediately returns that data without blocking. It reads a maximum
155-- of up to the size requested.
156{-# INLINABLE readArrayUpto #-}
157readArrayUpto :: Int -> Socket -> IO (Array Word8)
158readArrayUpto = readArrayUptoWith recvBuf
160-------------------------------------------------------------------------------
162-------------------------------------------------------------------------------
164waitWhen0 :: Int -> Socket -> IO ()
165waitWhen0 0 s = when rtsSupportsBoundThreads $
166#if MIN_VERSION_network(3,1,0)
167 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
169 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
171waitWhen0 _ _ = return ()
173sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
174sendAll _ _ len | len <= 0 = return ()
176 sent <- sendBuf s p len
178 -- assert (sent <= len)
179 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
181{-# INLINABLE writeArrayWith #-}
182writeArrayWith :: Storable a
183 => (h -> Ptr Word8 -> Int -> IO ())
187writeArrayWith _ _ arr | A.length arr == 0 = return ()
188writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
192 let p = unsafeForeignPtrToPtr aStart
195-- | Write an Array to a file handle.
198{-# INLINABLE writeArray #-}
199writeArray :: Storable a => Socket -> Array a -> IO ()
200writeArray = writeArrayWith sendAll
202-------------------------------------------------------------------------------
203-- Stream of Arrays IO
204-------------------------------------------------------------------------------
206{-# INLINABLE readArraysUptoWith #-}
207readArraysUptoWith :: (IsStream t, MonadIO m)
208 => (Int -> h -> IO (Array Word8))
209 -> Int -> h -> t m (Array Word8)
210readArraysUptoWith f size h = go
212 -- XXX use cons/nil instead
213 go = mkStream $ \_ yld _ stp -> do
214 arr <- liftIO $ f size h
219-- | @readArraysUpto size h@ reads a stream of arrays from file handle @h@.
220-- The maximum size of a single array is limited to @size@.
221-- 'fromHandleArraysUpto' ignores the prevailing 'TextEncoding' and 'NewlineMode'
223{-# INLINABLE readArraysUpto #-}
224readArraysUpto :: (IsStream t, MonadIO m)
225 => Int -> Socket -> t m (Array Word8)
226readArraysUpto = readArraysUptoWith readArrayUpto
228-- XXX read 'Array a' instead of Word8
230-- | @readArrays h@ reads a stream of arrays from file handle @h@.
231-- The maximum size of a single array is limited to @defaultChunkSize@.
232-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
236{-# INLINE readArrays #-}
237readArrays :: (IsStream t, MonadIO m) => Socket -> t m (Array Word8)
238readArrays = readArraysUpto 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-- | @readByChunksUpto 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 readByChunksUpto #-}
254readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
255readByChunksUpto 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 file 'Handle'. The
263-- stream ends when EOF is encountered.
267read :: (IsStream t, MonadIO m) => Socket -> t m Word8
268read = A.flattenArrays . readArrays
270-------------------------------------------------------------------------------
272-------------------------------------------------------------------------------
274-- | Write a stream of arrays to a handle.
277{-# INLINE writeArrays #-}
278writeArrays :: (MonadIO m, Storable a) => Socket -> SerialT m (Array a) -> m ()
279writeArrays h m = S.mapM_ (liftIO . writeArray h) m
281-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
284-- Note that if you use a chunk size less than 8K (GHC's default buffer
285-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
286-- do not want buffering to occur at GHC level as well. Same thing applies to
289-- | Like 'write' but provides control over the write buffer. Output will
290-- be written to the IO device as soon as we collect the specified number of
294{-# INLINE writeByChunks #-}
295writeByChunks :: MonadIO m => Int -> Socket -> SerialT m Word8 -> m ()
296writeByChunks n h m = writeArrays h $ A.arraysOf n m
298-- > write = 'writeByChunks' A.defaultChunkSize
300-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
301-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
302-- depends on the 'IOMode' and the current seek position of the handle.
306write :: MonadIO m => Socket -> SerialT m Word8 -> m ()
307write = writeByChunks A.defaultChunkSize
311write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
312write = toHandleWith A.defaultChunkSize
315-------------------------------------------------------------------------------
316-- IO with encoding/decoding Unicode characters
317-------------------------------------------------------------------------------
321-- > readUtf8 = decodeUtf8 . read
323-- Read a UTF8 encoded stream of unicode characters from a file handle.
326{-# INLINE readUtf8 #-}
327readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
328readUtf8 = decodeUtf8 . read
331-- > writeUtf8 h s = write h $ encodeUtf8 s
333-- Encode a stream of unicode characters to UTF8 and write it to the given file
334-- handle. Default block buffering applies to the writes.
337{-# INLINE writeUtf8 #-}
338writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
339writeUtf8 h s = write h $ encodeUtf8 s
341-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
342-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
343-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
344-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
348{-# INLINE writeUtf8ByLines #-}
349writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
350writeUtf8ByLines = undefined
352-- | Read UTF-8 lines from a file handle and apply the specified fold to each
353-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
356{-# INLINE readLines #-}
357readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
358readLines h f = foldLines (readUtf8 h) f
360-------------------------------------------------------------------------------
361-- Framing on a sequence
362-------------------------------------------------------------------------------
364-- | Read a stream from a file handle and split it into frames delimited by
365-- the specified sequence of elements. The supplied fold is applied on each
369{-# INLINE readFrames #-}
370readFrames :: (IsStream t, MonadIO m, Storable a)
371 => Array a -> Handle -> Fold m a b -> t m b
372readFrames = undefined -- foldFrames . read
374-- | Write a stream to the given file handle buffering up to frames separated
375-- by the given sequence or up to a maximum of @defaultChunkSize@.
378{-# INLINE writeByFrames #-}
379writeByFrames :: (IsStream t, MonadIO m, Storable a)
380 => Array a -> Handle -> t m a -> m ()
381writeByFrames = 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