packages feed

nova-nix-0.11.0.0 / src / Nix / Fetch / Download.hs

{-# LANGUAGE ScopedTypeVariables #-}-- | The evaluator's downloads: a URL's body read as a pull source, from-- a local file or through nova-nix's HTTP client ("Nix.Http"), each-- attempt under upstream's retry policy.module Nix.Fetch.Download  ( DownloadSource (..),    withUrlBody,    downloadBytes,  )whereimport Control.Exception (IOException, catch)import Data.Bifunctor (first)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport Data.Text (Text)import qualified Network.HTTP.Client as HTTPimport Nix.Http (FetchRetryPolicy, attemptFailureMessage, downloadUrlWith, fetchWriteFailure, ioRetryEffects, retryTransient)import Nix.Logger (Logger)import System.IO (IOMode (ReadMode), withBinaryFile)-- | Where a download reads a URL's body from.data DownloadSource  = -- | The file a @file:\/\/@ URL names, by its path.    LocalFile !FilePath  | -- | A URL the HTTP client requests.    RemoteUrl !Text  deriving (Eq, Show)-- | The bytes read from a local file at a time.localChunkBytes :: IntlocalChunkBytes = 65536-- | Read a URL's body as a pull source whose empty chunk ends it, handing-- the source to the consumer, and give what the consumer gives.  An-- attempt whose transfer fails in a way a retry could outlive is made-- again from the start, so a consumer starts from nothing each time; a-- failure no retry changes, a local file that cannot be read among them,-- is the message "Nix.Http" words it in.  The URL names the source in-- messages.withUrlBody :: Logger -> FetchRetryPolicy -> Text -> DownloadSource -> (IO ByteString -> IO a) -> IO (Either Text a)withUrlBody logger policy url source consume =  first attemptFailureMessage <$> retryTransient policy (ioRetryEffects logger) attempt  where    attempt = case source of      LocalFile path ->        (Right <$> withBinaryFile path ReadMode (\handle -> consume (BS.hGetSome handle localChunkBytes)))          `catch` \(err :: IOException) -> pure (Left (fetchWriteFailure url err))      RemoteUrl remote -> downloadUrlWith remote (fmap Right . consume . HTTP.brRead)-- | A URL's body, whole, as upstream reads a downloaded file.downloadBytes :: Logger -> FetchRetryPolicy -> Text -> DownloadSource -> IO (Either Text ByteString)downloadBytes logger policy url source = withUrlBody logger policy url source (drain [])  where    drain held pull = do      chunk <- pull      if BS.null chunk then pure (BS.concat (reverse held)) else drain (chunk : held) pull