-- | The HTTP transfer layer nova-nix's own HTTP client goes through, for-- every download it makes (@builtin:fetchurl@, the substituter, push, and-- the evaluator's @builtins.fetchurl@ and @builtins.fetchTarball@): the-- User-Agent each request carries, one request's download, and upstream's-- retry policy with the classification that decides what a retry can-- outlive.---- Upstream serves every transfer, a fetcher's and a substituter's alike,-- through one transfer layer, with one attempts setting, one backoff and-- one table of the failures that are never retried. Every caller shares-- this module for the same reason: a source tarball, a narinfo and a NAR-- fail and retry alike.module Nix.Http ( -- * Identity userAgent, withUserAgent, -- * Attempt failures AttemptFailure (..), attemptFailureMessage, catchSync, -- * Download downloadUrlWith, -- * Retry policy FetchRetryPolicy (..), defaultDownloadAttempts, defaultFetchRetryPolicy, RetryEffects (..), ioRetryEffects, retryTransient, retryDelayMs, -- * Classification TransferError (..), statusError, withTransfer, transferBodyReader, transferFailureHandlers, fetchStatusFailure, fetchExceptionFailure, exceptionFailure, fetchWriteFailure, fileUrlFailure, )whereimport Control.Concurrent (threadDelay)import Control.Exception (Handler (..), IOException, SomeAsyncException (..), SomeException, catch, catches, displayException, fromException, throwIO)import qualified Data.ByteString.Char8 as BS8import Data.Text (Text)import qualified Data.Text as Timport Data.Version (showVersion)import Data.Word (Word32)import qualified Network.HTTP.Client as HTTPimport qualified Network.HTTP.Client.TLS as HTTPSimport Network.HTTP.Types.Header (hUserAgent)import qualified Network.HTTP.Types.Status as HTTPimport Nix.Logger (Logger, logWarning)import Paths_nova_nix (version)import System.Random (randomRIO)-- ----------------------------------------------------------------------------- Identity-- ----------------------------------------------------------------------------- | @nova-nix\/VERSION (+repository)@: the product token upstream's shape-- calls for, and a comment naming where the client comes from.---- Upstream identifies itself on every request as @curl\/VERSION-- Nix\/VERSION@. A request with no User-Agent is what bot mitigation in-- front of a server scores lowest: ftp.gnu.org answers one with 403-- outright, and Cloudflare in front of cache.novavero.ai challenged every-- request a GitHub runner made without one while passing the same requests-- carrying this header. The fetcher, the substituter and push each send-- it through 'withUserAgent'. The version comes from Cabal, so the header-- names the build that made the request rather than a spelling that can-- drift at release time.userAgent :: BS8.ByteStringuserAgent = BS8.pack ("nova-nix/" <> showVersion version <> " (+https://github.com/Novavero-AI/nova-nix)")-- | The request with 'userAgent' as its only User-Agent, whatever it-- carried before.withUserAgent :: HTTP.Request -> HTTP.RequestwithUserAgent request = request { HTTP.requestHeaders = (hUserAgent, userAgent) : filter ((/= hUserAgent) . fst) (HTTP.requestHeaders request) }-- ----------------------------------------------------------------------------- Attempt failures-- ----------------------------------------------------------------------------- | How one download attempt failed, deciding whether the retry budget-- applies. 'TransientFailure' is a failure a fresh attempt could-- plausibly complete; 'FatalFailure' is deterministic - the same served-- object fails the same way every time.data AttemptFailure = TransientFailure !Text | FatalFailure !Text deriving (Eq, Show)-- | The failure's message, independent of its retry class.attemptFailureMessage :: AttemptFailure -> TextattemptFailureMessage failure = case failure of TransientFailure msg -> msg FatalFailure msg -> msg-- | Run an action, passing only synchronous exceptions to the handler.-- Asynchronous exceptions (a Ctrl-C, a timeout) re-throw untouched: an-- interrupt converted into a recoverable failure would be spent as-- retry budget, as fallthrough to the next cache, as a local build, or-- as a failed push instead of aborting. Every catch-all on the-- download, substitution, build and push paths goes through this one-- split.catchSync :: IO a -> (SomeException -> IO a) -> IO acatchSync action handler = action `catch` classify where classify someErr | Just (SomeAsyncException _) <- fromException someErr = throwIO someErr | otherwise = handler someErr-- ----------------------------------------------------------------------------- Download-- ----------------------------------------------------------------------------- | Request a URL with nova-nix's own linked HTTP client, on the-- process's one TLS manager so connections are pooled, and hand the body-- of a success to the consumer. A status other than 200, or a failure of-- the transfer or of the consumer's writes, becomes a 'Left' carrying its-- retry class ('transferFailureHandlers'); an asynchronous exception-- propagates. One call is one attempt: 'retryTransient' makes the-- retries.downloadUrlWith :: Text -> (HTTP.BodyReader -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)downloadUrlWith url consume = fetch `catches` transferFailureHandlers url where fetch = do manager <- HTTPS.getGlobalManager request <- withUserAgent <$> HTTP.parseRequest (T.unpack url) withTransfer request manager $ \response -> do let status = HTTP.responseStatus response if status == HTTP.status200 then consume (HTTP.responseBody response) else pure (Left (fetchStatusFailure url status))-- ----------------------------------------------------------------------------- Retry policy-- ----------------------------------------------------------------------------- | How many times one download is tried before it fails, unless-- @download-attempts@ says otherwise: upstream's default.defaultDownloadAttempts :: Word32defaultDownloadAttempts = 5-- | The delay before the first retry, in milliseconds; every later retry-- doubles it.retryBaseDelayMs :: IntretryBaseDelayMs = 250-- | The spread added to the backoff exponent so that clients which failed-- together do not retry together: a uniform draw from @[0, 0.5)@.retryJitterCeiling :: DoubleretryJitterCeiling = 0.5microsPerMilli :: IntmicrosPerMilli = 1000-- | How often one download is tried and how long to wait between tries:-- 'defaultFetchRetryPolicy', with the attempts @download-attempts@ sets,-- and in tests a shorter delay.data FetchRetryPolicy = FetchRetryPolicy { frpAttempts :: !Word32, frpBaseDelayMs :: !Int } deriving (Eq, Show)-- | The default policy: 'defaultDownloadAttempts' attempts, 250 ms before-- the first retry.defaultFetchRetryPolicy :: FetchRetryPolicydefaultFetchRetryPolicy = FetchRetryPolicy {frpAttempts = defaultDownloadAttempts, frpBaseDelayMs = retryBaseDelayMs}-- | The delay before retry number @retry@ (counting from one), given the-- jitter drawn for it: the base delay times @2 ^ (retry - 1 + jitter)@,-- truncated to whole milliseconds.retryDelayMs :: FetchRetryPolicy -> Word32 -> Double -> IntretryDelayMs policy retry jitter = truncate (fromIntegral (frpBaseDelayMs policy) * 2 ** (fromIntegral retry - 1 + jitter) :: Double)-- | What the retry loop needs from the outside world, injected so the-- policy is testable with no clock, no entropy and no network.data RetryEffects m = RetryEffects { reSleepMs :: !(Int -> m ()), reJitter :: !(m Double), reWarn :: !(Text -> m ()) }-- | The real effects: a sleep, a uniform jitter, and a warning to the-- logger in the shape of upstream's @warn("%s; retrying in %d ms", ...)@.ioRetryEffects :: Logger -> RetryEffects IOioRetryEffects logger = RetryEffects { reSleepMs = threadDelay . (* microsPerMilli), reJitter = randomRIO (0, retryJitterCeiling), reWarn = logWarning logger }-- | Run one download's attempt under the retry policy: a-- 'TransientFailure' is tried again after the backoff until the attempts-- are spent, while a 'FatalFailure' or a success ends the loop at once.-- Exceptions propagate, so a cancellation is never spent as retry budget.retryTransient :: (Monad m) => FetchRetryPolicy -> RetryEffects m -> m (Either AttemptFailure a) -> m (Either AttemptFailure a)retryTransient policy effects action = go 1 where go !attempt = do result <- action case result of Left (TransientFailure err) | attempt < frpAttempts policy -> do jitter <- reJitter effects let delay = retryDelayMs policy attempt jitter reWarn effects (err <> "; retrying in " <> T.pack (show delay) <> " ms") reSleepMs effects delay go (attempt + 1) _ -> pure result-- ----------------------------------------------------------------------------- Classification-- ----------------------------------------------------------------------------- | 'HTTP.withResponse', with the body read through-- 'transferBodyReader', so every failure of the connection is an-- 'HTTP.HttpException', the body's included.withTransfer :: HTTP.Request -> HTTP.Manager -> (HTTP.Response HTTP.BodyReader -> IO a) -> IO awithTransfer request manager consume = HTTP.withResponse request manager (consume . fmap (transferBodyReader request))-- | A response body reader whose failures are all-- 'HTTP.HttpException's. The client's manager wraps what opening a-- response throws (a reset, a TLS failure) into-- 'HTTP.InternalException', but hands the body reader over unwrapped-- (@responseOpen@ in http-client 0.7), so a connection reset or a torn-- TLS record mid-body arrives as a bare 'IOException' or TLS exception,-- the shape of a failure writing the output. Wrapping the read the way-- the manager wraps the open keeps the two apart: a transport failure is-- transient wherever it happens, as curl's receive errors are upstream,-- and a write failure is not. The reader only ever reads the-- connection, so every synchronous exception it raises is the-- transport's; an asynchronous one passes through untouched.transferBodyReader :: HTTP.Request -> HTTP.BodyReader -> HTTP.BodyReadertransferBodyReader request reader = reader `catchSync` asTransportFailure where asTransportFailure err = case fromException err :: Maybe HTTP.HttpException of Just _ -> throwIO err Nothing -> throwIO (HTTP.HttpExceptionRequest request (HTTP.InternalException err))-- | What a transfer attempt throws, turned into its failure: an-- 'HTTP.HttpException' by 'fetchExceptionFailure', an 'IOException' by-- 'fetchWriteFailure'. Nothing else is caught, so an asynchronous-- exception (an interrupt, a cancelled build) leaves the attempt as it-- arrived and is never spent as retry budget, and anything unforeseen-- reaches the caller's own boundary.transferFailureHandlers :: Text -> [Handler (Either AttemptFailure a)]transferFailureHandlers url = [ Handler (pure . Left . fetchExceptionFailure url), Handler (pure . Left . fetchWriteFailure url) ]-- | The verdict on a response that is not a success. An interrupted-- transfer is an asynchronous exception here, never a value. Only-- 'Transient' is retried. A binary cache store reads 'NotFound' and-- 'Forbidden' alike as the file not being in that cache, since an S3-- bucket that cannot be listed answers a missing key with 403.data TransferError = -- | 404 or 410: the file is not there. NotFound | -- | 401, 403 or 407: the request was refused. Forbidden | -- | A failure no retry can change. Misc | -- | A failure a retry could outlive. Transient deriving (Eq, Show)-- | Classify a response status, in this order: 404 and 410 are-- 'NotFound'; 401, 403 and 407 are 'Forbidden'; every other 4xx except 408-- and 429 (the server timed out waiting for the request, or asked for a-- slower pace) is 'Misc', as are 501, 505 and 511 (the server cannot speak-- this protocol, or a captive portal is in the way). Everything else is-- 'Transient', the remaining 5xx included.statusError :: HTTP.Status -> TransferErrorstatusError status | status `elem` [HTTP.status404, HTTP.status410] = NotFound | status `elem` [HTTP.status401, HTTP.status403, HTTP.status407] = Forbidden | HTTP.statusIsClientError status && status `notElem` [HTTP.status408, HTTP.status429] = Misc | status `elem` [HTTP.status501, HTTP.status505, HTTP.status511] = Misc | otherwise = Transient-- | A response status as an attempt's failure, by 'statusError': only a-- 'Transient' one is retried.fetchStatusFailure :: Text -> HTTP.Status -> AttemptFailurefetchStatusFailure url status = case statusError status of Transient -> TransientFailure message NotFound -> FatalFailure message Forbidden -> FatalFailure message Misc -> FatalFailure message where message = "HTTP " <> T.pack (show (HTTP.statusCode status)) <> " fetching " <> url-- | Classify a failure of the HTTP client: one no retry can change is-- fatal, and every other is transient. A URL the client cannot parse-- (@CURLE_URL_MALFORMAT@) is an 'HTTP.InvalidUrlException' from the-- parser, except for an empty host, which the parser accepts and the-- connection lookup rejects as 'HTTP.InvalidDestinationHost' on every-- attempt. A scheme the client does not speak-- (@CURLE_UNSUPPORTED_PROTOCOL@) is an 'HTTP.InvalidUrlException' too, or-- 'HTTP.TlsNotSupported' when the manager has no TLS. A redirect loop-- (@CURLE_TOO_MANY_REDIRECTS@) completes the set. Every other transport-- failure is transient, name resolution, TLS and a timeout included. The-- message names the URL and the failure only: the client's own rendering-- prints the whole request record over a dozen lines, and a retry would-- repeat it.fetchExceptionFailure :: Text -> HTTP.HttpException -> AttemptFailurefetchExceptionFailure url = exceptionFailure (describeFailure url)-- | The classification of 'fetchExceptionFailure', with the message made-- from the failure's detail by the given function, for a request that is-- not a download.exceptionFailure :: (String -> Text) -> HTTP.HttpException -> AttemptFailureexceptionFailure describe err = case err of HTTP.InvalidUrlException _ reason -> FatalFailure (describe reason) HTTP.HttpExceptionRequest _ content -> case content of HTTP.InvalidDestinationHost _ -> FatalFailure (describe "empty host") HTTP.TlsNotSupported -> FatalFailure (describe "TLS is not supported") HTTP.TooManyRedirects _ -> FatalFailure (describe "too many redirects") _ -> TransientFailure (describe (show content))-- | A failure writing what the transfer delivered: upstream's-- @CURLE_WRITE_ERROR@, never retried, since the disk that refused one-- write refuses the next. An 'IOException' reaching the attempt boundary-- is one, because 'withTransfer' has already raised every failure of the-- connection as an 'HTTP.HttpException'.fetchWriteFailure :: Text -> IOException -> AttemptFailurefetchWriteFailure url err = FatalFailure (describeFailure url (displayException err))-- | A @file://@ URL whose file cannot be read, or that names no file here,-- with the detail: never retried, since the same URL fails the same way-- every time, as upstream's transfer reads a file it cannot open as not-- being there.fileUrlFailure :: Text -> String -> AttemptFailurefileUrlFailure url detail = FatalFailure (describeFailure url detail)describeFailure :: Text -> String -> TextdescribeFailure url detail = "download error fetching " <> url <> ": " <> T.pack detail