packages feed

nova-nix-0.11.0.0 / test / Test / DaemonStore.hs

{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE TupleSections #-}-- | Tests of a command's store through a daemon ("Nix.Daemon.ClientStore"):-- the order derivations are added in, the spellings an add is sent in, the-- settings a client sends and the words a failure is reported in; the-- store's operations against a daemon in memory that records what it is-- sent, and how its connection fails and is replaced; the connection a-- socket makes, or on Windows a named pipe; and evaluation and adds-- against a daemon serving a store of its own.module Test.DaemonStore  ( testDaemonStore,    testDaemonStoreIO,  )whereimport Control.Concurrent.Async (async, asyncThreadId, wait)import Control.Concurrent.Chan (newChan, writeChan)import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)import Control.Exception (AsyncException (UserInterrupt), ErrorCall (..), IOException, bracket, displayException, finally, throwIO, try)import Control.Monad (void, when)import Control.Monad.Except (ExceptT (..), runExceptT)import Control.Monad.IO.Class (liftIO)import Data.Bifunctor (bimap, first)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Builder as BBimport qualified Data.ByteString.Char8 as BS8import qualified Data.ByteString.Lazy as BLimport Data.Either (isRight)import Data.Foldable (traverse_)import Data.Functor (($>))import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)import Data.List (find, nub, sort)import qualified Data.Map.Strict as Mapimport Data.Maybe (mapMaybe)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 HttpFixture (Reply (..), httpResponse, withHttpServer)import Network.Socket (Family (AF_UNIX), SockAddr (SockAddrUnix), SocketType (Stream), accept, bind, close, defaultProtocol, listen, socket)import Network.Socket.ByteString (recv, sendAll)import Nix.Builder (BuildStop (..), defaultBuildConfig)import Nix.Builder.BuildUser (ProcessPrivilege (..))import Nix.Builder.Sandbox (SandboxMode (..))import Nix.Builder.Settings (MachineDefaults (..))import Nix.CacheDirectory (cacheInfoFileName, cacheInfoText, directoryUrl)import Nix.Config (AssignedSettings (..), DefaultUse (..), HowAssigned (..), NixConfig (..), PathSetValue (..), defaultNixConfig)import qualified Nix.Daemon.Client as Clientimport Nix.Daemon.ClientStore  ( Connector,    DaemonAddress (..),    DaemonOpFailure (..),    DaemonStoreConfig (..),    clientSettings,    connectFailureText,    daemonAddressPath,    daemonOperation,    daemonStoreName,    derivationAddOrder,    dialDaemon,    evalWriteRequest,    flatMethod,    narMethod,    opFailureText,    openFailureText,    previouslyFailedText,    textMethod,    withDaemonFixedOutputs,    withDaemonPushSource,    withDaemonSession,    withDaemonStore,  )import qualified Nix.Daemon.Connection as Connimport Nix.Daemon.Dial (closeDaemonConnection, connectDaemon, connectionTransport)import qualified Nix.Daemon.Listen as Listenimport Nix.Daemon.LocalStore (newServedStore, serveLocal)import qualified Nix.Daemon.Ops as Opsimport qualified Nix.Daemon.Protocol as Protoimport Nix.DependencyGraph (DepNode (..))import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform (..), currentPlatform, drvFile, drvFileATerm, drvFileDerivation, drvFilePath, inputAddressed, toATerm)import Nix.Eval (NixValue (..), unrestrictedPolicy)import Nix.Eval.IO (EvalState (..), SessionStore (..), newEvalStateWith, sourceCopies)import Nix.Hash (FileIngestionMethod (..), bytesToHexText, makeFixedOutputPath, makeSourcePath, makeTextPath, sha256Digest)import Nix.Logger (ActivityStart (..), Logger, plainLogger)import Nix.Push (PushCompression (..), PushSummary (..))import Nix.Push.Directory (DirectoryPush (..), ed25519SeedBytes, pushToDirectory)import Nix.Push.Source (PushSource (..), PushedPath (..), localPushSource)import Nix.Realise (ClosureOutcome (..))import Nix.Store (GcRoot (..), Store (..), addToStore, closeStore, drvReferences, findRoots, isValid, openStore, queryReferences)import Nix.Store.Ops (EvalObjects (..), EvalWrite (..), EvalWrites (..), MadeOps (..), StoreOps (..), StoreQueries (..), withLocalStore)import Nix.Store.Path (StoreDir (..), StoreWriteMode (..), badStorePathText, defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)import Nix.Store.Path.Internal (StorePath (..))import Nix.Trust.Fetch (FixedOutputStore (..), fetchAndScan)import Nix.Trust.Scan (scanFetched)import qualified NovaCache.Hash as CHashimport qualified NovaCache.NAR as NARimport qualified NovaCache.Signing as Signingimport qualified System.Directory as Dirimport System.FilePath (takeFileName, (</>))import System.IO.Error (ioeGetErrorString, ioeSetErrorString, mkIOError, resourceVanishedErrorType)import qualified System.Info as SIimport Test.Daemon (withSocketDaemon)import Test.DaemonClient (Logged (..), Standing (..), barPath, channelTransport, eventLogger, fooPath, missingPath, sampleInfo, serverConfigAt, standing, withNarHash)import Test.Harness (TestResult (..), andThen, assertEqual, evalNixIOIn, findTestShell, forceRemoveIfExists, mkTestBuildDrv, runTest, runTestM, symlinksAvailable, throwawayKey)import Test.Push (cacheListing)import qualified Test.QuickCheck as QC-- ----------------------------------------------------------------------------- Without a connection-- ----------------------------------------------------------------------------- | The order derivations are added in, the spellings an add is sent in,-- and the words a failure is reported in.testDaemonStore :: IO [Bool]testDaemonStore = do  putStrLn "daemon/client-store"  sequence    [ runTestM "derivations are added with everything each one refers to before it" $ do        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll genDerivations inputsFirst)        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),      runTest "an input derivation and a source come before what names them, whatever the order of their keys" $        let early = StorePath (T.replicate 32 "0") "early.drv"            late = StorePath (T.replicate 32 "z") "late.drv"            earlyByName = StorePath (T.replicate 32 "1") "early-by-name.drv"            lateByName = StorePath (T.replicate 32 "y") "late-by-name.drv"            recipes =              [ (early, recipe "early" [late] []),                (late, recipe "late" [] []),                (earlyByName, recipe "early-by-name" [] [lateByName]),                (lateByName, recipe "late-by-name" [] [])              ]         in assertEqual "order" (Right [late, early, lateByName, earlyByName]) (map (\(path, _, _) -> path) <$> derivationAddOrder (recorded recipes)),      runTest "a recorded derivation that names no path, or does not parse, is refused in words that name it" $        let key = storePathToText defaultStoreDir (StorePath (T.replicate 32 "0") "garbled.drv")            parseRefused = case derivationAddOrder (Map.singleton key "not a derivation") of              Left message -> ("the recorded .drv for " <> key <> " does not parse: ") `T.isPrefixOf` message              Right _ -> False         in assertEqual "no path" (Left "no store path: not a path") (void <$> derivationAddOrder (Map.singleton "not a path" (toATerm (recipe "x" [] []))))              `andThen` assertEqual "no parse" True parseRefused              `andThen` assertEqual "nothing recorded" (Right []) (void <$> derivationAddOrder Map.empty),      runTest "an evaluation's write is asked for in upstream's spellings, a text alone naming references" $        assertEqual "text" (Ops.AddToStoreRequest "n" "text:sha256" (Set.singleton fooPath) Ops.NoRepair) (evalWriteRequest (TextWrite "n" (Set.singleton fooPath) "contents"))          `andThen` assertEqual "recursive" (Ops.AddToStoreRequest "n" "fixed:r:sha256" Set.empty Ops.NoRepair) (evalWriteRequest (NarWrite "n" "contents"))          `andThen` assertEqual "flat" (Ops.AddToStoreRequest "n" "fixed:sha256" Set.empty Ops.NoRepair) (evalWriteRequest (FlatWrite "n" "contents"))          `andThen` assertEqual "spellings" ("text:sha256", "fixed:r:sha256", "fixed:sha256") (textMethod, narMethod, flatMethod),      runTest "the settings a client sends come from its configuration, cores 0 where it sets none as upstream's client sends its own default, upstream's defaults for the rest, and as overrides the store settings a source set" $        let configured = defaultNixConfig {ncKeepFailed = True, ncFallback = True, ncCores = Just 2}            sent keepFailed tryFallback cores = Ops.ClientSettings keepFailed False tryFallback (Proto.Verbosity 3) 1 0 True cores True Map.empty            overridden = configured {ncSandbox = Just SandboxDisabled, ncSubstituters = ["https://cache.example"], ncRestrictEval = True}            assigned = replacedSettings ["sandbox", "substituters", "restrict-eval", "keep-failed", "cores"]         in assertEqual "configured" (sent True True 2) (clientSettings noneAssigned configured)              `andThen` assertEqual "defaults" (sent False False 0) (clientSettings noneAssigned defaultNixConfig)              `andThen` assertEqual "zero set" (sent False False 0) (clientSettings noneAssigned defaultNixConfig {ncCores = Just 0})              `andThen` assertEqual "overrides" ((sent True True 2) {Ops.csOverrides = Map.fromList [("sandbox", "false"), ("substituters", "https://cache.example")]}) (clientSettings assigned overridden)              `andThen` assertEqual "unset cores" 0 Ops.unsetCores,      runTest "a connection that cannot be made or opened, and a refusal, are worded as upstream words them" $        let socketAddress = DefaultSocket "/s"            named = NamedSocket "/run/s"         in assertEqual "connect" ("cannot connect to " <> connectEndpoint <> " at \"/s\": Connection refused") (connectFailureText socketAddress "Connection refused")              `andThen` assertEqual "previously failed" "opening a connection to remote store 'daemon' previously failed" (previouslyFailedText socketAddress)              `andThen` assertEqual "previously failed, named" "opening a connection to remote store 'unix:///run/s' previously failed" (previouslyFailedText named)              `andThen` assertEqual "open" "cannot open connection to remote store 'daemon': error: Nix daemon disconnected unexpectedly (maybe it crashed?)" (openFailureText socketAddress (Client.ConnectionLost Client.disconnectedMessage))              `andThen` assertEqual "open, named" "cannot open connection to remote store 'unix:///run/s': error: no" (openFailureText named (Client.DaemonFailed (Ops.daemonError "no")))              `andThen` assertEqual "refused" "the store refuses this" (opFailureText (DaemonRefused (Ops.daemonError "the store refuses this")))              `andThen` assertEqual "link" "gone" (opFailureText (LinkFailed "gone"))              `andThen` assertEqual "names" ("daemon", "unix:///run/s") (daemonStoreName socketAddress, daemonStoreName named)              `andThen` assertEqual "encoded names" ("unix:///run/a%20b:c@d/100%25/~s_-.", "unix:///caf%C3%A9/s") (daemonStoreName (NamedSocket "/run/a b:c@d/100%/~s_-."), daemonStoreName (NamedSocket "/caf\xC3\xA9/s"))              `andThen` assertEqual "path" "/run/s" (daemonAddressPath named)    ]-- | What a connection to the daemon is to on this platform, in the-- words of a failure to make one.connectEndpoint :: TextconnectEndpoint = if onWindows then "named pipe" else "socket"-- | Whether this is Windows, where the daemon listens on a named pipe and-- not a Unix socket.onWindows :: BoolonWindows = SI.os == "mingw32"-- | A derivation as evaluation records it, in the order to add it: its-- path, the derivation, and its ATerm.type Recorded = (StorePath, Derivation, BS.ByteString)-- | Derivations as evaluation records them: each ATerm by the text of its-- path.recorded :: [(StorePath, Derivation)] -> Map.Map Text BS.ByteStringrecorded recipes = Map.fromList [(storePathToText defaultStoreDir path, toATerm drv) | (path, drv) <- recipes]-- | A derivation that names input derivations and sources, whose name-- makes it differ from another.recipe :: Text -> [StorePath] -> [StorePath] -> Derivationrecipe name inputs sources =  Derivation    { drvOutputs = [DerivationOutput "out" (StorePath (T.replicate 32 "c") (name <> "-out")) "" ""],      drvInputDrvs = Map.fromList [(input, ["out"]) | input <- inputs],      drvInputSrcs = sort sources,      drvPlatform = X86_64_Linux,      drvBuilder = "/bin/sh",      drvArgs = [],      drvEnv = Map.singleton "name" (TE.encodeUtf8 name)    }-- | Derivations, each naming some of those generated before it as inputs-- and some as sources, and an input that is not among them.  The paths'-- hashes are random, so the order of their keys is unrelated to which-- names which.genDerivations :: QC.Gen [(StorePath, Derivation)]genDerivations = do  count <- QC.choose (0, 8)  hashes <- QC.vectorOf count (T.pack <$> QC.vectorOf 32 (QC.elements nix32Alphabet))  let paths = [StorePath hash ("d" <> T.pack (show index) <> ".drv") | (index, hash) <- zip [0 :: Int ..] (nub hashes)]      outside = StorePath (T.replicate 32 "a") "outside.drv"  mapM    ( \(position, path) -> do        inputs <- QC.sublistOf (take position paths)        sources <- QC.sublistOf (take position paths)        pure (path, recipe (spName path) (outside : inputs) sources)    )    (zip [0 ..] paths)  where    nix32Alphabet = "0123456789abcdfghijklmnpqrsvwxyz"-- | Whether the order derivations are added in places each once, each-- after every derivation of the map that it names, and keeps what was-- recorded.inputsFirst :: [(StorePath, Derivation)] -> QC.PropertyinputsFirst recipes = case derivationAddOrder (recorded recipes) of  Left refusal -> QC.counterexample (T.unpack refusal) False  Right order ->    let paths = [path | (path, _, _) <- order]        position = Map.fromList (zip paths [0 :: Int ..])        before dependency dependent = case (Map.lookup dependency position, Map.lookup dependent position) of          (Just earlier, Just later) -> earlier < later          _ -> True     in QC.conjoin          [ QC.counterexample "each derivation once" (sort paths QC.=== sort (map fst recipes)),            QC.counterexample "references first" (and [before reference path | (path, drv, _) <- order, reference <- drvReferences drv]),            QC.counterexample "what was recorded" (Map.fromList [(path, (drv, aterm)) | (path, drv, aterm) <- order] QC.=== Map.fromList [(path, (drv, toATerm drv)) | (path, drv) <- recipes])          ]-- ----------------------------------------------------------------------------- A daemon in memory-- ----------------------------------------------------------------------------- | What the daemon in memory holds, and every upload it was sent.data Held = Held  { heldValid :: !(Map.Map StorePath Proto.UnkeyedValidPathInfo),    heldUploads :: ![Upload],    -- | The temporary roots and the validity queries the daemon was asked,    -- in order.    heldCalls :: ![Called],    -- | The settings the client had sent when each validity query came, in    -- order: none before it has sent any.    heldSettings :: ![Maybe Ops.ClientSettings],    -- | The builds the daemon was asked for, in order: what to build and    -- in which mode.    heldBuilds :: ![([Proto.DerivedPath], Proto.BuildMode)],    -- | The bytes of each link the daemon was asked to root, in order.    heldIndirectRoots :: ![BS.ByteString],    -- | What the daemon reports while it builds, and the error it ends a    -- build with, if it fails the build.    heldBuildReport :: ![Ops.LogEvent],    heldBuildFailure :: !(Maybe Proto.DaemonError),    -- | The result the daemon gives for each opaque path it is asked to    -- realise, none for a path not here.    heldResults :: !(Map.Map StorePath Proto.BuildResult)  }-- | What the daemon in memory was asked: to root a path, which paths it-- holds, a path's record, and which paths a substituter offers.data Called  = TempRooted !StorePath  | Queried !(Set StorePath)  | InfoQueried !StorePath  | OfferQueried !(Set StorePath)  deriving (Eq, Show)-- | An upload as the daemon in memory was sent it.data Upload = Upload  { upName :: !BS.ByteString,    upMethod :: !Proto.ContentAddressMethod,    upAlgo :: !Text,    upReferences :: !(Set StorePath),    upBytes :: !BS.ByteString  }  deriving (Eq, Show)-- | The path the daemon in memory makes of an upload, or why it refuses.type PathFor = Ops.DumpUpload -> BS.ByteString -> Either Proto.DaemonError StorePath-- | The path an upload's content makes, as the daemon makes it.contentPath :: PathForcontentPath upload bytes = first (Ops.daemonError . badStorePathText) $ case Ops.duMethod upload of  Proto.TextMethod -> makeTextPath name digest (Set.toList (Ops.duReferences upload))  Proto.FixedMethod NarIngestion -> makeSourcePath name digest (Ops.duReferences upload)  Proto.FixedMethod FlatIngestion -> makeFixedOutputPath name "sha256" FlatIngestion digest  where    name = TE.decodeUtf8Lenient (Ops.duName upload)    digest = sha256Digest bytes-- | A store that refuses what a test does not ask of it.unavailableStore :: Ops.DaemonStore IOunavailableStore =  Ops.DaemonStore    { Ops.dsIsValidPath = \_ _ -> pure (Left notHere),      Ops.dsQueryValidPaths = \_ _ _ -> pure (Left notHere),      Ops.dsQuerySubstitutablePaths = \_ _ -> pure (Left notHere),      Ops.dsQueryReferrers = \_ _ -> pure (Left notHere),      Ops.dsQueryValidDerivers = \_ _ -> pure (Left notHere),      Ops.dsQueryDerivationOutputMap = \_ _ -> pure (Left notHere),      Ops.dsQueryAllValidPaths = \_ -> pure (Left notHere),      Ops.dsQueryPathInfo = \_ _ -> pure (Left notHere),      Ops.dsQueryMissing = \_ _ -> pure (Left notHere),      Ops.dsAddToStore = \_ _ -> pure (Ops.Taken (Left notHere)),      Ops.dsAddToStoreNar = \_ _ _ _ -> pure (Ops.Taken (Left notHere)),      Ops.dsBuildPaths = \_ _ _ -> pure (Left notHere),      Ops.dsBuildPathsWithResults = \_ _ _ -> pure (Left notHere),      Ops.dsEnsurePath = \_ _ -> pure (Left notHere),      Ops.dsAddTempRoot = \_ _ -> pure (Left notHere),      Ops.dsAddIndirectRoot = \_ _ -> pure (Left notHere),      Ops.dsFindRoots = \_ _ -> pure (Left notHere),      Ops.dsCollectGarbage = \_ _ -> pure (Left notHere),      Ops.dsOptimiseStore = \_ -> pure (Left notHere),      Ops.dsVerifyStore = \_ _ _ -> pure (Left notHere),      Ops.dsAddSignatures = \_ _ _ -> pure (Left notHere),      Ops.dsNarFromPath = \_ _ -> pure (Left notHere)    }  where    notHere = Ops.daemonError "not in these tests"-- | The daemon in memory: it answers which paths are valid and a path's-- info, takes temporary roots and indirect roots, records every dump it is-- sent and every build it is asked for, and makes the path 'PathFor' says.fakeDaemonStore :: Proto.NarHash -> PathFor -> IORef Held -> Ops.DaemonStore IOfakeDaemonStore narHash pathFor state =  unavailableStore    { Ops.dsQueryValidPaths = \work _ paths -> do        modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [Queried paths], heldSettings = heldSettings held ++ [Ops.connClient (Ops.workSettings work)]})        Right . Set.intersection paths . Map.keysSet . heldValid <$> readIORef state,      Ops.dsAddTempRoot = \_ path -> Right () <$ modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [TempRooted path]}),      Ops.dsAddIndirectRoot = \_ bytes -> Right () <$ modifyIORef' state (\held -> held {heldIndirectRoots = heldIndirectRoots held ++ [bytes]}),      Ops.dsBuildPaths = \work targets mode -> do        modifyIORef' state (\held -> held {heldBuilds = heldBuilds held ++ [(targets, mode)]})        held <- readIORef state        traverse_ (Ops.workReport work) (heldBuildReport held)        pure (maybe (Right ()) Left (heldBuildFailure held)),      Ops.dsQueryPathInfo = \_ path -> do        modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [InfoQueried path]})        Right . Map.lookup path . heldValid <$> readIORef state,      Ops.dsQueryAllValidPaths = \_ -> Right . Map.keysSet . heldValid <$> readIORef state,      Ops.dsQuerySubstitutablePaths = \_ paths -> do        modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [OfferQueried paths]})        pure (Right Set.empty),      Ops.dsBuildPathsWithResults = \_ targets mode -> do        modifyIORef' state (\held -> held {heldBuilds = heldBuilds held ++ [(targets, mode)]})        held <- readIORef state        pure (Right [Proto.KeyedBuildResult target result | target@(Proto.DerivedOpaque path) <- targets, Just result <- [Map.lookup path (heldResults held)]]),      Ops.dsAddToStore = \_ upload -> pure (collecting (finish upload))    }  where    finish upload bytes = do      let received = Upload (Ops.duName upload) (Ops.duMethod upload) (Ops.duAlgo upload) (Ops.duReferences upload) bytes      modifyIORef' state (\held -> held {heldUploads = heldUploads held ++ [received]})      case pathFor upload bytes of        Left refusal -> pure (Left refusal)        Right path -> do          let info = sampleInfo narHash (Ops.duReferences upload)          Right (Proto.ValidPathInfo path info) <$ modifyIORef' state (\held -> held {heldValid = Map.insert path info (heldValid held)})    collecting finishWith = Ops.Taking (more BS.empty) (finishWith BS.empty) (pure ())      where        more held chunk = pure (Ops.Taking (more (held <> chunk)) (finishWith (held <> chunk)) (pure ()))-- | How many connections a connector made, and how many it closed.data Dials = Dials  { dialsMade :: !(IORef Int),    dialsClosed :: !(IORef Int)  }newDials :: IO DialsnewDials = Dials <$> newIORef 0 <*> newIORef 0-- | How many connections a daemon in memory was given, and how many were-- closed.dialCounts :: Dials -> IO (Int, Int)dialCounts dials = (,) <$> readIORef (dialsMade dials) <*> readIORef (dialsClosed dials)-- | A connector to a daemon in memory: each connection is served, as the-- function given serves it, on a thread of its own, and closing it ends-- the daemon's input and waits for the thread.memoryConnector :: Dials -> (Conn.Transport IO -> IO Conn.ConnectionEnd) -> ConnectormemoryConnector dials serve = do  modifyIORef' (dialsMade dials) (+ 1)  toDaemon <- newChan  toClient <- newChan  daemonTransport <- channelTransport toDaemon toClient  clientTransport <- channelTransport toClient toDaemon  running <- async (serve daemonTransport `finally` writeChan toClient Nothing)  pure (Right (clientTransport, modifyIORef' (dialsClosed dials) (+ 1) *> writeChan toDaemon Nothing *> void (wait running)))-- | The daemon in memory, and a connector to it.data FakeDaemon = FakeDaemon  { fakeHeld :: !(IORef Held),    fakeDials :: !Dials,    fakeConnector :: !Connector  }-- | The version the daemon command serves: the newest, with the one-- feature its codec carries and not the one that stops a client sending-- settings.daemonVersion :: Proto.VersiondaemonVersion = Proto.Version Proto.latestVersionNumber (Set.singleton Proto.featureRealisationWithPath)-- | A daemon in memory that holds the paths given, with their references,-- and makes the paths 'PathFor' says.newFakeDaemon :: Proto.NarHash -> PathFor -> [(StorePath, Set StorePath)] -> IO FakeDaemonnewFakeDaemon narHash = newFakeDaemonServing narHash daemonVersion-- | 'newFakeDaemon' offering a version.newFakeDaemonServing :: Proto.NarHash -> Proto.Version -> PathFor -> [(StorePath, Set StorePath)] -> IO FakeDaemonnewFakeDaemonServing narHash version pathFor valid = do  state <- newIORef (Held (Map.fromList [(path, sampleInfo narHash references) | (path, references) <- valid]) [] [] [] [] [] [] Nothing Map.empty)  dials <- newDials  let serve = Conn.serveConnection (serverConfigAt version) Proto.Trusted (fakeDaemonStore narHash pathFor state)  pure (FakeDaemon state dials (memoryConnector dials serve))-- | The store a command is given over a daemon, reading its files from a-- directory.storeConfig :: StoreDir -> DaemonStoreConfigstoreConfig dir =  DaemonStoreConfig    { dscAddress = DefaultSocket "/run/nix/daemon-socket/socket",      dscFileDir = dir,      dscSettings = clientSettings noneAssigned defaultNixConfig,      dscLogger = quietLogger    }-- | No setting a source set.noneAssigned :: AssignedSettingsnoneAssigned = AssignedSettings Map.empty-- | Settings each of which a plain assignment set.replacedSettings :: [ByteString] -> AssignedSettingsreplacedSettings names = AssignedSettings (Map.fromList [(name, Replaced) | name <- names])-- | The directory a test gives a store whose files it never reads.unusedDir :: StoreDirunusedDir = StoreDir "/nonexistent/nn-daemon-store"-- | A logger that says nothing.quietLogger :: LoggerquietLogger = plainLogger (\_ _ -> pure ()) (const (pure ()))-- | Run an action with an empty scratch directory under the temporary-- directory, removed after.withScratch :: FilePath -> (FilePath -> IO a) -> IO awithScratch name action = do  tmp <- Dir.getTemporaryDirectory  let dir = tmp </> name  forceRemoveIfExists dir  Dir.createDirectoryIfMissing True dir  action dir `finally` forceRemoveIfExists dir-- | A derivation as evaluation makes it, named and recorded with the path-- its ATerm and references make.recordedDerivation :: Text -> [StorePath] -> [StorePath] -> Either Text RecordedrecordedDerivation name inputs sources = do  file <- first badStorePathText (drvFile name (recipe name inputs sources))  pure (drvFilePath file, drvFileDerivation file, drvFileATerm file)-- | An input derivation, and a derivation naming it whose path sorts-- before the input's, so that adding in the order of the keys would add-- the dependent first.dependentSortingFirst :: Either Text (Recorded, Recorded)dependentSortingFirst = do  input@(inputPath, _, _) <- recordedDerivation "input" [] []  candidates <- traverse (\index -> recordedDerivation ("dependent" <> T.pack (show index)) [inputPath] []) [1 .. dependentCount]  dependent <- maybe (Left "no dependent derivation sorts before its input") Right (find (\(path, _, _) -> path < inputPath) candidates)  pure (input, dependent)-- | How many derivations name an input at once: each sorts before it with-- probability one half, so that none does is vanishingly unlikely.dependentCount :: IntdependentCount = 64-- | The derivations as the map evaluation records them is keyed.derivationMap :: [Recorded] -> Map.Map Text BS.ByteStringderivationMap derivations = Map.fromList [(storePathToText defaultStoreDir path, aterm) | (path, _, aterm) <- derivations]-- | The upload that adds a derivation: its name, as a text that refers to-- what it refers to.derivationUpload :: Recorded -> UploadderivationUpload (path, drv, aterm) = Upload (TE.encodeUtf8 (spName path)) Proto.TextMethod "sha256" (Set.fromList (drvReferences drv)) aterm-- | What an evaluation made, as a command adds it.noObjects :: EvalObjectsnoObjects = EvalObjects Map.empty Map.empty Map.empty-- ----------------------------------------------------------------------------- With a connection-- ----------------------------------------------------------------------------- | The store's operations against a daemon in memory, the connection a-- socket makes, and evaluation and adds against a daemon serving a store-- of its own.testDaemonStoreIO :: IO [Bool]testDaemonStoreIO = do  putStrLn "daemon/client-store-sessions"  sockets <- socketTests  memory <- withNarHash "daemon/client-store-sessions" (\narHash -> concat <$> sequence [memoryTests narHash, unreadableTests narHash, pushTrustTests narHash])  served <- servedTests  pure (sockets <> memory <> served)-- | A connection to the daemon at an address, made and closed.socketTests :: IO [Bool]socketTests = do  raw <- rawSocketTests  rest <-    sequence      [ runTestM "an address nobody listens at and one that cannot name a daemon fail to connect, in the platform's words" $          if onWindows            then do              absent <- reached (connectDaemon "\\\\.\\pipe\\nn-dial-absent")              long <- reached (connectDaemon (BS.replicate 300 97))              pure $                assertEqual "absent" True (either ("CreateFileW: " `T.isPrefixOf`) (const False) absent)                  `andThen` assertEqual "not a pipe" (Left "not a named pipe's path, which is \\\\.\\pipe\\ and a name") long            else withScratch "nn-dial" $ \dir -> do              let stale = dir </> "stale"              bound <- socket AF_UNIX Stream defaultProtocol              bind bound (SockAddrUnix stale)              close bound              absent <- reached (connectDaemon (BS8.pack (dir </> "absent")))              refused <- reached (connectDaemon (BS8.pack stale))              long <- reached (connectDaemon (BS.replicate 300 97))              pure $                assertEqual "absent" (Left "No such file or directory") absent                  `andThen` assertEqual "refused" (Left "Connection refused") refused                  `andThen` assertEqual "too long" (Left "path is too long") long,        runTestM "a store over a daemon listening on a socket, or on Windows a named pipe, reads what the daemon's store holds and adds to it" $          withSocketDaemon Listen.ForceTrusted id $ \_ address _ -> do            let daemonAt = NamedSocket address                config = (storeConfig unusedDir) {dscAddress = daemonAt}                entry = NAR.NarRegular False "added through the daemon"            withDaemonStore config (dialDaemon daemonAt) $ \ops -> do              valid <- sqValidPaths (soQueries ops) (Set.fromList [fooPath, missingPath])              added <- soAddSourceTree ops "tree" Set.empty entry              validAfter <- traverse (sqValidPaths (soQueries ops) . Set.singleton) (either (const []) pure added)              pure $                assertEqual "valid" (Set.singleton fooPath) valid                  `andThen` assertEqual "added" (first badStorePathText (makeSourcePath "tree" (sha256Digest (NAR.serialise entry)) Set.empty)) added                  `andThen` assertEqual "valid after" (either (const []) (pure . Set.singleton) added) validAfter      ]  pure (raw <> rest)  where    reached connect = connect >>= either (pure . Left) (\connection -> Right () <$ closeDaemonConnection connection)-- | A Unix socket's connection, which a test binds and listens on itself.rawSocketTests :: IO [Bool]rawSocketTests  | onWindows = [] <$ putStrLn "  SKIP  Windows connects to the daemon's named pipe, not a Unix socket a test binds"  | otherwise =      sequence        [ runTestM "a daemon's socket connects, its transport carries bytes both ways, and a read after the daemon closes is the end" $            withScratch "nn-dial" $ \dir -> do              let path = dir </> "socket"              listener <- socket AF_UNIX Stream defaultProtocol              ( do                  bind listener (SockAddrUnix path)                  listen listener 1                  connected <- connectDaemon (BS8.pack path)                  case connected of                    Left reason -> pure (Fail reason)                    Right connection -> do                      (peer, _) <- accept listener                      let transport = connectionTransport connection                      sendAll peer "from the daemon"                      heard <- Conn.transportReceive transport                      Conn.transportSend transport (BB.byteString "from the client")                      received <- recv peer 64                      close peer                      ended <- Conn.transportReceive transport                      endedAgain <- Conn.transportReceive transport                      closeDaemonConnection connection                      pure $                        assertEqual "heard" (Just "from the daemon") heard                          `andThen` assertEqual "received" "from the client" received                          `andThen` assertEqual "ended" (Nothing, Nothing) (ended, endedAgain)                )                `finally` close listener        ]-- | The store's operations over a daemon in memory.memoryTests :: Proto.NarHash -> IO [Bool]memoryTests narHash =  sequence    [ runTestM "a store asked nothing, or asked only what the daemon took as it was made, never connects" $ do        daemon <- newFakeDaemon narHash contentPath []        let writesOnly = noObjects {eoStoreWrites = Map.singleton (storePathToText defaultStoreDir fooPath) ([], WriteText)}        answers <-          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->            (,,) <$> soAddEvalObjects ops noObjects <*> soAddEvalObjects ops writesOnly <*> sqValidPaths (soQueries ops) Set.empty        dials <- dialCounts (fakeDials daemon)        pure (assertEqual "answers" (Right (), Right (), Set.empty) answers `andThen` assertEqual "connections made and closed" (0, 0) dials),      runTestM "the queries ask the daemon: the valid paths among those given, and a path's references, none for one it does not hold" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.singleton barPath), (barPath, Set.empty)]        answers <-          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->            let queries = soQueries ops             in (,,,) <$> sqValidPaths queries (Set.fromList [fooPath, barPath, missingPath]) <*> sqReferences queries fooPath <*> sqReferences queries barPath <*> sqReferences queries missingPath        dials <- dialCounts (fakeDials daemon)        pure $          assertEqual "answers" (Set.fromList [fooPath, barPath], Right (Set.singleton barPath), Right Set.empty, Right Set.empty) answers            `andThen` assertEqual "one connection, made and closed" (1, 1) dials,      runTestM "a daemon that cannot be reached fails the operation that tried in upstream's words and every one after in its words for a failed connection, and is not tried again" $ do        calls <- newIORef (0 :: Int)        let config = storeConfig unusedDir            unreachable = modifyIORef' calls (+ 1) $> Left "Connection refused"            expected = connectFailureText (dscAddress config) "Connection refused"            entry = NAR.NarRegular False "x"        (queried, added, addedAgain) <-          withDaemonStore config unreachable $ \ops ->            (,,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty entry <*> soAddSourceTree ops "tree" Set.empty entry        tried <- readIORef calls        pure $ case queried of          Left (err :: IOException) ->            assertEqual "query" expected (T.pack (ioeGetErrorString err))              `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added              `andThen` assertEqual "add again" (Left (previouslyFailedText (dscAddress config))) addedAgain              `andThen` assertEqual "connections tried" 1 tried          Right found -> Fail ("expected the query to fail, got: " <> T.pack (show found)),      runTestM "a daemon that fails the handshake fails the operation that tried in upstream's words and every one after in its words for a failed connection, is closed at once, and is not tried again" $ do        made <- newIORef (0 :: Int)        closed <- newIORef (0 :: Int)        let config = storeConfig unusedDir            gone = Conn.Transport (pure Nothing) (\_ -> pure ())            connector = modifyIORef' made (+ 1) $> Right (gone, modifyIORef' closed (+ 1))            expected = openFailureText (dscAddress config) (Client.ConnectionLost Client.disconnectedMessage)        (queried, added) <-          withDaemonStore config connector $ \ops ->            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")        counts <- (,) <$> readIORef made <*> readIORef closed        pure $ case queried of          Left (err :: IOException) ->            assertEqual "query" expected (T.pack (ioeGetErrorString err))              `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added              `andThen` assertEqual "connections made and closed" (1, 1) counts          Right found -> Fail ("expected the query to fail, got: " <> T.pack (show found)),      runTestM "a connection that is lost while the settings are sent fails the operation that opened it with the reason, closes it, and fails every one after as a failed connection" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        let config = storeConfig unusedDir            connector = fakeConnector daemon >>= traverse (\(transport, closing) -> (,closing) <$> losingOnSetOptions transport)        (queried, added) <-          withDaemonStore config connector $ \ops ->            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")        dials <- dialCounts (fakeDials daemon)        pure $ case queried of          Left (err :: IOException) ->            assertEqual "query" Client.disconnectedMessage (T.pack (ioeGetErrorString err))              `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added              `andThen` assertEqual "connections made and closed" (1, 1) dials          Right found -> Fail ("expected the query to fail, got: " <> T.pack (show found)),      runTestM "an exception thrown while the settings are sent is reported as it is, not as a failed handshake, and closes the connection and fails every operation after as a failed connection" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        let config = storeConfig unusedDir            connector = fakeConnector daemon >>= traverse (\(transport, closing) -> pure (throwingOnSetOptions transport, closing))            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")        (queried, added) <-          withDaemonStore config connector $ \ops ->            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")        dials <- dialCounts (fakeDials daemon)        pure $          assertEqual "query" "the settings failed" (reason queried)            `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added            `andThen` assertEqual "connections made and closed" (1, 1) dials,      runTestM "an exception thrown while the handshake is made is worded as a failed handshake, closes the connection, and fails every operation after as a failed connection" $ do        made <- newIORef (0 :: Int)        closed <- newIORef (0 :: Int)        let config = storeConfig unusedDir            broken = Conn.Transport (throwIO (ErrorCall "the transport failed")) (\_ -> pure ())            connector = modifyIORef' made (+ 1) $> Right (broken, modifyIORef' closed (+ 1))            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")        (queried, added) <-          withDaemonStore config connector $ \ops ->            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")        counts <- (,) <$> readIORef made <*> readIORef closed        pure $          assertEqual "query" (openFailureText (dscAddress config) (Client.ConnectionLost "the transport failed")) (reason queried)            `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added            `andThen` assertEqual "connections made and closed" (1, 1) counts,      runTestM "a connector that throws is a failed connection, reported as the exception reads and not as a failed handshake, while an interrupt goes up and leaves the next operation to connect" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        thrown <- newIORef (0 :: Int)        let config = storeConfig unusedDir            failing = modifyIORef' thrown (+ 1) *> throwIO (ErrorCall "the connector failed")            interrupted = throwIO UserInterrupt            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")        (ordinary, afterOrdinary) <- withDaemonStore config failing $ \ops ->          (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> try (sqValidPaths (soQueries ops) (Set.singleton fooPath))        attempts <- newIORef (0 :: Int)        let interruptedOnce = do              attempt <- atomicModifyIORef' attempts (\n -> (n + 1, n))              if attempt == 0 then interrupted else fakeConnector daemon        (interrupt, afterInterrupt) <- withDaemonStore config interruptedOnce $ \ops ->          (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> sqValidPaths (soQueries ops) (Set.singleton fooPath)        failures <- readIORef thrown        pure $          assertEqual "ordinary" "the connector failed" (reason ordinary)            `andThen` assertEqual "after" (previouslyFailedText (dscAddress config)) (reason afterOrdinary)            `andThen` assertEqual "tried" 1 failures            `andThen` assertEqual "interrupt" (Left UserInterrupt) interrupt            `andThen` assertEqual "after the interrupt" (Set.singleton fooPath) afterInterrupt,      runTestM "a connection that breaks fails the operation that finds it with the reason and is closed, and the next operation connects again" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        broken <- newIORef False        let lossy transport = transport {Conn.transportReceive = readIORef broken >>= \gone -> if gone then pure Nothing else Conn.transportReceive transport}            connector = fmap (fmap (first lossy)) (fakeConnector daemon)            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")        (before, second, third) <-          withDaemonStore (storeConfig unusedDir) connector $ \ops -> do            before <- sqValidPaths (soQueries ops) (Set.singleton fooPath)            writeIORef broken True            second <- try (sqValidPaths (soQueries ops) (Set.singleton fooPath))            writeIORef broken False            third <- sqValidPaths (soQueries ops) (Set.singleton fooPath)            pure (before, second, third)        dials <- dialCounts (fakeDials daemon)        pure $          assertEqual "before" (Set.singleton fooPath) before            `andThen` assertEqual "second" Client.disconnectedMessage (reason second)            `andThen` assertEqual "third" (Set.singleton fooPath) third            `andThen` assertEqual "connections made and closed" (2, 2) dials,      runTestM "a transport that throws an IOException as an operation is sent fails the operation with its words and is closed, and the next operation connects again" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        broken <- newIORef False        let reset = ioeSetErrorString (mkIOError resourceVanishedErrorType "send" Nothing Nothing) "Broken pipe"            resetting transport = transport {Conn.transportSend = \builder -> readIORef broken >>= \gone -> if gone then ioError reset else Conn.transportSend transport builder}            connector = fmap (fmap (first resetting)) (fakeConnector daemon)            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")        (second, third) <-          withDaemonStore (storeConfig unusedDir) connector $ \ops -> do            void (sqValidPaths (soQueries ops) (Set.singleton fooPath))            writeIORef broken True            second <- try (sqValidPaths (soQueries ops) (Set.singleton fooPath))            writeIORef broken False            third <- sqValidPaths (soQueries ops) (Set.singleton fooPath)            pure (second, third)        dials <- dialCounts (fakeDials daemon)        pure $          assertEqual "second" (T.pack (displayException reset)) (reason second)            `andThen` assertEqual "third" (Set.singleton fooPath) third            `andThen` assertEqual "connections made and closed" (2, 2) dials,      runTestM "an exception that is not a failure to read from the connection or a file, thrown while a file is read for an upload, goes up and closes the connection, and the next operation connects again" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        let request = Ops.AddToStoreRequest "tree" narMethod Set.empty Ops.NoRepair            valid = Client.queryValidPaths (Set.singleton fooPath) Ops.NoSubstitute        (upload, afterUpload) <-          withDaemonSession (fakeConnector daemon) (dscAddress (storeConfig unusedDir)) (dscSettings (storeConfig unusedDir)) (\_ -> pure ()) $ \session ->            (,) <$> try (daemonOperation session (pure ()) (Client.addToStore request (throwIO (ErrorCall "the source failed")))) <*> daemonOperation session (pure ()) valid        dials <- dialCounts (fakeDials daemon)        pure $          assertEqual "upload" (Left (ErrorCall "the source failed")) (void <$> upload)            `andThen` assertEqual "next" (Right (Set.singleton fooPath)) afterUpload            `andThen` assertEqual "connections made and closed" (2, 2) dials,      runTestM "an operation settles while it holds the session, so the next operation starts after it and stops none of its activities" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        settling <- newEmptyMVar        settled <- newEmptyMVar        let valid = Client.queryValidPaths (Set.singleton fooPath) Ops.NoSubstitute        (waiting, answers) <-          withDaemonSession (fakeConnector daemon) (dscAddress (storeConfig unusedDir)) (dscSettings (storeConfig unusedDir)) (\_ -> pure ()) $ \session -> do            earlier <- async (daemonOperation session (putMVar settling () *> takeMVar settled) valid)            takeMVar settling            -- Steps that ask the daemon nothing, so the one thing this            -- operation can wait on is the session.            later <- async (daemonOperation session (pure ()) (pure ()))            waiting <- standing (asyncThreadId later)            putMVar settled ()            answers <- (,) <$> wait earlier <*> wait later            pure (waiting, answers)        pure $          assertEqual "the next operation waits while the earlier settles" Waiting waiting            `andThen` assertEqual "both answered" (Right (Set.singleton fooPath), Right ()) answers,      runTestM "the settings go to the daemon once the handshake is made, from the command's configuration, and are not sent where the daemon grants the feature that stops them" $ do        let configured = defaultNixConfig {ncKeepFailed = True, ncFallback = True, ncCores = Just 2}            config = (storeConfig unusedDir) {dscSettings = clientSettings noneAssigned configured}            queryOnce daemon = withDaemonStore config (fakeConnector daemon) (\ops -> sqValidPaths (soQueries ops) (Set.singleton fooPath))            stoppable = Proto.Version Proto.latestVersionNumber (Set.fromList [Proto.featureRealisationWithPath, Proto.featureDisableSetOptions])        sending <- newFakeDaemon narHash contentPath []        granting <- newFakeDaemonServing narHash stoppable contentPath []        unsetting <- newFakeDaemon narHash contentPath []        void (queryOnce sending)        void (queryOnce granting)        void (withDaemonStore (storeConfig unusedDir) (fakeConnector unsetting) (\ops -> sqValidPaths (soQueries ops) (Set.singleton fooPath)))        sentTo <- heldSettings <$> readIORef (fakeHeld sending)        grantedTo <- heldSettings <$> readIORef (fakeHeld granting)        unsetTo <- heldSettings <$> readIORef (fakeHeld unsetting)        pure $          assertEqual "sent" [Just (clientSettings noneAssigned configured)] sentTo            `andThen` assertEqual "sent keep-failed, fallback and cores" [Just (Ops.ClientSettings True False True (Proto.Verbosity 3) 1 0 True 2 True Map.empty)] sentTo            `andThen` assertEqual "cores where the configuration sets none" [Just (Ops.ClientSettings False False False (Proto.Verbosity 3) 1 0 True 0 True Map.empty)] unsetTo            `andThen` assertEqual "granted" [Nothing] grantedTo,      runTestM "a source tree is added as a NAR under its name and references, as the path its content makes" $ do        daemon <- newFakeDaemon narHash contentPath []        let entry = NAR.NarDirectory [("a", NAR.NarRegular False "x")]            nar = NAR.serialise entry            refs = Set.singleton fooPath        added <- withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) (\ops -> soAddSourceTree ops "tree" refs entry)        held <- readIORef (fakeHeld daemon)        pure $          assertEqual "path" (first badStorePathText (makeSourcePath "tree" (sha256Digest nar) refs)) added            `andThen` assertEqual "uploads" [Upload "tree" (Proto.FixedMethod NarIngestion) "sha256" refs nar] (heldUploads held),      runTestM "a daemon that makes another path than the one computed is refused, for a tree and for a derivation" $ do        daemon <- newFakeDaemon narHash (\_ _ -> Right barPath) []        let entry = NAR.NarRegular False "x"            wrong = StorePath (T.replicate 32 "d") "wrong.drv"            spelled = storePathToText defaultStoreDir            refusal computed = Left ("the store added '" <> spelled barPath <> "' where '" <> spelled computed <> "' was computed")        (tree, derivation) <-          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->            (,) <$> soAddSourceTree ops "tree" Set.empty entry <*> soAddEvalObjects ops noObjects {eoDerivations = recorded [(wrong, recipe "wrong" [] [])]}        pure $ case makeSourcePath "tree" (sha256Digest (NAR.serialise entry)) Set.empty of          Right computed -> assertEqual "tree" (refusal computed) tree `andThen` assertEqual "derivation" (refusal wrong) derivation          Left bad -> Fail (badStorePathText bad),      runTestM "an evaluation's copies, then its derivations inputs first, are added, a copy or derivation the daemon holds passed over and its writes not sent" $        withScratch "nn-store-objects" $ \root -> do          let sourceDir = root </> "src"              keptDir = root </> "kept"              nar = NAR.serialise (NAR.NarDirectory [("f", NAR.NarRegular False "contents")])              keptNar = NAR.serialise (NAR.NarDirectory [("g", NAR.NarRegular False "kept")])          Dir.createDirectoryIfMissing True sourceDir          Dir.createDirectoryIfMissing True keptDir          BS.writeFile (sourceDir </> "f") "contents"          BS.writeFile (keptDir </> "g") "kept"          case (makeSourcePath "src" (sha256Digest nar) Set.empty, makeSourcePath "kept" (sha256Digest keptNar) Set.empty, recordedDerivation "held" [] [], dependentSortingFirst) of            (Right copyPath, Right keptPath, Right held@(heldPath, _, _), Right (input, dependent)) -> do              daemon <- newFakeDaemon narHash contentPath [(heldPath, Set.empty), (keptPath, Set.empty)]              let objects =                    EvalObjects                      { eoSources = Map.fromList [(copyPath, T.pack sourceDir), (keptPath, T.pack keptDir)],                        eoStoreWrites = Map.singleton (storePathToText defaultStoreDir fooPath) ([], WriteText),                        eoDerivations = derivationMap [held, input, dependent]                      }              added <- withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) (`soAddEvalObjects` objects)              state <- readIORef (fakeHeld daemon)              let candidates = Set.fromList [copyPath, keptPath, heldPath, derivationPath input, derivationPath dependent]              pure $                assertEqual "added" (Right ()) added                  `andThen` assertEqual "uploads" [Upload "src" (Proto.FixedMethod NarIngestion) "sha256" Set.empty nar, derivationUpload input, derivationUpload dependent] (heldUploads state)                  `andThen` assertEqual "every copy and derivation rooted before the daemon was asked which it holds" (Just (candidates, candidates)) (rootedBeforeAsked (heldCalls state))            (copy, kept, heldDrv, pair) -> pure (Fail ("expected two copy paths and three derivations, got: " <> T.pack (show (copy, kept, fmap fst3 heldDrv, fmap (bimap fst3 fst3) pair)))),      runTestM "the store roots the path moHold is given on the daemon, and answers a validity query put after it with the daemon's answer" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        held <- withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops -> case soEvalWrites ops of          AddedAsMade made -> do            rooted <- moHold made fooPath            (,) rooted <$> sqValidPaths (soQueries ops) (Set.singleton fooPath)          WrittenInDirectory -> pure (Left "the store did not take writes as they are made", Set.empty)        state <- readIORef (fakeHeld daemon)        pure $          assertEqual "held" (Right (), Set.singleton fooPath) held            `andThen` assertEqual "calls" [TempRooted fooPath, Queried (Set.singleton fooPath)] (heldCalls state),      runTestM "a copy that changed after evaluation hashed it is refused in the local words, and no derivation is sent after it" $        withScratch "nn-store-changed" $ \root -> do          let sourceDir = root </> "src"              hashed = NAR.serialise (NAR.NarDirectory [("f", NAR.NarRegular False "contents")])          Dir.createDirectoryIfMissing True sourceDir          BS.writeFile (sourceDir </> "f") "changed"          case (makeSourcePath "src" (sha256Digest hashed) Set.empty, recordedDerivation "later" [] []) of            (Right copyPath, Right later) -> do              daemon <- newFakeDaemon narHash contentPath []              let objects = noObjects {eoSources = Map.singleton copyPath (T.pack sourceDir), eoDerivations = derivationMap [later]}              added <- withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) (`soAddEvalObjects` objects)              state <- readIORef (fakeHeld daemon)              pure $                assertEqual "refused" (Left ("refusing to register " <> storePathToText defaultStoreDir copyPath <> ": " <> T.pack sourceDir <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate")) added                  `andThen` assertEqual "sent" 1 (length (heldUploads state))            (copy, derivation) -> pure (Fail ("expected a copy path and a derivation, got: " <> T.pack (show (copy, fst3 <$> derivation)))),      runTestM "an add the daemon refuses fails with the daemon's message, and the connection goes on" $ do        daemon <- newFakeDaemon narHash (\_ _ -> Left (Ops.daemonError "the daemon refuses this")) [(fooPath, Set.empty)]        (tree, written, valid) <-          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops -> do            tree <- soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")            written <- case soEvalWrites ops of              AddedAsMade made -> moAdd made (TextWrite "note" Set.empty "text")              WrittenInDirectory -> pure (Left "the store did not take writes as they are made")            valid <- sqValidPaths (soQueries ops) (Set.singleton fooPath)            pure (tree, written, valid)        dials <- dialCounts (fakeDials daemon)        pure $          assertEqual "tree" (Left "the daemon refuses this") tree            `andThen` assertEqual "write" (Left "the daemon refuses this") written            `andThen` assertEqual "query" (Set.singleton fooPath) valid            `andThen` assertEqual "connections made and closed" (1, 1) dials,      runTestM "a tree evaluation makes is sent in its kind's spelling, and the path the daemon makes is the answer" $ do        daemon <- newFakeDaemon narHash contentPath []        let nar = NAR.serialise (NAR.NarRegular False "x")            writes =              [ TextWrite "note" (Set.singleton fooPath) "text",                NarWrite "tree" nar,                FlatWrite "file" "bytes"              ]        answered <-          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops -> case soEvalWrites ops of            AddedAsMade made -> traverse (moAdd made) writes            WrittenInDirectory -> pure [Left "the store did not take writes as they are made"]        state <- readIORef (fakeHeld daemon)        pure $          assertEqual            "paths"            [ first badStorePathText (makeTextPath "note" (sha256Digest "text") [fooPath]),              first badStorePathText (makeSourcePath "tree" (sha256Digest nar) Set.empty),              first badStorePathText (makeFixedOutputPath "file" "sha256" FlatIngestion (sha256Digest "bytes"))            ]            answered            `andThen` assertEqual              "uploads"              [ Upload "note" Proto.TextMethod "sha256" (Set.singleton fooPath) "text",                Upload "tree" (Proto.FixedMethod NarIngestion) "sha256" Set.empty nar,                Upload "file" (Proto.FixedMethod FlatIngestion) "sha256" Set.empty "bytes"              ]              (heldUploads state),      runTestM "a build asks the daemon to build each derivation's named outputs, and one naming no output is not asked" $ do        daemon <- newFakeDaemon narHash contentPath []        idle <- newFakeDaemon narHash contentPath []        built <-          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->            soBuild ops [(fooPath, Set.singleton "out"), (barPath, Set.fromList ["out", "dev"]), (missingPath, Set.empty)]        nothingAsked <-          withDaemonStore (storeConfig unusedDir) (fakeConnector idle) $ \ops ->            (,) <$> soBuild ops [] <*> soBuild ops [(fooPath, Set.empty)]        state <- readIORef (fakeHeld daemon)        dials <- dialCounts (fakeDials idle)        pure $          assertEqual "built" (Right ()) built            `andThen` assertEqual              "asked"              [ ( [(fooPath, Just (Set.singleton (Proto.OutputName "out"))), (barPath, Just (Set.fromList [Proto.OutputName "dev", Proto.OutputName "out"]))],                  Proto.BuildNormal                )              ]              [([(path, Proto.outputsSpecNames spec) | Proto.DerivedBuilt path spec <- targets], mode) | (targets, mode) <- heldBuilds state]            `andThen` assertEqual "nothing to build" (Right (), Right ()) nothingAsked            `andThen` assertEqual "connections made" (0, 0) dials,      runTestM "a check asks the daemon for every output of the derivation under the check mode" $ do        daemon <- newFakeDaemon narHash contentPath []        checked <- withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) (`soCheck` fooPath)        state <- readIORef (fakeHeld daemon)        pure $          assertEqual "checked" (Right ()) checked            `andThen` assertEqual "asked" [([Proto.DerivedBuilt fooPath Proto.AllOutputs], Proto.BuildCheck)] (heldBuilds state),      runTestM "a build the daemon fails stops with its message, and with status 1 from protocol 1.26 on, the activities it left open stopped, and one that cannot ask the daemon stops with the reason" $ do        let building = Building fooPath            report =              [ Ops.ActivityStarted (Ops.storeActivity defaultStoreDir (Proto.ActivityId 1) building),                Ops.ActivityResult (Proto.ActivityId 1) Proto.resBuildLogLine [Proto.FieldString "the builder says"]              ]            failure = (Ops.daemonError "builder for the derivation failed") {Proto.errExitStatus = 104}            failing version = do              daemon <- newFakeDaemonServing narHash version contentPath []              modifyIORef' (fakeHeld daemon) (\held -> held {heldBuildReport = report, heldBuildFailure = Just failure})              (logger, events) <- eventLogger              built <- withDaemonStore (storeConfig unusedDir) {dscLogger = logger} (fakeConnector daemon) $ \ops -> (,) <$> soBuild ops [(fooPath, Set.singleton "out")] <*> soCheck ops fooPath              logged <- events              pure (built, logged)            unreachable = pure (Left "Connection refused")        (current, currentLogged) <- failing daemonVersion        (older, _) <- failing (Proto.Version (Proto.VersionNumber 1 25) Set.empty)        cannot <- withDaemonStore (storeConfig unusedDir) unreachable $ \ops -> soBuild ops [(fooPath, Set.singleton "out")]        let stopped = [LoggedStart building, LoggedActivityLine building "the builder says", LoggedStop building]        pure $          assertEqual "current" (Left (BuildStop "builder for the derivation failed" 1), Left (BuildStop "builder for the derivation failed" 1)) current            `andThen` assertEqual "older" (Left (BuildStop "builder for the derivation failed" 104), Left (BuildStop "builder for the derivation failed" 104)) older            `andThen` assertEqual "each operation's activity started, given its line and stopped" (stopped <> stopped) currentLogged            `andThen` assertEqual "cannot ask" (Left (BuildStop (connectFailureText (dscAddress (storeConfig unusedDir)) "Connection refused") 1)) cannot,      runTestM "a session's settings carry the overrides a source set, and no override a source did not set" $ do        let configured = defaultNixConfig {ncSandbox = Just SandboxRelaxed, ncSubstituters = ["https://cache.example"], ncRestrictEval = True, ncKeepFailed = True, ncSandboxPaths = PathSetValue KeepsDefault (Set.singleton "/bin/sh"), ncRequireSigs = False}            assigned = replacedSettings ["sandbox", "substituters", "restrict-eval", "keep-failed", "sandbox-paths"]            config = (storeConfig unusedDir) {dscSettings = clientSettings assigned configured}        daemon <- newFakeDaemon narHash contentPath []        void (withDaemonStore config (fakeConnector daemon) (\ops -> sqValidPaths (soQueries ops) (Set.singleton fooPath)))        sentTo <- heldSettings <$> readIORef (fakeHeld daemon)        pure (assertEqual "sent" [Just (Ops.ClientSettings True False False (Proto.Verbosity 3) 1 0 True 0 True (Map.fromList [("extra-sandbox-paths", "/bin/sh"), ("sandbox", "relaxed"), ("substituters", "https://cache.example")]))] sentTo),      runTestM "an out-link is made by the client and rooted by the daemon, and a link inside the store, or a file in its place, is refused as the local store refuses it" $ do        linked <- symlinksAvailable        if not linked          then Pass <$ putStrLn "  SKIP  out-link roots need symlink privilege"          else withScratch "nn-store-outlink" $ \root -> do            let fileDir = StoreDir (root </> "store")                linkPath = root </> "links" </> "result"                insidePath = root </> "store" </> "result"                plainFile = root </> "plain"                config = storeConfig fileDir            daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]            BS.writeFile plainFile "not a link"            (made, inside, clobbered) <-              withDaemonStore config (fakeConnector daemon) $ \ops ->                (,,) <$> soAddOutLinkRoot ops linkPath fooPath <*> soAddOutLinkRoot ops insidePath fooPath <*> soAddOutLinkRoot ops plainFile fooPath            target <- Dir.getSymbolicLinkTarget linkPath            state <- readIORef (fakeHeld daemon)            let quoted path = "\"" <> T.pack path <> "\""            pure $              assertEqual "made" (Right linkPath) made                `andThen` assertEqual "points at the path in the directory the files are read from" (storePathToFilePath fileDir fooPath) target                `andThen` assertEqual "inside the store" (Left ("creating a garbage collector root (" <> quoted insidePath <> ") in the Nix store is forbidden (are you running nova-nix build inside the store?)")) inside                `andThen` assertEqual "a file in the way" (Left ("cannot create symlink " <> quoted plainFile <> "; already exists")) clobbered                `andThen` assertEqual "rooted for the connection before the link was looked at, the link made and the one refused" [TempRooted fooPath, TempRooted fooPath] (heldCalls state)                `andThen` assertEqual "the link's bytes recorded as an indirect root, for the link made alone" [BS8.pack linkPath] (heldIndirectRoots state)    ]  where    fst3 (path, _, _) = path    derivationPath (path, _, _) = path-- ----------------------------------------------------------------------------- Push and trust-- ----------------------------------------------------------------------------- | A build result that succeeded, as the daemon in memory is told to give-- it for a path.succeededResult :: Proto.BuildResultsucceededResult = builtResult (Proto.Succeeded (Proto.Success Proto.Substituted Map.empty))-- | A build result that failed with a status.failedResult :: Proto.FailureStatus -> Proto.BuildResultfailedResult status = builtResult (Proto.Failed (Proto.Failure status "failed" False))-- | A build result of an outcome, with no time taken.builtResult :: Proto.BuildOutcome -> Proto.BuildResultbuiltResult outcome = Proto.BuildResult outcome 0 0 0 Nothing Nothing-- | What a push reads of a path the daemon in memory holds with the NAR-- hash given, as a store's database spells the hash.pushedWith :: Proto.NarHash -> [StorePath] -> PushedPathpushedWith narHash references = PushedPath (CHash.formatNixHash (CHash.NixHash (Proto.narHashDigest narHash))) references Nothing-- | A store path, by the letter its hash repeats and its name.lettered :: Char -> Text -> StorePathlettered letter = StorePath (T.replicate 32 (T.singleton letter))-- | What a push reads and trust asks of a store through a daemon in-- memory that records what it is asked.pushTrustTests :: Proto.NarHash -> IO [Bool]pushTrustTests narHash =  sequence    [ runTestM "a push through the daemon roots each path before it asks its info, and reads the references, NAR hash and deriver the daemon gives" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.singleton barPath), (barPath, Set.empty)]        (found, absent, listed, referenced, unreferenced) <-          withDaemonPushSource (storeConfig unusedDir) (fakeConnector daemon) $ \source ->            (,,,,) <$> psPathInfo source fooPath <*> psPathInfo source missingPath <*> psAllValid source <*> psReferences source fooPath <*> psReferences source missingPath        state <- readIORef (fakeHeld daemon)        dials <- dialCounts (fakeDials daemon)        let rootedThenAsked path = [TempRooted path, InfoQueried path]        pure $          assertEqual "the record" (Right (Just (pushedWith narHash [barPath]))) found            `andThen` assertEqual "a path the daemon does not hold" (Right Nothing) absent            `andThen` assertEqual "every valid path" (Right (sort [fooPath, barPath])) listed            `andThen` assertEqual "the references of a held path" (Right [barPath]) referenced            `andThen` assertEqual "the references of a path the daemon does not hold" (Right []) unreferenced            `andThen` assertEqual "each path rooted, then asked, for its record and for its references" (concatMap rootedThenAsked [fooPath, missingPath, fooPath, missingPath]) (heldCalls state)            `andThen` assertEqual "connections made and closed" (1, 1) dials,      runTestM "a push through a daemon that cannot be reached fails each read with the reason, and is not tried again, and one that asks nothing never connects" $ do        let config = storeConfig unusedDir            unreachable = pure (Left "Connection refused")        (info, listed) <- withDaemonPushSource config unreachable $ \source -> (,) <$> psPathInfo source fooPath <*> psAllValid source        idle <- newFakeDaemon narHash contentPath []        withDaemonPushSource config (fakeConnector idle) (\_ -> pure ())        dials <- dialCounts (fakeDials idle)        pure $          assertEqual "info" (Left (connectFailureText (dscAddress config) "Connection refused")) info            `andThen` assertEqual "listing" (Left (previouslyFailedText (dscAddress config))) listed            `andThen` assertEqual "no connection for a source asked nothing" (0, 0) dials,      runTestM "a fetch through the daemon adds the fetch's derivation as a text with no references, unless the daemon holds it, and builds all its outputs" $        case recordedDerivation "fetched" [] [] of          Left bad -> pure (Fail bad)          Right (drvPath, drv, aterm) -> do            let node = DepNode drvPath drv Map.empty                recordedAterm path = if path == drvPath then Right aterm else Left "no .drv was recorded"                fetchWith daemon recorder = withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) recorder (`fosFetch` node)                buildsAll = [([Proto.DerivedBuilt drvPath Proto.AllOutputs], Proto.BuildNormal)]                upload = Upload (TE.encodeUtf8 (spName drvPath)) Proto.TextMethod "sha256" Set.empty aterm            empty <- newFakeDaemon narHash contentPath []            holding <- newFakeDaemon narHash contentPath [(drvPath, Set.empty)]            failing <- newFakeDaemon narHash contentPath []            modifyIORef' (fakeHeld failing) (\held -> held {heldBuildFailure = Just (Ops.daemonError "the builder failed")})            unrecorded <- newFakeDaemon narHash contentPath []            added <- fetchWith empty recordedAterm            skipped <- fetchWith holding recordedAterm            refused <- fetchWith failing recordedAterm            unknown <- fetchWith unrecorded (const (Left "no .drv was recorded"))            [addedState, skippedState, unrecordedState] <- traverse (readIORef . fakeHeld) [empty, holding, unrecorded]            unrecordedDials <- dialCounts (fakeDials unrecorded)            pure $              assertEqual "added" (Right ()) added                `andThen` assertEqual "uploaded" [upload] (heldUploads addedState)                `andThen` assertEqual "rooted before the daemon was asked which it holds" (Just (Set.singleton drvPath, Set.singleton drvPath)) (rootedBeforeAsked (heldCalls addedState))                `andThen` assertEqual "built" buildsAll (heldBuilds addedState)                `andThen` assertEqual "held" (Right ()) skipped                `andThen` assertEqual "not uploaded again" [] (heldUploads skippedState)                `andThen` assertEqual "built when held" buildsAll (heldBuilds skippedState)                `andThen` assertEqual "a build the daemon fails" (Left "the builder failed") refused                `andThen` assertEqual "no recorded derivation" (Left "no .drv was recorded") unknown                `andThen` assertEqual "nothing asked of the daemon" ([], [], (0, 0)) (heldCalls unrecordedState, heldBuilds unrecordedState, unrecordedDials),      runTestM "a substitution through the daemon roots the path first, asks nothing more for one the daemon holds, and ends as the daemon's result for any other says, never asking which substituters offer a path" $ do        let succeeded = lettered '3' "succeeded"            unoffered = lettered '4' "unoffered"            incomplete = lettered '5' "incomplete"            failed = lettered '6' "failed"            silent = lettered '7' "silent"            others = [succeeded, unoffered, incomplete, failed, silent]            results =              Map.fromList                [ (succeeded, succeededResult),                  (unoffered, failedResult Proto.NoSubstituters),                  (incomplete, failedResult Proto.DependencyFailed),                  (failed, failedResult Proto.MiscFailure)                ]        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        modifyIORef' (fakeHeld daemon) (\held -> held {heldResults = results})        outcomes <- withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) (const (Left "unused")) (\fixed -> traverse (fosSubstitute fixed) (fooPath : others))        state <- readIORef (fakeHeld daemon)        let rootedThenAsked path = [TempRooted path, Queried (Set.singleton path)]        pure $          assertEqual "outcomes, a result of no status being a failure" (map Right [ClosureComplete, ClosureComplete, ClosureUnavailable, ClosureIncomplete, ClosureFailed, ClosureFailed]) outcomes            `andThen` assertEqual "each path rooted, then asked whether the daemon holds it, and nothing else" (concatMap rootedThenAsked (fooPath : others)) (heldCalls state)            `andThen` assertEqual "only a path the daemon does not hold is realised, as an opaque path" [([Proto.DerivedOpaque path], Proto.BuildNormal) | path <- others] (heldBuilds state)            `andThen` assertEqual "no substituter was asked which paths it offers" [] [paths | OfferQueried paths <- heldCalls state],      runTestM "a substitution through a daemon older than protocol 1.34 fails with the client's reason for a path the daemon does not hold, and a path it holds needs no such answer" $ do        daemon <- newFakeDaemonServing narHash (Proto.Version (Proto.VersionNumber 1 33) Set.empty) contentPath [(fooPath, Set.empty)]        outcomes <- withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) (const (Left "unused")) (\fixed -> traverse (fosSubstitute fixed) [fooPath, barPath])        state <- readIORef (fakeHeld daemon)        pure $          assertEqual "outcomes" [Right ClosureComplete, Left "BuildPathsWithResults needs protocol 1.34, which the daemon does not speak"] outcomes            `andThen` assertEqual "nothing built" [] (heldBuilds state),      runTestM "a path held is asked of the daemon after it is rooted, and a daemon that cannot be reached is the reason" $ do        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]        held <- withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) (const (Left "unused")) (\fixed -> traverse (fosHeld fixed) [fooPath, barPath])        state <- readIORef (fakeHeld daemon)        unreachable <- withDaemonFixedOutputs (storeConfig unusedDir) (pure (Left "Connection refused")) (const (Left "unused")) (\fixed -> (,) <$> fosHeld fixed fooPath <*> fosSubstitute fixed fooPath)        pure $          assertEqual "held" [Right True, Right False] held            `andThen` assertEqual "each path rooted, then asked" [TempRooted fooPath, Queried (Set.singleton fooPath), TempRooted barPath, Queried (Set.singleton barPath)] (heldCalls state)            `andThen` assertEqual "unreachable" (Left (connectFailureText (dscAddress (storeConfig unusedDir)) "Connection refused"), Left (previouslyFailedText (dscAddress (storeConfig unusedDir)))) unreachable    ]-- ----------------------------------------------------------------------------- A source the process cannot read-- ----------------------------------------------------------------------------- | Adds of a source the process cannot read, through the archive walk-- itself ('NAR.withNarSource'), to a store reached through a daemon and to-- the local store.  A file, or a directory, with every permission removed-- is the unreadable source.  Windows has no mode that stops a file's owner-- reading it, and a process with the superuser's privileges reads a file-- whatever its mode, so these are skipped there, each with its reason.unreadableTests :: Proto.NarHash -> IO [Bool]unreadableTests narHash  | onWindows = [] <$ putStrLn "  SKIP  Windows has no file mode that stops a file's owner reading it"  | otherwise = withScratch "nn-store-unreadable" $ \root -> do      Dir.createDirectoryIfMissing True (root </> "store")      filed <- unreadableSource root "filed"      directoried <- unreadableSource root "directoried"      case (filed, directoried) of        (Right (filePath, fileDir), Right (dirPath, dirDir)) -> do          let file = fileDir </> unreadableName              storeRoot = StoreDir (root </> "store")              sourcesOf path dir = noObjects {eoSources = Map.singleton path (T.pack dir)}              walkWords path access = Left (T.pack path <> ": " <> access <> ": permission denied (Permission denied)")          readable <- denied file (isRight <$> (try (BS.readFile file) :: IO (Either IOException BS.ByteString)))          if readable            then [] <$ putStrLn "  SKIP  this process reads a file whose permissions are all removed, as the superuser does"            else              sequence                [ runTestM "an unreadable file in a source fails the add with the walk's words, closes the connection the upload was sent on, and leaves the next operation to connect again" $ do                    daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]                    (added, valid) <-                      denied file $                        withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) $ \ops ->                          (,) <$> soAddEvalObjects ops (sourcesOf filePath fileDir) <*> sqValidPaths (soQueries ops) (Set.singleton fooPath)                    state <- readIORef (fakeHeld daemon)                    dials <- dialCounts (fakeDials daemon)                    pure $                      assertEqual "added" (walkWords file "reading file") added                        `andThen` assertEqual "valid" (Set.singleton fooPath) valid                        `andThen` assertEqual "uploads" [] (heldUploads state)                        `andThen` assertEqual "connections made and closed" (2, 2) dials,                  runTestM "an unreadable directory in a source fails the add with the walk's words before anything is sent, and the connection goes on" $ do                    daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]                    (added, valid) <-                      denied dirDir $                        withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) $ \ops ->                          (,) <$> soAddEvalObjects ops (sourcesOf dirPath dirDir) <*> sqValidPaths (soQueries ops) (Set.singleton fooPath)                    state <- readIORef (fakeHeld daemon)                    dials <- dialCounts (fakeDials daemon)                    pure $                      assertEqual "added" (walkWords dirDir "listing directory") added                        `andThen` assertEqual "valid" (Set.singleton fooPath) valid                        `andThen` assertEqual "uploads" [] (heldUploads state)                        `andThen` assertEqual "connections made and closed" (1, 1) dials,                  runTestM "the local store answers an unreadable file in a source with the walk's words, and holds nothing of it" $ do                    (added, valid) <-                      denied file $                        withLocalStore quietLogger (defaultBuildConfig storeRoot) $ \ops ->                          (,) <$> soAddEvalObjects ops (sourcesOf filePath fileDir) <*> sqValidPaths (soQueries ops) (Set.singleton filePath)                    left <- Dir.doesPathExist (storePathToFilePath storeRoot filePath)                    pure $                      assertEqual "added" (walkWords file "reading file") added                        `andThen` assertEqual "valid" Set.empty valid                        `andThen` assertEqual "left behind" False left                ]        (copy, other) -> sequence [runTest "an unreadable source can be set up" (Fail ("expected two source trees, got: " <> T.pack (show (copy, other))))]-- | The name of the file in each source 'unreadableSource' makes.unreadableName :: FilePathunreadableName = "unreadable.txt"-- | A directory holding one file, and the path evaluation computes for it-- while it is readable.unreadableSource :: FilePath -> FilePath -> IO (Either Text (StorePath, FilePath))unreadableSource root name = do  let dir = root </> name      contents = "contents"      entry = NAR.NarDirectory [(BS8.pack unreadableName, NAR.NarRegular False contents)]  Dir.createDirectoryIfMissing True dir  BS.writeFile (dir </> unreadableName) contents  pure (bimap badStorePathText (,dir) (makeSourcePath (T.pack name) (sha256Digest (NAR.serialise entry)) Set.empty))-- | Run an action with every permission removed from a path, restored-- after so that the scratch directory can be removed.denied :: FilePath -> IO a -> IO adenied path = bracket (Dir.getPermissions path <* Dir.setPermissions path Dir.emptyPermissions) (Dir.setPermissions path) . const-- | The paths rooted before the first validity query, and the paths that-- query asked about, where the daemon was asked nothing else first and-- rooted something.rootedBeforeAsked :: [Called] -> Maybe (Set StorePath, Set StorePath)rootedBeforeAsked calls = case span isRooted calls of  (roots@(_ : _), Queried asked : _) -> Just (Set.fromList [path | TempRooted path <- roots], asked)  _ -> Nothing  where    isRooted = \case      TempRooted _ -> True      _ -> False-- | A transport whose reads end once the client has sent the operation-- that sets its options, as a daemon that goes away while it reads them-- looks to the client.losingOnSetOptions :: Conn.Transport IO -> IO (Conn.Transport IO)losingOnSetOptions transport = do  lost <- newIORef False  let send builder = do        when (BS.take (BS.length setOptionsCode) (BL.toStrict (BB.toLazyByteString builder)) == setOptionsCode) (writeIORef lost True)        Conn.transportSend transport builder      receive = readIORef lost >>= \gone -> if gone then pure Nothing else Conn.transportReceive transport  pure transport {Conn.transportReceive = receive, Conn.transportSend = send}-- | A transport that throws once the client sends the operation that sets-- its options.throwingOnSetOptions :: Conn.Transport IO -> Conn.Transport IOthrowingOnSetOptions transport = transport {Conn.transportSend = send}  where    send builder      | BS.take (BS.length setOptionsCode) (BL.toStrict (BB.toLazyByteString builder)) == setOptionsCode = throwIO (ErrorCall "the settings failed")      | otherwise = Conn.transportSend transport builder-- | What a request that sets the client's options begins with: its-- operation code, 19 on the wire, as a 64-bit number.setOptionsCode :: BS.ByteStringsetOptionsCode = BL.toStrict (BB.toLazyByteString (BB.word64LE 19))-- ----------------------------------------------------------------------------- A daemon serving a store of its own-- ----------------------------------------------------------------------------- | Evaluation and adds against a daemon serving a store of its own, over-- memory.servedTests :: IO [Bool]servedTests =  sequence    [ runTestM "an evaluation hands the daemon builtins.toFile's text as it makes it, after the copy it names, and the daemon then takes the derivation" $        withServedDaemon $ \served -> do          Dir.createDirectoryIfMissing True (servedRoot served </> "src")          BS.writeFile (servedRoot served </> "src" </> "hello.txt") "hello"          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do            evaluated <- evaluateRecording served ops "(let src = ./src; note = builtins.toFile \"note\" \"see ${src}\"; in derivation { name = \"served\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; inherit src note; }).drvPath"            case evaluated of              Left failure -> pure (Fail failure)              Right (_, objects) -> case (Map.keys (eoSources objects), mapMaybe (parseStorePath defaultStoreDir) (Map.keys (eoStoreWrites objects)), mapMaybe (parseStorePath defaultStoreDir) (Map.keys (eoDerivations objects))) of                ([src], [note], [drv]) -> do                  let store = servedStore served                  during <- traverse (isValid store) [src, note, drv]                  added <- soAddEvalObjects ops objects                  after <- traverse (isValid store) [src, note, drv]                  references <- traverse (referencesIn store) [src, note, drv]                  pure $                    assertEqual "valid as evaluation made them" [True, True, False] during                      `andThen` assertEqual "added" (Right ()) added                      `andThen` assertEqual "valid after" [True, True, True] after                      `andThen` assertEqual "references" [Set.empty, Set.singleton src, Set.fromList [src, note]] references                (sources, writes, derivations) -> pure (Fail ("expected one copy, one write and one derivation, got: " <> T.pack (show (sources, writes, derivations)))),      runTestM "a tree added through the daemon is valid in its store with the references it was added with" $        withServedDaemon $ \served ->          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do            let entry = NAR.NarDirectory [("link", NAR.NarSymlink "somewhere"), ("data", NAR.NarRegular False "data")]                store = servedStore served            dependency <- soAddSourceTree ops "dependency" Set.empty (NAR.NarRegular False "dependency")            case dependency of              Left refusal -> pure (Fail refusal)              Right dependencyPath -> do                tree <- soAddSourceTree ops "tree" (Set.singleton dependencyPath) entry                held <- traverse (isValid store) (either (const []) (\path -> [dependencyPath, path]) tree)                references <- either (const (pure Set.empty)) (referencesIn store) tree                pure $                  assertEqual "path" (first badStorePathText (makeSourcePath "tree" (sha256Digest (NAR.serialise entry)) (Set.singleton dependencyPath))) tree                    `andThen` assertEqual "valid" [True, True] held                    `andThen` assertEqual "references" (Set.singleton dependencyPath) references,      runTestM "derivations the daemon only takes with their inputs valid are all added, whichever order their keys give" $        withServedDaemon $ \served ->          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do            evaluated <- evaluateRecording served ops manyDependents            case evaluated of              Left failure -> pure (Fail failure)              Right (_, objects) -> do                added <- soAddEvalObjects ops objects                held <- traverse (isValid (servedStore served)) (mapMaybe (parseStorePath defaultStoreDir) (Map.keys (eoDerivations objects)))                pure $                  assertEqual "derivations" (dependentCount + 1) (Map.size (eoDerivations objects))                    `andThen` assertEqual "added" (Right ()) added                    `andThen` assertEqual "all valid" True (and held && not (null held)),      runTestM "a derivation whose input the daemon does not hold is refused in the daemon's words, and is not added" $        withServedDaemon $ \served ->          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do            evaluated <- evaluateRecording served ops "(let input = derivation { name = \"input\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; }; in derivation { name = \"dependent\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; args = [ \"${input}\" ]; }).drvPath"            case evaluated of              Left failure -> pure (Fail failure)              Right (named, objects) -> case (parseStorePath defaultStoreDir named, Map.keys (Map.delete named (eoDerivations objects))) of                (Just dependentPath, [inputKey]) -> do                  added <- soAddEvalObjects ops objects {eoDerivations = Map.filterWithKey (\key _ -> key == named) (eoDerivations objects)}                  held <- isValid (servedStore served) dependentPath                  pure $ case added of                    Left message -> assertEqual "the daemon's words" True (("cannot read derivation '" <> inputKey <> "': ") `T.isPrefixOf` message) `andThen` assertEqual "valid" False held                    Right () -> Fail "expected the add to be refused"                other -> pure (Fail ("expected the named derivation and its input, got: " <> T.pack (show other))),      runTestM "a build through the daemon realises the output, gives its builder's lines to the logger and roots ./result" $ do        shell <- findTestShell        linked <- symlinksAvailable        withServedDaemonConfigured unsandboxed $ \served -> case builtRecipe shell of          Left failure -> pure (Fail failure)          Right (built@(drvPath, _, _), builtOutput) -> do            (logger, events) <- eventLogger            let store = servedStore served                config = (servedConfig served) {dscLogger = logger}            withDaemonStore config (servedConnector served) $ \ops -> do              added <- soAddEvalObjects ops noObjects {eoDerivations = derivationMap [built]}              realised <- soBuild ops [(drvPath, Set.singleton "out")]              valid <- isValid store builtOutput              contents <- try (BS.readFile (storePathToFilePath (stDir store) builtOutput))              logged <- events              rooted <-                if linked                  then outLinkRooted served ops builtOutput                  else Pass <$ putStrLn "  SKIP  out-link roots need symlink privilege"              let building = Building drvPath                  activity = [event | event <- logged, not (isMessage event)]                  isMessage = \case LoggedMessage _ _ -> True; _ -> False              pure $                assertEqual "added" (Right ()) added                  `andThen` assertEqual "built" (Right ()) realised                  `andThen` assertEqual "valid" True valid                  `andThen` assertEqual "contents" (Right "built\n") (first (\(err :: IOException) -> displayException err) contents)                  `andThen` assertEqual "the build an activity of the logger, its builder's line the activity's" [LoggedStart building, LoggedActivityLine building "hi", LoggedStop building] activity                  `andThen` rooted,      runTestM "a push through the daemon writes to a cache byte for byte what a push of the store opened directly writes" $        withServedDaemon $ \served -> case throwawayKey (BS.replicate ed25519SeedBytes 5) >>= Signing.parseSecretKey . fst of          Left failure -> pure (Fail (T.pack failure))          Right secretKey -> pushedBothWays served secretKey,      runTestM "a fetch through the daemon makes a builtin fetch's output valid in the daemon's store, and the scan reads it, while an input no substituter offers is left unread" $        let contents = "fetched through the daemon\n"         in withHttpServer (\_ _ -> Send (httpResponse "200 OK" contents)) $ \url _ _ -> withServedDaemonConfigured unsandboxed $ \served ->              case (fetchRecipe "fetched" (OtherPlatform "builtin") "builtin:fetchurl" url contents, fetchRecipe "offered-nowhere" currentPlatform "/bin/sh" "http://127.0.0.1:9/never" contents) of                (Right ((fetchedPath, fetchedDrv, fetchedAterm), fetchedOutput), Right ((otherPath, otherDrv, otherAterm), otherOutput)) -> do                  let store = servedStore served                      inputs = [(DepNode fetchedPath fetchedDrv Map.empty, fetchedOutput), (DepNode otherPath otherDrv Map.empty, otherOutput)]                      recordedAterm path = maybe (Left "no .drv was recorded") Right (lookup path [(fetchedPath, fetchedAterm), (otherPath, otherAterm)])                  scanned <- withDaemonFixedOutputs (servedConfig served) (servedConnector served) recordedAterm (`fetchAndScan` inputs)                  held <- traverse (isValid store) [fetchedOutput, otherOutput]                  fetched <- try (BS.readFile (storePathToFilePath (stDir store) fetchedOutput))                  expected <- scanFetched (storePathToFilePath (stDir store) fetchedOutput)                  pure $                    assertEqual "scanned" (Right (Map.singleton fetchedOutput expected)) scanned                      `andThen` assertEqual "held in the daemon's store" [True, False] held                      `andThen` assertEqual "contents" (Right contents) (first (\(err :: IOException) -> displayException err) fetched)                (fetch, other) -> pure (Fail ("expected two fixed-output recipes, got: " <> T.pack (show (snd <$> fetch, snd <$> other)))),      runTestM "a substitution through the daemon takes a path from a file:// cache that does not declare mass queries, and a path the cache lacks is unavailable" $        withScratch "nn-daemon-store-cache" $ \cacheRoot -> case signingKeys (BS.replicate ed25519SeedBytes 6) of          Left failure -> pure (Fail (T.pack failure))          Right (secretKey, publicKey) -> do            let cache = cacheRoot </> "cache"                cached = lettered 'p' "cached"                lacking = lettered 'q' "lacking"                daemonConfig = unsandboxed {ncSubstituters = [directoryUrl cache], ncTrustedPublicKeys = [Signing.renderPublicKey publicKey]}            pushed <- pushedToCache (cacheRoot </> "source") cache secretKey cached            cacheInfo <- BS.readFile (cache </> cacheInfoFileName)            withServedDaemonConfigured daemonConfig $ \served -> do              outcomes <- withDaemonFixedOutputs (servedConfig served) (servedConnector served) (const (Left "unused")) (\fixed -> traverse (fosSubstitute fixed) [cached, lacking])              held <- traverse (isValid (servedStore served)) [cached, lacking]              contents <- try (BS.readFile (storePathToFilePath (stDir (servedStore served)) cached </> "data"))              pure $                assertEqual "pushed to the cache" (Right (PushSummary 1 0)) pushed                  `andThen` assertEqual "the cache names its store directory and no mass query" cacheInfoText cacheInfo                  `andThen` assertEqual "outcomes" (map Right [ClosureComplete, ClosureUnavailable]) outcomes                  `andThen` assertEqual "held in the daemon's store" [True, False] held                  `andThen` assertEqual "contents" (Right (treeContents cached)) (first (\(err :: IOException) -> displayException err) contents)    ]-- | A fixed-output derivation named @name@ that fetches a URL with a-- builder and for a platform, as evaluation records it, and the path of its-- output, which the contents it is fixed to make.fetchRecipe :: Text -> Platform -> BS.ByteString -> Text -> BS.ByteString -> Either Text (Recorded, StorePath)fetchRecipe name platform builder url contents = do  output <- first badStorePathText (makeFixedOutputPath name "sha256" FlatIngestion (sha256Digest contents))  let drv =        Derivation          { drvOutputs = [DerivationOutput "out" output "sha256" (bytesToHexText (sha256Digest contents))],            drvInputDrvs = Map.empty,            drvInputSrcs = [],            drvPlatform = platform,            drvBuilder = builder,            drvArgs = [],            drvEnv = Map.fromList [("url", TE.encodeUtf8 url), ("out", TE.encodeUtf8 (storePathToText defaultStoreDir output))]          }  file <- first badStorePathText (drvFile name drv)  pure ((drvFilePath file, drvFileDerivation file, drvFileATerm file), output)-- | Paths added through the daemon, and one the store's own writer-- registers with a deriver, pushed to a cache directory through the daemon-- and, signed by the same key, from the store opened directly: the two-- caches hold the same files.pushedBothWays :: Served -> Signing.SecretKey -> IO TestResultpushedBothWays served secretKey = fmap (either Fail id) . runExceptT $ do  let store = servedStore served      derived = lettered 'd' "derived.drv"      derivedOutput = lettered 'f' "derived"      derivedSource = servedRoot served </> "derived-source"      daemonCache = servedRoot served </> "cache-daemon"      directCache = servedRoot served </> "cache-direct"      pushTo cache = pushToDirectory (DirectoryPush cache secretKey PushNone)      entry = NAR.NarDirectory [("link", NAR.NarSymlink "somewhere"), ("data", NAR.NarRegular False "data")]  tree <- ExceptT . withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> runExceptT $ do    dependency <- ExceptT (soAddSourceTree ops "dependency" Set.empty (NAR.NarRegular False "dependency"))    ExceptT (soAddSourceTree ops "tree" (Set.singleton dependency) entry)  -- The writer records a deriver, which a tree added through the daemon  -- has none of, so the narinfos carry that line too.  liftIO $ do    Dir.createDirectoryIfMissing True derivedSource    BS.writeFile (derivedSource </> "data") "built from a derivation"    addToStore store derivedSource derivedOutput (Just (T.pack (storePathToFilePath (stDir store) derived))) [tree]  let roots = [derivedOutput, tree]  (throughDaemon, direct, daemonFiles, directFiles) <- liftIO $ do    throughDaemon <- withDaemonPushSource (servedConfig served) (servedConnector served) (\source -> pushTo daemonCache source roots)    direct <- pushTo directCache (localPushSource store) roots    (,,,) throughDaemon direct <$> cacheListing daemonCache <*> cacheListing directCache  pure $    assertEqual "pushed through the daemon" (Right (PushSummary 3 0)) throughDaemon      `andThen` assertEqual "pushed directly" (Right (PushSummary 3 0)) direct      `andThen` assertEqual "the files of the two caches" directFiles daemonFiles      `andThen` assertEqual "a narinfo and a NAR for each path, and the cache's own file" True (length daemonFiles > 6)-- | A secret key from a seed, with the public key that verifies what it-- signs.signingKeys :: BS.ByteString -> Either String (Signing.SecretKey, Signing.PublicKey)signingKeys seed = do  (keyText, publicKey) <- throwawayKey seed  secretKey <- Signing.parseSecretKey keyText  pure (secretKey, publicKey)-- | What the tree of a path holds in its file @data@.treeContents :: StorePath -> BS.ByteStringtreeContents path = TE.encodeUtf8 (spName path) <> "\n"-- | A store of its own under a directory, holding a path with a tree, which-- is pushed to a @file://@ cache directory as 'pushToDirectory' writes one.pushedToCache :: FilePath -> FilePath -> Signing.SecretKey -> StorePath -> IO (Either Text PushSummary)pushedToCache sourceDir cache secretKey path = do  let tree = sourceDir </> "tree"      storeDir = sourceDir </> "store"  traverse_ (Dir.createDirectoryIfMissing True) [tree, storeDir]  BS.writeFile (tree </> "data") (treeContents path)  bracket (openStore quietLogger (StoreDir storeDir)) closeStore $ \store -> do    addToStore store tree path Nothing []    pushToDirectory (DirectoryPush cache secretKey PushNone) (localPushSource store) [path]-- | The daemon's own settings for a build: unsandboxed, with no cache to-- ask.unsandboxed :: NixConfigunsandboxed = defaultNixConfig {ncSandbox = Just SandboxDisabled, ncSubstituters = []}-- | A derivation named @built@ whose builder, run by the shell given,-- writes a line and its output, as evaluation records it, and the output's-- path: input-addressed, as a daemon checks it is before it builds.builtRecipe :: Text -> Either Text (Recorded, StorePath)builtRecipe shell = do  file <- first badStorePathText (inputAddressed "built" [] (mkTestBuildDrv shell (StorePath (T.replicate 32 "0") "built") "echo hi; echo built > $out"))  case drvOutputs (drvFileDerivation file) of    [output] -> Right ((drvFilePath file, drvFileDerivation file, drvFileATerm file), doPath output)    other -> Left ("expected the one output, got " <> T.pack (show (length other)))-- | The link a build's output is given in the working directory, a-- directory of its own, by name alone: made, pointing at the output, and-- the output the daemon's store roots through it.outLinkRooted :: Served -> StoreOps IO -> StorePath -> IO TestResultoutLinkRooted served ops builtOutput = do  let store = servedStore served  rooted <- Dir.withCurrentDirectory (servedRoot served) (soAddOutLinkRoot ops "result" builtOutput)  case rooted of    Left failure -> pure (Fail failure)    Right link -> do      target <- Dir.getSymbolicLinkTarget link      roots <- findRoots store      pure $        assertEqual "named in the working directory" "result" (takeFileName link)          `andThen` assertEqual "points at the output" (storePathToFilePath (stDir store) builtOutput) target          `andThen` assertEqual "rooted by the daemon's store" [GcRoot link (T.pack (storePathToFilePath (stDir store) builtOutput))] roots-- | An expression of one input derivation and the many that name it as an-- input, so that some sort before it.manyDependents :: TextmanyDependents =  T.unlines    [ "let",      "  input = derivation { name = \"input\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; };",      "  dependent = n: derivation { name = \"dependent-${toString n}\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; args = [ \"${input}\" ]; };",      "in builtins.concatStringsSep \"\\n\" (map (n: (dependent n).drvPath) (builtins.genList (n: n) " <> T.pack (show dependentCount) <> "))"    ]-- | Evaluate an expression that is a string in a read-write session over-- the daemon's store, and answer the string and what the session recorded-- for the store to add, as a command reads it from the session.evaluateRecording :: Served -> StoreOps IO -> Text -> IO (Either Text (Text, EvalObjects))evaluateRecording served ops source = do  st <- newEvalStateWith quietLogger unrestrictedPolicy [] (ReadWriteSession ops) (servedFileDir served) (servedRoot served)  evaluated <- evalNixIOIn st (servedRoot served) source  made <- EvalObjects . sourceCopies <$> readIORef (esSourcePathCache st) <*> readIORef (esStoreWriteCache st) <*> readIORef (esDrvClosure st)  pure $ case evaluated of    Right (VStr bytes _) -> either (\err -> Left ("the string is not UTF-8: " <> T.pack (show err))) (\text -> Right (text, made)) (TE.decodeUtf8' bytes)    Right other -> Left ("expected a string, got: " <> T.pack (show other))    Left failure -> Left failure-- | The references a store records for a path.referencesIn :: Store -> StorePath -> IO (Set StorePath)referencesIn store path = Set.fromList . mapMaybe (parseStorePath (stDir store)) <$> queryReferences (stDB store) path-- | A daemon serving a store of its own in a scratch directory, over-- memory.data Served = Served  { servedRoot :: !FilePath,    servedStore :: !Store,    servedConnector :: !Connector  }-- | The directory the served store's files are in, which a command's-- store configuration reads them from and an evaluation over it gives its-- session as its store directory.  Paths cross the wire under the-- canonical store directory whatever it is.servedFileDir :: Served -> StoreDirservedFileDir = stDir . servedStore-- | The configuration of a command's store over the served daemon.servedConfig :: Served -> DaemonStoreConfigservedConfig = storeConfig . servedFileDir-- | Run a test against a daemon serving a store of its own in a scratch-- directory, over memory, which serves the version the daemon command-- serves and names paths under the canonical store directory.withServedDaemon :: (Served -> IO TestResult) -> IO TestResultwithServedDaemon = withServedDaemonConfigured defaultNixConfig-- | 'withServedDaemon', the daemon's own settings given.withServedDaemonConfigured :: NixConfig -> (Served -> IO TestResult) -> IO TestResultwithServedDaemonConfigured daemonConfig body = withScratch "nn-daemon-store" $ \root -> do  Dir.createDirectoryIfMissing True (root </> "store")  bracket (openStore quietLogger (StoreDir (root </> "store"))) closeStore $ \store -> do    served <- newServedStore servedDefaults store    dials <- newDials    body (Served root store (memoryConnector dials (serveLocal served (serverConfigAt daemonVersion) {Conn.scConfig = daemonConfig} Proto.Trusted)))-- | Machine defaults a served store's builds fall back on, the same on-- every machine: one core, no sandbox helper or bundled shell, not root,-- so no build users, and no certificate bundle.servedDefaults :: MachineDefaultsservedDefaults =  MachineDefaults    { mdCores = 1,      mdSandboxHelper = Nothing,      mdSandboxShell = Set.empty,      mdPrivilege = RunsUnprivileged,      mdUserPool = "/nix/var/nix/userpool",      mdCaFile = Nothing    }