on cd3ce3e help sign in
580 lines 22 kB history raw
1#include "inline.hs"
3-- |
4-- Module : Streamly.Internal.FileSystem.File
5-- Copyright : (c) 2019 Composewell Technologies
6--
7-- License : BSD3
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
10-- Portability : GHC
11--
12-- Read and write streams and arrays to and from files specified by their paths
13-- in the file system. Unlike the handle based APIs which can have a read/write
14-- session consisting of multiple reads and writes to the handle, these APIs
15-- are one shot read or write APIs. These APIs open the file handle, perform
16-- the requested operation and close the handle. Thease are safer compared to
17-- the handle based APIs as there is no possibility of a file descriptor
18-- leakage.
19--
20-- > import qualified Streamly.Internal.FileSystem.File as File
21--
23module Streamly.Internal.FileSystem.File
24 (
25 -- * Streaming IO
26 -- | Stream data to or from a file or device sequentially. When reading,
27 -- the stream is lazy and generated on-demand as the consumer consumes it.
28 -- Read IO requests to the IO device are performed in chunks limited to a
29 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
30 -- documentation. One IO request may or may not read the full
31 -- chunk. If the whole stream is not consumed, it is possible that we may
32 -- read slightly more from the IO device than what the consumer needed.
33 -- Unless specified otherwise in the API, writes are collected into chunks
34 -- of @defaultChunkSize@ before they are written to the IO device.
36 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
37 -- including disks, files, memory devices, terminals, pipes, sockets and
38 -- fifos. While random access APIs work only for files or devices that have
39 -- random access or seek capability for example disks, memory devices.
40 -- Devices like terminals, pipes, sockets and fifos do not have random
41 -- access capability.
43 -- ** File IO Using Handle
44 withFile
46 -- ** Read From File
47 , readWithBufferOf
48 , read
49 -- , readShared
50 -- , readUtf8
51 -- , readLines
52 -- , readFrames
54 , toBytes
56 -- -- * Array Read
57 , readChunksWithBufferOf
58 , readChunks
60 , toChunksWithBufferOf
61 , toChunks
63 -- ** Write To File
64 , write
65 -- , writeUtf8
66 -- , writeUtf8ByLines
67 -- , writeByFrames
68 , writeWithBufferOf
70 , fromBytes
71 , fromBytesWithBufferOf
73 -- -- * Array Write
74 , writeArray
75 , writeChunks
76 , fromChunks
78 -- ** Append To File
79 , append
80 , appendWithBufferOf
81 -- , appendShared
82 , appendArray
83 , appendChunks
84 )
85where
87import Control.Monad.Catch (MonadCatch)
88import Control.Monad.IO.Class (MonadIO(..))
89import Data.Word (Word8)
90import Foreign.Storable (Storable(..))
91import System.IO (Handle, openFile, IOMode(..), hClose)
92import Prelude hiding (read)
94import qualified Control.Monad.Catch as MC
95import qualified System.IO as SIO
97import Streamly.Internal.Data.Fold.Types (Fold(..))
98import Streamly.Internal.Data.Unfold.Types (Unfold(..))
99import Streamly.Internal.Data.Array.Storable.Foreign.Types
100 (Array(..), defaultChunkSize, writeNUnsafe)
101import Streamly.Internal.Data.Stream.Serial (SerialT)
102import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
103import Streamly.Internal.Data.SVar (MonadAsync)
104-- import Streamly.Data.Fold (Fold)
105-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
107import qualified Streamly.Internal.Data.Fold.Types as FL
108import qualified Streamly.Internal.Data.Unfold as UF
109import qualified Streamly.Internal.FileSystem.Handle as FH
110import qualified Streamly.Internal.Memory.ArrayStream as AS
111import qualified Streamly.Data.Array.Storable.Foreign as A
112import qualified Streamly.Prelude as S
114-------------------------------------------------------------------------------
115-- References
116-------------------------------------------------------------------------------
117--
118-- The following references may be useful to build an understanding about the
119-- file API design:
120--
121-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
122-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
123-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
124-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
125-- https://www.w3.org/TR/FileAPI/ for http file API.
127-------------------------------------------------------------------------------
128-- Safe file reading
129-------------------------------------------------------------------------------
131-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
132-- the resulting handle to the computation @act@. The handle will be
133-- closed on exit from 'withFile', whether by normal termination or by
134-- raising an exception. If closing the handle raises an exception, then
135-- this exception will be raised by 'withFile' rather than any exception
136-- raised by 'act'.
137--
138-- /Internal/
139--
140{-# INLINE withFile #-}
141withFile :: (IsStream t, MonadCatch m, MonadAsync m)
142 => FilePath -> IOMode -> (Handle -> t m a) -> t m a
143withFile file mode = S.bracket (liftIO $ openFile file mode) (liftIO . hClose)
145-- | Transform an 'Unfold' from a 'Handle' to an unfold from a 'FilePath'. The
146-- resulting unfold opens a handle in 'ReadMode', uses it using the supplied
147-- unfold and then makes sure that the handle is closed on normal termination
148-- or in case of an exception. If closing the handle raises an exception, then
149-- this exception will be raised by 'usingFile'.
150--
151-- /Internal/
152--
153{-# INLINABLE usingFile #-}
154usingFile :: (MonadCatch m, MonadAsync m)
155 => Unfold m Handle a -> Unfold m FilePath a
156usingFile =
157 UF.bracket (\file -> liftIO $ openFile file ReadMode)
158 (liftIO . hClose)
160{-# INLINABLE usingFile2 #-}
161usingFile2 :: (MonadCatch m, MonadAsync m)
162 => Unfold m (x, Handle) a -> Unfold m (x, FilePath) a
163usingFile2 = UF.bracket before after
165 where
167 before (x, file) = do
168 h <- liftIO $ openFile file ReadMode
169 return (x, h)
171 after (_, h) = liftIO $ hClose h
173-------------------------------------------------------------------------------
174-- Array IO (Input)
175-------------------------------------------------------------------------------
177-- TODO readArrayOf
179-------------------------------------------------------------------------------
180-- Array IO (output)
181-------------------------------------------------------------------------------
183-- | Write an array to a file. Overwrites the file if it exists.
184--
185-- @since 0.7.0
186{-# INLINABLE writeArray #-}
187writeArray :: Storable a => FilePath -> Array a -> IO ()
188writeArray file arr = SIO.withFile file WriteMode (`FH.writeArray` arr)
190-- | append an array to a file.
191--
192-- @since 0.7.0
193{-# INLINABLE appendArray #-}
194appendArray :: Storable a => FilePath -> Array a -> IO ()
195appendArray file arr = SIO.withFile file AppendMode (`FH.writeArray` arr)
197-------------------------------------------------------------------------------
198-- Stream of Arrays IO
199-------------------------------------------------------------------------------
201-- | @toChunksWithBufferOf size file@ reads a stream of arrays from file @file@.
202-- The maximum size of a single array is specified by @size@. The actual size
203-- read may be less than or equal to @size@.
204{-# INLINABLE toChunksWithBufferOf #-}
205toChunksWithBufferOf :: (IsStream t, MonadCatch m, MonadAsync m)
206 => Int -> FilePath -> t m (Array Word8)
207toChunksWithBufferOf size file =
208 withFile file ReadMode (FH.toChunksWithBufferOf size)
210-- XXX read 'Array a' instead of Word8
211--
212-- | @toChunks file@ reads a stream of arrays from file @file@.
213-- The maximum size of a single array is limited to @defaultChunkSize@. The
214-- actual size read may be less than @defaultChunkSize@.
215--
216-- > toChunks = toChunksWithBufferOf defaultChunkSize
217--
218-- @since 0.7.0
219{-# INLINE toChunks #-}
220toChunks :: (IsStream t, MonadCatch m, MonadAsync m)
221 => FilePath -> t m (Array Word8)
222toChunks = toChunksWithBufferOf defaultChunkSize
224-------------------------------------------------------------------------------
225-- Read File to Stream
226-------------------------------------------------------------------------------
228-- TODO for concurrent streams implement readahead IO. We can send multiple
229-- read requests at the same time. For serial case we can use async IO. We can
230-- also control the read throughput in mbps or IOPS.
232-- | Unfold the tuple @(bufsize, filepath)@ into a stream of 'Word8' arrays.
233-- Read requests to the IO device are performed using a buffer of size
234-- @bufsize@. The size of an array in the resulting stream is always less than
235-- or equal to @bufsize@.
236--
237-- /Internal/
238--
239{-# INLINE readChunksWithBufferOf #-}
240readChunksWithBufferOf :: (MonadCatch m, MonadAsync m)
241 => Unfold m (Int, FilePath) (Array Word8)
242readChunksWithBufferOf = usingFile2 FH.readChunksWithBufferOf
244-- | Unfolds a 'FilePath' into a stream of 'Word8' arrays. Requests to the IO
245-- device are performed using a buffer of size
246-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize'. The
247-- size of arrays in the resulting stream are therefore less than or equal to
248-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize'.
249--
250-- /Internal/
251{-# INLINE readChunks #-}
252readChunks :: (MonadCatch m, MonadAsync m) => Unfold m FilePath (Array Word8)
253readChunks = usingFile FH.readChunks
255-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
256-- to the IO device are performed using buffers of @bufsize@.
257--
258-- /Internal/
259{-# INLINE readWithBufferOf #-}
260readWithBufferOf :: (MonadCatch m, MonadAsync m) => Unfold m (Int, FilePath) Word8
261readWithBufferOf = usingFile2 FH.readWithBufferOf
263-- | Unfolds a file path into a byte stream. IO requests to the device are
264-- performed in sizes of
265-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize'.
266--
267-- @since 0.7.0
268{-# INLINE read #-}
269read :: (MonadCatch m, MonadAsync m) => Unfold m FilePath Word8
270read = UF.concat (usingFile FH.readChunks) A.read
272-- | Generate a stream of bytes from a file specified by path. The stream ends
273-- when EOF is encountered. File is locked using multiple reader and single
274-- writer locking mode.
275--
276-- /Internal/
277--
278{-# INLINE toBytes #-}
279toBytes :: (IsStream t, MonadCatch m, MonadAsync m) => FilePath -> t m Word8
280toBytes file = AS.concat $ withFile file ReadMode FH.toChunks
282{-
283-- | Generate a stream of elements of the given type from a file 'Handle'. The
284-- stream ends when EOF is encountered. File is not locked for exclusive reads,
285-- writers can keep writing to the file.
286--
287-- @since 0.7.0
288{-# INLINE readShared #-}
289readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
290readShared = undefined
291-}
293-------------------------------------------------------------------------------
294-- Writing
295-------------------------------------------------------------------------------
297{-# INLINE fromChunksMode #-}
298fromChunksMode :: (MonadAsync m, MonadCatch m, Storable a)
299 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
300fromChunksMode mode file xs = S.drain $
301 withFile file mode (\h -> S.mapM (liftIO . FH.writeArray h) xs)
303-- | Write a stream of arrays to a file. Overwrites the file if it exists.
304--
305-- @since 0.7.0
306{-# INLINE fromChunks #-}
307fromChunks :: (MonadAsync m, MonadCatch m, Storable a)
308 => FilePath -> SerialT m (Array a) -> m ()
309fromChunks = fromChunksMode WriteMode
311-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
312--
313-- XXX test this
314-- Note that if you use a chunk size less than 8K (GHC's default buffer
315-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
316-- do not want buffering to occur at GHC level as well. Same thing applies to
317-- writes as well.
319-- | Like 'write' but provides control over the write buffer. Output will
320-- be written to the IO device as soon as we collect the specified number of
321-- input elements.
322--
323-- @since 0.7.0
324{-# INLINE fromBytesWithBufferOf #-}
325fromBytesWithBufferOf :: (MonadAsync m, MonadCatch m)
326 => Int -> FilePath -> SerialT m Word8 -> m ()
327fromBytesWithBufferOf n file xs = fromChunks file $ AS.arraysOf n xs
329-- > write = 'writeWithBufferOf' defaultChunkSize
330--
331-- | Write a byte stream to a file. Combines the bytes in chunks of size
332-- up to 'A.defaultChunkSize' before writing. If the file exists it is
333-- truncated to zero size before writing. If the file does not exist it is
334-- created. File is locked using single writer locking mode.
335--
336-- /Internal/
337{-# INLINE fromBytes #-}
338fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
339fromBytes = fromBytesWithBufferOf defaultChunkSize
341{-
342{-# INLINE write #-}
343write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
344write = toHandleWith A.defaultChunkSize
345-}
347-- | Write a stream of chunks to a handle. Each chunk in the stream is written
348-- to the device as a separate IO request.
349--
350-- /Internal/
351{-# INLINE writeChunks #-}
352writeChunks :: (MonadIO m, MonadCatch m, Storable a)
353 => FilePath -> Fold m (Array a) ()
354writeChunks path = Fold step initial extract
355 where
356 initial = do
357 h <- liftIO (openFile path WriteMode)
358 fld <- FL.initialize (FH.writeChunks h)
359 `MC.onException` liftIO (hClose h)
360 return (fld, h)
361 step (fld, h) x = do
362 r <- FL.runStep fld x `MC.onException` liftIO (hClose h)
363 return (r, h)
364 extract (Fold _ initial1 extract1, h) = do
365 liftIO $ hClose h
366 initial1 >>= extract1
368-- | @writeWithBufferOf chunkSize handle@ writes the input stream to @handle@.
369-- Bytes in the input stream are collected into a buffer until we have a chunk
370-- of size @chunkSize@ and then written to the IO device.
371--
372-- /Internal/
373{-# INLINE writeWithBufferOf #-}
374writeWithBufferOf :: (MonadIO m, MonadCatch m)
375 => Int -> FilePath -> Fold m Word8 ()
376writeWithBufferOf n path =
377 FL.lchunksOf n (writeNUnsafe n) (writeChunks path)
379-- > write = 'writeWithBufferOf' A.defaultChunkSize
380--
381-- | Write a byte stream to a file. Accumulates the input in chunks of up to
382-- 'Streamly.Internal.Data.Array.Storable.Foreign.Types.defaultChunkSize' before writing to
383-- the IO device.
384--
385-- /Internal/
386--
387{-# INLINE write #-}
388write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
389write = writeWithBufferOf defaultChunkSize
391-- | Append a stream of arrays to a file.
392--
393-- @since 0.7.0
394{-# INLINE appendChunks #-}
395appendChunks :: (MonadAsync m, MonadCatch m, Storable a)
396 => FilePath -> SerialT m (Array a) -> m ()
397appendChunks = fromChunksMode AppendMode
399-- | Like 'append' but provides control over the write buffer. Output will
400-- be written to the IO device as soon as we collect the specified number of
401-- input elements.
402--
403-- @since 0.7.0
404{-# INLINE appendWithBufferOf #-}
405appendWithBufferOf :: (MonadAsync m, MonadCatch m)
406 => Int -> FilePath -> SerialT m Word8 -> m ()
407appendWithBufferOf n file xs = appendChunks file $ AS.arraysOf n xs
409-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
410-- 'A.defaultChunkSize' before writing. If the file exists then the new data
411-- is appended to the file. If the file does not exist it is created. File is
412-- locked using single writer locking mode.
413--
414-- @since 0.7.0
415{-# INLINE append #-}
416append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
417append = appendWithBufferOf defaultChunkSize
419{-
420-- | Like 'append' but the file is not locked for exclusive writes.
421--
422-- @since 0.7.0
423{-# INLINE appendShared #-}
424appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
425appendShared = undefined
426-}
428-------------------------------------------------------------------------------
429-- IO with encoding/decoding Unicode characters
430-------------------------------------------------------------------------------
432{-
433-- |
434-- > readUtf8 = decodeUtf8 . read
435--
436-- Read a UTF8 encoded stream of unicode characters from a file handle.
437--
438-- @since 0.7.0
439{-# INLINE readUtf8 #-}
440readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
441readUtf8 = decodeUtf8 . read
443-- |
444-- > writeUtf8 h s = write h $ encodeUtf8 s
445--
446-- Encode a stream of unicode characters to UTF8 and write it to the given file
447-- handle. Default block buffering applies to the writes.
448--
449-- @since 0.7.0
450{-# INLINE writeUtf8 #-}
451writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
452writeUtf8 h s = write h $ encodeUtf8 s
454-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
455-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
456-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
457-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
458-- option.
459--
460-- @since 0.7.0
461{-# INLINE writeUtf8ByLines #-}
462writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
463writeUtf8ByLines = undefined
465-- | Read UTF-8 lines from a file handle and apply the specified fold to each
466-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
467--
468-- @since 0.7.0
469{-# INLINE readLines #-}
470readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
471readLines h f = foldLines (readUtf8 h) f
473-------------------------------------------------------------------------------
474-- Framing on a sequence
475-------------------------------------------------------------------------------
477-- | Read a stream from a file handle and split it into frames delimited by
478-- the specified sequence of elements. The supplied fold is applied on each
479-- frame.
480--
481-- @since 0.7.0
482{-# INLINE readFrames #-}
483readFrames :: (IsStream t, MonadIO m, Storable a)
484 => Array a -> Handle -> Fold m a b -> t m b
485readFrames = undefined -- foldFrames . read
487-- | Write a stream to the given file handle buffering up to frames separated
488-- by the given sequence or up to a maximum of @defaultChunkSize@.
489--
490-- @since 0.7.0
491{-# INLINE writeByFrames #-}
492writeByFrames :: (IsStream t, MonadIO m, Storable a)
493 => Array a -> Handle -> t m a -> m ()
494writeByFrames = undefined
496-------------------------------------------------------------------------------
497-- Random Access IO (Seek)
498-------------------------------------------------------------------------------
500-- XXX handles could be shared, so we may not want to use the handle state at
501-- all for these APIs. we can use pread and pwrite instead. On windows we will
502-- need to use readFile/writeFile with an offset argument.
504-------------------------------------------------------------------------------
506-- | Read the element at the given index treating the file as an array.
507--
508-- @since 0.7.0
509{-# INLINE readIndex #-}
510readIndex :: Storable a => Handle -> Int -> Maybe a
511readIndex arr i = undefined
513-- NOTE: To represent a range to read we have chosen (start, size) instead of
514-- (start, end). This helps in removing the ambiguity of whether "end" is
515-- included in the range or not.
516--
517-- We could avoid specifying the range to be read and instead use "take size"
518-- on the stream, but it may end up reading more and then consume it partially.
520-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
521-- from @handle@ starting at the offset @pos@ from the beginning of the file.
522--
523-- Reads are performed in chunks of size @chunkSize@. For block devices, to
524-- avoid reading partial blocks @chunkSize@ must align with the block size of
525-- the underlying device. If the underlying block size is unknown, it is a good
526-- idea to keep it a multiple 4KiB. This API ensures that the start of each
527-- chunk is aligned with @chunkSize@ from second chunk onwards.
528--
529{-# INLINE readSliceWith #-}
530readSliceWith :: (IsStream t, MonadIO m, Storable a)
531 => Int -> Handle -> Int -> Int -> t m a
532readSliceWith chunkSize h pos len = undefined
534-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
535-- at index @i@ and reading up to @count@ elements in the forward direction
536-- ending at the index @i + count - 1@.
537--
538-- @since 0.7.0
539{-# INLINE readSlice #-}
540readSlice :: (IsStream t, MonadIO m, Storable a)
541 => Handle -> Int -> Int -> t m a
542readSlice = readSliceWith defaultChunkSize
544-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
545-- at index @i@ and reading up to @count@ elements in the reverse direction
546-- ending at the index @i - count + 1@.
547--
548-- @since 0.7.0
549{-# INLINE readSliceRev #-}
550readSliceRev :: (IsStream t, MonadIO m, Storable a)
551 => Handle -> Int -> Int -> t m a
552readSliceRev h i count = undefined
554-- | Write the given element at the given index in the file.
555--
556-- @since 0.7.0
557{-# INLINE writeIndex #-}
558writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
559writeIndex h i a = undefined
561-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
562-- starting at index @i@ and writing up to @count@ elements in the forward
563-- direction ending at the index @i + count - 1@.
564--
565-- @since 0.7.0
566{-# INLINE writeSlice #-}
567writeSlice :: (IsStream t, Monad m, Storable a)
568 => Handle -> Int -> Int -> t m a -> m ()
569writeSlice h i len s = undefined
571-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
572-- starting at index @i@ and writing up to @count@ elements in the reverse
573-- direction ending at the index @i - count + 1@.
574--
575-- @since 0.7.0
576{-# INLINE writeSliceRev #-}
577writeSliceRev :: (IsStream t, Monad m, Storable a)
578 => Handle -> Int -> Int -> t m a -> m ()
579writeSliceRev arr i len s = undefined
580-}