on 005b4b7 help sign in
501 lines 18 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
8#include "inline.hs"
10-- |
11-- Module : Streamly.FileSystem.File
12-- Copyright : (c) 2019 Harendra Kumar
13--
14-- License : BSD3
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
17-- Portability : GHC
18--
19-- Read and write streams and arrays to and from files specified by their paths
20-- in the file system. Unlike the handle based APIs which can have a read/write
21-- session consisting of multiple reads and writes to the handle, these APIs
22-- are one shot read or write APIs. These APIs open the file handle, perform
23-- the requested operation and close the handle. Thease are safer compared to
24-- the handle based APIs as there is no possiblity of a file descriptor
25-- leakage.
26--
27-- > import qualified Streamly.FileSystem.File as File
28--
30module Streamly.FileSystem.File
31 (
32 -- * Streaming IO
33 -- | Stream data to or from a file or device sequentially. When reading,
34 -- the stream is lazy and generated on-demand as the consumer consumes it.
35 -- Read IO requests to the IO device are performed in chunks limited to a
36 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
37 -- documentation. One IO request may or may not read the full
38 -- chunk. If the whole stream is not consumed, it is possible that we may
39 -- read slightly more from the IO device than what the consumer needed.
40 -- Unless specified otherwise in the API, writes are collected into chunks
41 -- of @defaultChunkSize@ before they are written to the IO device.
43 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
44 -- including disks, files, memory devices, terminals, pipes, sockets and
45 -- fifos. While random access APIs work only for files or devices that have
46 -- random access or seek capability for example disks, memory devices.
47 -- Devices like terminals, pipes, sockets and fifos do not have random
48 -- access capability.
50 -- ** File IO Using Handle
51 withFile
53 -- ** Read From File
54 , read
55 -- , readShared
56 -- , readTailForever
58 -- , readUtf8
59 -- , readLines
60 -- , readFrames
61 -- , readByChunks
63 -- -- * Array Read
64 -- , readArrayOf
66 , readArraysUpto
67 -- , readArraysOf
68 , readArrays
70 -- ** Write To File
71 , write
72 -- , writeUtf8
73 -- , writeUtf8ByLines
74 -- , writeByFrames
75 , writeByChunks
77 -- -- * Array Write
78 , writeArray
79 , writeArrays
81 -- ** Append To File
82 , append
83 , appendByChunks
84 -- , appendShared
85 , appendArray
86 , appendArrays
88 -- -- * Random Access (Seek)
89 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
90 -- files that have random access or seek capability. This type of devices
91 -- include disks, files, memory devices and exclude terminals, pipes,
92 -- sockets and fifos.
93 --
94 -- , readIndex
95 -- , readSlice
96 -- , readSliceRev
97 -- , readAt -- read from a given position to th end of file
98 -- , readSliceArrayUpto
99 -- , readSliceArrayOf
101 -- , writeIndex
102 -- , writeSlice
103 -- , writeSliceRev
104 -- , writeAt -- start writing at the given position
105 -- , writeSliceArray
106 )
107where
109import Control.Monad.Catch (MonadCatch)
110import Control.Monad.IO.Class (MonadIO(..))
111import Data.Word (Word8)
112import Foreign.Storable (Storable(..))
113import System.IO (Handle, openFile, IOMode(..), hClose)
114import Prelude hiding (read)
116import qualified System.IO as SIO
118import Streamly.Mem.Array.Types (Array(..))
119import Streamly.Streams.Serial (SerialT)
120import Streamly.Streams.StreamK.Type (IsStream)
121import Streamly.SVar (MonadAsync)
122-- import Streamly.Fold (Fold)
123-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
125import qualified Streamly.FileSystem.Handle as FH
126import qualified Streamly.Mem.Array as A
127import qualified Streamly.Mem.Array.Types as A hiding (flattenArrays)
128import qualified Streamly.Prelude as S
130-------------------------------------------------------------------------------
131-- References
132-------------------------------------------------------------------------------
133--
134-- The following references may be useful to build an understanding about the
135-- file API design:
136--
137-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
138-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
139-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
140-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
141-- https://www.w3.org/TR/FileAPI/ for http file API.
143-------------------------------------------------------------------------------
144-- Safe file reading
145-------------------------------------------------------------------------------
147-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
148-- the resulting handle to the computation @act@. The handle will be
149-- closed on exit from 'withFile', whether by normal termination or by
150-- raising an exception. If closing the handle raises an exception, then
151-- this exception will be raised by 'withFile' rather than any exception
152-- raised by 'act'.
153{-# INLINE withFile #-}
154withFile :: (IsStream t, MonadCatch m, MonadIO m)
155 => FilePath -> IOMode -> (Handle -> t m a) -> t m a
156withFile file mode = S.bracket (liftIO $ openFile file mode) (liftIO . hClose)
158-------------------------------------------------------------------------------
159-- Array IO (Input)
160-------------------------------------------------------------------------------
162-- TODO readArrayOf
164-------------------------------------------------------------------------------
165-- Array IO (output)
166-------------------------------------------------------------------------------
168-- | Write an array to a file. Overwrites the file if it exists.
169--
170-- @since 0.7.0
171{-# INLINABLE writeArray #-}
172writeArray :: Storable a => FilePath -> Array a -> IO ()
173writeArray file arr = SIO.withFile file WriteMode (\h -> FH.writeArray h arr)
175-- | append an array to a file.
176--
177-- @since 0.7.0
178{-# INLINABLE appendArray #-}
179appendArray :: Storable a => FilePath -> Array a -> IO ()
180appendArray file arr = SIO.withFile file AppendMode (\h -> FH.writeArray h arr)
182-------------------------------------------------------------------------------
183-- Stream of Arrays IO
184-------------------------------------------------------------------------------
186-- | @readArraysUpto size file@ reads a stream of arrays from file @file@.
187-- The maximum size of a single array is specified by @size@. The actual size
188-- read may be less than or equal to @size@.
189{-# INLINABLE readArraysUpto #-}
190readArraysUpto :: (IsStream t, MonadCatch m, MonadIO m)
191 => Int -> FilePath -> t m (Array Word8)
192readArraysUpto size file = withFile file ReadMode (FH.readArraysUpto size)
194-- XXX read 'Array a' instead of Word8
195--
196-- | @readArrays file@ reads a stream of arrays from file @file@.
197-- The maximum size of a single array is limited to @defaultChunkSize@.
198--
199-- > readArrays = readArraysUpto defaultChunkSize
200--
201-- @since 0.7.0
202{-# INLINE readArrays #-}
203readArrays :: (IsStream t, MonadCatch m, MonadIO m)
204 => FilePath -> t m (Array Word8)
205readArrays = readArraysUpto A.defaultChunkSize
207-------------------------------------------------------------------------------
208-- Read File to Stream
209-------------------------------------------------------------------------------
211-- TODO for concurrent streams implement readahead IO. We can send multiple
212-- read requests at the same time. For serial case we can use async IO. We can
213-- also control the read throughput in mbps or IOPS.
215{-
216-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file
217-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
218-- as soon as EOF is encountered.
219--
220{-# INLINE readByChunksUpto #-}
221readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
222readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
223-}
225-- TODO
226-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
227--
228-- > read = 'readByChunks' A.defaultChunkSize
229-- | Generate a stream of elements of the given type from a file specified by
230-- path. The stream ends when EOF is encountered. File is locked using multiple
231-- reader and single writer locking mode.
232--
233-- @since 0.7.0
234{-# INLINE read #-}
235read :: (IsStream t, MonadCatch m, MonadIO m) => FilePath -> t m Word8
236read file = A.flattenArrays $ withFile file ReadMode FH.readArrays
238{-
239-- | Generate a stream of elements of the given type from a file 'Handle'. The
240-- stream ends when EOF is encountered. File is not locked for exclusive reads,
241-- writers can keep writing to the file.
242--
243-- @since 0.7.0
244{-# INLINE readShared #-}
245readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
246readShared = undefined
248-- | Read a stream from a given file path. When end of file (EOF) is reached
249-- this API waits for more data to be written to the file and keeps reading it
250-- as it is written.
251--
252-- @since 0.7.0
253{-# INLINE readTailForever #-}
254readTailForever :: (IsStream t, MonadIO m) => Handle -> t m Word8
255readTailForever = undefined
256-}
258-------------------------------------------------------------------------------
259-- Writing
260-------------------------------------------------------------------------------
262{-# INLINE writeArraysMode #-}
263writeArraysMode :: (MonadAsync m, MonadCatch m, Storable a)
264 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
265writeArraysMode mode file xs = S.drain $
266 withFile file mode (\h -> S.mapM (liftIO . FH.writeArray h) xs)
268-- | Write a stream of arrays to a file. Overwrites the file if it exists.
269--
270-- @since 0.7.0
271{-# INLINE writeArrays #-}
272writeArrays :: (MonadAsync m, MonadCatch m, Storable a)
273 => FilePath -> SerialT m (Array a) -> m ()
274writeArrays = writeArraysMode WriteMode
276-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
277--
278-- XXX test this
279-- Note that if you use a chunk size less than 8K (GHC's default buffer
280-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
281-- do not want buffering to occur at GHC level as well. Same thing applies to
282-- writes as well.
284-- | Like 'write' but provides control over the write buffer. Output will
285-- be written to the IO device as soon as we collect the specified number of
286-- input elements.
287--
288-- @since 0.7.0
289{-# INLINE writeByChunks #-}
290writeByChunks :: (MonadAsync m, MonadCatch m)
291 => Int -> FilePath -> SerialT m Word8 -> m ()
292writeByChunks n file xs = writeArrays file $ A.arraysOf n xs
294-- > write = 'writeByChunks' A.defaultChunkSize
295--
296-- | Write a byte stream to a file. Combines the bytes in chunks of size
297-- up to 'A.defaultChunkSize' before writing. If the file exists it is
298-- truncated to zero size before writing. If the file does not exist it is
299-- created. File is locked using single writer locking mode.
300--
301-- @since 0.7.0
302{-# INLINE write #-}
303write :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
304write = writeByChunks A.defaultChunkSize
306{-
307{-# INLINE write #-}
308write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
309write = toHandleWith A.defaultChunkSize
310-}
312-- | Append a stream of arrays to a file.
313--
314-- @since 0.7.0
315{-# INLINE appendArrays #-}
316appendArrays :: (MonadAsync m, MonadCatch m, Storable a)
317 => FilePath -> SerialT m (Array a) -> m ()
318appendArrays = writeArraysMode AppendMode
320-- | Like 'append' but provides control over the write buffer. Output will
321-- be written to the IO device as soon as we collect the specified number of
322-- input elements.
323--
324-- @since 0.7.0
325{-# INLINE appendByChunks #-}
326appendByChunks :: (MonadAsync m, MonadCatch m)
327 => Int -> FilePath -> SerialT m Word8 -> m ()
328appendByChunks n file xs = appendArrays file $ A.arraysOf n xs
330-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
331-- 'A.defaultChunkSize' before writing. If the file exists then the new data
332-- is appended to the file. If the file does not exist it is created. File is
333-- locked using single writer locking mode.
334--
335-- @since 0.7.0
336{-# INLINE append #-}
337append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
338append = appendByChunks A.defaultChunkSize
340{-
341-- | Like 'append' but the file is not locked for exclusive writes.
342--
343-- @since 0.7.0
344{-# INLINE appendShared #-}
345appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
346appendShared = undefined
347-}
349-------------------------------------------------------------------------------
350-- IO with encoding/decoding Unicode characters
351-------------------------------------------------------------------------------
353{-
354-- |
355-- > readUtf8 = decodeUtf8 . read
356--
357-- Read a UTF8 encoded stream of unicode characters from a file handle.
358--
359-- @since 0.7.0
360{-# INLINE readUtf8 #-}
361readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
362readUtf8 = decodeUtf8 . read
364-- |
365-- > writeUtf8 h s = write h $ encodeUtf8 s
366--
367-- Encode a stream of unicode characters to UTF8 and write it to the given file
368-- handle. Default block buffering applies to the writes.
369--
370-- @since 0.7.0
371{-# INLINE writeUtf8 #-}
372writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
373writeUtf8 h s = write h $ encodeUtf8 s
375-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
376-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
377-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
378-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
379-- option.
380--
381-- @since 0.7.0
382{-# INLINE writeUtf8ByLines #-}
383writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
384writeUtf8ByLines = undefined
386-- | Read UTF-8 lines from a file handle and apply the specified fold to each
387-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
388--
389-- @since 0.7.0
390{-# INLINE readLines #-}
391readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
392readLines h f = foldLines (readUtf8 h) f
394-------------------------------------------------------------------------------
395-- Framing on a sequence
396-------------------------------------------------------------------------------
398-- | Read a stream from a file handle and split it into frames delimited by
399-- the specified sequence of elements. The supplied fold is applied on each
400-- frame.
401--
402-- @since 0.7.0
403{-# INLINE readFrames #-}
404readFrames :: (IsStream t, MonadIO m, Storable a)
405 => Array a -> Handle -> Fold m a b -> t m b
406readFrames = undefined -- foldFrames . read
408-- | Write a stream to the given file handle buffering up to frames separated
409-- by the given sequence or up to a maximum of @defaultChunkSize@.
410--
411-- @since 0.7.0
412{-# INLINE writeByFrames #-}
413writeByFrames :: (IsStream t, MonadIO m, Storable a)
414 => Array a -> Handle -> t m a -> m ()
415writeByFrames = undefined
417-------------------------------------------------------------------------------
418-- Random Access IO (Seek)
419-------------------------------------------------------------------------------
421-- XXX handles could be shared, so we may not want to use the handle state at
422-- all for these APIs. we can use pread and pwrite instead. On windows we will
423-- need to use readFile/writeFile with an offset argument.
425-------------------------------------------------------------------------------
427-- | Read the element at the given index treating the file as an array.
428--
429-- @since 0.7.0
430{-# INLINE readIndex #-}
431readIndex :: Storable a => Handle -> Int -> Maybe a
432readIndex arr i = undefined
434-- NOTE: To represent a range to read we have chosen (start, size) instead of
435-- (start, end). This helps in removing the ambiguity of whether "end" is
436-- included in the range or not.
437--
438-- We could avoid specifying the range to be read and instead use "take size"
439-- on the stream, but it may end up reading more and then consume it partially.
441-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
442-- from @handle@ starting at the offset @pos@ from the beginning of the file.
443--
444-- Reads are performed in chunks of size @chunkSize@. For block devices, to
445-- avoid reading partial blocks @chunkSize@ must align with the block size of
446-- the underlying device. If the underlying block size is unknown, it is a good
447-- idea to keep it a multiple 4KiB. This API ensures that the start of each
448-- chunk is aligned with @chunkSize@ from second chunk onwards.
449--
450{-# INLINE readSliceWith #-}
451readSliceWith :: (IsStream t, MonadIO m, Storable a)
452 => Int -> Handle -> Int -> Int -> t m a
453readSliceWith chunkSize h pos len = undefined
455-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
456-- at index @i@ and reading up to @count@ elements in the forward direction
457-- ending at the index @i + count - 1@.
458--
459-- @since 0.7.0
460{-# INLINE readSlice #-}
461readSlice :: (IsStream t, MonadIO m, Storable a)
462 => Handle -> Int -> Int -> t m a
463readSlice = readSliceWith A.defaultChunkSize
465-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
466-- at index @i@ and reading up to @count@ elements in the reverse direction
467-- ending at the index @i - count + 1@.
468--
469-- @since 0.7.0
470{-# INLINE readSliceRev #-}
471readSliceRev :: (IsStream t, MonadIO m, Storable a)
472 => Handle -> Int -> Int -> t m a
473readSliceRev h i count = undefined
475-- | Write the given element at the given index in the file.
476--
477-- @since 0.7.0
478{-# INLINE writeIndex #-}
479writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
480writeIndex h i a = undefined
482-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
483-- starting at index @i@ and writing up to @count@ elements in the forward
484-- direction ending at the index @i + count - 1@.
485--
486-- @since 0.7.0
487{-# INLINE writeSlice #-}
488writeSlice :: (IsStream t, Monad m, Storable a)
489 => Handle -> Int -> Int -> t m a -> m ()
490writeSlice h i len s = undefined
492-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
493-- starting at index @i@ and writing up to @count@ elements in the reverse
494-- direction ending at the index @i - count + 1@.
495--
496-- @since 0.7.0
497{-# INLINE writeSliceRev #-}
498writeSliceRev :: (IsStream t, Monad m, Storable a)
499 => Handle -> Int -> Int -> t m a -> m ()
500writeSliceRev arr i len s = undefined
501-}