on ced5261 help sign in
573 lines 21 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE FlexibleContexts #-}
4#include "inline.hs"
6-- |
7-- Module : Streamly.Internal.FileSystem.File
8-- Copyright : (c) 2019 Harendra Kumar
9--
10-- License : BSD3
11-- Maintainer : streamly@composewell.com
12-- Stability : experimental
13-- Portability : GHC
14--
15-- Read and write streams and arrays to and from files specified by their paths
16-- in the file system. Unlike the handle based APIs which can have a read/write
17-- session consisting of multiple reads and writes to the handle, these APIs
18-- are one shot read or write APIs. These APIs open the file handle, perform
19-- the requested operation and close the handle. Thease are safer compared to
20-- the handle based APIs as there is no possibility of a file descriptor
21-- leakage.
22--
23-- > import qualified Streamly.Internal.FileSystem.File as File
24--
26module Streamly.Internal.FileSystem.File
27 (
28 -- * Streaming IO
29 -- | Stream data to or from a file or device sequentially. When reading,
30 -- the stream is lazy and generated on-demand as the consumer consumes it.
31 -- Read IO requests to the IO device are performed in chunks limited to a
32 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
33 -- documentation. One IO request may or may not read the full
34 -- chunk. If the whole stream is not consumed, it is possible that we may
35 -- read slightly more from the IO device than what the consumer needed.
36 -- Unless specified otherwise in the API, writes are collected into chunks
37 -- of @defaultChunkSize@ before they are written to the IO device.
39 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
40 -- including disks, files, memory devices, terminals, pipes, sockets and
41 -- fifos. While random access APIs work only for files or devices that have
42 -- random access or seek capability for example disks, memory devices.
43 -- Devices like terminals, pipes, sockets and fifos do not have random
44 -- access capability.
46 -- ** File IO Using Handle
47 withFile
49 -- ** Read From File
50 , read
51 -- , readShared
52 -- , readTailForever
54 -- , readUtf8
55 -- , readLines
56 -- , readFrames
57 -- , readChunks
59 , toBytes
61 -- -- * Array Read
62 -- , readArrayOf
64 , toChunksWithBufferOf
65 , toChunks
67 -- ** Write To File
68 , write
69 -- , writeUtf8
70 -- , writeUtf8ByLines
71 -- , writeByFrames
72 , writeWithBufferOf
74 , fromBytes
75 , fromBytesWithBufferOf
77 -- -- * Array Write
78 , writeArray
79 , writeChunks
80 , fromChunks
82 -- ** Append To File
83 , append
84 , appendWithBufferOf
85 -- , appendShared
86 , appendArray
87 , appendChunks
88 )
89where
91import Control.Monad.Catch (MonadCatch)
92import Control.Monad.IO.Class (MonadIO(..))
93import Data.Word (Word8)
94import Foreign.Storable (Storable(..))
95import System.IO (Handle, openFile, IOMode(..), hClose)
96import Prelude hiding (read)
98import qualified Control.Monad.Catch as MC
99import qualified System.IO as SIO
101import Streamly.Internal.Data.Fold.Types (Fold(..))
102import Streamly.Internal.Data.Unfold.Types (Unfold(..))
103import Streamly.Internal.Memory.Array.Types
104 (Array(..), defaultChunkSize, writeNUnsafe)
105import Streamly.Internal.Data.Stream.Serial (SerialT)
106import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
107import Streamly.Internal.Data.SVar (MonadAsync)
108-- import Streamly.Data.Fold (Fold)
109-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
111import qualified Streamly.Internal.Data.Fold.Types as FL
112import qualified Streamly.Internal.Data.Unfold as UF
113import qualified Streamly.Internal.FileSystem.Handle as FH
114import qualified Streamly.Internal.Memory.ArrayStream as AS
115import qualified Streamly.Memory.Array as A
116import qualified Streamly.Prelude as S
118-------------------------------------------------------------------------------
119-- References
120-------------------------------------------------------------------------------
121--
122-- The following references may be useful to build an understanding about the
123-- file API design:
124--
125-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
126-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
127-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
128-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
129-- https://www.w3.org/TR/FileAPI/ for http file API.
131-------------------------------------------------------------------------------
132-- Safe file reading
133-------------------------------------------------------------------------------
135-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
136-- the resulting handle to the computation @act@. The handle will be
137-- closed on exit from 'withFile', whether by normal termination or by
138-- raising an exception. If closing the handle raises an exception, then
139-- this exception will be raised by 'withFile' rather than any exception
140-- raised by 'act'.
141--
142-- /Internal/
143--
144{-# INLINE withFile #-}
145withFile :: (IsStream t, MonadCatch m, MonadIO m)
146 => FilePath -> IOMode -> (Handle -> t m a) -> t m a
147withFile file mode = S.bracket (liftIO $ openFile file mode) (liftIO . hClose)
149-- | Transform an 'Unfold' from a 'Handle' to an unfold from a 'FilePath'. The
150-- resulting unfold opens a handle in 'ReadMode', uses it using the supplied
151-- unfold and then makes sure that the handle is closed on normal termination
152-- or in case of an exception. If closing the handle raises an exception, then
153-- this exception will be raised by 'usingFile'.
154--
155-- /Internal/
156--
157{-# INLINABLE usingFile #-}
158usingFile :: (MonadCatch m, MonadIO m)
159 => Unfold m Handle a -> Unfold m FilePath a
160usingFile =
161 UF.bracket (\file -> liftIO $ openFile file ReadMode)
162 (liftIO . hClose)
164-------------------------------------------------------------------------------
165-- Array IO (Input)
166-------------------------------------------------------------------------------
168-- TODO readArrayOf
170-------------------------------------------------------------------------------
171-- Array IO (output)
172-------------------------------------------------------------------------------
174-- | Write an array to a file. Overwrites the file if it exists.
175--
176-- @since 0.7.0
177{-# INLINABLE writeArray #-}
178writeArray :: Storable a => FilePath -> Array a -> IO ()
179writeArray file arr = SIO.withFile file WriteMode (`FH.writeArray` arr)
181-- | append an array to a file.
182--
183-- @since 0.7.0
184{-# INLINABLE appendArray #-}
185appendArray :: Storable a => FilePath -> Array a -> IO ()
186appendArray file arr = SIO.withFile file AppendMode (`FH.writeArray` arr)
188-------------------------------------------------------------------------------
189-- Stream of Arrays IO
190-------------------------------------------------------------------------------
192-- | @toChunksWithBufferOf size file@ reads a stream of arrays from file @file@.
193-- The maximum size of a single array is specified by @size@. The actual size
194-- read may be less than or equal to @size@.
195{-# INLINABLE toChunksWithBufferOf #-}
196toChunksWithBufferOf :: (IsStream t, MonadCatch m, MonadIO m)
197 => Int -> FilePath -> t m (Array Word8)
198toChunksWithBufferOf size file =
199 withFile file ReadMode (FH.toChunksWithBufferOf size)
201-- XXX read 'Array a' instead of Word8
202--
203-- | @toChunks file@ reads a stream of arrays from file @file@.
204-- The maximum size of a single array is limited to @defaultChunkSize@. The
205-- actual size read may be less than @defaultChunkSize@.
206--
207-- > toChunks = toChunksWithBufferOf defaultChunkSize
208--
209-- @since 0.7.0
210{-# INLINE toChunks #-}
211toChunks :: (IsStream t, MonadCatch m, MonadIO m)
212 => FilePath -> t m (Array Word8)
213toChunks = toChunksWithBufferOf defaultChunkSize
215-------------------------------------------------------------------------------
216-- Read File to Stream
217-------------------------------------------------------------------------------
219-- TODO for concurrent streams implement readahead IO. We can send multiple
220-- read requests at the same time. For serial case we can use async IO. We can
221-- also control the read throughput in mbps or IOPS.
223{-
224-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
225-- to the IO device are performed using buffers of @bufsize@.
226--
227-- @since 0.7.0
228{-# INLINE readWithBufferOf #-}
229readWithBufferOf :: MonadIO m => Unfold m (Int, FilePath) Word8
230readWithBufferOf = UF.concat (usingFilexxx FH.readChunksWithBufferOf) A.read
231-}
233-- | Unfolds a file path into a byte stream. IO requests to the device are
234-- performed in sizes of
235-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
236--
237-- @since 0.7.0
238{-# INLINE read #-}
239read :: (MonadCatch m, MonadIO m) => Unfold m FilePath Word8
240read = UF.concat (usingFile FH.readChunks) A.read
242{-
243-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
244-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
245-- as soon as EOF is encountered.
246--
247{-# INLINE readInChunksOf #-}
248readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
249readInChunksOf chunkSize h = A.flattenArrays $ toChunksWithBufferOf chunkSize h
250-}
252-- TODO
253-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
254--
255-- > read = 'readByChunks' defaultChunkSize
256-- | Generate a stream of bytes from a file specified by path. The stream ends
257-- when EOF is encountered. File is locked using multiple reader and single
258-- writer locking mode.
259--
260-- /Internal/
261--
262{-# INLINE toBytes #-}
263toBytes :: (IsStream t, MonadCatch m, MonadIO m) => FilePath -> t m Word8
264toBytes file = AS.concat $ withFile file ReadMode FH.toChunks
266{-
267-- | Generate a stream of elements of the given type from a file 'Handle'. The
268-- stream ends when EOF is encountered. File is not locked for exclusive reads,
269-- writers can keep writing to the file.
270--
271-- @since 0.7.0
272{-# INLINE readShared #-}
273readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
274readShared = undefined
276-- | Read a stream from a given file path. When end of file (EOF) is reached
277-- this API waits for more data to be written to the file and keeps reading it
278-- as it is written.
279--
280-- @since 0.7.0
281{-# INLINE readTailForever #-}
282readTailForever :: (IsStream t, MonadIO m) => Handle -> t m Word8
283readTailForever = undefined
284-}
286-------------------------------------------------------------------------------
287-- Writing
288-------------------------------------------------------------------------------
290{-# INLINE fromChunksMode #-}
291fromChunksMode :: (MonadAsync m, MonadCatch m, Storable a)
292 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
293fromChunksMode mode file xs = S.drain $
294 withFile file mode (\h -> S.mapM (liftIO . FH.writeArray h) xs)
296-- | Write a stream of arrays to a file. Overwrites the file if it exists.
297--
298-- @since 0.7.0
299{-# INLINE fromChunks #-}
300fromChunks :: (MonadAsync m, MonadCatch m, Storable a)
301 => FilePath -> SerialT m (Array a) -> m ()
302fromChunks = fromChunksMode WriteMode
304-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
305--
306-- XXX test this
307-- Note that if you use a chunk size less than 8K (GHC's default buffer
308-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
309-- do not want buffering to occur at GHC level as well. Same thing applies to
310-- writes as well.
312-- | Like 'write' but provides control over the write buffer. Output will
313-- be written to the IO device as soon as we collect the specified number of
314-- input elements.
315--
316-- @since 0.7.0
317{-# INLINE fromBytesWithBufferOf #-}
318fromBytesWithBufferOf :: (MonadAsync m, MonadCatch m)
319 => Int -> FilePath -> SerialT m Word8 -> m ()
320fromBytesWithBufferOf n file xs = fromChunks file $ AS.arraysOf n xs
322-- > write = 'writeWithBufferOf' defaultChunkSize
323--
324-- | Write a byte stream to a file. Combines the bytes in chunks of size
325-- up to 'A.defaultChunkSize' before writing. If the file exists it is
326-- truncated to zero size before writing. If the file does not exist it is
327-- created. File is locked using single writer locking mode.
328--
329-- /Internal/
330{-# INLINE fromBytes #-}
331fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
332fromBytes = fromBytesWithBufferOf defaultChunkSize
334{-
335{-# INLINE write #-}
336write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
337write = toHandleWith A.defaultChunkSize
338-}
340-- | Write a stream of chunks to a handle. Each chunk in the stream is written
341-- to the device as a separate IO request.
342--
343-- /Internal/
344{-# INLINE writeChunks #-}
345writeChunks :: (MonadIO m, MonadCatch m, Storable a)
346 => FilePath -> Fold m (Array a) ()
347writeChunks path = Fold step initial extract
348 where
349 initial = do
350 h <- liftIO (openFile path WriteMode)
351 fld <- FL.initialize (FH.writeChunks h)
352 `MC.onException` liftIO (hClose h)
353 return (fld, h)
354 step (fld, h) x = do
355 r <- FL.runStep fld x `MC.onException` liftIO (hClose h)
356 return (r, h)
357 extract (Fold _ initial1 extract1, h) = do
358 liftIO $ hClose h
359 initial1 >>= extract1
361-- | @writeWithBufferOf chunkSize handle@ writes the input stream to @handle@.
362-- Bytes in the input stream are collected into a buffer until we have a chunk
363-- of size @chunkSize@ and then written to the IO device.
364--
365-- /Internal/
366{-# INLINE writeWithBufferOf #-}
367writeWithBufferOf :: (MonadIO m, MonadCatch m)
368 => Int -> FilePath -> Fold m Word8 ()
369writeWithBufferOf n path =
370 FL.lchunksOf n (writeNUnsafe n) (writeChunks path)
372-- > write = 'writeWithBufferOf' A.defaultChunkSize
373--
374-- | Write a byte stream to a file. Accumulates the input in chunks of up to
375-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing to
376-- the IO device.
377--
378-- /Internal/
379--
380{-# INLINE write #-}
381write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
382write = writeWithBufferOf defaultChunkSize
384-- | Append a stream of arrays to a file.
385--
386-- @since 0.7.0
387{-# INLINE appendChunks #-}
388appendChunks :: (MonadAsync m, MonadCatch m, Storable a)
389 => FilePath -> SerialT m (Array a) -> m ()
390appendChunks = fromChunksMode AppendMode
392-- | Like 'append' but provides control over the write buffer. Output will
393-- be written to the IO device as soon as we collect the specified number of
394-- input elements.
395--
396-- @since 0.7.0
397{-# INLINE appendWithBufferOf #-}
398appendWithBufferOf :: (MonadAsync m, MonadCatch m)
399 => Int -> FilePath -> SerialT m Word8 -> m ()
400appendWithBufferOf n file xs = appendChunks file $ AS.arraysOf n xs
402-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
403-- 'A.defaultChunkSize' before writing. If the file exists then the new data
404-- is appended to the file. If the file does not exist it is created. File is
405-- locked using single writer locking mode.
406--
407-- @since 0.7.0
408{-# INLINE append #-}
409append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
410append = appendWithBufferOf defaultChunkSize
412{-
413-- | Like 'append' but the file is not locked for exclusive writes.
414--
415-- @since 0.7.0
416{-# INLINE appendShared #-}
417appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
418appendShared = undefined
419-}
421-------------------------------------------------------------------------------
422-- IO with encoding/decoding Unicode characters
423-------------------------------------------------------------------------------
425{-
426-- |
427-- > readUtf8 = decodeUtf8 . read
428--
429-- Read a UTF8 encoded stream of unicode characters from a file handle.
430--
431-- @since 0.7.0
432{-# INLINE readUtf8 #-}
433readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
434readUtf8 = decodeUtf8 . read
436-- |
437-- > writeUtf8 h s = write h $ encodeUtf8 s
438--
439-- Encode a stream of unicode characters to UTF8 and write it to the given file
440-- handle. Default block buffering applies to the writes.
441--
442-- @since 0.7.0
443{-# INLINE writeUtf8 #-}
444writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
445writeUtf8 h s = write h $ encodeUtf8 s
447-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
448-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
449-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
450-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
451-- option.
452--
453-- @since 0.7.0
454{-# INLINE writeUtf8ByLines #-}
455writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
456writeUtf8ByLines = undefined
458-- | Read UTF-8 lines from a file handle and apply the specified fold to each
459-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
460--
461-- @since 0.7.0
462{-# INLINE readLines #-}
463readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
464readLines h f = foldLines (readUtf8 h) f
466-------------------------------------------------------------------------------
467-- Framing on a sequence
468-------------------------------------------------------------------------------
470-- | Read a stream from a file handle and split it into frames delimited by
471-- the specified sequence of elements. The supplied fold is applied on each
472-- frame.
473--
474-- @since 0.7.0
475{-# INLINE readFrames #-}
476readFrames :: (IsStream t, MonadIO m, Storable a)
477 => Array a -> Handle -> Fold m a b -> t m b
478readFrames = undefined -- foldFrames . read
480-- | Write a stream to the given file handle buffering up to frames separated
481-- by the given sequence or up to a maximum of @defaultChunkSize@.
482--
483-- @since 0.7.0
484{-# INLINE writeByFrames #-}
485writeByFrames :: (IsStream t, MonadIO m, Storable a)
486 => Array a -> Handle -> t m a -> m ()
487writeByFrames = undefined
489-------------------------------------------------------------------------------
490-- Random Access IO (Seek)
491-------------------------------------------------------------------------------
493-- XXX handles could be shared, so we may not want to use the handle state at
494-- all for these APIs. we can use pread and pwrite instead. On windows we will
495-- need to use readFile/writeFile with an offset argument.
497-------------------------------------------------------------------------------
499-- | Read the element at the given index treating the file as an array.
500--
501-- @since 0.7.0
502{-# INLINE readIndex #-}
503readIndex :: Storable a => Handle -> Int -> Maybe a
504readIndex arr i = undefined
506-- NOTE: To represent a range to read we have chosen (start, size) instead of
507-- (start, end). This helps in removing the ambiguity of whether "end" is
508-- included in the range or not.
509--
510-- We could avoid specifying the range to be read and instead use "take size"
511-- on the stream, but it may end up reading more and then consume it partially.
513-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
514-- from @handle@ starting at the offset @pos@ from the beginning of the file.
515--
516-- Reads are performed in chunks of size @chunkSize@. For block devices, to
517-- avoid reading partial blocks @chunkSize@ must align with the block size of
518-- the underlying device. If the underlying block size is unknown, it is a good
519-- idea to keep it a multiple 4KiB. This API ensures that the start of each
520-- chunk is aligned with @chunkSize@ from second chunk onwards.
521--
522{-# INLINE readSliceWith #-}
523readSliceWith :: (IsStream t, MonadIO m, Storable a)
524 => Int -> Handle -> Int -> Int -> t m a
525readSliceWith chunkSize h pos len = undefined
527-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
528-- at index @i@ and reading up to @count@ elements in the forward direction
529-- ending at the index @i + count - 1@.
530--
531-- @since 0.7.0
532{-# INLINE readSlice #-}
533readSlice :: (IsStream t, MonadIO m, Storable a)
534 => Handle -> Int -> Int -> t m a
535readSlice = readSliceWith defaultChunkSize
537-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
538-- at index @i@ and reading up to @count@ elements in the reverse direction
539-- ending at the index @i - count + 1@.
540--
541-- @since 0.7.0
542{-# INLINE readSliceRev #-}
543readSliceRev :: (IsStream t, MonadIO m, Storable a)
544 => Handle -> Int -> Int -> t m a
545readSliceRev h i count = undefined
547-- | Write the given element at the given index in the file.
548--
549-- @since 0.7.0
550{-# INLINE writeIndex #-}
551writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
552writeIndex h i a = undefined
554-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
555-- starting at index @i@ and writing up to @count@ elements in the forward
556-- direction ending at the index @i + count - 1@.
557--
558-- @since 0.7.0
559{-# INLINE writeSlice #-}
560writeSlice :: (IsStream t, Monad m, Storable a)
561 => Handle -> Int -> Int -> t m a -> m ()
562writeSlice h i len s = undefined
564-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
565-- starting at index @i@ and writing up to @count@ elements in the reverse
566-- direction ending at the index @i - count + 1@.
567--
568-- @since 0.7.0
569{-# INLINE writeSliceRev #-}
570writeSliceRev :: (IsStream t, Monad m, Storable a)
571 => Handle -> Int -> Int -> t m a -> m ()
572writeSliceRev arr i len s = undefined
573-}