on cc072be help sign in
570 lines 21 kB history raw
1#include "inline.hs"
3-- |
4-- Module : Streamly.Internal.FileSystem.File
5-- Copyright : (c) 2019 Harendra Kumar
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 , read
48 -- , readShared
49 -- , readTailForever
51 -- , readUtf8
52 -- , readLines
53 -- , readFrames
54 -- , readChunks
56 , toBytes
58 -- -- * Array Read
59 -- , readArrayOf
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 , writeArray
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 Foreign.Storable (Storable(..))
92import System.IO (Handle, openFile, IOMode(..), hClose)
93import Prelude hiding (read)
95import qualified Control.Monad.Catch as MC
96import qualified System.IO as SIO
98import Streamly.Internal.Data.Fold.Types (Fold(..))
99import Streamly.Internal.Data.Unfold.Types (Unfold(..))
100import Streamly.Internal.Memory.Array.Types
101 (Array(..), defaultChunkSize, writeNUnsafe)
102import Streamly.Internal.Data.Stream.Serial (SerialT)
103import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
104import Streamly.Internal.Data.SVar (MonadAsync)
105-- import Streamly.Data.Fold (Fold)
106-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
108import qualified Streamly.Internal.Data.Fold.Types as FL
109import qualified Streamly.Internal.Data.Unfold as UF
110import qualified Streamly.Internal.FileSystem.Handle as FH
111import qualified Streamly.Internal.Memory.ArrayStream as AS
112import qualified Streamly.Memory.Array as A
113import qualified Streamly.Prelude as S
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-- /Internal/
140--
141{-# INLINE withFile #-}
142withFile :: (IsStream t, MonadCatch m, MonadIO m)
143 => FilePath -> IOMode -> (Handle -> t m a) -> t 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-- /Internal/
153--
154{-# INLINABLE usingFile #-}
155usingFile :: (MonadCatch m, MonadIO m)
156 => Unfold m Handle a -> Unfold m FilePath a
157usingFile =
158 UF.bracket (\file -> liftIO $ openFile file ReadMode)
159 (liftIO . hClose)
161-------------------------------------------------------------------------------
162-- Array IO (Input)
163-------------------------------------------------------------------------------
165-- TODO readArrayOf
167-------------------------------------------------------------------------------
168-- Array IO (output)
169-------------------------------------------------------------------------------
171-- | Write an array to a file. Overwrites the file if it exists.
172--
173-- @since 0.7.0
174{-# INLINABLE writeArray #-}
175writeArray :: Storable a => FilePath -> Array a -> IO ()
176writeArray file arr = SIO.withFile file WriteMode (`FH.writeArray` arr)
178-- | append an array to a file.
179--
180-- @since 0.7.0
181{-# INLINABLE appendArray #-}
182appendArray :: Storable a => FilePath -> Array a -> IO ()
183appendArray file arr = SIO.withFile file AppendMode (`FH.writeArray` arr)
185-------------------------------------------------------------------------------
186-- Stream of Arrays IO
187-------------------------------------------------------------------------------
189-- | @toChunksWithBufferOf size file@ reads a stream of arrays from file @file@.
190-- The maximum size of a single array is specified by @size@. The actual size
191-- read may be less than or equal to @size@.
192{-# INLINABLE toChunksWithBufferOf #-}
193toChunksWithBufferOf :: (IsStream t, MonadCatch m, MonadIO m)
194 => Int -> FilePath -> t m (Array Word8)
195toChunksWithBufferOf size file =
196 withFile file ReadMode (FH.toChunksWithBufferOf size)
198-- XXX read 'Array a' instead of Word8
199--
200-- | @toChunks file@ reads a stream of arrays from file @file@.
201-- The maximum size of a single array is limited to @defaultChunkSize@. The
202-- actual size read may be less than @defaultChunkSize@.
203--
204-- > toChunks = toChunksWithBufferOf defaultChunkSize
205--
206-- @since 0.7.0
207{-# INLINE toChunks #-}
208toChunks :: (IsStream t, MonadCatch m, MonadIO m)
209 => FilePath -> t m (Array Word8)
210toChunks = toChunksWithBufferOf defaultChunkSize
212-------------------------------------------------------------------------------
213-- Read File to Stream
214-------------------------------------------------------------------------------
216-- TODO for concurrent streams implement readahead IO. We can send multiple
217-- read requests at the same time. For serial case we can use async IO. We can
218-- also control the read throughput in mbps or IOPS.
220{-
221-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
222-- to the IO device are performed using buffers of @bufsize@.
223--
224-- @since 0.7.0
225{-# INLINE readWithBufferOf #-}
226readWithBufferOf :: MonadIO m => Unfold m (Int, FilePath) Word8
227readWithBufferOf = UF.concat (usingFilexxx FH.readChunksWithBufferOf) A.read
228-}
230-- | Unfolds a file path into a byte stream. IO requests to the device are
231-- performed in sizes of
232-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
233--
234-- @since 0.7.0
235{-# INLINE read #-}
236read :: (MonadCatch m, MonadIO m) => Unfold m FilePath Word8
237read = UF.concat (usingFile FH.readChunks) A.read
239{-
240-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
241-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
242-- as soon as EOF is encountered.
243--
244{-# INLINE readInChunksOf #-}
245readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
246readInChunksOf chunkSize h = A.flattenArrays $ toChunksWithBufferOf chunkSize h
247-}
249-- TODO
250-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
251--
252-- > read = 'readByChunks' defaultChunkSize
253-- | Generate a stream of bytes from a file specified by path. The stream ends
254-- when EOF is encountered. File is locked using multiple reader and single
255-- writer locking mode.
256--
257-- /Internal/
258--
259{-# INLINE toBytes #-}
260toBytes :: (IsStream t, MonadCatch m, MonadIO m) => FilePath -> t m Word8
261toBytes file = AS.concat $ withFile file ReadMode FH.toChunks
263{-
264-- | Generate a stream of elements of the given type from a file 'Handle'. The
265-- stream ends when EOF is encountered. File is not locked for exclusive reads,
266-- writers can keep writing to the file.
267--
268-- @since 0.7.0
269{-# INLINE readShared #-}
270readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
271readShared = undefined
273-- | Read a stream from a given file path. When end of file (EOF) is reached
274-- this API waits for more data to be written to the file and keeps reading it
275-- as it is written.
276--
277-- @since 0.7.0
278{-# INLINE readTailForever #-}
279readTailForever :: (IsStream t, MonadIO m) => Handle -> t m Word8
280readTailForever = undefined
281-}
283-------------------------------------------------------------------------------
284-- Writing
285-------------------------------------------------------------------------------
287{-# INLINE fromChunksMode #-}
288fromChunksMode :: (MonadAsync m, MonadCatch m, Storable a)
289 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
290fromChunksMode mode file xs = S.drain $
291 withFile file mode (\h -> S.mapM (liftIO . FH.writeArray h) xs)
293-- | Write a stream of arrays to a file. Overwrites the file if it exists.
294--
295-- @since 0.7.0
296{-# INLINE fromChunks #-}
297fromChunks :: (MonadAsync m, MonadCatch m, Storable a)
298 => FilePath -> SerialT m (Array a) -> m ()
299fromChunks = fromChunksMode WriteMode
301-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
302--
303-- XXX test this
304-- Note that if you use a chunk size less than 8K (GHC's default buffer
305-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
306-- do not want buffering to occur at GHC level as well. Same thing applies to
307-- writes as well.
309-- | Like 'write' but provides control over the write buffer. Output will
310-- be written to the IO device as soon as we collect the specified number of
311-- input elements.
312--
313-- @since 0.7.0
314{-# INLINE fromBytesWithBufferOf #-}
315fromBytesWithBufferOf :: (MonadAsync m, MonadCatch m)
316 => Int -> FilePath -> SerialT m Word8 -> m ()
317fromBytesWithBufferOf n file xs = fromChunks file $ AS.arraysOf n xs
319-- > write = 'writeWithBufferOf' defaultChunkSize
320--
321-- | Write a byte stream to a file. Combines the bytes in chunks of size
322-- up to 'A.defaultChunkSize' before writing. If the file exists it is
323-- truncated to zero size before writing. If the file does not exist it is
324-- created. File is locked using single writer locking mode.
325--
326-- /Internal/
327{-# INLINE fromBytes #-}
328fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
329fromBytes = fromBytesWithBufferOf defaultChunkSize
331{-
332{-# INLINE write #-}
333write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
334write = toHandleWith A.defaultChunkSize
335-}
337-- | Write a stream of chunks to a handle. Each chunk in the stream is written
338-- to the device as a separate IO request.
339--
340-- /Internal/
341{-# INLINE writeChunks #-}
342writeChunks :: (MonadIO m, MonadCatch m, Storable a)
343 => FilePath -> Fold m (Array a) ()
344writeChunks path = Fold step initial extract
345 where
346 initial = do
347 h <- liftIO (openFile path WriteMode)
348 fld <- FL.initialize (FH.writeChunks h)
349 `MC.onException` liftIO (hClose h)
350 return (fld, h)
351 step (fld, h) x = do
352 r <- FL.runStep fld x `MC.onException` liftIO (hClose h)
353 return (r, h)
354 extract (Fold _ initial1 extract1, h) = do
355 liftIO $ hClose h
356 initial1 >>= extract1
358-- | @writeWithBufferOf chunkSize handle@ writes the input stream to @handle@.
359-- Bytes in the input stream are collected into a buffer until we have a chunk
360-- of size @chunkSize@ and then written to the IO device.
361--
362-- /Internal/
363{-# INLINE writeWithBufferOf #-}
364writeWithBufferOf :: (MonadIO m, MonadCatch m)
365 => Int -> FilePath -> Fold m Word8 ()
366writeWithBufferOf n path =
367 FL.lchunksOf n (writeNUnsafe n) (writeChunks path)
369-- > write = 'writeWithBufferOf' A.defaultChunkSize
370--
371-- | Write a byte stream to a file. Accumulates the input in chunks of up to
372-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing to
373-- the IO device.
374--
375-- /Internal/
376--
377{-# INLINE write #-}
378write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
379write = writeWithBufferOf defaultChunkSize
381-- | Append a stream of arrays to a file.
382--
383-- @since 0.7.0
384{-# INLINE appendChunks #-}
385appendChunks :: (MonadAsync m, MonadCatch m, Storable a)
386 => FilePath -> SerialT m (Array a) -> m ()
387appendChunks = fromChunksMode AppendMode
389-- | Like 'append' but provides control over the write buffer. Output will
390-- be written to the IO device as soon as we collect the specified number of
391-- input elements.
392--
393-- @since 0.7.0
394{-# INLINE appendWithBufferOf #-}
395appendWithBufferOf :: (MonadAsync m, MonadCatch m)
396 => Int -> FilePath -> SerialT m Word8 -> m ()
397appendWithBufferOf n file xs = appendChunks file $ AS.arraysOf n xs
399-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
400-- 'A.defaultChunkSize' before writing. If the file exists then the new data
401-- is appended to the file. If the file does not exist it is created. File is
402-- locked using single writer locking mode.
403--
404-- @since 0.7.0
405{-# INLINE append #-}
406append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
407append = appendWithBufferOf defaultChunkSize
409{-
410-- | Like 'append' but the file is not locked for exclusive writes.
411--
412-- @since 0.7.0
413{-# INLINE appendShared #-}
414appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
415appendShared = undefined
416-}
418-------------------------------------------------------------------------------
419-- IO with encoding/decoding Unicode characters
420-------------------------------------------------------------------------------
422{-
423-- |
424-- > readUtf8 = decodeUtf8 . read
425--
426-- Read a UTF8 encoded stream of unicode characters from a file handle.
427--
428-- @since 0.7.0
429{-# INLINE readUtf8 #-}
430readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
431readUtf8 = decodeUtf8 . read
433-- |
434-- > writeUtf8 h s = write h $ encodeUtf8 s
435--
436-- Encode a stream of unicode characters to UTF8 and write it to the given file
437-- handle. Default block buffering applies to the writes.
438--
439-- @since 0.7.0
440{-# INLINE writeUtf8 #-}
441writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
442writeUtf8 h s = write h $ encodeUtf8 s
444-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
445-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
446-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
447-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
448-- option.
449--
450-- @since 0.7.0
451{-# INLINE writeUtf8ByLines #-}
452writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
453writeUtf8ByLines = undefined
455-- | Read UTF-8 lines from a file handle and apply the specified fold to each
456-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
457--
458-- @since 0.7.0
459{-# INLINE readLines #-}
460readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
461readLines h f = foldLines (readUtf8 h) f
463-------------------------------------------------------------------------------
464-- Framing on a sequence
465-------------------------------------------------------------------------------
467-- | Read a stream from a file handle and split it into frames delimited by
468-- the specified sequence of elements. The supplied fold is applied on each
469-- frame.
470--
471-- @since 0.7.0
472{-# INLINE readFrames #-}
473readFrames :: (IsStream t, MonadIO m, Storable a)
474 => Array a -> Handle -> Fold m a b -> t m b
475readFrames = undefined -- foldFrames . read
477-- | Write a stream to the given file handle buffering up to frames separated
478-- by the given sequence or up to a maximum of @defaultChunkSize@.
479--
480-- @since 0.7.0
481{-# INLINE writeByFrames #-}
482writeByFrames :: (IsStream t, MonadIO m, Storable a)
483 => Array a -> Handle -> t m a -> m ()
484writeByFrames = undefined
486-------------------------------------------------------------------------------
487-- Random Access IO (Seek)
488-------------------------------------------------------------------------------
490-- XXX handles could be shared, so we may not want to use the handle state at
491-- all for these APIs. we can use pread and pwrite instead. On windows we will
492-- need to use readFile/writeFile with an offset argument.
494-------------------------------------------------------------------------------
496-- | Read the element at the given index treating the file as an array.
497--
498-- @since 0.7.0
499{-# INLINE readIndex #-}
500readIndex :: Storable a => Handle -> Int -> Maybe a
501readIndex arr i = undefined
503-- NOTE: To represent a range to read we have chosen (start, size) instead of
504-- (start, end). This helps in removing the ambiguity of whether "end" is
505-- included in the range or not.
506--
507-- We could avoid specifying the range to be read and instead use "take size"
508-- on the stream, but it may end up reading more and then consume it partially.
510-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
511-- from @handle@ starting at the offset @pos@ from the beginning of the file.
512--
513-- Reads are performed in chunks of size @chunkSize@. For block devices, to
514-- avoid reading partial blocks @chunkSize@ must align with the block size of
515-- the underlying device. If the underlying block size is unknown, it is a good
516-- idea to keep it a multiple 4KiB. This API ensures that the start of each
517-- chunk is aligned with @chunkSize@ from second chunk onwards.
518--
519{-# INLINE readSliceWith #-}
520readSliceWith :: (IsStream t, MonadIO m, Storable a)
521 => Int -> Handle -> Int -> Int -> t m a
522readSliceWith chunkSize h pos len = undefined
524-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
525-- at index @i@ and reading up to @count@ elements in the forward direction
526-- ending at the index @i + count - 1@.
527--
528-- @since 0.7.0
529{-# INLINE readSlice #-}
530readSlice :: (IsStream t, MonadIO m, Storable a)
531 => Handle -> Int -> Int -> t m a
532readSlice = readSliceWith defaultChunkSize
534-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
535-- at index @i@ and reading up to @count@ elements in the reverse direction
536-- ending at the index @i - count + 1@.
537--
538-- @since 0.7.0
539{-# INLINE readSliceRev #-}
540readSliceRev :: (IsStream t, MonadIO m, Storable a)
541 => Handle -> Int -> Int -> t m a
542readSliceRev h i count = undefined
544-- | Write the given element at the given index in the file.
545--
546-- @since 0.7.0
547{-# INLINE writeIndex #-}
548writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
549writeIndex h i a = undefined
551-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
552-- starting at index @i@ and writing up to @count@ elements in the forward
553-- direction ending at the index @i + count - 1@.
554--
555-- @since 0.7.0
556{-# INLINE writeSlice #-}
557writeSlice :: (IsStream t, Monad m, Storable a)
558 => Handle -> Int -> Int -> t m a -> m ()
559writeSlice h i len s = undefined
561-- | @writeSliceRev 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 reverse
563-- direction ending at the index @i - count + 1@.
564--
565-- @since 0.7.0
566{-# INLINE writeSliceRev #-}
567writeSliceRev :: (IsStream t, Monad m, Storable a)
568 => Handle -> Int -> Int -> t m a -> m ()
569writeSliceRev arr i len s = undefined
570-}