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