{-# LANGUAGE LambdaCase #-}-- | Tests of the daemon's client ("Nix.Daemon.Client"): sessions run in-- memory against the daemon's side of a connection-- ("Nix.Daemon.Connection") over a store held in memory, the operations-- an older daemon is not sent, and the daemon's messages given to a logger.module Test.DaemonClient ( testDaemonClient, testDaemonClientIO, Logged (..), eventLogger, Standing (..), standing, channelTransport, sampleInfo, serverConfigAt, withNarHash, fooPath, barPath, missingPath, )whereimport Control.Concurrent (ThreadId, throwTo, yield)import Control.Concurrent.Async (async, asyncThreadId, wait, withAsync)import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, takeMVar, tryPutMVar)import Control.Exception (Exception, finally, try, uninterruptibleMask_)import Control.Monad (void)import qualified Data.ByteString as BSimport qualified Data.ByteString.Builder as BBimport qualified Data.ByteString.Lazy as BLimport Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)import qualified Data.Map.Strict as Mapimport qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport GHC.Conc (ThreadStatus (..), threadStatus)import Nix.Config (defaultNixConfig)import qualified Nix.Daemon.Client as Clientimport qualified Nix.Daemon.Connection as Connimport qualified Nix.Daemon.Ops as Opsimport qualified Nix.Daemon.Protocol as Protoimport Nix.Hash (sha256Digest)import Nix.Logger (ActivityStart (..), Level (..), Logger (..), plainLogger)import Nix.Store.Path (StoreDir, defaultStoreDir)import Nix.Store.Path.Internal (StorePath (..))import qualified System.Info as SIimport System.Timeout (timeout)import Test.Harness (TestResult (..), andThen, assertEqual, runTest, runTestM)-- ----------------------------------------------------------------------------- Without a connection-- ----------------------------------------------------------------------------- | The daemon's messages, without a connection.testDaemonClient :: IO [Bool]testDaemonClient = do putStrLn "daemon/client" sequence [ runTestM "the daemon's messages reach a logger as the local store's own calls" $ do (logger, events) <- eventLogger relay <- Client.newRelay defaultStoreDir logger let building = Building fooPath started = Ops.storeActivity defaultStoreDir (Proto.ActivityId 7) building unknown = Proto.ActivityId 99 mapM_ (Client.relayMessage relay) [ Proto.StderrNext "warning: x\n", Proto.StderrStartActivity started, Proto.StderrStartActivity started {Proto.actId = Proto.ActivityId 8, Proto.actType = Proto.ActivityType 100}, Proto.StderrResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "built a line"], Proto.StderrResult unknown Proto.resBuildLogLine [Proto.FieldString "an unknown activity's line"], Proto.StderrResult (Proto.ActivityId 7) Proto.resPostBuildLogLine [Proto.FieldString "hooked"], Proto.StderrResult (Proto.ActivityId 7) (Proto.ResultType 105) [Proto.FieldInt 1], Proto.StderrStopActivity (Proto.ActivityId 8), Proto.StderrStopActivity (Proto.ActivityId 7), Proto.StderrResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "after the stop"] ] assertEqual "logged" [ LoggedMessage LevelError "warning: x", LoggedStart building, LoggedActivityLine building "built a line", LoggedBuildLine "an unknown activity's line", LoggedMessage LevelInfo "post-build-hook: hooked", LoggedStop building, LoggedBuildLine "after the stop" ] <$> events, runTest "a message of the daemon's is what a logger takes of it, and a line is shown without its trailing whitespace and with any byte that is not UTF-8 replaced" $ let started = Ops.storeActivity defaultStoreDir (Proto.ActivityId 3) (Substituting fooPath "https://cache.example") relayedAs = Client.relayed defaultStoreDir in assertEqual "message" (Client.RelayedMessage "caf\xFFFD") (relayedAs (Proto.StderrNext "caf\xE9 \t\r\n ")) `andThen` assertEqual "start" (Client.RelayedStart 3 (Substituting fooPath "https://cache.example")) (relayedAs (Proto.StderrStartActivity started)) `andThen` assertEqual "another kind" Client.RelayedNothing (relayedAs (Proto.StderrStartActivity started {Proto.actType = Proto.ActivityType 100})) `andThen` assertEqual "result of another kind" Client.RelayedNothing (relayedAs (Proto.StderrResult (Proto.ActivityId 3) (Proto.ResultType 105) [Proto.FieldInt 1])) `andThen` assertEqual "result with no line" Client.RelayedNothing (relayedAs (Proto.StderrResult (Proto.ActivityId 3) Proto.resBuildLogLine [])) `andThen` assertEqual "stop" (Client.RelayedStop 3) (relayedAs (Proto.StderrStopActivity (Proto.ActivityId 3))) `andThen` assertEqual "end of the work" Client.RelayedNothing (relayedAs Proto.StderrLast), runTestM "activities a failed operation left open are stopped, latest first, once, and an activity started under a number already open stops the one it replaces" $ do (logger, events) <- eventLogger relay <- Client.newRelay defaultStoreDir logger let start number target = Proto.StderrStartActivity (Ops.storeActivity defaultStoreDir (Proto.ActivityId number) target) mapM_ (Client.relayMessage relay) [start 1 (Building fooPath), start 2 (Checking barPath), start 1 (Building missingPath)] Client.stopOpenActivities relay Client.stopOpenActivities relay Client.relayMessage relay (Proto.StderrStopActivity (Proto.ActivityId 2)) assertEqual "logged" [ LoggedStart (Building fooPath), LoggedStart (Checking barPath), LoggedStart (Building missingPath), LoggedStop (Building fooPath), LoggedStop (Checking barPath), LoggedStop (Building missingPath) ] <$> events, runTestM "an exception that arrives as the daemon's start of an activity is kept leaves the activity kept, so that it is stopped" $ do -- The logger's start call cannot be interrupted until its last -- step, so the exception thrown while it runs is delivered the -- moment the call lets it, which is where the call is only -- masked by the relay. inLogger <- newEmptyMVar proceed <- newEmptyMVar stops <- newIORef (0 :: Int) let logger = (plainLogger (\_ _ -> pure ()) (\_ -> pure ())) { logActivity = \_ -> do putMVar inLogger () uninterruptibleMask_ (takeMVar proceed) pure (\_ -> pure (), modifyIORef' stops (+ 1)) } start = Proto.StderrStartActivity (Ops.storeActivity defaultStoreDir (Proto.ActivityId 1) (Building fooPath)) relay <- Client.newRelay defaultStoreDir logger reader <- async (try (Client.relayMessage relay start)) takeMVar inLogger thrower <- async (throwTo (asyncThreadId reader) Interrupted) throwing <- standing (asyncThreadId thrower) putMVar proceed () interrupted <- wait reader wait thrower Client.stopOpenActivities relay stopped <- readIORef stops pure $ assertEqual "the exception waits for the reader" Waiting throwing `andThen` assertEqual "the reader was interrupted when the start was kept" (Left Interrupted) interrupted `andThen` assertEqual "the activity was kept, so it is stopped" 1 stopped ]-- ----------------------------------------------------------------------------- Sessions-- ----------------------------------------------------------------------------- | Sessions run in memory against the daemon's side of a connection.testDaemonClientIO :: IO [Bool]testDaemonClientIO = do putStrLn "daemon/client-sessions" withNarHash "daemon/client-sessions" $ \narHash -> sessionTests narHash-- | The sessions, given the NAR hash the store's infos carry.sessionTests :: Proto.NarHash -> IO [Bool]sessionTests narHash = sequence [ runTestM "the handshake agrees the newest version and the three features, and hears the daemon's version and trust" $ do (outcome, end) <- session narHash Proto.Trusted latest $ (,) <$> Client.agreedVersion <*> Client.daemonInfo pure $ assertEqual "outcome" (Right (Client.offeredVersion, Just (Proto.HandshakeInfo (Just nixVersion) (Just Proto.Trusted)))) outcome `andThen` assertEqual "end" Conn.ClientClosed end, runTestM "an older daemon's version is agreed, with no features and none of what it tells from later versions, and a request it does not carry is not sent while the session goes on" $ do let older = Proto.Version (Proto.VersionNumber 1 30) Set.empty (outcome, _) <- session narHash Proto.NotTrusted older $ do version <- Client.agreedVersion refused <- Client.attempt (Client.buildPathsWithResults [] Proto.BuildNormal) valid <- Client.isValidPath fooPath info <- Client.daemonInfo pure (version, refused, valid, info) pure $ assertEqual "outcome" (Right (older, Left (Client.NotSent "BuildPathsWithResults needs protocol 1.34, which the daemon does not speak"), True, Just (Proto.HandshakeInfo Nothing Nothing))) outcome, runTestM "a daemon older than an operation is not sent it, saying which version it needs, and a query's substitute flag is left out below 1.27, as upstream's client leaves it out" $ do let oldest = Proto.Version Proto.minimumVersionNumber Set.empty (outcome, _) <- session narHash Proto.Trusted oldest $ do missing <- Client.attempt (Client.queryMissing [Proto.DerivedOpaque fooPath]) outputs <- Client.attempt (Client.queryDerivationOutputMap drvPath) results <- Client.attempt (Client.buildPathsWithResults [Proto.DerivedOpaque fooPath] Proto.BuildNormal) valid <- Client.queryValidPaths (Set.fromList [fooPath, missingPath]) Ops.Substitute after <- Client.isValidPath fooPath pure (missing, outputs, results, valid, after) let notSent operation minor = Left (Client.NotSent (operation <> " needs protocol 1." <> minor <> ", which the daemon does not speak")) pure $ case outcome of Right (missing, outputs, results, valid, after) -> assertEqual "missing" (notSent "QueryMissing" "19") (void missing) `andThen` assertEqual "outputs" (notSent "QueryDerivationOutputMap" "22") (void outputs) `andThen` assertEqual "results" (notSent "BuildPathsWithResults" "34") (void results) `andThen` assertEqual "valid" (Set.singleton fooPath) valid `andThen` assertEqual "after" True after Left failure -> Fail (T.pack (show failure)), runTestM "the queries answer what the store holds" $ do (outcome, _) <- session narHash Proto.Trusted latest $ do valid <- Client.isValidPath fooPath invalid <- Client.isValidPath missingPath validAmong <- Client.queryValidPaths (Set.fromList [fooPath, missingPath]) Ops.NoSubstitute everything <- Client.queryAllValidPaths referrers <- Client.queryReferrers barPath info <- Client.queryPathInfo fooPath noInfo <- Client.queryPathInfo missingPath outputs <- Client.queryDerivationOutputMap drvPath missing <- Client.queryMissing [Proto.DerivedOpaque missingPath] pure (valid, invalid, validAmong, everything, referrers, info, noInfo, outputs, missing) pure $ case outcome of Right (valid, invalid, validAmong, everything, referrers, info, noInfo, outputs, missing) -> assertEqual "valid" True valid `andThen` assertEqual "invalid" False invalid `andThen` assertEqual "valid among" (Set.singleton fooPath) validAmong `andThen` assertEqual "everything" (Set.fromList [fooPath, barPath, drvPath]) everything `andThen` assertEqual "referrers" (Set.singleton fooPath) referrers `andThen` assertEqual "info" (Just (sampleInfo narHash (Set.singleton barPath))) info `andThen` assertEqual "no info" Nothing noInfo `andThen` assertEqual "outputs" (Map.fromList [(Proto.OutputName "out", Just fooPath)]) outputs `andThen` assertEqual "missing" (Proto.Missing Set.empty Set.empty (Set.singleton missingPath) 0 0) missing Left failure -> Fail (T.pack (show failure)), runTestM "settings sent reach the store's work, and roots and paths asked for reach the store" $ do (outcome, _, fake) <- sessionWith narHash Proto.Trusted latest $ do Client.setOptions sampleSettings Client.addTempRoot fooPath Client.addIndirectRoot rootedLink Client.ensurePath barPath pure $ assertEqual "outcome" (Right ()) outcome `andThen` assertEqual "settings" (Just sampleSettings) (fakeSettings fake) `andThen` assertEqual "temporary roots" (Set.singleton fooPath) (fakeTempRoots fake) `andThen` assertEqual "indirect roots" (Set.singleton rootedLink) (fakeIndirectRoots fake) `andThen` assertEqual "ensured" [barPath] (fakeEnsured fake), runTestM "a NAR uploaded in chunks reaches the store whole, and its path is valid after" $ do chunks <- newIORef ["nar of ", "new", ""] let source = atomicModifyIORef' chunks (\case (chunk : rest) -> (rest, chunk); [] -> ([], BS.empty)) info = Proto.ValidPathInfo newPath (sampleInfo narHash Set.empty) (outcome, _, fake) <- sessionWith narHash Proto.Trusted latest $ do Client.addToStoreNar info Ops.NoRepair Ops.CheckSigs source Client.isValidPath newPath pure $ assertEqual "outcome" (Right True) outcome `andThen` assertEqual "uploaded" ["nar of new"] (fakeUploads fake), runTestM "a dump uploaded makes a path, whose info the client is given" $ do chunks <- newIORef ["the ", "dump", ""] let source = atomicModifyIORef' chunks (\case (chunk : rest) -> (rest, chunk); [] -> ([], BS.empty)) (outcome, _, fake) <- sessionWith narHash Proto.Trusted latest (Client.addToStore (Ops.AddToStoreRequest "dump" "text:sha256" Set.empty Ops.NoRepair) source) pure $ assertEqual "outcome" (Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty))) outcome `andThen` assertEqual "uploaded" ["the dump"] (fakeUploads fake), runTestM "an upload the daemon answers with more output than the connection holds is not stuck, the daemon's messages being read while the frames are sent" $ do state <- newIORef (startingFake narHash) toDaemon <- newEmptyMVar toClient <- newEmptyMVar daemonTransport <- boundedTransport toDaemon toClient clientTransport <- boundedTransport toClient toDaemon heard <- newIORef (0 :: Int) chunks <- newIORef (replicate uploadChunkCount "chunk;" <> [BS.empty]) let source = atomicModifyIORef' chunks (\case (chunk : rest) -> (rest, chunk); [] -> ([], BS.empty)) request = Ops.AddToStoreRequest "dump" "text:sha256" Set.empty Ops.NoRepair store = (fakeStore narHash state) {Ops.dsAddToStore = \work _ -> pure (reportingEachChunk work state narHash)} daemon = Conn.serveConnection (serverConfigAt latest) Proto.Trusted store daemonTransport `finally` tryPutMVar toClient Nothing countLines = \case Proto.StderrNext _ -> modifyIORef' heard (+ 1); _ -> pure () finished <- withAsync daemon $ \_ -> timeout uploadDeadlockMicros (Client.runClient storeDir Client.offeredVersion clientTransport countLines (Client.addToStore request source) `finally` tryPutMVar toDaemon Nothing) linesHeard <- readIORef heard fake <- readIORef state pure $ case finished of Nothing -> Fail "the upload did not finish: the daemon's output was not read while the frames were sent" Just outcome -> assertEqual "outcome" (Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty))) outcome `andThen` assertEqual "uploaded" [BS.concat (replicate uploadChunkCount "chunk;")] (fakeUploads fake) `andThen` assertEqual "lines heard" uploadChunkCount linesHeard, runTestM "a build's messages reach the report as they come, then its results" $ do reported <- newIORef [] (outcome, _, _) <- sessionReporting (\message -> modifyIORef' reported (message :)) narHash Proto.Trusted latest $ do results <- Client.buildPathsWithResults [Proto.DerivedOpaque fooPath] Proto.BuildNormal Client.buildPaths [Proto.DerivedOpaque fooPath] Proto.BuildNormal pure results messages <- reverse <$> readIORef reported pure $ assertEqual "outcome" (Right [Proto.KeyedBuildResult (Proto.DerivedOpaque fooPath) sampleBuildResult]) outcome `andThen` assertEqual "messages" (concat (replicate 2 buildMessages)) messages, runTestM "a daemon's error fails the operation, and the session goes on" $ do (outcome, _) <- session narHash Proto.Trusted latest $ do failed <- Client.attempt (Client.queryReferrers refusedPath) valid <- Client.isValidPath fooPath pure (failed, valid) pure (assertEqual "outcome" (Right (Left (Client.DaemonFailed (Ops.daemonError refusalMessage)), True)) outcome), runTestM "a request the daemon refuses before its work fails, and the connection it closes is lost" $ do (outcome, end) <- session narHash Proto.NotTrusted latest $ do refused <- Client.attempt (Client.addToStoreNar (Proto.ValidPathInfo newPath (sampleInfo narHash Set.empty)) Ops.Repair Ops.CheckSigs (pure BS.empty)) after <- Client.attempt (Client.isValidPath fooPath) final <- Client.attempt (Client.isValidPath fooPath) pure (refused, isLeft after, final) pure $ assertEqual "outcome" (Right (Left (Client.DaemonFailed (Ops.daemonError "you are not privileged to repair store paths")), True, Left (Client.ConnectionLost Client.disconnectedMessage))) outcome `andThen` assertEqual "end" (Conn.ClosedOnError (Ops.daemonError "you are not privileged to repair store paths")) end, runTestM "a daemon that is gone fails the handshake in upstream's words" $ do let gone = Conn.Transport (pure Nothing) (\_ -> pure ()) outcome <- Client.runClient storeDir Client.offeredVersion gone (\_ -> pure ()) (pure ()) pure (assertEqual "outcome" (Left (Client.ConnectionLost Client.disconnectedMessage)) outcome), runTestM "a session opened once serves operations run one after another, the daemon's bytes carried between them" $ do state <- newIORef (startingFake narHash) toDaemon <- newChan toClient <- newChan daemonTransport <- channelTransport toDaemon toClient clientTransport <- channelTransport toClient toDaemon let daemon = Conn.serveConnection (serverConfigAt latest) Proto.Trusted (fakeStore narHash state) daemonTransport `finally` writeChan toClient Nothing report _ = pure () continued = Client.continueSession storeDir clientTransport report withAsync daemon $ \running -> do opened <- Client.openSession storeDir Client.offeredVersion clientTransport report case opened of Left failure -> pure (Fail (T.pack (show failure))) Right fresh -> do (valid, afterValid) <- continued fresh (Client.isValidPath fooPath) (referrers, afterReferrers) <- continued afterValid (Client.queryReferrers barPath) (version, _) <- continued afterReferrers Client.agreedVersion writeChan toDaemon Nothing end <- wait running pure $ assertEqual "valid" (Right True) valid `andThen` assertEqual "referrers" (Right (Set.singleton fooPath)) referrers `andThen` assertEqual "version" (Right Client.offeredVersion) version `andThen` assertEqual "end" Conn.ClientClosed end ] where latest = Client.offeredVersion isLeft = either (const True) (const False)-- ----------------------------------------------------------------------------- The daemon's side, in memory-- ----------------------------------------------------------------------------- | What the store in memory holds and was asked.data Fake = Fake { fakeValid :: !(Map.Map StorePath Proto.UnkeyedValidPathInfo), fakeSettings :: !(Maybe Ops.ClientSettings), fakeTempRoots :: !(Set.Set StorePath), fakeIndirectRoots :: !(Set.Set BS.ByteString), fakeEnsured :: ![StorePath], fakeUploads :: ![BS.ByteString] }-- | The store's starting state: @foo@ referring to @bar@, and a-- derivation whose @out@ is @foo@.startingFake :: Proto.NarHash -> FakestartingFake narHash = Fake { fakeValid = Map.fromList [(fooPath, sampleInfo narHash (Set.singleton barPath)), (barPath, sampleInfo narHash Set.empty), (drvPath, sampleInfo narHash Set.empty)], fakeSettings = Nothing, fakeTempRoots = Set.empty, fakeIndirectRoots = Set.empty, fakeEnsured = [], fakeUploads = [] }-- | A session with the daemon, trusting the client or not and offering a-- version, over the store in memory, and how the daemon's side ended.session :: Proto.NarHash -> Proto.Trust -> Proto.Version -> Client.ClientT IO a -> IO (Either Client.ClientFailure a, Conn.ConnectionEnd)session narHash trust version steps = (\(outcome, end, _) -> (outcome, end)) <$> sessionWith narHash trust version steps-- | 'session', with the store's state after it.sessionWith :: Proto.NarHash -> Proto.Trust -> Proto.Version -> Client.ClientT IO a -> IO (Either Client.ClientFailure a, Conn.ConnectionEnd, Fake)sessionWith = sessionReporting (\_ -> pure ())-- | 'sessionWith', the daemon's messages given to a report.sessionReporting :: (Proto.StderrMessage -> IO ()) -> Proto.NarHash -> Proto.Trust -> Proto.Version -> Client.ClientT IO a -> IO (Either Client.ClientFailure a, Conn.ConnectionEnd, Fake)sessionReporting report narHash trust version steps = do state <- newIORef (startingFake narHash) toDaemon <- newChan toClient <- newChan daemonTransport <- channelTransport toDaemon toClient clientTransport <- channelTransport toClient toDaemon let daemon = Conn.serveConnection (serverConfigAt version) trust (fakeStore narHash state) daemonTransport `finally` writeChan toClient Nothing withAsync daemon $ \running -> do outcome <- Client.runClient storeDir Client.offeredVersion clientTransport report steps `finally` writeChan toDaemon Nothing end <- wait running held <- readIORef state pure (outcome, end, held)-- | What the daemon in memory tells every connection, offering a version.serverConfigAt :: Proto.Version -> Conn.ServerConfigserverConfigAt version = Conn.ServerConfig { Conn.scStoreDir = storeDir, Conn.scVersion = version, Conn.scNixVersion = nixVersion, Conn.scVerbosity = Proto.Verbosity 3, Conn.scConfig = defaultNixConfig }-- | One side of a connection in memory: it reads what the other side-- writes to the channel it reads, and writes to the other's. A-- 'Nothing' in its channel is the end of its input, and every read after-- it is the end too.channelTransport :: Chan (Maybe BS.ByteString) -> Chan (Maybe BS.ByteString) -> IO (Conn.Transport IO)channelTransport incoming outgoing = do ended <- newIORef False let receive = do done <- readIORef ended if done then pure Nothing else readChan incoming >>= \case Nothing -> Nothing <$ writeIORef ended True Just bytes | BS.null bytes -> receive | otherwise -> pure (Just bytes) sendBytes builder = writeChan outgoing (Just (BL.toStrict (BB.toLazyByteString builder))) pure (Conn.Transport receive sendBytes)-- | One side of a connection in memory that holds one write at a time: a-- write waits until the other side has read the one before it, as a-- socket's buffer fills, so a side that writes while the other does the-- same stops until one of them reads. A 'Nothing' is the end of the-- input, and every read after it is the end too.boundedTransport :: MVar (Maybe BS.ByteString) -> MVar (Maybe BS.ByteString) -> IO (Conn.Transport IO)boundedTransport incoming outgoing = do ended <- newIORef False let receive = do done <- readIORef ended if done then pure Nothing else takeMVar incoming >>= \case Nothing -> Nothing <$ writeIORef ended True Just bytes | BS.null bytes -> receive | otherwise -> pure (Just bytes) sendBytes builder = putMVar outgoing (Just (BL.toStrict (BB.toLazyByteString builder))) pure (Conn.Transport receive sendBytes)-- | How many chunks the upload of a connection that holds one write at a-- time has: well past the writes the two directions hold between them.uploadChunkCount :: IntuploadChunkCount = 32-- | How long that upload may take before it counts as stuck: well past-- what it takes.uploadDeadlockMicros :: IntuploadDeadlockMicros = 30 * 1000 * 1000-- | A dump the store takes that reports a line for each chunk it is sent,-- and keeps the whole dump once it has it.reportingEachChunk :: Ops.Work IO -> IORef Fake -> Proto.NarHash -> Ops.Intake IO Proto.ValidPathInforeportingEachChunk work state narHash = Ops.Taking (more BS.empty) (finish BS.empty) (pure ()) where more held chunk = do Ops.workReport work (Ops.LogLine (Proto.Verbosity 0) "received a chunk") pure (Ops.Taking (more (held <> chunk)) (finish (held <> chunk)) (pure ())) finish dump = Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty)) <$ modifyIORef' state (\fake -> fake {fakeUploads = fakeUploads fake ++ [dump]})-- | The store in memory, over its state.fakeStore :: Proto.NarHash -> IORef Fake -> Ops.DaemonStore IOfakeStore narHash state = Ops.DaemonStore { Ops.dsIsValidPath = \_ path -> Right . Map.member path <$> valid, Ops.dsQueryValidPaths = \_ _ paths -> Right . Set.intersection paths . Map.keysSet <$> valid, Ops.dsQuerySubstitutablePaths = \_ _ -> pure (Right Set.empty), Ops.dsQueryReferrers = \_ path -> if path == refusedPath then pure (Left (Ops.daemonError refusalMessage)) else Right . Map.keysSet . Map.filter (Set.member path . Proto.upiReferences) <$> valid, Ops.dsQueryValidDerivers = \_ _ -> pure (Right Set.empty), Ops.dsQueryDerivationOutputMap = \_ _ -> pure (Right (Map.fromList [(Proto.OutputName "out", Just fooPath)])), Ops.dsQueryAllValidPaths = \work -> record work *> (Right . Map.keysSet <$> valid), Ops.dsQueryPathInfo = \_ path -> Right . Map.lookup path <$> valid, Ops.dsQueryMissing = \_ targets -> pure (Right (Proto.Missing Set.empty Set.empty (Set.fromList [path | Proto.DerivedOpaque path <- targets]) 0 0)), Ops.dsAddToStore = \_ _ -> pure (collecting (\dump -> Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty)) <$ upload dump)), Ops.dsAddToStoreNar = \_ (Proto.ValidPathInfo path info) _ _ -> pure (collecting (\nar -> Right () <$ (upload nar *> modifyIORef' state (\fake -> fake {fakeValid = Map.insert path info (fakeValid fake)})))), Ops.dsBuildPaths = \work _ _ -> Right () <$ mapM_ (Ops.workReport work) buildEvents, Ops.dsBuildPathsWithResults = \work targets _ -> Right [Proto.KeyedBuildResult target sampleBuildResult | target <- targets] <$ mapM_ (Ops.workReport work) buildEvents, Ops.dsEnsurePath = \work path -> Right () <$ (record work *> modifyIORef' state (\fake -> fake {fakeEnsured = fakeEnsured fake ++ [path]})), Ops.dsAddTempRoot = \work path -> Right () <$ (record work *> modifyIORef' state (\fake -> fake {fakeTempRoots = Set.insert path (fakeTempRoots fake)})), Ops.dsAddIndirectRoot = \_ link -> Right () <$ modifyIORef' state (\fake -> fake {fakeIndirectRoots = Set.insert link (fakeIndirectRoots fake)}), Ops.dsFindRoots = \_ _ -> pure (Right Map.empty), 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 valid = fakeValid <$> readIORef state notHere = Ops.daemonError "not in these tests" upload bytes = modifyIORef' state (\fake -> fake {fakeUploads = fakeUploads fake ++ [bytes]}) -- The settings the client last sent, as an operation's work carries -- them. record work = modifyIORef' state (\fake -> fake {fakeSettings = Ops.connClient (Ops.workSettings work)}) collecting finish = Ops.Taking (more BS.empty) (finish BS.empty) (pure ()) where more held chunk = pure (Ops.Taking (more (held <> chunk)) (finish (held <> chunk)) (pure ()))-- | What a build the store in memory runs reports, and what the client is-- sent for it.buildEvents :: [Ops.LogEvent]buildEvents = [ Ops.LogLine (Proto.Verbosity 0) "a line", Ops.ActivityStarted buildActivity, Ops.ActivityResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "built a line"], Ops.ActivityStopped (Proto.ActivityId 7) ]buildMessages :: [Proto.StderrMessage]buildMessages = [ Proto.StderrNext "a line\n", Proto.StderrStartActivity buildActivity, Proto.StderrResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "built a line"], Proto.StderrStopActivity (Proto.ActivityId 7) ]buildActivity :: Proto.ActivitybuildActivity = Proto.Activity (Proto.ActivityId 7) (Proto.Verbosity 3) (Proto.ActivityType 105) "building 'foo'" [] (Proto.ActivityId 0)-- | The result the store in memory gives each build.sampleBuildResult :: Proto.BuildResultsampleBuildResult = Proto.BuildResult (Proto.Succeeded (Proto.Success Proto.Built Map.empty)) 1 1700000000 1700000001 Nothing Nothing-- | Settings a client sends.sampleSettings :: Ops.ClientSettingssampleSettings = Ops.ClientSettings False True False (Proto.Verbosity 4) 2 30 True 3 True (Map.fromList [("max-jobs", "2")])-- | A path's info with the NAR hash and the references given.sampleInfo :: Proto.NarHash -> Set.Set StorePath -> Proto.UnkeyedValidPathInfosampleInfo narHash references = Proto.UnkeyedValidPathInfo { Proto.upiDeriver = Nothing, Proto.upiNarHash = narHash, Proto.upiReferences = references, Proto.upiRegistrationTime = 1700000000, Proto.upiNarSize = 10, Proto.upiUltimate = False, Proto.upiSignatures = Set.empty, Proto.upiContentAddress = Nothing }-- | A NAR hash: the SHA-256 of a NAR in these tests, which a SHA-256-- digest always makes.sampleNarHash :: Maybe Proto.NarHashsampleNarHash = Proto.narHashFromDigest (sha256Digest "nar of new")-- | Run tests given the NAR hash their infos carry, or fail them where-- there is none.withNarHash :: Text -> (Proto.NarHash -> IO [Bool]) -> IO [Bool]withNarHash group tests = maybe (sequence [runTest (group <> ": a NAR hash from a SHA-256 digest") (Fail "a SHA-256 digest made no NAR hash")]) tests sampleNarHash-- | The message the store in memory fails a query with.refusalMessage :: TextrefusalMessage = "the store refuses this path"-- | Paths the sessions name.fooPath, barPath, drvPath, missingPath, newPath, refusedPath, dumpPath :: StorePathfooPath = StorePath "00000000000000000000000000000001" "foo"barPath = StorePath "00000000000000000000000000000002" "bar"drvPath = StorePath "00000000000000000000000000000003" "foo.drv"missingPath = StorePath "00000000000000000000000000000005" "missing"newPath = StorePath "00000000000000000000000000000007" "new"refusedPath = StorePath "00000000000000000000000000000008" "refused"dumpPath = StorePath "00000000000000000000000000000009" "dump"-- | The store directory paths cross the wire under.storeDir :: StoreDirstoreDir = defaultStoreDir-- | The Nix version the daemon in memory names itself by.nixVersion :: BS.ByteStringnixVersion = "nova-nix (test)"-- | An exception a test throws to a thread.data Interrupted = Interrupted deriving (Eq, Show)instance Exception Interrupted-- | Where a thread stands once it can go no further.data Standing = -- | Blocked on something another thread must do: an exception thrown -- to a thread that has not let it in, or a lock another holds. Waiting | -- | Run to its end, by returning or by an exception. Ended deriving (Eq, Show)-- | Wait until a thread is blocked or has ended, and say which.standing :: ThreadId -> IO Standingstanding thread = threadStatus thread >>= \case ThreadRunning -> yield *> standing thread ThreadBlocked _ -> pure Waiting ThreadFinished -> pure Ended ThreadDied -> pure Ended-- | What a logger was given, as the calls the store makes.data Logged = -- | A message, at a level. LoggedMessage !Level !Text | -- | A build line given to the logger itself, not to an activity. LoggedBuildLine !BS.ByteString | -- | An activity started. LoggedStart !ActivityStart | -- | A build line given to an activity's sink. LoggedActivityLine !ActivityStart !BS.ByteString | -- | An activity stopped. LoggedStop !ActivityStart deriving (Eq, Show)-- | A logger that keeps each call it is given, and what has been given in-- order.eventLogger :: IO (Logger, IO [Logged])eventLogger = do events <- newIORef [] let record event = modifyIORef' events (event :) logger = Logger { logAt = \level message -> record (LoggedMessage level message), logBuildLine = record . LoggedBuildLine, logActivity = \start -> do record (LoggedStart start) pure (record . LoggedActivityLine start, record (LoggedStop start)) } pure (logger, reverse <$> readIORef events)-- | An absolute out-link as the client spells it, which a daemon records-- unchanged: a Windows daemon takes only a drive-qualified or UNC link.rootedLink :: BS.ByteStringrootedLink | SI.os == "mingw32" = "C:\\home\\u\\result" | otherwise = "/home/u/result"