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.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'.
107{-# INLINE withSocket #-}
108withSocket :: (MonadCatch m, MonadIO m) => Socket -> (Socket -> m ()) -> m ()
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"?
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
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-------------------------------------------------------------------------------
131-------------------------------------------------------------------------------
133{-# INLINABLE readArrayUptoWith #-}
135 :: (h -> Ptr Word8 -> Int -> IO Int)
139readArrayUptoWith f size h = do
140 ptr <- mallocPlainForeignPtrBytes size
141 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
142 withForeignPtr ptr $ \p -> do
146 , aEnd = p `plusPtr` n
147 , aBound = p `plusPtr` size
149 -- XXX shrink only if the diff is significant
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-------------------------------------------------------------------------------
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
170 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
172waitWhen0 _ _ = return ()
174sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
175sendAll _ _ len | len <= 0 = return ()
177 sent <- sendBuf s p len
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 ())
188writeArrayWith _ _ arr | A.length arr == 0 = return ()
189writeArrayWith f h Array{..} = withForeignPtr aStart $ \p ->
193 let p = unsafeForeignPtrToPtr aStart
196-- | Write an Array to a file handle.
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
213 -- XXX use cons/nil instead
214 go = mkStream $ \_ yld _ stp -> do
215 arr <- liftIO $ f size h
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'
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
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'
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.
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.
254{-# INLINE readByChunksUpto #-}
255readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
256readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
260-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
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.
268read :: (IsStream t, MonadIO m) => Socket -> t m Word8
269read = AS.flatten . readArrays
271-------------------------------------------------------------------------------
273-------------------------------------------------------------------------------
275-- | Write a stream of arrays to a handle.
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.
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
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
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
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.
307write :: MonadIO m => Socket -> SerialT m Word8 -> m ()
308write = writeByChunks A.defaultChunkSize
312write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
313write = toHandleWith A.defaultChunkSize
316-------------------------------------------------------------------------------
317-- IO with encoding/decoding Unicode characters
318-------------------------------------------------------------------------------
322-- > readUtf8 = decodeUtf8 . read
324-- Read a UTF8 encoded stream of unicode characters from a file handle.
327{-# INLINE readUtf8 #-}
328readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
329readUtf8 = decodeUtf8 . read
332-- > writeUtf8 h s = write h $ encodeUtf8 s
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.
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'
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.
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
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@.
379{-# INLINE writeByFrames #-}
380writeByFrames :: (IsStream t, MonadIO m, Storable a)
381 => Array a -> Handle -> t m a -> m ()
382writeByFrames = 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