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