{-# LANGUAGE ScopedTypeVariables #-}-- | Push store paths to a nova-cache binary cache. "Nix.Push.Directory"-- writes them to a binary cache in a local directory instead, from the-- same pieces.---- == The push choreography---- 1. Compute the full reference closure of the requested paths from the-- records of the t'PushSource' - the store's database, or a daemon's-- answers - because a cache must never hold a path without its-- dependencies, or substitution 404s on cold machines.-- 2. Fetch @\/narinfo-hashes@ from the cache and skip paths already there.-- 3. Upload every missing NAR, then every narinfo. NARs go first-- globally: a narinfo is the public announcement that a path is-- available, so it must never appear before its bytes do.-- 4. Verify one round-trip: fetch a narinfo back and check the server-- signed it.---- == Where a push reads---- A t'PushSource' ("Nix.Push.Source") is what a push reads: each path's-- references, NAR hash and deriver, which the source records, and its-- files, which are read from the source's store directory. A store opened-- directly gives its database's records, and a store reached through a-- daemon ("Nix.Daemon.ClientStore") asks the daemon for them and reads the-- files from the directory the daemon's store keeps them in.---- == Path forms---- The store database and filesystem use the platform store dir-- (@C:\\nix\\store@ on Windows). Published narinfos always use the-- canonical store dir (@\/nix\/store@) with forward slashes - the form the-- store-path hashes were computed against and the form cache servers-- validate. 'StorePath' itself is directory-agnostic, so translation is-- just a matter of which renderer runs at which boundary.---- == Compression---- Uploads default to @Compression: none@ - the cache's existing-- content is uncompressed, and mixing artifact kinds is an operator-- decision, not a default flip. 'PushZstd' compresses each NAR with-- nova-cache's zstandard encoder before upload: the narinfo's file-- fields describe the compressed artifact, its object name carries-- the compressed file hash, and the substituter decompresses under-- the declared NarSize bound.---- == Uploading in parts---- A proxy in front of a cache can refuse a request body over its own-- limit, as Cloudflare in front of the public cache refuses one over-- 100 MB with 413. A NAR up to 'pcPartSize' goes in one-- @PUT nar\/\<file\>@; a larger one goes through nova-cache's multipart-- upload: @POST nar\/\<file\>\/uploads@ begins it, each-- @PUT nar\/\<file\>\/uploads\/\<id\>\/\<n\>@ sends one part in order,-- and @POST nar\/\<file\>\/uploads\/\<id\>@ completes it with the part-- count and the total size. A cache that answers the beginning with-- 404, as a nova-cache without multipart upload does, gets the NAR in-- one @PUT@.---- The retries follow nova-cache's rule for a client. A part, or the-- request that begins an upload, is sent again under 'pcRetry' when it-- fails as upstream's transfer layer retries a transfer, its response-- lost or an error status such as 503 ('Nix.Http.exceptionFailure',-- 'Nix.Http.statusError'): the server replaces a part it holds, and a-- repeated beginning only leaves an empty upload it reclaims. A part-- answered 404 or 409 means the server no longer holds the parts before-- it, so a new upload begins. A completion answered with anything but-- 200, or not at all, may still have joined the NAR, so the push goes-- on and the narinfo decides: the server checks its FileSize and-- FileHash against the NAR it holds, and when it refuses the narinfo,-- the NAR is uploaded again. A push stops after a fixed number of-- uploads of one NAR, so a cache that keeps losing parts cannot hold it-- in a loop.---- The NAR is held whole, as for one @PUT@, and each part is a slice of-- it. Holding one part at a time would need a streaming zstd encoder,-- which nova-cache's one-shot 'Zstd.compress' is not, and two passes-- over the path, since an upload is begun under the object's name and a-- zstd object is named by the hash of the whole compressed file.module Nix.Push ( -- * Configuration PushConfig (..), PushCompression (..), PushSummary (..), PartSize, mkPartSize, partSizeBytes, defaultPartSize, -- * Pushing pushPaths, computeClosure, preparePath, loadKeyFile, -- * Cache layout narInfoFileName, narDirSegment, -- * Progress lines logSkipped, logNar, logPushed, -- * Pure pieces (exported for tests) parsePushCompression, pushCompressionValues, mkNarInfo, mkPushArtifact, PushArtifact (..), planMissing, isDerivationPath, outputPathsOnly, narFileName, stripHashPrefix, storePathBasename, checkRecordedNarHash, narHashMatches, splitParts, )whereimport Control.Exception (IOException, displayException, try)import Control.Monad (foldM, forM, forM_, unless, when)import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError)import Control.Monad.IO.Class (liftIO)import Data.Bifunctor (first)import qualified Data.ByteString as BSimport Data.Char (isDigit)import Data.List (sort)import Data.Set (Set)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport qualified Network.HTTP.Client as HTTPimport qualified Network.HTTP.Client.TLS as HTTPSimport qualified Network.HTTP.Types as HTTPimport Nix.Compression (compressionNameNone, compressionNameZstd)import Nix.Http (AttemptFailure (..), FetchRetryPolicy, TransferError (..), attemptFailureMessage, catchSync, exceptionFailure, ioRetryEffects, retryTransient, statusError, withTransfer, withUserAgent)import Nix.Logger (Logger, logMessage)import Nix.Push.Source (PushSource (..), PushedPath (..))import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.Path (StorePath (spHash, spName), defaultStoreDir, storePathBasename, storePathToFilePath, storePathToText)import qualified NovaCache.Hash as Hashimport qualified NovaCache.NAR as NARimport NovaCache.NarInfo (NarInfo (..), parseNarInfo, renderNarInfo)import NovaCache.Signing (normalizeKeyText)import qualified NovaCache.Zstd as Zstd-- ----------------------------------------------------------------------------- Named constants-- ----------------------------------------------------------------------------- | Cache endpoint listing all stored narinfo hashes, one per line.narinfoHashesEndpoint :: TextnarinfoHashesEndpoint = "narinfo-hashes"-- | The directory of a cache, and the first segment of a NAR's URL, under-- which NAR files live.narDirSegment :: TextnarDirSegment = "nar"-- | File extension for an uncompressed NAR.narExtension :: TextnarExtension = ".nar"-- | Extension for narinfo objects.narInfoExtension :: TextnarInfoExtension = ".narinfo"-- | Extension for zstd-compressed NAR objects.narZstExtension :: TextnarZstExtension = ".nar.zst"-- | Authorization scheme prefix for the API key.bearerPrefix :: BS.ByteStringbearerPrefix = "Bearer "-- | The most characters of a server's error message an error quotes.errorBodyChars :: InterrorBodyChars = 200-- | Path segment under @nar\/\<file\>@ where nova-cache keeps the file's-- multipart uploads.uploadsSegment :: TextuploadsSegment = "uploads"-- | Keys of the body that completes a multipart upload, as nova-cache-- reads them.partsField, fileSizeField :: TextpartsField = "Parts"fileSizeField = "FileSize"-- | Hex digits in the id nova-cache issues for an upload: 128 random-- bits, in lowercase.uploadIdDigits :: IntuploadIdDigits = 32-- | The most uploads of one NAR a push begins. A part answered 404 or-- 409, or a narinfo refused after a completion that was not answered-- with 200, begins one more; past this many the push fails, so a cache-- that keeps losing parts cannot hold it in a loop.maxNarUploads :: IntmaxNarUploads = 3-- ----------------------------------------------------------------------------- Configuration and results-- ----------------------------------------------------------------------------- | How each NAR is packaged for upload. A property of the-- destination cache, as upstream models compression on binary cache-- stores - not a per-path whim.data PushCompression = PushNone | PushZstd deriving (Eq, Show)-- | The accepted @--compression@ spellings, for parser errors and the-- CLI help line - one rendering of the register in "Nix.Compression".pushCompressionValues :: TextpushCompressionValues = compressionNameNone <> ", " <> compressionNameZstd-- | Parse the CLI spelling of a push compression. The spellings are-- the narinfo @Compression@ names from "Nix.Compression", so the CLI-- vocabulary and the wire vocabulary cannot drift.parsePushCompression :: Text -> Either Text PushCompressionparsePushCompression name | name == compressionNameNone = Right PushNone | name == compressionNameZstd = Right PushZstd | otherwise = Left ( "unknown --compression " <> name <> " (expected: " <> pushCompressionValues <> ")" )-- | Where and how to push.data PushConfig = PushConfig { -- | Cache base URL, no trailing slash (e.g. @https:\/\/cache.example.com@). pcCacheUrl :: !Text, -- | Bearer token for authenticated writes. 'Nothing' sends no -- Authorization header (only useful against an open-writes server). pcApiKey :: !(Maybe Text), -- | Artifact packaging for this destination (see 'PushCompression'). pcCompression :: !PushCompression, -- | The most bytes of a NAR one request carries: a NAR up to this -- size goes in one @PUT@, a larger one in parts of this size. A -- property of the destination, whose proxy sets the limit. pcPartSize :: !PartSize, -- | How often a request of a multipart upload that is safe to send -- again is tried, and the wait between tries. pcRetry :: !FetchRetryPolicy } deriving (Eq, Show)-- | The most bytes of a NAR one request carries, at least one. The-- constructor is not exported, so every value is 'defaultPartSize' or-- one 'mkPartSize' accepted.newtype PartSize = PartSize Int deriving (Eq, Show)-- | A part size of the given number of bytes; 'Nothing' below one, where-- no part could carry any of a NAR.mkPartSize :: Int -> Maybe PartSizemkPartSize bytes | bytes >= 1 = Just (PartSize bytes) | otherwise = Nothing-- | The bytes a part size allows.partSizeBytes :: PartSize -> IntpartSizeBytes (PartSize bytes) = bytes-- | 64 MiB. Cloudflare in front of the public cache refuses a request-- body over 100 MB with 413, and 64 MiB is under that whether the limit-- counts 10^8 bytes or 100 MiB. nova-cache holds a NAR to 4 GiB and an-- upload to 10,000 parts, so a NAR at its cap takes 64 parts of this-- size.defaultPartSize :: PartSizedefaultPartSize = PartSize (64 * 1024 * 1024)-- | What a push accomplished.data PushSummary = PushSummary { -- | Paths uploaded (NAR + narinfo). psPushed :: !Int, -- | Closure paths skipped because the cache already had them. psSkipped :: !Int } deriving (Eq, Show)-- ----------------------------------------------------------------------------- Key loading-- ----------------------------------------------------------------------------- | Read a key from a file, a cache's API key or a secret signing key's-- text, dropping byte-order marks and surrounding whitespace. Key files-- written by Windows tooling are a known source of BOM contamination;-- 'normalizeKeyText' makes the transfer byte-clean.---- The bytes are decoded as UTF-8 EXPLICITLY: locale text IO decodes by-- console code page, which turns the BOM bytes into codepage characters-- that no normalizer recognizes - on the very consoles the BOM handling-- exists for.loadKeyFile :: FilePath -> IO (Either Text Text)loadKeyFile path = do attempt <- try (BS.readFile path) pure $ case attempt of Left (e :: IOException) -> Left ("cannot read key file: " <> T.pack (show e)) Right bytes -> case TE.decodeUtf8' bytes of Left _ -> Left ("key file is not valid UTF-8: " <> T.pack path) Right raw -> let key = normalizeKeyText raw in if T.null key then Left ("key file is empty: " <> T.pack path) else Right key-- ----------------------------------------------------------------------------- Closure computation-- ----------------------------------------------------------------------------- | Compute the full reference closure of the given paths from the-- source's records, in reverse-topological order: every path's references-- precede it (postorder over the references; a self-reference or-- already-visited path is skipped). Publishing narinfos in this order-- never announces a path whose references are not yet visible. Only the-- references are asked of the source, so a path that is not sent needs no-- other record. A path the source does not hold has no references here,-- and 'preparePath' refuses it. Fails if the source cannot give a path's-- references, such as one that does not parse as a store path: that would-- mean a corrupt database, and pushing a closure with holes would poison-- the cache.computeClosure :: PushSource -> [StorePath] -> IO (Either Text [StorePath])computeClosure source roots = runExceptT (reverse . snd <$> foldM visit (Set.empty, []) roots) where visit :: (Set Text, [StorePath]) -> StorePath -> ExceptT Text IO (Set Text, [StorePath]) visit (seen, acc) sp | spHash sp `Set.member` seen = pure (seen, acc) | otherwise = do refs <- ExceptT (psReferences source sp) (seenAfterRefs, accAfterRefs) <- foldM visit (Set.insert (spHash sp) seen, acc) refs pure (seenAfterRefs, sp : accAfterRefs)-- ----------------------------------------------------------------------------- Pure planning and rendering-- ----------------------------------------------------------------------------- | Paths whose narinfo hash the cache does not already have.planMissing :: Set Text -> [StorePath] -> [StorePath]planMissing remote = filter (\sp -> not (spHash sp `Set.member` remote))-- | Whether a store path is a derivation: a recipe, not an output.isDerivationPath :: StorePath -> BoolisDerivationPath sp = derivationExtension `T.isSuffixOf` spName sp-- | Every valid path that is not a derivation: outputs and sources alike.-- A store registers its derivations as valid paths like anything else, but-- a binary cache serves build outputs only: nova-cache refuses a narinfo-- for a @.drv@ outright, and no substituter asks a cache for a recipe it-- can rebuild from the expression. @push --all@ therefore means every-- valid path except derivations.outputPathsOnly :: [StorePath] -> [StorePath]outputPathsOnly = filter (not . isDerivationPath)-- | The suffix that marks a derivation's store path.derivationExtension :: TextderivationExtension = ".drv"-- | Drop a @\<algo\>:@ prefix from a formatted hash, leaving the digest.stripHashPrefix :: Text -> TextstripHashPrefix h = case T.breakOn ":" h of (_, rest) | not (T.null rest) -> T.drop 1 rest _ -> h-- | The name of a path's narinfo in a cache, @\<hash\>.narinfo@.narInfoFileName :: StorePath -> TextnarInfoFileName sp = spHash sp <> narInfoExtension-- | The NAR object filename for a given (uncompressed) NAR hash.narFileName :: Text -> TextnarFileName narHash = stripHashPrefix narHash <> narExtension-- | The uploadable artifact for one NAR under the configured-- compression: the bytes the cache stores, the file fields the-- narinfo declares, and the object name. With 'PushNone' every field-- equals the NAR's own.data PushArtifact = PushArtifact { paBytes :: !BS.ByteString, paFileHash :: !Text, paFileSize :: !Int, paCompressionText :: !Text, paObjectName :: !Text, -- | The source NAR's hash and byte count, recorded at packaging -- time: a narinfo built from this artifact can only ever describe -- one byte stream, so the NAR fields and file fields cannot be -- paired wrongly by a caller. paNarHash :: !Text, paNarSize :: !Int } deriving (Eq, Show)-- | Package one NAR for upload. The zstd object is named by its own-- (compressed) file hash, the convention the public caches follow.mkPushArtifact :: PushCompression -> Text -> BS.ByteString -> PushArtifactmkPushArtifact compression narHash narBytes = case compression of PushNone -> PushArtifact { paBytes = narBytes, paFileHash = narHash, paFileSize = BS.length narBytes, paCompressionText = compressionNameNone, paObjectName = narFileName narHash, paNarHash = narHash, paNarSize = BS.length narBytes } PushZstd -> let compressed = Zstd.compress Zstd.defaultCompressionLevel narBytes fileHash = Hash.formatNixHash (Hash.hashBytes compressed) in PushArtifact { paBytes = compressed, paFileHash = fileHash, paFileSize = BS.length compressed, paCompressionText = compressionNameZstd, paObjectName = stripHashPrefix fileHash <> narZstExtension, paNarHash = narHash, paNarSize = BS.length narBytes }-- | Construct the narinfo describing a store path. Every artifact-- and NAR field - file hash, file size, compression, object name, NAR-- hash, NAR size - comes from the one t'PushArtifact', so the narinfo-- is internally consistent by construction. The @StorePath@ uses-- the canonical @\/nix\/store@ form; references and the deriver are-- basenames, matching the wire format.---- The file hash and size are forced into their @Just@, as the other-- fields taken from the artifact are by their strictness, so a narinfo-- holds no thunk over the artifact, whose bytes are the whole NAR: a-- push that keeps its narinfos until every NAR is in place keeps no NAR.mkNarInfo :: PushArtifact -> StorePath -> [StorePath] -> Maybe StorePath -> NarInfomkNarInfo artifact sp refs deriver = NarInfo { niStorePath = storePathToText defaultStoreDir sp, niUrl = narDirSegment <> "/" <> paObjectName artifact, niCompression = paCompressionText artifact, niFileHash = Just $! paFileHash artifact, niFileSize = Just $! fromIntegral (paFileSize artifact), niNarHash = paNarHash artifact, niNarSize = fromIntegral (paNarSize artifact), niReferences = sort (map storePathBasename refs), niDeriver = storePathBasename <$> deriver, niSigs = [], niCA = Nothing }-- | A NAR's bytes as the parts of a multipart upload, in order: each-- holds the part size but the last, which holds the rest. A part is a-- slice of the bytes, not a copy.splitParts :: PartSize -> BS.ByteString -> [BS.ByteString]splitParts size bytes | BS.null bytes = [] | otherwise = part : splitParts size rest where (part, rest) = BS.splitAt (partSizeBytes size) bytes-- ----------------------------------------------------------------------------- Push orchestration-- ----------------------------------------------------------------------------- | Push the closure of the given paths to the cache.---- Serializes one NAR at a time (bounded memory), uploads all NARs before-- any narinfo, and finishes with a signed round-trip check. Any failure-- aborts with an error. One before the first narinfo leaves only NARs no-- narinfo names, which are invisible to clients; one after it leaves the-- narinfos already published as well. An interrupt is not a failure: it-- stops the push and propagates. Its progress lines go to the source's-- logger.pushPaths :: PushConfig -> PushSource -> [StorePath] -> IO (Either Text PushSummary)pushPaths cfg source roots = -- Every synchronous exception: the push raises sqlite-simple's from the -- database, walk failures and IO errors from the serialiser, and IO -- errors from the logger, and each is a failed push, reported as its -- exception says, as every other failure here is, for the command to -- word. runExceptT run `catchSync` \e -> pure (Left (T.pack (displayException e))) where logger = psLogger source run :: ExceptT Text IO PushSummary run = do manager <- liftIO newPushManager closure <- ExceptT (computeClosure source roots) remote <- fetchRemoteHashes manager cfg let missing = planMissing remote closure skipped = length closure - length missing logSkipped logger skipped -- Phase 1: NARs, one at a time. What is kept for phase 2 is each -- path's narinfo and how its upload ended, and neither holds the -- NAR's bytes ('mkNarInfo' forces what it takes from the artifact), -- so each NAR is dropped once uploaded. uploaded <- forM missing $ \sp -> do (narInfo, upload) <- uploadNar logger manager cfg source 0 sp pure (sp, narInfo, upload) -- Phase 2: narinfos, only after every NAR is in place, in the -- closure's deps-first order: a freshly announced path's references -- are always already announced. A NAR whose upload was not -- confirmed is checked here, by its narinfo, and not in phase 1, -- since a narinfo accepted there would announce a path before its -- references. forM_ uploaded $ \(sp, narInfo, upload) -> do publishNarInfo logger manager cfg source sp narInfo upload logPushed logger sp -- Round-trip: the first pushed narinfo must come back signed. case uploaded of ((sp, _, _) : _) -> verifySignedRoundTrip logger manager cfg sp [] -> pure () pure PushSummary {psPushed = length uploaded, psSkipped = skipped}-- | HTTP manager for pushes. Large NAR uploads over residential uplinks-- can take many minutes, so the response timeout is disabled rather than-- guessed at.newPushManager :: IO HTTP.ManagernewPushManager = HTTP.newManager HTTPS.tlsManagerSettings {HTTP.managerResponseTimeout = HTTP.responseTimeoutNone}-- | Fetch the set of narinfo hashes the cache already stores. The-- endpoint is push-tool plumbing and the server requires the write key-- for it (nova-cache 0.5), so the request authenticates like the PUTs.fetchRemoteHashes :: HTTP.Manager -> PushConfig -> ExceptT Text IO (Set Text)fetchRemoteHashes manager cfg = do let url = pcCacheUrl cfg <> "/" <> narinfoHashesEndpoint response <- httpRequest manager "GET" url (authHeaders cfg) Nothing expectOk ("GET " <> narinfoHashesEndpoint) response pure (Set.fromList (filter (not . T.null) (map T.strip (T.lines (responseText response)))))-- | Serialize a store path to a NAR, cross-check the source's NAR hash,-- and upload the bytes, given how many uploads of the NAR this push has-- begun before. Returns the narinfo to publish in phase 2, and whether-- the cache confirmed the NAR.uploadNar :: Logger -> HTTP.Manager -> PushConfig -> PushSource -> Int -> StorePath -> ExceptT Text IO (NarInfo, NarUpload)uploadNar logger manager cfg source begun sp = do (artifact, narInfo) <- preparePath (pcCompression cfg) source sp logNar logger sp artifact upload <- sendNar logger manager cfg begun (niUrl narInfo) (paBytes artifact) pure (narInfo, upload)-- | What a push uploads for one store path: its NAR, packaged as the-- compression asks, and the narinfo that describes it. The NAR is-- serialized from the source's store directory and held to the NAR hash-- the source records ('checkRecordedNarHash'); the references and the-- deriver come from the same record, which is asked for once.preparePath :: PushCompression -> PushSource -> StorePath -> ExceptT Text IO (PushArtifact, NarInfo)preparePath compression source sp = do narEntry <- liftIO (ExecBit.serialiseFromPath (psCaseHack source) (storePathToFilePath (psStoreDir source) sp)) let narBytes = NAR.serialise narEntry narHash = Hash.formatNixHash (Hash.hashBytes narBytes) recorded <- ExceptT (psPathInfo source sp) liftEither (checkRecordedNarHash recorded narHash sp) let artifact = mkPushArtifact compression narHash narBytes pure (artifact, mkNarInfo artifact sp (foldMap ppReferences recorded) (recorded >>= ppDeriver))-- | Pre-upload integrity gate. The source recorded the path's NAR hash-- at registration; a mismatch now means the path changed on disk - refuse-- to publish corruption. An on-disk path with NO registration (an-- interrupted build) is refused too: its references are unknown, so-- publishing would fabricate an empty-reference narinfo and serve a-- closure with holes.checkRecordedNarHash :: Maybe PushedPath -> Text -> StorePath -> Either Text ()checkRecordedNarHash recorded narHash sp = case recorded of Nothing -> Left ( "store integrity: " <> storePathBasename sp <> " is on disk but not registered as valid; refusing to publish it with unknown references" ) Just info | not (narHashMatches (ppNarHash info) narHash) -> Left ( "store integrity: " <> storePathBasename sp <> " hashes to " <> narHash <> " but the DB recorded " <> ppNarHash info ) | otherwise -> Right ()-- | Recorded and computed NAR hashes match when both parse as-- @sha256:@ and nix-base32 and their decoded digests agree. A recorded-- value that does not parse, such as base16, falls back to exact text-- equality, so it stays comparable rather than un-checkable.narHashMatches :: Text -> Text -> BoolnarHashMatches recorded computed = case (Hash.parseNixHash recorded, Hash.parseNixHash computed) of (Right a, Right b) -> a == b _ -> recorded == computed-- | Upload a rendered narinfo (the server validates and signs it). The-- server checks a narinfo's FileSize and FileHash against the NAR it-- holds and refuses one whose NAR it does not hold, or holds otherwise,-- with 400. After a NAR's upload was not confirmed, a 400 is that-- refusal, so the NAR is uploaded again, while fewer than-- 'maxNarUploads' uploads of it have been begun, and the narinfo is-- sent after it.publishNarInfo :: Logger -> HTTP.Manager -> PushConfig -> PushSource -> StorePath -> NarInfo -> NarUpload -> ExceptT Text IO ()publishNarInfo logger manager cfg source sp narInfo upload = do let body = TE.encodeUtf8 (renderNarInfo narInfo) response <- httpRequest manager "PUT" (cacheUrl cfg object) (authHeaders cfg) (Just body) let status = HTTP.responseStatus response refused = describeResponse label response unless (status == HTTP.status200) $ case upload of NarUnconfirmed begun completion | status == HTTP.status400 && begun < maxNarUploads -> do logLine logger (retryTag <> refused <> "; uploading the NAR again") (resent, reupload) <- uploadNar logger manager cfg source begun sp publishNarInfo logger manager cfg source sp resent reupload | otherwise -> throwError (refused <> "; the NAR's last completion: " <> completion <> " (" <> countedUploads begun <> " begun)") NarStored -> throwError refused where object = narInfoFileName sp label = "PUT " <> object-- | Fetch a just-pushed narinfo back and require a signature on it.verifySignedRoundTrip :: Logger -> HTTP.Manager -> PushConfig -> StorePath -> ExceptT Text IO ()verifySignedRoundTrip logger manager cfg sp = do let object = narInfoFileName sp url = pcCacheUrl cfg <> "/" <> object response <- httpRequest manager "GET" url [] Nothing expectOk ("GET " <> object) response narInfo <- liftEither (either (Left . T.pack) Right (parseNarInfo (responseText response))) when (null (niSigs narInfo)) $ throwError ("round-trip check failed: " <> object <> " came back unsigned") logLine logger "[ok] round-trip verified, signature present"-- ----------------------------------------------------------------------------- Sending a NAR-- ----------------------------------------------------------------------------- | Whether the cache is known to hold a NAR once its upload ends.data NarUpload = -- | The cache answered the upload with 200. NarStored | -- | A multipart upload's completion was answered with something -- other than 200, or not at all, so the NAR may or may not be in -- place, and its narinfo decides. (uploads of the NAR begun so far, -- the completion's answer) NarUnconfirmed !Int !Text-- | An upload, by the id nova-cache issued for it: 'uploadIdDigits'-- lowercase hex digits, checked before the id goes into a request path.newtype UploadId = UploadId Text-- | The id in a response that begins an upload, or 'Nothing' for text-- that is not one nova-cache issues.parseUploadId :: Text -> Maybe UploadIdparseUploadId txt | T.length txt == uploadIdDigits && T.all isLowerHex txt = Just (UploadId txt) | otherwise = Nothing where isLowerHex c = isDigit c || (c >= 'a' && c <= 'f')-- | How the cache answered the request that begins an upload.data Begun = -- | 201, with the upload's id. Begun !UploadId | -- | 404: the cache has no multipart upload. NoMultipart-- | How the cache answered the parts of an upload sent so far.data PartsAnswer = -- | 200 to each: the cache holds them. PartsHeld | -- | 404 or 409 to the last: the cache no longer holds the parts -- before it, so the upload cannot be completed. (the answer) PartsLost !Text-- | Send a NAR's bytes to its object: in one @PUT@ when they fit in one-- part, in parts otherwise.sendNar :: Logger -> HTTP.Manager -> PushConfig -> Int -> Text -> BS.ByteString -> ExceptT Text IO NarUploadsendNar logger manager cfg begun object bytes | BS.length bytes <= partSizeBytes (pcPartSize cfg) = putWholeNar manager cfg object bytes | otherwise = uploadInParts logger manager cfg begun object bytes-- | Send a NAR's bytes in one @PUT@.putWholeNar :: HTTP.Manager -> PushConfig -> Text -> BS.ByteString -> ExceptT Text IO NarUploadputWholeNar manager cfg object bytes = do response <- httpRequest manager "PUT" (cacheUrl cfg object) (authHeaders cfg) (Just bytes) NarStored <$ expectOk ("PUT " <> object) response-- | Send a NAR's bytes through a multipart upload, given how many uploads-- of it this push has begun before: begin one, send the parts, and-- complete it. An upload whose parts the cache lost is begun again, up-- to 'maxNarUploads' in all.uploadInParts :: Logger -> HTTP.Manager -> PushConfig -> Int -> Text -> BS.ByteString -> ExceptT Text IO NarUploaduploadInParts logger manager cfg begun object bytes = do started <- beginUpload logger manager cfg uploads case started of NoMultipart -> do logLine logger (narTag <> "POST " <> uploads <> " returned HTTP 404, so the NAR goes in one request") putWholeNar manager cfg object bytes Begun (UploadId uploadId) -> do let upload = uploads <> "/" <> uploadId answer <- sendParts logger manager cfg upload parts case answer of PartsHeld -> completeUpload logger manager cfg (begun + 1) upload (length parts) (BS.length bytes) PartsLost lost | begun + 1 < maxNarUploads -> do logLine logger (retryTag <> lost <> "; beginning a new upload") uploadInParts logger manager cfg (begun + 1) object bytes | otherwise -> throwError (lost <> " (" <> countedUploads maxNarUploads <> " begun)") where uploads = object <> "/" <> uploadsSegment parts = splitParts (pcPartSize cfg) bytes-- | Begin an upload, again under the retry policy while the response is-- lost or is one a retry could outlive.beginUpload :: Logger -> HTTP.Manager -> PushConfig -> Text -> ExceptT Text IO BegunbeginUpload logger manager cfg uploads = retrying logger cfg (answer <$> tryRequest manager "POST" (cacheUrl cfg uploads) (authHeaders cfg) Nothing) where label = "POST " <> uploads answer (Left err) = Left (transportFailure label err) answer (Right response) | status == HTTP.status201 = maybe (Left (FatalFailure (label <> " answered with no upload id: " <> T.take errorBodyChars (responseText response)))) (Right . Begun) (parseUploadId (T.strip (responseText response))) | status == HTTP.status404 = Right NoMultipart | otherwise = Left (statusFailure label response) where status = HTTP.responseStatus response-- | Send the parts in order from part 1, stopping at the first the cache-- answers with 'PartsLost'.sendParts :: Logger -> HTTP.Manager -> PushConfig -> Text -> [BS.ByteString] -> ExceptT Text IO PartsAnswersendParts logger manager cfg upload = go . zip [1 :: Int ..] where go [] = pure PartsHeld go ((number, part) : rest) = do answer <- sendPart logger manager cfg (upload <> "/" <> T.pack (show number)) part case answer of PartsHeld -> go rest lost@(PartsLost _) -> pure lost-- | Send one part, again under the retry policy while the response is-- lost or is one a retry could outlive: the cache replaces a part it-- holds, so a part that did arrive is not doubled.sendPart :: Logger -> HTTP.Manager -> PushConfig -> Text -> BS.ByteString -> ExceptT Text IO PartsAnswersendPart logger manager cfg path part = retrying logger cfg (answer <$> tryRequest manager "PUT" (cacheUrl cfg path) (authHeaders cfg) (Just part)) where label = "PUT " <> path answer (Left err) = Left (transportFailure label err) answer (Right response) | status == HTTP.status200 = Right PartsHeld | status `elem` [HTTP.status404, HTTP.status409] = Right (PartsLost (describeResponse label response)) | otherwise = Left (statusFailure label response) where status = HTTP.responseStatus response-- | Complete an upload, declaring how many parts it holds and how many-- bytes they join to. Never sent again here: the server joins the whole-- NAR before it answers, so an answer other than 200, or none, leaves-- the NAR unconfirmed for its narinfo to decide, and fails nothing. The-- HTTP client itself sends a request once more when a connection it kept-- open turns out closed before any answer; a completion that arrives-- twice gets an error or joins the same parts, and the narinfo decides-- either way.completeUpload :: Logger -> HTTP.Manager -> PushConfig -> Int -> Text -> Int -> Int -> ExceptT Text IO NarUploadcompleteUpload logger manager cfg begun upload count size = do answer <- liftIO (tryRequest manager "POST" (cacheUrl cfg upload) (authHeaders cfg) (Just totals)) case answer of Right response | HTTP.responseStatus response == HTTP.status200 -> pure NarStored unconfirmed -> do let completion = either (attemptFailureMessage . transportFailure label) (describeResponse label) unconfirmed logLine logger (narTag <> completion <> "; the narinfo decides whether the NAR is stored") pure (NarUnconfirmed begun completion) where label = "POST " <> upload totals = TE.encodeUtf8 ( T.unlines [ partsField <> ": " <> T.pack (show count), fileSizeField <> ": " <> T.pack (show size) ] )-- ----------------------------------------------------------------------------- HTTP plumbing-- ----------------------------------------------------------------------------- | Issue an HTTP request with optional body. The body is read through-- 'withTransfer', so a connection lost mid-body is an-- 'HTTP.HttpException' like every other failure of the request, and that-- is the one exception caught.tryRequest :: HTTP.Manager -> BS.ByteString -> Text -> [(HTTP.HeaderName, BS.ByteString)] -> Maybe BS.ByteString -> IO (Either HTTP.HttpException (HTTP.Response BS.ByteString))tryRequest manager method url headers body = try $ do request0 <- HTTP.parseRequest (T.unpack url) let request = withUserAgent request0 { HTTP.method = method, HTTP.requestHeaders = headers, HTTP.requestBody = maybe (HTTP.requestBody request0) HTTP.RequestBodyBS body } withTransfer request manager $ \response -> do chunks <- HTTP.brConsume (HTTP.responseBody response) pure (BS.concat chunks <$ response)-- | 'tryRequest', with a failure of the request as a push error.httpRequest :: HTTP.Manager -> BS.ByteString -> Text -> [(HTTP.HeaderName, BS.ByteString)] -> Maybe BS.ByteString -> ExceptT Text IO (HTTP.Response BS.ByteString)httpRequest manager method url headers body = ExceptT (first failed <$> tryRequest manager method url headers body) where failed = attemptFailureMessage . exceptionFailure (\detail -> "HTTP error for " <> url <> ": " <> T.pack detail)-- | Run a request that is safe to send again under the push's retry-- policy: a 'TransientFailure' is sent again after upstream's backoff,-- which upstream's transfer layer applies to an upload as to a download-- (@TransferItem::finish@ in @filetransfer.cc@ at 2.24.9), and a-- 'FatalFailure', or the last attempt's failure, fails the push. A-- retry is announced to the logger.retrying :: Logger -> PushConfig -> IO (Either AttemptFailure a) -> ExceptT Text IO aretrying logger cfg attempt = ExceptT (first attemptFailureMessage <$> retryTransient (pcRetry cfg) (ioRetryEffects logger) attempt)-- | A response the protocol gives no meaning, as an attempt's failure:-- transient when it is an error upstream's transfer layer retries-- ('statusError'), fatal when it is any other error or no error at all.statusFailure :: Text -> HTTP.Response BS.ByteString -> AttemptFailurestatusFailure label response | not (HTTP.statusIsClientError status || HTTP.statusIsServerError status) = FatalFailure message | otherwise = case statusError status of Transient -> TransientFailure message NotFound -> FatalFailure message Forbidden -> FatalFailure message Misc -> FatalFailure message where status = HTTP.responseStatus response message = describeResponse label response-- | A request that got no response, as an attempt's failure, classified-- as upstream classifies a transfer's ('exceptionFailure'), with a-- message naming the request and the client's failure.transportFailure :: Text -> HTTP.HttpException -> AttemptFailuretransportFailure label = exceptionFailure (\detail -> label <> " failed: " <> T.pack detail)-- | A count of uploads with its noun.countedUploads :: Int -> TextcountedUploads 1 = "1 upload"countedUploads n = T.pack (show n) <> " uploads"-- | A response as an error: the request, the status, and the start of-- the server's message.describeResponse :: Text -> HTTP.Response BS.ByteString -> TextdescribeResponse label response = label <> " returned HTTP " <> T.pack (show (HTTP.statusCode (HTTP.responseStatus response))) <> ": " <> T.take errorBodyChars (responseText response)-- | The URL of a path under the cache.cacheUrl :: PushConfig -> Text -> TextcacheUrl cfg path = pcCacheUrl cfg <> "/" <> path-- | Authorization headers for authenticated writes.authHeaders :: PushConfig -> [(HTTP.HeaderName, BS.ByteString)]authHeaders cfg = case pcApiKey cfg of Nothing -> [] Just key -> [("Authorization", bearerPrefix <> TE.encodeUtf8 key)]-- | Require a 200 response, with a readable error otherwise.expectOk :: Text -> HTTP.Response BS.ByteString -> ExceptT Text IO ()expectOk label response = unless (HTTP.responseStatus response == HTTP.status200) $ throwError (describeResponse label response)-- | The response body as text, decoded leniently: an error body need not-- be UTF-8, and what the protocol answers otherwise is ASCII.responseText :: HTTP.Response BS.ByteString -> TextresponseText = TE.decodeUtf8With (\_ _ -> Just '\xFFFD') . HTTP.responseBody-- | Tell the logger a progress line.logLine :: Logger -> Text -> ExceptT Text IO ()logLine logger = liftIO . logMessage logger-- ----------------------------------------------------------------------------- Progress lines-- ----------------------------------------------------------------------------- | The tag of the line for paths a cache holds already.skipTag :: TextskipTag = "[skip] "-- | The tag of a NAR's lines.narTag :: TextnarTag = "[nar] "-- | The tag of the line for a path a cache now holds.pushTag :: TextpushTag = "[push] "-- | The tag of the line for a NAR upload the push begins again.retryTag :: TextretryTag = "[retry] "-- | Report how many paths of the closure the cache holds already, if any.logSkipped :: Logger -> Int -> ExceptT Text IO ()logSkipped logger skipped = when (skipped > 0) $ logLine logger (skipTag <> T.pack (show skipped) <> " path(s) already cached")-- | Report a path's NAR, packaged for the cache, with the NAR's size.logNar :: Logger -> StorePath -> PushArtifact -> ExceptT Text IO ()logNar logger sp artifact = logLine logger (narTag <> storePathBasename sp <> " (" <> T.pack (show (paNarSize artifact)) <> " bytes)")-- | Report a path whose narinfo the cache now holds.logPushed :: Logger -> StorePath -> ExceptT Text IO ()logPushed logger sp = logLine logger (pushTag <> storePathBasename sp)