packages feed

nova-nix-0.11.0.0 / src / Nix / Daemon / LocalStore.hs

{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE TupleSections #-}-- | The local store as a daemon serves it: each connection's-- t'DaemonStore' over the daemon's one open t'Store'.---- The daemon holds the store's lease for as long as it runs, so no-- collection starts while it serves ("Nix.Store.Handle").  Each-- connection reads the store's database through a connection of its-- own, which it closes as it ends, and keeps its own temporary roots,-- which a listing of roots shows with every other connection's and which-- go with it.---- Each operation builds and substitutes under the configuration its-- connection's settings give ("Nix.Builder.Settings"), on the defaults-- the daemon found for the machine as it started, and its store reports-- to the client: each message as a line at its level, and each build,-- check and substitution as an activity, as upstream's derivation and-- substitution goals start theirs ('storeActivity'), each line its-- builder writes a result of it.---- A client adds paths as upstream's daemon adds them for its clients: a-- dump made into the path its content address makes, and a NAR with what-- its path claims of itself, held to the signatures of the keys the-- connection trusts where the client's trust and @require-sigs@ say so-- ("Nix.Store.Import").  An upload is written to a staging directory as-- it arrives and moved to its path once it has been checked; what one-- holds between two of its chunks is released when it ends, or when the-- connection does.  Each path added, or found valid, is a temporary root-- of the connection, as upstream's store roots the paths it adds.---- What the store does not do through a daemon yet is refused, with the-- client told so: adding signatures, collecting garbage and repairing,-- and optimising and verifying the store, which nova-nix does not do at-- all.---- What the daemon tells a client names a path under @\/nix\/store@, the-- directory every store path is computed under, as the wire does,-- wherever the store keeps its files.module Nix.Daemon.LocalStore  ( ServedStore,    newServedStore,    serveLocal,  )whereimport Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_, newMVar, readMVar)import Control.Exception (Handler (..), IOException, bracket, catch, catches, displayException, finally, mask_, uninterruptibleMask_)import Control.Monad (filterM, join)import Data.Bifunctor (bimap, first)import Data.Bits (toIntegralSized)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport Data.Foldable (foldlM, traverse_)import Data.Functor ((<&>))import Data.IORef (IORef, atomicModifyIORef', newIORef)import Data.Int (Int64)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (catMaybes)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 Data.Word (Word64)import Database.SQLite.Simple (SQLError)import Nix.Builder (BuildConfig (..), BuildStop, buildRequests, buildRequestsEach, checkStored, planMissingPaths, readDrvFromStore, stopReported, substitutablePaths, substituteFromCaches)import Nix.Builder.Settings (MachineDefaults, settingsBuildConfig)import Nix.Config (NixConfig (..))import Nix.Daemon.Connection (ConnectionEnd, ServerConfig (..), Transport, serveConnection)import Nix.Daemon.Ops (CheckSigs (..), ClientSettings (..), ConnectionSettings (..), DaemonStore (..), DumpUpload (..), Intake (..), LogEvent (..), Repair (..), RootCensoring (..), Substitute (..), Work (..), daemonError, logVerbosity, storeActivity)import Nix.Daemon.Protocol  ( DaemonError,    OutputName (..),    Trust,    UnkeyedValidPathInfo (..),    ValidPathInfo (..),    grammarText,    narHashDigest,    narHashFromDigest,  )import qualified Nix.Daemon.Protocol as Protoimport Nix.Derivation (Derivation, DerivationOutput (..), drvOutputs, fromATerm)import Nix.HostPath (hostPathBytes)import Nix.Key (KeyRefusal (..), keyRefusalReason, parsePublicKey, trustedKeys, verifyingKey)import Nix.Logger (Level (..), Logger (..), logWarning)import Nix.Realise (ClosureOutcome (..), MissingPaths (..), OutputSelection (..), RequestOutcome (..), Wanted (..), realiseFailureMessage)import qualified Nix.Realise as Realiseimport Nix.Store (SignatureRequirement (..), Store (..), isValid)import Nix.Store.CaseSensitive (volumeCaseHack)import Nix.Store.DB (PathInfo (..), PathRegistration (..), Ultimate (..), closeStoreDB, openStoreDB, queryAllValidPaths, queryPathInfo, queryReferences, queryReferrers, queryValidDerivers, statedRegistrationTime)import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.GC (GcRoot (..), addIndirectRoot, findRoots)import Nix.Store.Import (NarImportStart (..), NarImportStep (..), abandonDumpAdd, abandonNarImport, admitNar, beginDumpAdd, beginNarImport, endDumpAdd, endNarImport, endedDumpPath, feedDumpAdd, feedNarImport, placeDump)import Nix.Store.Path (StorePath (spName), defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)import NovaCache.Hash (NixHash (..), formatNixHash, parseNixHash)import qualified System.OsPath as OP-- ----------------------------------------------------------------------------- The store-- ----------------------------------------------------------------------------- | The store a daemon serves, the machine's defaults its builds fall-- back on, every connection's temporary roots, by the connection's-- number, and the number the next activity of any connection takes.data ServedStore = ServedStore  { ssStore :: !Store,    ssDefaults :: !MachineDefaults,    ssTempRoots :: !(MVar (Map Int (Set StorePath))),    ssNextConnection :: !(MVar Int),    ssNextActivity :: !(IORef Word64)  }-- | Serve an open store, which the caller keeps open for as long as it-- serves, its builds on the machine defaults given.newServedStore :: MachineDefaults -> Store -> IO ServedStorenewServedStore defaults store = ServedStore store defaults <$> newMVar Map.empty <*> newMVar 0 <*> newIORef firstActivity-- | The number of the daemon's first activity: 0 is an activity's parent-- when it has none.firstActivity :: Word64firstActivity = 1-- | Serve one connection over the store, its temporary roots dropped and-- its database connection closed as it ends.serveLocal :: ServedStore -> ServerConfig -> Trust -> Transport IO -> IO ConnectionEndserveLocal served config trust transport =  bracket (openStoreDB (stDir (ssStore served))) closeStoreDB $ \db ->    bracket register release $ \(number, hold) ->      serveConnection config trust (connectionStore served (scConfig config) (ssStore served) {stDB = db} number hold) transport  where    register = do      number <- modifyMVar (ssNextConnection served) (\next -> pure (next + 1, next))      hold <- UploadHold <$> newIORef (pure ())      (number, hold) <$ modifyMVar_ (ssTempRoots served) (pure . Map.insert number Set.empty)    -- The release cannot be cut short: a hangup the watcher sees as the    -- connection ends would otherwise leave the connection's roots held,    -- or an upload's staging behind.    release (number, hold) = uninterruptibleMask_ (releaseUpload hold `finally` modifyMVar_ (ssTempRoots served) (pure . Map.delete number))-- ----------------------------------------------------------------------------- Uploads-- ----------------------------------------------------------------------------- | What the upload a connection is taking in holds between two of its-- chunks, as the action that releases it.  The store gives an upload up-- itself when it fails or ends; the connection, which can be stopped-- between two chunks, as a client that hangs up stops it, releases what-- is held as it ends.  Releasing twice is harmless, since giving up an-- upload never touches a store path ("Nix.Store.Import").newtype UploadHold = UploadHold (IORef (IO ()))-- | Hold what an upload begun holds, given what releases it, releasing-- what an earlier upload still held.  It is called with asynchronous-- exceptions masked around the upload's beginning, so nothing begun goes-- unheld.holdUpload :: UploadHold -> IO () -> IO ()holdUpload (UploadHold cell) release = uninterruptibleMask_ (join (atomicModifyIORef' cell (release,)))-- | Release what the connection's upload holds, if anything, and hold-- nothing after.  The release is taken and run with asynchronous-- exceptions held off, so none comes between the two or cuts the release-- short, leaving what it removes behind.releaseUpload :: UploadHold -> IO ()releaseUpload (UploadHold cell) = uninterruptibleMask_ (join (atomicModifyIORef' cell (pure (),)))-- ----------------------------------------------------------------------------- One connection's view-- ----------------------------------------------------------------------------- | The store as one connection sees it, under the daemon's settings-- given, reading through its own handle on the database.connectionStore :: ServedStore -> NixConfig -> Store -> Int -> UploadHold -> DaemonStore IOconnectionStore served daemonConfig store number hold =  DaemonStore    { dsIsValidPath = \_ path -> reading (isValid store path),      dsQueryValidPaths = queryValid . working,      dsQuerySubstitutablePaths = \w paths -> let Working config opStore = working w in (>>= first daemonError) <$> reading (substitutablePaths config opStore (Set.toAscList paths)),      dsQueryReferrers = \_ path -> (>>= storePaths) <$> reading (queryReferrers (stDB store) path),      dsQueryValidDerivers = \_ path -> (>>= storePaths) <$> reading (queryValidDerivers (stDB store) path),      dsQueryDerivationOutputMap = \_ path -> outputMap path,      dsQueryAllValidPaths = \_ -> (>>= storePaths) <$> reading (queryAllValidPaths (stDB store)),      dsQueryPathInfo = \_ path -> pathInfo path,      dsQueryMissing = \w targets -> let Working config opStore = working w in (>>= bimap daemonError protocolMissing) <$> reading (planMissingPaths config opStore (map wantedFor targets)),      dsAddToStore = addDump . reporting,      dsAddToStoreNar = \w -> addNar (storeSettings daemonConfig (workSettings w)) (reporting w),      dsBuildPaths = buildPaths . working,      dsBuildPathsWithResults = buildPathsWithResults . working,      dsEnsurePath = \w path -> addTempRoot path >>= either (pure . Left) (const (ensurePath (working w) path)),      dsAddTempRoot = \_ path -> addTempRoot path,      dsAddIndirectRoot = \_ link -> reading (addIndirectRoot store link),      dsFindRoots = \_ censoring -> roots censoring,      dsCollectGarbage = \_ _ -> pure (Left (daemonError "the nova-nix daemon does not collect garbage yet")),      dsOptimiseStore = \_ -> pure (Left (daemonError "optimising the store is not available in nova-nix")),      dsVerifyStore = \_ _ _ -> pure (Left (daemonError "verifying the store is not available in nova-nix")),      dsAddSignatures = \_ _ _ -> pure (Left (daemonError "the nova-nix daemon does not add signatures yet")),      dsNarFromPath = narFromPath    }  where    addTempRoot path = reading (modifyMVar_ (ssTempRoots served) (pure . Map.adjust (Set.insert path) number))    working = operationStore served daemonConfig store    pathInfo path =      reading ((,) <$> queryPathInfo (stDB store) path <*> queryReferences (stDB store) path) >>= \case        Left err -> pure (Left err)        Right (Nothing, _) -> pure (Right Nothing)        Right (Just info, references) -> pure (Just <$> protocolInfo store info references)    outputMap drvPath =      reading (isValid store drvPath) >>= \case        Left err -> pure (Left err)        Right False -> pure (Left (notValid drvPath))        Right True ->          reading (BS.readFile (storePathToFilePath (stDir store) drvPath)) >>= \case            Left err -> pure (Left err)            Right aterm -> pure $ case fromATerm aterm of              Left refusal -> Left (daemonError refusal)              Right drv -> Right (Map.fromList [(OutputName (doName output), Just (doPath output)) | output <- drvOutputs drv])    roots censoring =      reading (findRoots store >>= traverse rootLink) >>= \case        Left err -> pure (Left err)        Right links -> do          held <- readMVar (ssTempRoots served)          let temporary = [Right (path, tempRootName censoring holder) | (holder, paths) <- Map.toList held, path <- Set.toList paths]          pure ((\pairs -> Map.fromListWith Set.union [(path, Set.singleton link) | (path, link) <- pairs]) <$> sequence (links ++ temporary))    rootLink root = do      spelled <- hostPathBytes <$> OP.encodeFS (grLink root)      pure ((,) <$> storePath (grPath root) <*> maybe (Left (daemonError ("cannot spell the root '" <> T.pack (grLink root) <> "' as bytes"))) Right spelled)    narFromPath path sink =      reading (isValid store path) >>= \case        Left err -> pure (Left err)        Right False -> pure (Left (notValid path))        Right True -> reading (ExecBit.withNarSource (volumeCaseHack (stCaseSensitivity store)) (storePathToFilePath (stDir store) path) (pump sink))    pump sink pull =      pull >>= \chunk ->        if BS.null chunk then pure () else sink chunk >> pump sink pull    storePaths = fmap Set.fromList . traverse storePath    storePath spelled = maybe (Left (daemonError ("the store's database names '" <> spelled <> "', which is not a path in it"))) Right (parseStorePath (stDir store) spelled)    -- Upstream's refusal of a path that is not valid.    notValid path = daemonError ("path '" <> storePathToText defaultStoreDir path <> "' is not valid")    -- The store as an add uses it, telling the client what it says.    reporting w = let Working _ opStore = working w in opStore    -- A NAR with what its path claims of itself, as upstream's store adds    -- one: admitted by its signatures or its content address, its path a    -- temporary root, a path already valid not read, and another    -- imported from its NAR as it arrives.    addNar config opStore (ValidPathInfo path info) repair checkSigs = case repair of      Repair -> pure (Taken (Left repairingRefusal))      NoRepair ->        signatureRequirement config checkSigs >>= \required -> case (,) <$> required <*> registrationClaim store path info of          Left err -> pure (Taken (Left err))          Right (requirement, claim) ->            refusedOr (admitNar opStore requirement claim) $ \admitted ->              addTempRoot path >>= \case                Left err -> pure (Taken (Left err))                Right () ->                  beginHeld (beginNarImport admitted) heldImport >>= \case                    Left err -> pure (Taken (Left err))                    Right NarAlreadyValid -> pure (Taken (Right ()))                    Right (NarImportBegun begun) -> pure (importing begun)    heldImport = \case      NarImportBegun begun -> holdUpload hold (abandonNarImport begun)      NarAlreadyValid -> pure ()    importing begun = Taking (feedImport begun) (ending (refusedValue (endNarImport begun) (pure . Right))) (abandoning (abandonNarImport begun))    feedImport begun chunk =      reading (feedNarImport begun chunk) >>= \case        Left err -> settled (Left err)        Right (Left refusal) -> settled (Left (daemonError refusal))        Right (Right (NarImportGoesOn next)) -> pure (importing next)        Right (Right NarImported) -> settled (Right ())    -- A dump made into the path its content address makes, as upstream's    -- store adds one: written as it arrives, then, once it ends, its path    -- a temporary root and the path made valid from it unless it is    -- already, and the path's info answered.    addDump opStore upload = case duRepair upload of      Repair -> pure (Taken (Left repairingRefusal))      NoRepair ->        beginHeld (beginDumpAdd opStore (grammarText (duName upload)) (duMethod upload) (duAlgo upload) (duReferences upload)) (traverse_ (holdUpload hold . abandonDumpAdd)) >>= \case          Left err -> pure (Taken (Left err))          Right (Left refusal) -> pure (Taken (Left (daemonError refusal)))          Right (Right add) -> pure (dumping add)    dumping add = Taking (feedDump add) (ending (endDump add)) (abandoning (abandonDumpAdd add))    feedDump add chunk =      reading (feedDumpAdd add chunk) >>= \case        Left err -> settled (Left err)        Right (Left refusal) -> settled (Left (daemonError refusal))        Right (Right next) -> pure (dumping next)    endDump add =      refusedValue (endDumpAdd add) $ \ended ->        let path = endedDumpPath ended         in addTempRoot path >>= \case              Left err -> pure (Left err)              Right () -> refusedValue (placeDump ended) $ \() -> fmap (ValidPathInfo path) <$> (pathInfo path <&> (>>= maybe (Left (notValid path)) Right))    -- A store call's refusal as the client is sent it, or what follows    -- from its value; a failure to read the disk or the database is sent    -- as the error it is.    refusedOr call continue =      reading call >>= \case        Left err -> pure (Taken (Left err))        Right (Left refusal) -> pure (Taken (Left (daemonError refusal)))        Right (Right value) -> continue value    refusedValue call continue =      reading call >>= \case        Left err -> pure (Left err)        Right (Left refusal) -> pure (Left (daemonError refusal))        Right (Right value) -> continue value    -- Begin an upload with what it then holds held, no exception coming    -- between the two.    beginHeld begin holding = mask_ (reading begin >>= \begun -> begun <$ traverse_ holding begun)    -- An upload that has ended, its store having given up what it held.    settled outcome = Taken outcome <$ releaseUpload hold    ending end = end <* releaseUpload hold    abandoning abandon = abandon >> releaseUpload hold-- ----------------------------------------------------------------------------- An operation's store-- ----------------------------------------------------------------------------- | What an operation builds and substitutes under, and the store it does-- so in.data Working = Working !BuildConfig !Store-- | The store as an operation uses it: reporting to the client, and-- building under the configuration the connection's settings give-- ('storeSettings'), with no cache when the client said not to-- substitute, as upstream's worker has none then.operationStore :: ServedStore -> NixConfig -> Store -> Work IO -> WorkingoperationStore served daemonConfig store w = Working config store {stLogger = tunnelLogger served (workReport w)}  where    settings = workSettings w    configured = settingsBuildConfig (ssDefaults served) (storeSettings daemonConfig settings) (stDir store)    config      | maybe True csUseSubstitutes (connClient settings) = configured      | otherwise = configured {bcCaches = []}-- | The settings a connection's store works under, given the daemon's:-- the connection's, with the daemon's own @require-sigs@.  Upstream's-- store reads that setting as it opens, before a client's settings-- arrive, so a trusted client that sets it changes nothing.storeSettings :: NixConfig -> ConnectionSettings -> NixConfigstoreSettings daemonConfig settings = (connConfig settings) {ncRequireSigs = ncRequireSigs daemonConfig}-- | A logger that reports to a client: a message as a line at its level,-- and an activity under a number no other activity of the daemon has,-- each line its builder writes a result of it.  A line outside any-- activity goes as an info-level line.  A report the client cannot be-- sent is dropped, as a logger drops a line it cannot deliver and as-- upstream's daemon stops sending to a client that has gone, so the work-- for a client that hung up stops for the hangup rather than going on-- past a failed write.tunnelLogger :: ServedStore -> (LogEvent -> IO ()) -> LoggertunnelLogger served send =  Logger    { logAt = \level -> report . LogLine (logVerbosity level) . TE.encodeUtf8,      logBuildLine = report . LogLine (logVerbosity LevelInfo),      logActivity = \start -> do        activity <- atomicModifyIORef' (ssNextActivity served) (\next -> (next + 1, Proto.ActivityId next))        report (ActivityStarted (storeActivity defaultStoreDir activity start))        pure (report . ActivityResult activity Proto.resBuildLogLine . pure . Proto.FieldString, report (ActivityStopped activity))    }  where    report event = send event `catch` \(_ :: IOException) -> pure ()-- ----------------------------------------------------------------------------- Building and substituting-- ----------------------------------------------------------------------------- | The valid paths among those asked, after substituting those a cache-- offers when asked to, as upstream's daemon substitutes them: what-- realising them would take is worked out first, a derivation's own-- path left out, and a substitution that fails is a warning.queryValid :: Working -> Substitute -> Set StorePath -> IO (Either DaemonError (Set StorePath))queryValid (Working config store) substitute paths = case substitute of  NoSubstitute -> valid  Substitute ->    reading (planMissingPaths config store [WantedPath path | path <- Set.toAscList paths, not (".drv" `T.isSuffixOf` spName path)]) >>= \case      Left err -> pure (Left err)      Right (Left why) -> pure (Left (daemonError why))      Right (Right plan) -> traverse_ substituteOne (Set.toAscList (mpSubstitute plan)) *> valid  where    valid = fmap Set.fromList <$> reading (filterM (isValid store) (Set.toAscList paths))    substituteOne path =      reading (substituteFromCaches config store [path]) >>= \case        Right ClosureComplete -> pure ()        _ -> logWarning (stLogger store) (requiredMessage path)-- | Make a path valid: one that is already valid is, and another is-- substituted with what it references, or fails in upstream's words.ensurePath :: Working -> StorePath -> IO (Either DaemonError ())ensurePath working path = (>>= either (Left . daemonError . snd) (const (Right ()))) <$> pathOutcome working path-- | How making a path valid ends, as upstream's goal for substituting it-- ends: valid already, or substituted; or failed, with the kind of-- failure and upstream's message, no cache holding the path or something-- it references.  A cache that cannot be asked ends the whole call, as-- upstream's goal throws then.pathOutcome :: Working -> StorePath -> IO (Either DaemonError (Either (Proto.FailureStatus, Text) Proto.SuccessStatus))pathOutcome (Working config store) path =  reading (isValid store path) >>= \case    Left err -> pure (Left err)    Right True -> pure (Right (Right Proto.AlreadyValid))    Right False ->      reading (substituteFromCaches config store [path]) <&> \case        Left err -> Left err        Right ClosureComplete -> Right (Right Proto.Substituted)        Right (ClosureQueryFailed why) -> Left (daemonError why)        Right ClosureIncomplete -> Right (Left (Proto.DependencyFailed, "some references of path '" <> spelled <> "' could not be realised"))        Right ClosureUnavailable -> Right (Left (Proto.NoSubstituters, requiredMessage path))        Right ClosureFailed -> Right (Left (Proto.NoSubstituters, requiredMessage path))  where    spelled = storePathToText defaultStoreDir path-- | Upstream's report of a path no cache could substitute.requiredMessage :: StorePath -> TextrequiredMessage path = "path '" <> storePathToText defaultStoreDir path <> "' is required, but there is no substituter that can build it"-- | Realise derived paths as upstream's daemon builds them: each store-- path as it is made valid ('ensurePath'), and the outputs of each-- derivation asked for built, or under 'Proto.BuildCheck' checked.  The-- first failure stops the call with the status the build gives, and a-- derivation that cannot be obtained stops it before anything is done.buildPaths :: Working -> [Proto.DerivedPath] -> Proto.BuildMode -> IO (Either DaemonError ())buildPaths working@(Working config store) targets = \case  Proto.BuildRepair -> pure (Left repairingRefusal)  Proto.BuildNormal -> realised (\requests -> (>>= stopped) <$> reading (buildRequests config store requests))  Proto.BuildCheck -> realised (foldlM (\done (drvPath, _) -> either (pure . Left) (const ((>>= stopped) <$> reading (checkStored config store drvPath))) done) (Right ()))  where    realised build =      requestsFor working targets >>= \case        Left err -> pure (Left err)        Right (Requested _ _ _ (unobtained : _)) -> pure (Left (daemonError (unobtainedMessage unobtained)))        Right (Requested opaque requests _ []) ->          foldlM (\done path -> either (pure . Left) (const (ensurePath working path)) done) (Right ()) opaque >>= either (pure . Left) (const (build requests))    stopped = \case      Left stop -> Left (stoppedWith stop)      Right () -> Right ()-- | Realise derived paths as 'buildPaths' does, and say how each ended,-- in the order asked, leaving out one left unrealised when another failed-- as upstream leaves out a goal that never finished.  A derivation that-- cannot be obtained fails its request, and nothing else is realised, as-- upstream's worker stops once a requested goal fails.buildPathsWithResults :: Working -> [Proto.DerivedPath] -> Proto.BuildMode -> IO (Either DaemonError [Proto.KeyedBuildResult])buildPathsWithResults working@(Working config store) targets mode = case mode of  Proto.BuildRepair -> pure (Left repairingRefusal)  Proto.BuildNormal -> realised Realise.BuildNormal  Proto.BuildCheck -> realised Realise.BuildCheck  where    realised realiseMode =      requestsFor working targets >>= \case        Left err -> pure (Left err)        Right (Requested _ _ _ unobtained@(_ : _)) ->          pure (Right [Proto.KeyedBuildResult target (failedAs Proto.DependencyFailed (TE.encodeUtf8 (unobtainedMessage drvPath))) | target@(Proto.DerivedBuilt drvPath _) <- targets, drvPath `elem` unobtained])        Right (Requested opaque requests derivations []) -> do          ensuring <- traverse (\path -> fmap (path,) <$> pathOutcome working path) opaque          case Map.fromList <$> sequence ensuring of            Left err -> pure (Left err)            Right ensured -> (>>= either stoppedCall (Right . keyedResults derivations ensured)) <$> reading (buildRequestsEach config realiseMode store requests)    stoppedCall = Left . stoppedWith    keyedResults derivations ensured outcomes = [Proto.KeyedBuildResult target result | target <- targets, Just result <- [resultFor derivations ensured outcomes target]]    resultFor derivations ensured outcomes = \case      Proto.DerivedOpaque path -> either (\(status, message) -> failedAs status (TE.encodeUtf8 message)) (`succeededWith` Map.empty) <$> Map.lookup path ensured      Proto.DerivedBuilt drvPath spec -> outcomeResult drvPath (Map.lookup drvPath derivations) spec <$> Map.lookup drvPath outcomes    outcomeResult drvPath drv spec = \case      RequestRealised Realise.AlreadyValid -> succeededWith Proto.AlreadyValid outputs      RequestRealised Realise.Substituted -> succeededWith Proto.Substituted outputs      RequestRealised Realise.Built -> (succeededWith Proto.Built outputs) {Proto.brTimesBuilt = 1}      RequestRealised Realise.Checked -> (succeededWith Proto.Built outputs) {Proto.brTimesBuilt = 1}      RequestFailed failure -> failedAs (failureKind failure) (TE.encodeUtf8 (realiseFailureMessage (stDir store) failure))      RequestDependencyFailed _ _ -> failedAs Proto.DependencyFailed (TE.encodeUtf8 (dependencyFailedMessage drvPath drv))      where        outputs = foldMap (realisations spec) drv    failedAs status message = noTimes (Proto.Failed (Proto.Failure status message False))    succeededWith status outputs = noTimes (Proto.Succeeded (Proto.Success status outputs))    noTimes outcome = Proto.BuildResult outcome 0 0 0 Nothing Nothing    -- The outputs a target asks of a derivation, each where the    -- derivation puts it.    realisations spec drv =      Map.fromList        [ (OutputName (doName output), Proto.UnkeyedRealisation (doPath output) Set.empty)        | output <- drvOutputs drv,          maybe True (Set.member (OutputName (doName output))) (Proto.outputsSpecNames spec)        ]-- | Upstream's report of a derivation not built because one it needs-- failed, with the paths of its outputs.dependencyFailedMessage :: StorePath -> Maybe Derivation -> TextdependencyFailedMessage drvPath drv =  "Cannot build '" <> spelled drvPath <> "'.\nReason: 1 dependency failed." <> foldMap outputPaths drv  where    spelled = storePathToText defaultStoreDir    outputPaths built = case Set.toAscList (Set.fromList (map doPath (drvOutputs built))) of      [] -> ""      paths -> "\nOutput paths:" <> foldMap (("\n  " <>) . spelled) paths-- | The error a stopped build is sent as, with the status it exits with.stoppedWith :: BuildStop -> DaemonErrorstoppedWith stop = (daemonError message) {Proto.errExitStatus = fromIntegral status}  where    (message, status) = stopReported stop-- | Which of upstream's kinds of failure a realisation's failure is.failureKind :: Realise.RealiseFailure -> Proto.FailureStatusfailureKind = \case  Realise.BuildFailed _ -> Proto.PermanentFailure  Realise.FixedOutputRejected _ -> Proto.OutputRejected  Realise.NotDeterministic {} -> Proto.NotDeterministic  Realise.SubstitutesFailed _ -> Proto.TransientFailure  Realise.CacheQueryFailed _ -> Proto.MiscFailure  Realise.InvalidDerivation _ -> Proto.MiscFailure  Realise.OutputsNotValid _ -> Proto.MiscFailure  Realise.MissingDerivation _ -> Proto.MiscFailure  Realise.MissingOutputs _ _ -> Proto.MiscFailure-- | What realising some derived paths asks for: the store paths to make-- valid, each derivation with the outputs asked of it, each derivation as-- the store holds it, and the derivations that could not be obtained.data Requested = Requested ![StorePath] ![(StorePath, Set Text)] !(Map StorePath Derivation) ![StorePath]-- | One derived path as realising it asks for it.data RequestedPath  = OpaqueTarget !StorePath  | DerivationTarget !StorePath !(Set Text) !Derivation  | UnobtainedTarget !StorePath-- | The derived paths as what realising them asks for.  A derivation the-- store does not hold is substituted first, as upstream's goal obtains-- one before it builds it, and one no cache gives is not obtained; one-- it holds is read, which names every output where all are asked for.requestsFor :: Working -> [Proto.DerivedPath] -> IO (Either DaemonError Requested)requestsFor working@(Working config _) targets = fmap gather . sequence <$> traverse request targets  where    request = \case      Proto.DerivedOpaque path -> pure (Right (OpaqueTarget path))      Proto.DerivedBuilt drvPath spec ->        pathOutcome working drvPath >>= \case          Left err -> pure (Left err)          Right (Left _) -> pure (Right (UnobtainedTarget drvPath))          Right (Right _) -> bimap daemonError (\drv -> DerivationTarget drvPath (outputsAsked spec drv) drv) <$> readDrvFromStore config drvPath    outputsAsked spec drv = maybe (Set.fromList (map doName (drvOutputs drv))) (Set.map outputNameText) (Proto.outputsSpecNames spec)    gather chosen =      Requested        [path | OpaqueTarget path <- chosen]        [(drvPath, names) | DerivationTarget drvPath names _ <- chosen]        (Map.fromList [(drvPath, drv) | DerivationTarget drvPath _ drv <- chosen])        [drvPath | UnobtainedTarget drvPath <- chosen]-- | Upstream's report of a derivation it could not obtain to build.unobtainedMessage :: StorePath -> TextunobtainedMessage drvPath = "failed to obtain derivation of '" <> storePathToText defaultStoreDir drvPath <> "'"-- | What realising a derived path asks for, as the planner takes it.wantedFor :: Proto.DerivedPath -> WantedwantedFor = \case  Proto.DerivedOpaque path -> WantedPath path  Proto.DerivedBuilt drvPath spec -> WantedOutputs drvPath (maybe EveryOutput (TheseOutputs . Set.map outputNameText) (Proto.outputsSpecNames spec))-- | An output's name as text.outputNameText :: OutputName -> TextoutputNameText (OutputName name) = name-- | What realising some paths would take, as the protocol says it.protocolMissing :: MissingPaths -> Proto.MissingprotocolMissing plan = Proto.Missing (mpBuild plan) (mpSubstitute plan) (mpUnknown plan) (mpDownloadSize plan) (mpNarSize plan)-- | How a connection's temporary root is listed: by the connection that-- holds it, where upstream names the process that holds one, which for-- its daemon is the connection's worker.tempRootName :: RootCensoring -> Int -> ByteStringtempRootName censoring holder = case censoring of  CensorRoots -> "{censored}"  ShowRoots -> "{temp:" <> TE.encodeUtf8 (T.pack (show holder)) <> "}"-- | A path's info from the store's database, in the protocol's terms.protocolInfo :: Store -> PathInfo -> [Text] -> Either DaemonError UnkeyedValidPathInfoprotocolInfo store info references = do  deriver <- traverse spelledPath (piDeriver info)  refs <- traverse spelledPath references  narHash <- either (const (Left (corrupt "its NAR hash"))) Right (parseNixHash (piNarHash info)) >>= \(NixHash digest) -> maybe (Left (corrupt "its NAR hash")) Right (narHashFromDigest digest)  pure    UnkeyedValidPathInfo      { upiDeriver = deriver,        upiNarHash = narHash,        upiReferences = Set.fromList refs,        upiRegistrationTime = fromIntegral (piRegTime info) :: Int64,        upiNarSize = fromIntegral (piNarSize info),        upiUltimate = piUltimate info == Ultimate,        upiSignatures = piSignatures info,        upiContentAddress = piContentAddress info      }  where    spelledPath spelled = maybe (Left (corrupt ("'" <> spelled <> "'"))) Right (parseStorePath (stDir store) spelled)    corrupt what = daemonError ("the store's database holds an entry for '" <> piPath info <> "' whose " <> what <> " cannot be read")-- ----------------------------------------------------------------------------- Failures-- ----------------------------------------------------------------------------- | Run a read of the store, its failure to read the disk or the-- database an error the client is sent.reading :: IO a -> IO (Either DaemonError a)reading action =  (Right <$> action)    `catches` [ Handler (\(err :: IOException) -> pure (Left (daemonError (T.pack (displayException err))))),                Handler (\(err :: SQLError) -> pure (Left (daemonError (T.pack (displayException err)))))              ]-- | What the daemon does not do yet.repairingRefusal :: DaemonErrorrepairingRefusal = daemonError "repairing is not available in nova-nix"-- ----------------------------------------------------------------------------- Adding paths-- ----------------------------------------------------------------------------- | What an import holds its path to, as upstream's store holds a path it-- is handed a NAR for: the signatures of the keys the connection trusts-- ('trustedKeys'), unless the client may and does ask that they not be-- checked ('Nix.Daemon.Ops.authorize' has held an untrusted client to-- them) or @require-sigs@ is off, when no key is read.  A key that does-- not read is refused in upstream's words, whatever the path, as-- upstream reads every trusted key before it counts a path's-- signatures.signatureRequirement :: NixConfig -> CheckSigs -> IO (Either DaemonError SignatureRequirement)signatureRequirement config = \case  NoCheckSigs -> pure (Right SignaturesNotRequired)  CheckSigs    | not (ncRequireSigs config) -> pure (Right SignaturesNotRequired)    | otherwise -> case traverse trustedKey (ncTrustedPublicKeys config) of        Left err -> pure (Left err)        Right given -> bimap (keyRefusal SecretKeyFile) RequireSignature <$> trustedKeys (catMaybes given) (ncSecretKeyFiles config)  where    trustedKey spelled = bimap (keyRefusal (TrustedKeySpelled spelled)) verifyingKey (parsePublicKey (TE.encodeUtf8 spelled))-- | Where a key that does not read was found: spelled in-- @trusted-public-keys@, or in a file @secret-key-files@ names.data KeySource = TrustedKeySpelled !Text | SecretKeyFile-- | Upstream's refusal of a key that does not read: one that is not a-- name, a colon and base64 with the trace upstream adds as it decodes a-- key, which names the key it has not yet read, so the name is always-- empty, and shows a public key's spelling but never a secret one's; and-- one of the wrong size on its own.keyRefusal :: KeySource -> KeyRefusal -> DaemonErrorkeyRefusal source refusal = case refusal of  KeyUnreadable _ -> (daemonError (keyRefusalReason refusal)) {Proto.errTraces = ["while decoding key named ''" <> rawValue]}  SecretKeyNotValid -> daemonError (keyRefusalReason refusal)  PublicKeyNotValid -> daemonError (keyRefusalReason refusal)  where    rawValue = case source of      TrustedKeySpelled spelled -> " with raw value '" <> TE.encodeUtf8 spelled <> "'"      SecretKeyFile -> ""-- | What a path an upload names claims of itself, as the store registers-- it: its deriver spelled as the database spells a path.  A NAR size this-- platform cannot count to is refused before anything is read.registrationClaim :: Store -> StorePath -> UnkeyedValidPathInfo -> Either DaemonError PathRegistrationregistrationClaim store path info = case toIntegralSized (upiNarSize info) of  Nothing -> Left (daemonError ("cannot add path '" <> storePathToText defaultStoreDir path <> "': its NAR size " <> T.pack (show (upiNarSize info)) <> " is more than this platform can count"))  Just size ->    Right      PathRegistration        { prPath = path,          prNarHash = formatNixHash (NixHash (narHashDigest (upiNarHash info))),          prNarSize = size,          prDeriver = T.pack . storePathToFilePath (stDir store) <$> upiDeriver info,          prReferences = Set.toAscList (upiReferences info),          prUltimate = if upiUltimate info then Ultimate else NotUltimate,          prSignatures = upiSignatures info,          prContentAddress = upiContentAddress info,          prRegistrationTime = statedRegistrationTime (upiRegistrationTime info)        }