on cea6762 help sign in
609 lines 23 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 : pre-release
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 , readChunksFromToWith
59 , readChunks
61 , toChunksWithBufferOf
62 , toChunks
64 -- ** Write To File
65 , write
66 -- , writeUtf8
67 -- , writeUtf8ByLines
68 -- , writeByFrames
69 , writeWithBufferOf
71 , fromBytes
72 , fromBytesWithBufferOf
74 -- -- * Array Write
75 , putChunk
76 , writeChunks
77 , fromChunks
79 -- ** Append To File
80 , append
81 , appendWithBufferOf
82 -- , appendShared
83 , appendArray
84 , appendChunks
85 )
86where
88import Control.Monad.Catch (MonadCatch)
89import Control.Monad.IO.Class (MonadIO(..))
90import Data.Word (Word8)
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.Control.Concurrent (MonadAsync)
98import Streamly.Internal.Data.Fold.Type (Fold(..))
99import Streamly.Internal.Data.Unfold.Type (Unfold(..))
100import Streamly.Internal.Data.Array.Foreign.Type (Array(..), writeNUnsafe)
101import Streamly.Internal.Data.Stream.Serial (SerialT)
102import Streamly.Internal.Data.Stream.IsStream.Type (IsStream)
103-- import Streamly.Data.Fold (Fold)
104-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
105import Streamly.Internal.System.IO (defaultChunkSize)
107import qualified Streamly.Internal.Data.Array.Foreign as A
108import qualified Streamly.Internal.Data.Fold.Type as FL
109import qualified Streamly.Internal.Data.Unfold as UF
110import qualified Streamly.Internal.FileSystem.Handle as FH
111import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
112import qualified Streamly.Internal.Data.Stream.IsStream 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-- /Pre-release/
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-- /Pre-release/
152--
153{-# INLINE 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{-# INLINE 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{-# INLINE usingFile3 #-}
174usingFile3 :: (MonadCatch m, MonadAsync m)
175 => Unfold m (x, y, z, Handle) a -> Unfold m (x, y, z, FilePath) a
176usingFile3 = UF.bracket before after
178 where
180 before (x, y, z, file) = do
181 h <- liftIO $ openFile file ReadMode
182 return (x, y, z, h)
184 after (_, _, _, h) = liftIO $ hClose h
186-------------------------------------------------------------------------------
187-- Array IO (Input)
188-------------------------------------------------------------------------------
190-- TODO readArrayOf
192-------------------------------------------------------------------------------
193-- Array IO (output)
194-------------------------------------------------------------------------------
196-- | Write an array to a file. Overwrites the file if it exists.
197--
198-- @since 0.7.0
199{-# INLINABLE putChunk #-}
200putChunk :: FilePath -> Array a -> IO ()
201putChunk file arr = SIO.withFile file WriteMode (`FH.putChunk` arr)
203-- | append an array to a file.
204--
205-- @since 0.7.0
206{-# INLINABLE appendArray #-}
207appendArray :: FilePath -> Array a -> IO ()
208appendArray file arr = SIO.withFile file AppendMode (`FH.putChunk` arr)
210-------------------------------------------------------------------------------
211-- Stream of Arrays IO
212-------------------------------------------------------------------------------
214-- | @toChunksWithBufferOf size file@ reads a stream of arrays from file @file@.
215-- The maximum size of a single array is specified by @size@. The actual size
216-- read may be less than or equal to @size@.
217{-# INLINE toChunksWithBufferOf #-}
218toChunksWithBufferOf :: (IsStream t, MonadCatch m, MonadAsync m)
219 => Int -> FilePath -> t m (Array Word8)
220toChunksWithBufferOf size file =
221 withFile file ReadMode (FH.toChunksWithBufferOf size)
223-- XXX read 'Array a' instead of Word8
224--
225-- | @toChunks file@ reads a stream of arrays from file @file@.
226-- The maximum size of a single array is limited to @defaultChunkSize@. The
227-- actual size read may be less than @defaultChunkSize@.
228--
229-- > toChunks = toChunksWithBufferOf defaultChunkSize
230--
231-- @since 0.7.0
232{-# INLINE toChunks #-}
233toChunks :: (IsStream t, MonadCatch m, MonadAsync m)
234 => FilePath -> t m (Array Word8)
235toChunks = toChunksWithBufferOf defaultChunkSize
237-------------------------------------------------------------------------------
238-- Read File to Stream
239-------------------------------------------------------------------------------
241-- TODO for concurrent streams implement readahead IO. We can send multiple
242-- read requests at the same time. For serial case we can use async IO. We can
243-- also control the read throughput in mbps or IOPS.
245-- | Unfold the tuple @(bufsize, filepath)@ into a stream of 'Word8' arrays.
246-- Read requests to the IO device are performed using a buffer of size
247-- @bufsize@. The size of an array in the resulting stream is always less than
248-- or equal to @bufsize@.
249--
250-- /Pre-release/
251--
252{-# INLINE readChunksWithBufferOf #-}
253readChunksWithBufferOf :: (MonadCatch m, MonadAsync m)
254 => Unfold m (Int, FilePath) (Array Word8)
255readChunksWithBufferOf = usingFile2 FH.readChunksWithBufferOf
257-- | Unfold the tuple @(from, to, bufsize, filepath)@ into a stream
258-- of 'Word8' arrays.
259-- Read requests to the IO device are performed using a buffer of size
260-- @bufsize@ starting from absolute offset of @from@ till the absolute
261-- position of @to@. The size of an array in the resulting stream is always
262-- less than or equal to @bufsize@.
263--
264-- /Pre-release/
265{-# INLINE readChunksFromToWith #-}
266readChunksFromToWith :: (MonadCatch m, MonadAsync m) =>
267 Unfold m (Int, Int, Int, FilePath) (Array Word8)
268readChunksFromToWith = usingFile3 FH.readChunksFromToWith
270-- | Unfolds a 'FilePath' into a stream of 'Word8' arrays. Requests to the IO
271-- device are performed using a buffer of size
272-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'. The
273-- size of arrays in the resulting stream are therefore less than or equal to
274-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
275--
276-- /Pre-release/
277{-# INLINE readChunks #-}
278readChunks :: (MonadCatch m, MonadAsync m) => Unfold m FilePath (Array Word8)
279readChunks = usingFile FH.readChunks
281-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
282-- to the IO device are performed using buffers of @bufsize@.
283--
284-- /Pre-release/
285{-# INLINE readWithBufferOf #-}
286readWithBufferOf :: (MonadCatch m, MonadAsync m) => Unfold m (Int, FilePath) Word8
287readWithBufferOf = usingFile2 FH.readWithBufferOf
289-- | Unfolds a file path into a byte stream. IO requests to the device are
290-- performed in sizes of
291-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
292--
293-- @since 0.7.0
294{-# INLINE read #-}
295read :: (MonadCatch m, MonadAsync m) => Unfold m FilePath Word8
296read = UF.many (usingFile FH.readChunks) A.read
298-- | Generate a stream of bytes from a file specified by path. The stream ends
299-- when EOF is encountered. File is locked using multiple reader and single
300-- writer locking mode.
301--
302-- /Pre-release/
303--
304{-# INLINE toBytes #-}
305toBytes :: (IsStream t, MonadCatch m, MonadAsync m) => FilePath -> t m Word8
306toBytes file = AS.concat $ withFile file ReadMode FH.toChunks
308{-
309-- | Generate a stream of elements of the given type from a file 'Handle'. The
310-- stream ends when EOF is encountered. File is not locked for exclusive reads,
311-- writers can keep writing to the file.
312--
313-- @since 0.7.0
314{-# INLINE readShared #-}
315readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
316readShared = undefined
317-}
319-------------------------------------------------------------------------------
320-- Writing
321-------------------------------------------------------------------------------
323{-# INLINE fromChunksMode #-}
324fromChunksMode :: (MonadAsync m, MonadCatch m)
325 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
326fromChunksMode mode file xs = S.drain $
327 withFile file mode (\h -> S.mapM (FH.putChunk h) xs)
329-- | Write a stream of arrays to a file. Overwrites the file if it exists.
330--
331-- @since 0.7.0
332{-# INLINE fromChunks #-}
333fromChunks :: (MonadAsync m, MonadCatch m)
334 => FilePath -> SerialT m (Array a) -> m ()
335fromChunks = fromChunksMode WriteMode
337-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
338--
339-- XXX test this
340-- Note that if you use a chunk size less than 8K (GHC's default buffer
341-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
342-- do not want buffering to occur at GHC level as well. Same thing applies to
343-- writes as well.
345-- | Like 'write' but provides control over the write buffer. Output will
346-- be written to the IO device as soon as we collect the specified number of
347-- input elements.
348--
349-- @since 0.7.0
350{-# INLINE fromBytesWithBufferOf #-}
351fromBytesWithBufferOf :: (MonadAsync m, MonadCatch m)
352 => Int -> FilePath -> SerialT m Word8 -> m ()
353fromBytesWithBufferOf n file xs = fromChunks file $ AS.arraysOf n xs
355-- > write = 'writeWithBufferOf' defaultChunkSize
356--
357-- | Write a byte stream to a file. Combines the bytes in chunks of size
358-- up to 'A.defaultChunkSize' before writing. If the file exists it is
359-- truncated to zero size before writing. If the file does not exist it is
360-- created. File is locked using single writer locking mode.
361--
362-- /Pre-release/
363{-# INLINE fromBytes #-}
364fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
365fromBytes = fromBytesWithBufferOf defaultChunkSize
367{-
368{-# INLINE write #-}
369write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
370write = toHandleWith A.defaultChunkSize
371-}
373-- | Write a stream of chunks to a handle. Each chunk in the stream is written
374-- to the device as a separate IO request.
375--
376-- /Pre-release/
377{-# INLINE writeChunks #-}
378writeChunks :: (MonadIO m, MonadCatch m)
379 => FilePath -> Fold m (Array a) ()
380writeChunks path = Fold step initial extract
381 where
382 initial = do
383 h <- liftIO (openFile path WriteMode)
384 fld <- FL.initialize (FH.writeChunks h)
385 `MC.onException` liftIO (hClose h)
386 return $ FL.Partial (fld, h)
387 step (fld, h) x = do
388 r <- FL.snoc fld x `MC.onException` liftIO (hClose h)
389 return $ FL.Partial (r, h)
390 extract (Fold _ initial1 extract1, h) = do
391 liftIO $ hClose h
392 res <- initial1
393 case res of
394 FL.Partial fs -> extract1 fs
395 FL.Done fb -> return fb
397-- | @writeWithBufferOf chunkSize handle@ writes the input stream to @handle@.
398-- Bytes in the input stream are collected into a buffer until we have a chunk
399-- of size @chunkSize@ and then written to the IO device.
400--
401-- /Pre-release/
402{-# INLINE writeWithBufferOf #-}
403writeWithBufferOf :: (MonadIO m, MonadCatch m)
404 => Int -> FilePath -> Fold m Word8 ()
405writeWithBufferOf n path =
406 FL.chunksOf n (writeNUnsafe n) (writeChunks path)
408-- > write = 'writeWithBufferOf' A.defaultChunkSize
409--
410-- | Write a byte stream to a file. Accumulates the input in chunks of up to
411-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize' before writing to
412-- the IO device.
413--
414-- /Pre-release/
415--
416{-# INLINE write #-}
417write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
418write = writeWithBufferOf defaultChunkSize
420-- | Append a stream of arrays to a file.
421--
422-- @since 0.7.0
423{-# INLINE appendChunks #-}
424appendChunks :: (MonadAsync m, MonadCatch m)
425 => FilePath -> SerialT m (Array a) -> m ()
426appendChunks = fromChunksMode AppendMode
428-- | Like 'append' but provides control over the write buffer. Output will
429-- be written to the IO device as soon as we collect the specified number of
430-- input elements.
431--
432-- @since 0.7.0
433{-# INLINE appendWithBufferOf #-}
434appendWithBufferOf :: (MonadAsync m, MonadCatch m)
435 => Int -> FilePath -> SerialT m Word8 -> m ()
436appendWithBufferOf n file xs = appendChunks file $ AS.arraysOf n xs
438-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
439-- 'A.defaultChunkSize' before writing. If the file exists then the new data
440-- is appended to the file. If the file does not exist it is created. File is
441-- locked using single writer locking mode.
442--
443-- @since 0.7.0
444{-# INLINE append #-}
445append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
446append = appendWithBufferOf defaultChunkSize
448{-
449-- | Like 'append' but the file is not locked for exclusive writes.
450--
451-- @since 0.7.0
452{-# INLINE appendShared #-}
453appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
454appendShared = undefined
455-}
457-------------------------------------------------------------------------------
458-- IO with encoding/decoding Unicode characters
459-------------------------------------------------------------------------------
461{-
462-- |
463-- > readUtf8 = decodeUtf8 . read
464--
465-- Read a UTF8 encoded stream of unicode characters from a file handle.
466--
467-- @since 0.7.0
468{-# INLINE readUtf8 #-}
469readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
470readUtf8 = decodeUtf8 . read
472-- |
473-- > writeUtf8 h s = write h $ encodeUtf8 s
474--
475-- Encode a stream of unicode characters to UTF8 and write it to the given file
476-- handle. Default block buffering applies to the writes.
477--
478-- @since 0.7.0
479{-# INLINE writeUtf8 #-}
480writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
481writeUtf8 h s = write h $ encodeUtf8 s
483-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
484-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
485-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
486-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
487-- option.
488--
489-- @since 0.7.0
490{-# INLINE writeUtf8ByLines #-}
491writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
492writeUtf8ByLines = undefined
494-- | Read UTF-8 lines from a file handle and apply the specified fold to each
495-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
496--
497-- @since 0.7.0
498{-# INLINE readLines #-}
499readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
500readLines h f = foldLines (readUtf8 h) f
502-------------------------------------------------------------------------------
503-- Framing on a sequence
504-------------------------------------------------------------------------------
506-- | Read a stream from a file handle and split it into frames delimited by
507-- the specified sequence of elements. The supplied fold is applied on each
508-- frame.
509--
510-- @since 0.7.0
511{-# INLINE readFrames #-}
512readFrames :: (IsStream t, MonadIO m, Storable a)
513 => Array a -> Handle -> Fold m a b -> t m b
514readFrames = undefined -- foldFrames . read
516-- | Write a stream to the given file handle buffering up to frames separated
517-- by the given sequence or up to a maximum of @defaultChunkSize@.
518--
519-- @since 0.7.0
520{-# INLINE writeByFrames #-}
521writeByFrames :: (IsStream t, MonadIO m, Storable a)
522 => Array a -> Handle -> t m a -> m ()
523writeByFrames = undefined
525-------------------------------------------------------------------------------
526-- Random Access IO (Seek)
527-------------------------------------------------------------------------------
529-- XXX handles could be shared, so we may not want to use the handle state at
530-- all for these APIs. we can use pread and pwrite instead. On windows we will
531-- need to use readFile/writeFile with an offset argument.
533-------------------------------------------------------------------------------
535-- | Read the element at the given index treating the file as an array.
536--
537-- @since 0.7.0
538{-# INLINE readIndex #-}
539readIndex :: Storable a => Handle -> Int -> Maybe a
540readIndex arr i = undefined
542-- NOTE: To represent a range to read we have chosen (start, size) instead of
543-- (start, end). This helps in removing the ambiguity of whether "end" is
544-- included in the range or not.
545--
546-- We could avoid specifying the range to be read and instead use "take size"
547-- on the stream, but it may end up reading more and then consume it partially.
549-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
550-- from @handle@ starting at the offset @pos@ from the beginning of the file.
551--
552-- Reads are performed in chunks of size @chunkSize@. For block devices, to
553-- avoid reading partial blocks @chunkSize@ must align with the block size of
554-- the underlying device. If the underlying block size is unknown, it is a good
555-- idea to keep it a multiple 4KiB. This API ensures that the start of each
556-- chunk is aligned with @chunkSize@ from second chunk onwards.
557--
558{-# INLINE readSliceWith #-}
559readSliceWith :: (IsStream t, MonadIO m, Storable a)
560 => Int -> Handle -> Int -> Int -> t m a
561readSliceWith chunkSize h pos len = undefined
563-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
564-- at index @i@ and reading up to @count@ elements in the forward direction
565-- ending at the index @i + count - 1@.
566--
567-- @since 0.7.0
568{-# INLINE readSlice #-}
569readSlice :: (IsStream t, MonadIO m, Storable a)
570 => Handle -> Int -> Int -> t m a
571readSlice = readSliceWith defaultChunkSize
573-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
574-- at index @i@ and reading up to @count@ elements in the reverse direction
575-- ending at the index @i - count + 1@.
576--
577-- @since 0.7.0
578{-# INLINE readSliceRev #-}
579readSliceRev :: (IsStream t, MonadIO m, Storable a)
580 => Handle -> Int -> Int -> t m a
581readSliceRev h i count = undefined
583-- | Write the given element at the given index in the file.
584--
585-- @since 0.7.0
586{-# INLINE writeIndex #-}
587writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
588writeIndex h i a = undefined
590-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
591-- starting at index @i@ and writing up to @count@ elements in the forward
592-- direction ending at the index @i + count - 1@.
593--
594-- @since 0.7.0
595{-# INLINE writeSlice #-}
596writeSlice :: (IsStream t, Monad m, Storable a)
597 => Handle -> Int -> Int -> t m a -> m ()
598writeSlice h i len s = undefined
600-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
601-- starting at index @i@ and writing up to @count@ elements in the reverse
602-- direction ending at the index @i - count + 1@.
603--
604-- @since 0.7.0
605{-# INLINE writeSliceRev #-}
606writeSliceRev :: (IsStream t, Monad m, Storable a)
607 => Handle -> Int -> Int -> t m a -> m ()
608writeSliceRev arr i len s = undefined
609-}