on 30c98dc help sign in
613 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 : 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 , readWith
48 , read
49 -- , readShared
50 -- , readUtf8
51 -- , readLines
52 -- , readFrames
54 , toBytes
56 -- -- * Array Read
57 , readChunksWith
58 , readChunksFromToWith
59 , readChunks
61 , toChunksWith
62 , toChunks
64 -- ** Write To File
65 , write
66 -- , writeUtf8
67 -- , writeUtf8ByLines
68 -- , writeByFrames
69 , writeWith
71 , fromBytes
72 , fromBytesWith
74 -- -- * Array Write
75 , putChunk
76 , writeChunks
77 , fromChunks
79 -- ** Append To File
80 , append
81 , appendWith
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.Data.Fold (chunksOf)
98import Streamly.Internal.Control.Concurrent (MonadAsync)
99import Streamly.Internal.Data.Array.Unboxed.Type (Array(..), writeNUnsafe)
100import Streamly.Internal.Data.Fold.Type (Fold(..))
101import Streamly.Internal.Data.Stream.Type (Stream)
102import Streamly.Internal.Data.Stream.IsStream.Type (IsStream)
103import Streamly.Internal.Data.Unfold.Type (Unfold(..))
104-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
105import Streamly.Internal.System.IO (defaultChunkSize)
107import qualified Streamly.Data.Array.Unboxed as A
108import qualified Streamly.Data.Unfold as UF
109import qualified Streamly.Internal.Data.Fold.Type as FL
110 (Step(..), snoc, initialize)
111import qualified Streamly.Internal.Data.Unfold as UF (bracket)
112import qualified Streamly.Internal.FileSystem.Handle as FH
113import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
114import qualified Streamly.Internal.Data.Stream.IsStream as S
116-------------------------------------------------------------------------------
117-- References
118-------------------------------------------------------------------------------
119--
120-- The following references may be useful to build an understanding about the
121-- file API design:
122--
123-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
124-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
125-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
126-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
127-- https://www.w3.org/TR/FileAPI/ for http file API.
129-------------------------------------------------------------------------------
130-- Safe file reading
131-------------------------------------------------------------------------------
133-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
134-- the resulting handle to the computation @act@. The handle will be
135-- closed on exit from 'withFile', whether by normal termination or by
136-- raising an exception. If closing the handle raises an exception, then
137-- this exception will be raised by 'withFile' rather than any exception
138-- raised by 'act'.
139--
140-- /Pre-release/
141--
142{-# INLINE withFile #-}
143withFile :: (IsStream t, MonadCatch m, MonadAsync m)
144 => FilePath -> IOMode -> (Handle -> t m a) -> t m a
145withFile file mode = S.bracket (liftIO $ openFile file mode) (liftIO . hClose)
147-- | Transform an 'Unfold' from a 'Handle' to an unfold from a 'FilePath'. The
148-- resulting unfold opens a handle in 'ReadMode', uses it using the supplied
149-- unfold and then makes sure that the handle is closed on normal termination
150-- or in case of an exception. If closing the handle raises an exception, then
151-- this exception will be raised by 'usingFile'.
152--
153-- /Pre-release/
154--
155{-# INLINE usingFile #-}
156usingFile :: (MonadCatch m, MonadAsync m)
157 => Unfold m Handle a -> Unfold m FilePath a
158usingFile =
159 UF.bracket (\file -> liftIO $ openFile file ReadMode)
160 (liftIO . hClose)
162{-# INLINE usingFile2 #-}
163usingFile2 :: (MonadCatch m, MonadAsync m)
164 => Unfold m (x, Handle) a -> Unfold m (x, FilePath) a
165usingFile2 = UF.bracket before after
167 where
169 before (x, file) = do
170 h <- liftIO $ openFile file ReadMode
171 return (x, h)
173 after (_, h) = liftIO $ hClose h
175{-# INLINE usingFile3 #-}
176usingFile3 :: (MonadCatch m, MonadAsync m)
177 => Unfold m (x, y, z, Handle) a -> Unfold m (x, y, z, FilePath) a
178usingFile3 = UF.bracket before after
180 where
182 before (x, y, z, file) = do
183 h <- liftIO $ openFile file ReadMode
184 return (x, y, z, h)
186 after (_, _, _, h) = liftIO $ hClose h
188-------------------------------------------------------------------------------
189-- Array IO (Input)
190-------------------------------------------------------------------------------
192-- TODO readArrayOf
194-------------------------------------------------------------------------------
195-- Array IO (output)
196-------------------------------------------------------------------------------
198-- | Write an array to a file. Overwrites the file if it exists.
199--
200-- @since 0.7.0
201{-# INLINABLE putChunk #-}
202putChunk :: FilePath -> Array a -> IO ()
203putChunk file arr = SIO.withFile file WriteMode (`FH.putChunk` arr)
205-- | append an array to a file.
206--
207-- @since 0.7.0
208{-# INLINABLE appendArray #-}
209appendArray :: FilePath -> Array a -> IO ()
210appendArray file arr = SIO.withFile file AppendMode (`FH.putChunk` arr)
212-------------------------------------------------------------------------------
213-- Stream of Arrays IO
214-------------------------------------------------------------------------------
216-- | @toChunksWith size file@ reads a stream of arrays from file @file@.
217-- The maximum size of a single array is specified by @size@. The actual size
218-- read may be less than or equal to @size@.
219--
220-- @since 0.9.0
221{-# INLINE toChunksWith #-}
222toChunksWith :: (IsStream t, MonadCatch m, MonadAsync m)
223 => Int -> FilePath -> t m (Array Word8)
224toChunksWith size file =
225 withFile file ReadMode (FH.getChunksWith size)
227-- XXX read 'Array a' instead of Word8
228--
229-- | @toChunks file@ reads a stream of arrays from file @file@.
230-- The maximum size of a single array is limited to @defaultChunkSize@. The
231-- actual size read may be less than @defaultChunkSize@.
232--
233-- > toChunks = toChunksWith defaultChunkSize
234--
235-- @since 0.7.0
236{-# INLINE toChunks #-}
237toChunks :: (IsStream t, MonadCatch m, MonadAsync m)
238 => FilePath -> t m (Array Word8)
239toChunks = toChunksWith 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.
249-- | Unfold the tuple @(bufsize, filepath)@ into a stream of 'Word8' arrays.
250-- Read requests to the IO device are performed using a buffer of size
251-- @bufsize@. The size of an array in the resulting stream is always less than
252-- or equal to @bufsize@.
253--
254-- /Pre-release/
255--
256{-# INLINE readChunksWith #-}
257readChunksWith :: (MonadCatch m, MonadAsync m)
258 => Unfold m (Int, FilePath) (Array Word8)
259readChunksWith = usingFile2 FH.readChunksWith
261-- | Unfold the tuple @(from, to, bufsize, filepath)@ into a stream
262-- of 'Word8' arrays.
263-- Read requests to the IO device are performed using a buffer of size
264-- @bufsize@ starting from absolute offset of @from@ till the absolute
265-- position of @to@. The size of an array in the resulting stream is always
266-- less than or equal to @bufsize@.
267--
268-- /Pre-release/
269{-# INLINE readChunksFromToWith #-}
270readChunksFromToWith :: (MonadCatch m, MonadAsync m) =>
271 Unfold m (Int, Int, Int, FilePath) (Array Word8)
272readChunksFromToWith = usingFile3 FH.readChunksFromToWith
274-- | Unfolds a 'FilePath' into a stream of 'Word8' arrays. Requests to the IO
275-- device are performed using a buffer of size
276-- 'Streamly.Internal.Data.Array.Unboxed.Type.defaultChunkSize'. The
277-- size of arrays in the resulting stream are therefore less than or equal to
278-- 'Streamly.Internal.Data.Array.Unboxed.Type.defaultChunkSize'.
279--
280-- /Pre-release/
281{-# INLINE readChunks #-}
282readChunks :: (MonadCatch m, MonadAsync m) => Unfold m FilePath (Array Word8)
283readChunks = usingFile FH.readChunks
285-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
286-- to the IO device are performed using buffers of @bufsize@.
287--
288-- /Pre-release/
289{-# INLINE readWith #-}
290readWith :: (MonadCatch m, MonadAsync m) => Unfold m (Int, FilePath) Word8
291readWith = usingFile2 FH.readWith
293-- | Unfolds a file path into a byte stream. IO requests to the device are
294-- performed in sizes of
295-- 'Streamly.Internal.Data.Array.Unboxed.Type.defaultChunkSize'.
296--
297-- @since 0.7.0
298{-# INLINE read #-}
299read :: (MonadCatch m, MonadAsync m) => Unfold m FilePath Word8
300read = UF.many A.read (usingFile FH.readChunks)
302-- | Generate a stream of bytes from a file specified by path. The stream ends
303-- when EOF is encountered. File is locked using multiple reader and single
304-- writer locking mode.
305--
306-- /Pre-release/
307--
308{-# INLINE toBytes #-}
309toBytes :: (IsStream t, MonadCatch m, MonadAsync m) => FilePath -> t m Word8
310toBytes file = AS.concat $ withFile file ReadMode FH.getChunks
312{-
313-- | Generate a stream of elements of the given type from a file 'Handle'. The
314-- stream ends when EOF is encountered. File is not locked for exclusive reads,
315-- writers can keep writing to the file.
316--
317-- @since 0.7.0
318{-# INLINE readShared #-}
319readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
320readShared = undefined
321-}
323-------------------------------------------------------------------------------
324-- Writing
325-------------------------------------------------------------------------------
327{-# INLINE fromChunksMode #-}
328fromChunksMode :: (MonadAsync m, MonadCatch m)
329 => IOMode -> FilePath -> Stream m (Array a) -> m ()
330fromChunksMode mode file xs = S.drain $
331 withFile file mode (\h -> S.mapM (FH.putChunk h) xs)
333-- | Write a stream of arrays to a file. Overwrites the file if it exists.
334--
335-- @since 0.7.0
336{-# INLINE fromChunks #-}
337fromChunks :: (MonadAsync m, MonadCatch m)
338 => FilePath -> Stream m (Array a) -> m ()
339fromChunks = fromChunksMode WriteMode
341-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
342--
343-- XXX test this
344-- Note that if you use a chunk size less than 8K (GHC's default buffer
345-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
346-- do not want buffering to occur at GHC level as well. Same thing applies to
347-- writes as well.
349-- | Like 'write' but provides control over the write buffer. Output will
350-- be written to the IO device as soon as we collect the specified number of
351-- input elements.
352--
353-- @since 0.9.0
354{-# INLINE fromBytesWith #-}
355fromBytesWith :: (MonadAsync m, MonadCatch m)
356 => Int -> FilePath -> Stream m Word8 -> m ()
357fromBytesWith n file xs = fromChunks file $ AS.arraysOf n xs
359-- > write = 'writeWith' defaultChunkSize
360--
361-- | Write a byte stream to a file. Combines the bytes in chunks of size
362-- up to 'A.defaultChunkSize' before writing. If the file exists it is
363-- truncated to zero size before writing. If the file does not exist it is
364-- created. File is locked using single writer locking mode.
365--
366-- /Pre-release/
367{-# INLINE fromBytes #-}
368fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> Stream m Word8 -> m ()
369fromBytes = fromBytesWith defaultChunkSize
371{-
372{-# INLINE write #-}
373write :: (MonadIO m, Storable a) => Handle -> Stream m a -> m ()
374write = toHandleWith A.defaultChunkSize
375-}
377-- | Write a stream of chunks to a handle. Each chunk in the stream is written
378-- to the device as a separate IO request.
379--
380-- /Pre-release/
381{-# INLINE writeChunks #-}
382writeChunks :: (MonadIO m, MonadCatch m)
383 => FilePath -> Fold m (Array a) ()
384writeChunks path = Fold step initial extract
385 where
386 initial = do
387 h <- liftIO (openFile path WriteMode)
388 fld <- FL.initialize (FH.writeChunks h)
389 `MC.onException` liftIO (hClose h)
390 return $ FL.Partial (fld, h)
391 step (fld, h) x = do
392 r <- FL.snoc fld x `MC.onException` liftIO (hClose h)
393 return $ FL.Partial (r, h)
394 extract (Fold _ initial1 extract1, h) = do
395 liftIO $ hClose h
396 res <- initial1
397 case res of
398 FL.Partial fs -> extract1 fs
399 FL.Done fb -> return fb
401-- | @writeWith chunkSize handle@ writes the input stream to @handle@.
402-- Bytes in the input stream are collected into a buffer until we have a chunk
403-- of size @chunkSize@ and then written to the IO device.
404--
405-- /Pre-release/
406{-# INLINE writeWith #-}
407writeWith :: (MonadIO m, MonadCatch m)
408 => Int -> FilePath -> Fold m Word8 ()
409writeWith n path =
410 chunksOf n (writeNUnsafe n) (writeChunks path)
412-- > write = 'writeWith' A.defaultChunkSize
413--
414-- | Write a byte stream to a file. Accumulates the input in chunks of up to
415-- 'Streamly.Internal.Data.Array.Unboxed.Type.defaultChunkSize' before writing to
416-- the IO device.
417--
418-- /Pre-release/
419--
420{-# INLINE write #-}
421write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
422write = writeWith defaultChunkSize
424-- | Append a stream of arrays to a file.
425--
426-- @since 0.7.0
427{-# INLINE appendChunks #-}
428appendChunks :: (MonadAsync m, MonadCatch m)
429 => FilePath -> Stream m (Array a) -> m ()
430appendChunks = fromChunksMode AppendMode
432-- | Like 'append' but provides control over the write buffer. Output will
433-- be written to the IO device as soon as we collect the specified number of
434-- input elements.
435--
436-- @since 0.9.0
437{-# INLINE appendWith #-}
438appendWith :: (MonadAsync m, MonadCatch m)
439 => Int -> FilePath -> Stream m Word8 -> m ()
440appendWith n file xs = appendChunks file $ AS.arraysOf n xs
442-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
443-- 'A.defaultChunkSize' before writing. If the file exists then the new data
444-- is appended to the file. If the file does not exist it is created. File is
445-- locked using single writer locking mode.
446--
447-- @since 0.7.0
448{-# INLINE append #-}
449append :: (MonadAsync m, MonadCatch m) => FilePath -> Stream m Word8 -> m ()
450append = appendWith defaultChunkSize
452{-
453-- | Like 'append' but the file is not locked for exclusive writes.
454--
455-- @since 0.7.0
456{-# INLINE appendShared #-}
457appendShared :: MonadIO m => Handle -> Stream m Word8 -> m ()
458appendShared = undefined
459-}
461-------------------------------------------------------------------------------
462-- IO with encoding/decoding Unicode characters
463-------------------------------------------------------------------------------
465{-
466-- |
467-- > readUtf8 = decodeUtf8 . read
468--
469-- Read a UTF8 encoded stream of unicode characters from a file handle.
470--
471-- @since 0.7.0
472{-# INLINE readUtf8 #-}
473readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
474readUtf8 = decodeUtf8 . read
476-- |
477-- > writeUtf8 h s = write h $ encodeUtf8 s
478--
479-- Encode a stream of unicode characters to UTF8 and write it to the given file
480-- handle. Default block buffering applies to the writes.
481--
482-- @since 0.7.0
483{-# INLINE writeUtf8 #-}
484writeUtf8 :: MonadIO m => Handle -> Stream m Char -> m ()
485writeUtf8 h s = write h $ encodeUtf8 s
487-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
488-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
489-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
490-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
491-- option.
492--
493-- @since 0.7.0
494{-# INLINE writeUtf8ByLines #-}
495writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
496writeUtf8ByLines = undefined
498-- | Read UTF-8 lines from a file handle and apply the specified fold to each
499-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
500--
501-- @since 0.7.0
502{-# INLINE readLines #-}
503readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
504readLines h f = foldLines (readUtf8 h) f
506-------------------------------------------------------------------------------
507-- Framing on a sequence
508-------------------------------------------------------------------------------
510-- | Read a stream from a file handle and split it into frames delimited by
511-- the specified sequence of elements. The supplied fold is applied on each
512-- frame.
513--
514-- @since 0.7.0
515{-# INLINE readFrames #-}
516readFrames :: (IsStream t, MonadIO m, Storable a)
517 => Array a -> Handle -> Fold m a b -> t m b
518readFrames = undefined -- foldFrames . read
520-- | Write a stream to the given file handle buffering up to frames separated
521-- by the given sequence or up to a maximum of @defaultChunkSize@.
522--
523-- @since 0.7.0
524{-# INLINE writeByFrames #-}
525writeByFrames :: (IsStream t, MonadIO m, Storable a)
526 => Array a -> Handle -> t m a -> m ()
527writeByFrames = undefined
529-------------------------------------------------------------------------------
530-- Random Access IO (Seek)
531-------------------------------------------------------------------------------
533-- XXX handles could be shared, so we may not want to use the handle state at
534-- all for these APIs. we can use pread and pwrite instead. On windows we will
535-- need to use readFile/writeFile with an offset argument.
537-------------------------------------------------------------------------------
539-- | Read the element at the given index treating the file as an array.
540--
541-- @since 0.7.0
542{-# INLINE readIndex #-}
543readIndex :: Storable a => Handle -> Int -> Maybe a
544readIndex arr i = undefined
546-- NOTE: To represent a range to read we have chosen (start, size) instead of
547-- (start, end). This helps in removing the ambiguity of whether "end" is
548-- included in the range or not.
549--
550-- We could avoid specifying the range to be read and instead use "take size"
551-- on the stream, but it may end up reading more and then consume it partially.
553-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
554-- from @handle@ starting at the offset @pos@ from the beginning of the file.
555--
556-- Reads are performed in chunks of size @chunkSize@. For block devices, to
557-- avoid reading partial blocks @chunkSize@ must align with the block size of
558-- the underlying device. If the underlying block size is unknown, it is a good
559-- idea to keep it a multiple 4KiB. This API ensures that the start of each
560-- chunk is aligned with @chunkSize@ from second chunk onwards.
561--
562{-# INLINE readSliceWith #-}
563readSliceWith :: (IsStream t, MonadIO m, Storable a)
564 => Int -> Handle -> Int -> Int -> t m a
565readSliceWith chunkSize h pos len = undefined
567-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
568-- at index @i@ and reading up to @count@ elements in the forward direction
569-- ending at the index @i + count - 1@.
570--
571-- @since 0.7.0
572{-# INLINE readSlice #-}
573readSlice :: (IsStream t, MonadIO m, Storable a)
574 => Handle -> Int -> Int -> t m a
575readSlice = readSliceWith defaultChunkSize
577-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
578-- at index @i@ and reading up to @count@ elements in the reverse direction
579-- ending at the index @i - count + 1@.
580--
581-- @since 0.7.0
582{-# INLINE readSliceRev #-}
583readSliceRev :: (IsStream t, MonadIO m, Storable a)
584 => Handle -> Int -> Int -> t m a
585readSliceRev h i count = undefined
587-- | Write the given element at the given index in the file.
588--
589-- @since 0.7.0
590{-# INLINE writeIndex #-}
591writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
592writeIndex h i a = undefined
594-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
595-- starting at index @i@ and writing up to @count@ elements in the forward
596-- direction ending at the index @i + count - 1@.
597--
598-- @since 0.7.0
599{-# INLINE writeSlice #-}
600writeSlice :: (IsStream t, Monad m, Storable a)
601 => Handle -> Int -> Int -> t m a -> m ()
602writeSlice h i len s = undefined
604-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
605-- starting at index @i@ and writing up to @count@ elements in the reverse
606-- direction ending at the index @i - count + 1@.
607--
608-- @since 0.7.0
609{-# INLINE writeSliceRev #-}
610writeSliceRev :: (IsStream t, Monad m, Storable a)
611 => Handle -> Int -> Int -> t m a -> m ()
612writeSliceRev arr i len s = undefined
613-}