packages feed

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

{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}-- | A command's store reached through a daemon in upstream's worker-- protocol: the operations of a t'Nix.Store.Ops.StoreOps' over a client-- session ("Nix.Daemon.Client"), on a Unix socket or on Windows a named-- pipe ("Nix.Daemon.Dial").  A command's connection is opened at the-- first operation that needs one and closed when the command is done with-- the store, and a command that asks nothing of the store never connects.---- == Where paths live---- Paths go on the wire under @\/nix\/store@, the directory every path is-- computed under, while the files of the store are read from the-- directory the command was given ('dscFileDir'): evaluation reads a-- tree the daemon holds there, and a copy of a path evaluation named is-- sent from there.  A command that evaluates over this store gives its-- evaluation session the same directory.---- == Adds---- A daemon's client cannot write the store's directory, so evaluation-- hands each tree it writes to the store as it makes it-- ('Nix.Store.Ops.AddedAsMade'), sent as upstream's client sends it-- ('evalWriteRequest').  What evaluation only named is sent when the-- command adds what evaluation made ('soAddEvalObjects'): each copy of a-- path, then each derivation after every derivation and source it refers-- to ('derivationAddOrder'), a daemon needing each reference valid first.-- A path the daemon answers is held to the path evaluation computed.---- == Temporary roots---- A connection's temporary roots end with it.  The daemon roots each path-- it adds for the connection.  The client roots a path before it asks the-- daemon whether it holds the path where it then relies on the answer-- without sending the path, so a collection between the question and the-- use cannot remove it: each source and derivation an add considers-- ('soAddEvalObjects'), each fetched path evaluation adopts ('moHold'),-- and each path whose record or files a push or trust relies on (see-- below).  The other queries ('sqValidPaths', 'sqReferences') root-- nothing, and the path a pinned fetch names is taken as held on an-- unrooted answer of 'sqValidPaths', as upstream's early exit for a-- pinned fetch takes it.---- == Builds---- A build asks the daemon to build each derivation's named outputs, and a-- check to build every output of a derivation again under the check mode,-- as upstream's client asks.  What the daemon says while it works reaches-- the command's logger as the calls the local store makes for the same-- work ('Nix.Daemon.Client.relayMessage'), and any activity a failed-- operation leaves open is stopped when it ends.  A build the daemon fails-- stops with the daemon's message and status; from protocol 1.26 on the-- status is not sent and reads as 1, as upstream's client reads it.  A-- read-only evaluation's realisation substitutes in the daemon, as-- upstream's does through its daemon.---- == Push and trust---- A push ('withDaemonPushSource') asks the daemon what it records of each-- path, its references, NAR hash and deriver, and reads the path's files-- from 'dscFileDir', as upstream's client of a daemon on the same machine-- reads them: the daemon is asked what it records of the path, never for-- its NAR.  Trust ('withDaemonFixedOutputs') has the daemon fetch each-- input a builtin fetches, by adding its derivation and building it, and-- substitute every other input, with what it references, by building its-- path; the files of an input the daemon holds are read from-- 'dscFileDir'.  Each path whose record or files a push or trust relies-- on is rooted for the connection before the daemon is asked about it, so-- a collection cannot remove it between the answer and the read of its-- files.  The list a push of every path starts from is not rooted, so a-- path collected between the listing and its read fails the push.---- A daemon's result for a substitution does not tell a download that-- failed from a path no substituter offers, nor a reference whose download-- failed from one no substituter offers.  Through a daemon an input whose-- download failed, or whose references' download failed, is therefore left-- unread and the report names it as not read, where a store opened-- directly stops the command; every other outcome matches.---- == Out-links---- The client makes a build's result link itself, in the directory the-- command runs in, and the daemon roots it: the path is rooted for the-- connection before the link is looked at, and the link's absolute spelling-- is recorded as an indirect root once it exists, as upstream's client-- roots one.---- == Settings---- After the handshake the client sends the settings 'dscSettings' holds,-- as upstream's client does, unless the daemon grants-- 'Nix.Daemon.Protocol.featureDisableSetOptions'.  They carry the-- configuration's keep-failed, fallback and cores, and as overrides the-- store settings a source set that the configuration reads-- ('clientSettings').---- == Failures---- An operation the daemon refuses fails with the daemon's message, as-- upstream's client throws it, and the connection goes on.  A connection-- that cannot be opened, in its connecting, its handshake or its-- settings, fails the operation that tried with the reason, and every-- operation after with upstream's words for it ('previouslyFailedText'),-- without trying again.  A connection that breaks, or that an upload-- breaks by failing to read a local file, fails the operation that found-- it and is closed; the next operation opens a new one, which holds none-- of the old one's temporary roots.module Nix.Daemon.ClientStore  ( -- * Where the daemon is    DaemonAddress (..),    daemonAddressPath,    daemonStoreName,    Connector,    dialDaemon,    -- * A connection's session    DaemonSession,    withDaemonSession,    daemonOperation,    DaemonOpFailure (..),    opFailureText,    -- * The store    DaemonStoreConfig (..),    withDaemonStore,    withDaemonPushSource,    withDaemonFixedOutputs,    clientSettings,    -- * What is sent    evalWriteRequest,    derivationAddOrder,    textMethod,    narMethod,    flatMethod,    -- * What is said of a failure    connectFailureText,    openFailureText,    previouslyFailedText,  )whereimport Control.Concurrent.MVar (MVar, newMVar, putMVar, swapMVar, takeMVar)import Control.Exception (Handler (..), IOException, bracket, catches, displayException, finally, mask, onException, try)import Control.Monad (unless, when)import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError, withExceptT)import Control.Monad.IO.Class (liftIO)import Data.Bifunctor (bimap, first)import Data.Bool (bool)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport Data.Foldable (for_, traverse_)import Data.IORef (atomicModifyIORef', newIORef)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe)import Data.Set (Set)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Word (Word32)import Nix.Config (AssignedSettings, NixConfig (..), storeSettingOverrides)import Nix.Daemon.Client  ( ClientFailure (..),    ClientSession,    ClientT,    Relay,    addIndirectRoot,    addTempRoot,    addToStore,    agreedVersion,    buildPaths,    buildPathsWithResults,    continueSession,    newRelay,    offeredVersion,    openSession,    queryAllValidPaths,    queryPathInfo,    queryValidPaths,    relayMessage,    setOptions,    stopOpenActivities,  )import Nix.Daemon.Connection (Transport)import qualified Nix.Daemon.Dial as Dialimport Nix.Daemon.Ops (AddToStoreRequest (..), ClientSettings (..), Repair (..), Substitute (..), unsetCores)import Nix.Daemon.Protocol (BuildOutcome (..), BuildResult (..), DaemonError (..), DerivedPath (..), Failure (..), FailureStatus (DependencyFailed, NoSubstituters), KeyedBuildResult (..), OutputName (..), OutputsSpec (..), StderrMessage, UnkeyedValidPathInfo (..), ValidPathInfo (..), Verbosity (..), Version (..), featureDisableSetOptions, namedOutputs, narHashDigest)import qualified Nix.Daemon.Protocol as Protoimport Nix.DependencyGraph (DepNode (..))import Nix.Derivation (Derivation, fromATerm)import Nix.Eval.Policy (hostPathRules)import Nix.Fetch.Url (encodeUrlPath, pathToUrlPath)import Nix.Hash (makeSourcePath, sha256Digest)import Nix.Http (catchSync)import Nix.Logger (Logger)import Nix.Push.Source (PushSource (..), PushedPath (..))import Nix.Realise (ClosureOutcome (..))import Nix.Store (drvReferences)import Nix.Store.CaseSensitive (CaseSensitivity, pathCaseHack, probeCaseSensitivity, volumeCaseHack)import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.GC (LinkRooting (..), makeOutLinkRoot)import Nix.Store.Ops (BuildStop (..), EvalObjects (..), EvalWrite (..), EvalWrites (..), MadeOps (..), StoreOps (..), StoreQueries (..), evalWriteContents, madeAnotherPath, nothingToAdd)import Nix.Store.Path (StoreDir (..), StorePath (spName), badStorePathText, defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText, storeTextToFilePath)import Nix.Trust.Fetch (FixedOutputStore (..))import Nix.Trust.Scan (scanFetched)import NovaCache.Hash (NixHash (..), formatNixHash)import qualified NovaCache.NAR as NARimport System.IO.Error (illegalOperationErrorType, ioeSetErrorString, mkIOError)-- ----------------------------------------------------------------------------- Where the daemon is-- ----------------------------------------------------------------------------- | The socket a daemon listens on, or on Windows the named pipe.data DaemonAddress  = -- | The address the daemon listens on unless it is told another    -- ('Nix.Daemon.Listen.daemonSocketPath'), as the bytes of a socket's    -- path or on Windows a named pipe's.    DefaultSocket !ByteString  | -- | The address a @unix:\/\/PATH@ store names, as the bytes of a    -- socket's path or on Windows a named pipe's.  A path that is the    -- default's is a 'DefaultSocket' instead, as upstream names a store    -- at the default's path @daemon@.    NamedSocket !ByteString  deriving (Eq, Show)-- | The bytes of the path of the socket.daemonAddressPath :: DaemonAddress -> ByteStringdaemonAddressPath = \case  DefaultSocket path -> path  NamedSocket path -> path-- | What a store at the address is called in a message, as upstream's-- store reference renders it: @daemon@ for the default address, and-- @unix:\/\/@ and the path of any other, each segment of the path-- percent-encoded keeping only the unreserved characters, @:@ and @\@@-- (upstream's @encodeUrlPath@).daemonStoreName :: DaemonAddress -> TextdaemonStoreName = \case  DefaultSocket _ -> "daemon"  NamedSocket path -> "unix://" <> shown (encodeUrlPath (pathToUrlPath hostPathRules path))-- | How a connection to the daemon is made: a transport over it and the-- action that closes it, or why none could be made.type Connector = IO (Either Text (Transport IO, IO ()))-- | Connect to the daemon at an address ("Nix.Daemon.Dial"); the reason-- for a connection that cannot be made is the operating system's, or on-- Windows the pipe client's.dialDaemon :: DaemonAddress -> ConnectordialDaemon address = fmap (\connection -> (Dial.connectionTransport connection, Dial.closeDaemonConnection connection)) <$> Dial.connectDaemon (daemonAddressPath address)-- ----------------------------------------------------------------------------- A connection's session-- ----------------------------------------------------------------------------- | An open connection: the transport it runs over, the session its-- handshake made, and what closes it.data Link = Link  { linkTransport :: !(Transport IO),    linkSession :: !ClientSession,    linkClose :: !(IO ())  }-- | Where a session's connection stands.data LinkState  = -- | None is open: none was needed yet, or the one that was open broke    -- and was closed.  The next operation opens one.    Unopened  | -- | One is open.    Open !Link  | -- | An attempt to open one failed.  Every operation after fails    -- without trying again.    OpenFailed  | -- | The session has ended.    Closed-- | A command's connection to a daemon, opened at its first operation.-- The state is taken for the length of an operation, so one runs at a-- time.data DaemonSession = DaemonSession  { sessionConnector :: !Connector,    sessionAddress :: !DaemonAddress,    sessionSettings :: !ClientSettings,    sessionReport :: !(StderrMessage -> IO ()),    sessionState :: !(MVar LinkState)  }-- | Why an operation through a daemon did not answer.data DaemonOpFailure  = -- | The daemon refused the operation, with its error, and the    -- connection goes on.    DaemonRefused !DaemonError  | -- | The connection could not be opened or broke, or the client will    -- not send the operation, for this reason.    LinkFailed !Text  deriving (Eq, Show)-- | The words a failure is reported in: the daemon's message, as-- upstream's client throws it, or the reason a connection failed.opFailureText :: DaemonOpFailure -> TextopFailureText = \case  DaemonRefused refusal -> daemonErrorText refusal  LinkFailed reason -> reason-- | A daemon's error as text: its message, with any byte that is not-- UTF-8 replaced.  The traces it carries are not shown.daemonErrorText :: DaemonError -> TextdaemonErrorText = shown . errMessage-- | The verbosity the daemon's messages are reported at, and the client-- tells the daemon to send them at: info, upstream's default.reportVerbosity :: VerbosityreportVerbosity = Verbosity 3-- | Run an action with a session to the daemon at an address, which sends-- the settings given after each handshake, over connections the-- connector makes as operations need them, and closes the one that is-- open when the action ends, by returning or by an exception.  The-- daemon's messages go to the report.  A connection that cannot be-- opened fails every operation after the one that tried-- ('previouslyFailedText'), and a connection that breaks is replaced by-- the next operation's.withDaemonSession :: Connector -> DaemonAddress -> ClientSettings -> (StderrMessage -> IO ()) -> (DaemonSession -> IO a) -> IO awithDaemonSession connector address settings report action =  bracket (newMVar Unopened) end (action . DaemonSession connector address settings report)  where    end state =      swapMVar state Closed >>= \case        Open link -> linkClose link        _ -> pure ()-- | Run steps over the session's connection, one operation at a time,-- opening the connection when the session has none and its opening has-- not failed.  A daemon's refusal is the operation's failure and the-- connection goes on.  A connection that breaks, in the middle of an-- operation or before it, fails the operation with the reason, as does-- an 'IOException' of the transport or of a chunk source the steps read-- from, and a failed access of the walk of a local tree-- (t'NAR.NarWalkError', which a file that cannot be read raises): the-- connection is closed, since a framed upload is cut short, and the next-- operation opens another.  An exception of any other kind, and an-- interrupt, closes the connection and goes on up.---- The action given runs once the operation has ended, however it ended,-- and before the next operation can start: the operation still holds the-- session, so the action never meets another operation's work.daemonOperation :: DaemonSession -> IO () -> ClientT IO a -> IO (Either DaemonOpFailure a)daemonOperation session settle steps = mask $ \restore -> do  state <- takeMVar var  case state of    Closed -> release state *> ioError sessionEnded    OpenFailed -> Left (LinkFailed (previouslyFailedText (sessionAddress session))) <$ release state    Open link -> runOn restore link    Unopened -> do      opened <- restore (openLink session) `onException` release Unopened      case opened of        Left reason -> Left (LinkFailed reason) <$ release OpenFailed        Right link -> runOn restore link  where    var = sessionState session    -- Hands the session on in a state, once the operation has settled.    release next = settle `finally` putMVar var next    sessionEnded = ioeSetErrorString (mkIOError illegalOperationErrorType "daemonOperation" Nothing Nothing) "used after the session ended"    runOn restore link = do      ran <-        ( (Right <$> restore (continueSession defaultStoreDir (linkTransport link) (sessionReport session) (linkSession link) steps))            `catches` [ Handler (\(err :: IOException) -> pure (Left (T.pack (displayException err)))),                        Handler (\(err :: NAR.NarWalkError) -> pure (Left (walkFailureText err)))                      ]        )          `onException` dropLink link      case ran of        Left reason -> lose link reason        Right (Left (ConnectionLost reason), _) -> lose link reason        Right (Left (DaemonFailed refusal), next) -> continuing link next (Left (DaemonRefused refusal))        Right (Left (NotSent reason), next) -> continuing link next (Left (LinkFailed reason))        Right (Right answer, next) -> continuing link next (Right answer)    continuing link next outcome = outcome <$ release (Open link {linkSession = next})    lose link reason = Left (LinkFailed reason) <$ dropLink link    dropLink link = linkClose link `finally` release Unopened-- | Make a connection, its handshake and its settings, or say why they-- cannot be made.  The connector runs with asynchronous exceptions-- masked, so what it returns is closed whatever arrives next, and so is-- a connection whose handshake or settings fail, the close masked too.  A-- failure to connect is reported as the connector gives it, a failure of-- the handshake in upstream's words for one ('openFailureText'), which-- wrap only the handshake's errors, and a failure of the settings as the-- daemon says it.  A synchronous exception counts as a failure of the-- step it is thrown in; an asynchronous one goes up.openLink :: DaemonSession -> IO (Either Text Link)openLink session = mask $ \restore ->  connecting >>= \case    Left reason -> pure (Left reason)    Right (transport, close) -> do      made <- restore (greeting transport >>= either (pure . Left) (settling transport close)) `onException` close      either (\reason -> Left reason <$ close) (pure . Right) made  where    address = sessionAddress session    report = sessionReport session    connecting = (first (connectFailureText address) <$> sessionConnector session) `catchSync` (pure . Left . exceptionText)    greeting transport = first (openFailureText address) <$> (openSession defaultStoreDir offeredVersion transport report `catchSync` (pure . Left . ConnectionLost . exceptionText))    settling transport close fresh = settled `catchSync` (pure . Left . exceptionText)      where        settled = do          (sent, next) <- continueSession defaultStoreDir transport report fresh (sendSettings (sessionSettings session))          pure (either (Left . failureText) (\() -> Right (Link transport next close)) sent)    exceptionText = T.pack . displayException-- | Send the client's settings for the connection, as upstream's client-- does once the handshake is made, unless the daemon grants-- 'featureDisableSetOptions'.sendSettings :: ClientSettings -> ClientT IO ()sendSettings settings = do  version <- agreedVersion  unless (Set.member featureDisableSetOptions (versionFeatures version)) (setOptions settings)-- ----------------------------------------------------------------------------- The store-- ----------------------------------------------------------------------------- | Where a command's daemon store is, how it reads files, and what the-- daemon is told.data DaemonStoreConfig = DaemonStoreConfig  { -- | The daemon.    dscAddress :: !DaemonAddress,    -- | The directory the command's store files are read from: the trees    -- the daemon holds, which evaluation reads, and the copies of paths it    -- named, which are sent from here.  Paths cross the wire under    -- @\/nix\/store@ whatever it is.    dscFileDir :: !StoreDir,    -- | The settings sent after each handshake ('clientSettings').    dscSettings :: !ClientSettings,    -- | Where the daemon's messages are reported.    dscLogger :: !Logger  }-- | The settings a client sends, from its configuration and the settings a-- source set: keep-failed, fallback and cores as the configuration has-- them, cores being 'unsetCores' where it sets none, as upstream's client-- sends its own default for the daemon to read as its machine's, the-- verbosity the daemon's messages are reported at, and as overrides the-- store settings a source set that the configuration reads-- ('storeSettingOverrides'): a store setting it does not read, such as-- @builders@ or @connect-timeout@, is not sent whatever a source says.-- Each setting the configuration does not model takes the default-- upstream's client sends.clientSettings :: AssignedSettings -> NixConfig -> ClientSettingsclientSettings assigned config =  ClientSettings    { csKeepFailed = ncKeepFailed config,      csKeepGoing = False,      csTryFallback = ncFallback config,      csVerbosity = reportVerbosity,      csMaxBuildJobs = defaultMaxBuildJobs,      csMaxSilentTime = noSilentTimeLimit,      csVerboseBuild = True,      csBuildCores = fromMaybe unsetCores (ncCores config),      csUseSubstitutes = True,      csOverrides = storeSettingOverrides assigned config    }-- | Upstream's default for @max-jobs@: one build at a time.defaultMaxBuildJobs :: Word32defaultMaxBuildJobs = 1-- | Upstream's default for @max-silent-time@: a build is never stopped for-- its silence.noSilentTimeLimit :: Word32noSilentTimeLimit = 0-- | Run an action with a command's store operations through a daemon,-- over a session ('withDaemonSession') that connects only when an-- operation first asks the daemon something.---- The queries ask the daemon: 'sqValidPaths' fails with an 'IOError' on a-- failure, as a local store's database does, the type having no other-- channel for one.  An add sends each source and derivation the-- evaluation named that the daemon does not hold, holding the path the-- daemon makes to the one evaluation computed.  A build or a check asks-- the daemon to build, and stops with the daemon's message and status,-- which from protocol 1.26 on reads as 1, as upstream's client reads it;-- what the daemon says meanwhile reaches 'dscLogger' as the local store's-- own calls do.  An out-link is made by the client and rooted by the-- daemon.  A read-only evaluation's realisation substitutes in the daemon,-- as upstream's does through its daemon.withDaemonStore :: DaemonStoreConfig -> Connector -> (StoreOps IO -> IO a) -> IO awithDaemonStore config connector action = withStoreSession config connector (action . daemonOps config)-- | Run an action over a session to the daemon ('withDaemonSession') and-- the relay its messages go to ('dscLogger'), which every operation of a-- command's store runs over ('operate').withStoreSession :: DaemonStoreConfig -> Connector -> (StoreSession -> IO a) -> IO awithStoreSession config connector action = do  relay <- newRelay defaultStoreDir (dscLogger config)  withDaemonSession connector (dscAddress config) (dscSettings config) (relayMessage relay) (action . StoreSession relay)-- | Run an action with what a push reads, a t'PushSource', through a-- daemon, over a session that connects when it first asks the daemon-- something.  Each path's references, NAR hash and deriver are asked of-- the daemon, and the files of the path are read from 'dscFileDir', as-- upstream's client of a daemon on the same machine reads them.  Each-- path whose record is asked, which a push then reads the files of, is-- rooted for the connection first, so a collection cannot remove it-- between the answer and the read of its files.  The list of every path-- ('psAllValid') is not rooted, so a path collected between the listing-- and its read fails the push.  The volume's case sensitivity is probed-- once, when the action starts.withDaemonPushSource :: DaemonStoreConfig -> Connector -> (PushSource -> IO a) -> IO awithDaemonPushSource config connector action = withStoreSession config connector $ \session -> do  sensitivity <- probeCaseSensitivity (unStoreDir (dscFileDir config))  action    PushSource      { psStoreDir = dscFileDir config,        psCaseHack = volumeCaseHack sensitivity,        psLogger = dscLogger config,        psReferences = referencesOfRecord session,        psPathInfo = pathInfoOf session,        psAllValid = bimap opFailureText Set.toAscList <$> operate session queryAllValidPaths      }-- | A path rooted for the connection, then its record: 'Nothing' for a-- path the daemon does not hold.pathInfoOf :: StoreSession -> StorePath -> IO (Either Text (Maybe PushedPath))pathInfoOf session path = bimap opFailureText (fmap pushedPath) <$> operate session (addTempRoot path *> queryPathInfo path)-- | The references of a path's record, as 'pathInfoOf' gives it: none for-- a path the daemon does not hold.referencesOfRecord :: StoreSession -> StorePath -> IO (Either Text [StorePath])referencesOfRecord session path = fmap (maybe [] ppReferences) <$> pathInfoOf session path-- | What a push reads of a daemon's record of a path, its NAR hash spelled-- as a store's database spells it.pushedPath :: UnkeyedValidPathInfo -> PushedPathpushedPath info =  PushedPath    { ppNarHash = formatNixHash (NixHash (narHashDigest (upiNarHash info))),      ppReferences = Set.toAscList (upiReferences info),      ppDeriver = upiDeriver info    }-- | Run an action with what trust asks of a store, a t'FixedOutputStore',-- through a daemon, over a session that connects when it first asks the-- daemon something.  The function gives the ATerm recorded for a-- derivation.---- A fetch adds the input's derivation, which nothing else refers to, as-- 'soAddEvalObjects' adds one, unless the daemon holds it, and has the-- daemon build every output of it.  A substitution roots the path, asks-- the daemon whether it holds it, and if not has the daemon realise it as-- an opaque path, which substitutes it with what it references, under the-- fallback setting the session sent.  A path the daemon holds asks no-- substituter anything.  A realisation that succeeds is complete; one the-- daemon fails because no substituter offers the path is unavailable, and-- because a dependency failed, incomplete: a path left unread, the run-- going on, as for a store opened directly.  Any other failure, or no-- result for the path, is a failed substitution, which stops the run.  A-- daemon's result does not tell a download that failed from a path no-- substituter offers, so a path whose download failed, or whose-- references' download failed, is unavailable or incomplete too, where a-- store opened directly fails it.  A daemon older than protocol 1.34-- cannot say how a realisation ended, so the substitution of a path it-- does not hold fails with the client's reason.  Each path whose files-- are read is rooted before the daemon is asked whether it holds it, and-- the files are read from 'dscFileDir'.withDaemonFixedOutputs :: DaemonStoreConfig -> Connector -> (StorePath -> Either Text ByteString) -> (FixedOutputStore IO -> IO a) -> IO awithDaemonFixedOutputs config connector recordedAterm action = withStoreSession config connector $ \session ->  action    FixedOutputStore      { fosFetch = fetchThrough config session recordedAterm,        fosSubstitute = \path -> first opFailureText <$> operate session (substituteOpaque path),        fosHeld = \path -> first opFailureText <$> operate session (rootedValid path),        fosScan = scanFetched . storePathToFilePath (dscFileDir config)      }-- | Have the daemon fetch an input: its derivation added as a text with no-- references, since a derivation a builtin fetches names no input, then-- built for every output.fetchThrough :: DaemonStoreConfig -> StoreSession -> (StorePath -> Either Text ByteString) -> DepNode -> IO (Either Text ())fetchThrough config session recordedAterm node = runExceptT $ do  aterm <- liftEither (recordedAterm path)  ExceptT (addEvalObjects config session EvalObjects {eoSources = Map.empty, eoStoreWrites = Map.empty, eoDerivations = Map.singleton (storePathToText defaultStoreDir path) aterm})  withExceptT opFailureText (ExceptT (operate session (buildPaths [DerivedBuilt path AllOutputs] Proto.BuildNormal)))  where    path = dnDrvPath node-- | A path rooted for the connection, then whether the daemon holds it,-- without substituting it.rootedValid :: StorePath -> ClientT IO BoolrootedValid path = addTempRoot path *> (Set.member path <$> queryValidPaths (Set.singleton path) NoSubstitute)-- | Make a path valid through the daemon, as a substitution in a store-- opened directly does ('ClosureOutcome'): the path is rooted, and one the-- daemon holds is complete.  Any other is realised as an opaque path,-- which has the daemon's substituters offer it with what it references,-- and ends as the daemon's result for it says ('substitutionOutcome').-- The daemon's substituters are not asked first which of them offer the-- path: a daemon asks only those that declare they take such a question,-- and one that does not would be taken for not offering a path it holds.substituteOpaque :: StorePath -> ClientT IO ClosureOutcomesubstituteOpaque path = rootedValid path >>= bool (substitutionOutcome path <$> buildPathsWithResults [DerivedOpaque path] Proto.BuildNormal) (pure ClosureComplete)-- | The outcome of a path's realisation from the result the daemon gave-- it: success is complete; no substituter offering the path is-- unavailable; a reference that could not be substituted, because no-- substituter offers it or its download failed, is incomplete; any other-- failure, or no result for the path, is a failed substitution.substitutionOutcome :: StorePath -> [KeyedBuildResult] -> ClosureOutcomesubstitutionOutcome path results = case lookup (DerivedOpaque path) [(kbrPath keyed, brOutcome (kbrResult keyed)) | keyed <- results] of  Just (Succeeded _) -> ClosureComplete  Just (Failed failure) -> case failureStatus failure of    NoSubstituters -> ClosureUnavailable    DependencyFailed -> ClosureIncomplete    _ -> ClosureFailed  Nothing -> ClosureFailed-- | A command's session with the relay the daemon's messages go to, which-- every operation of the store runs over ('operate').data StoreSession = StoreSession  { ssRelay :: !Relay,    ssSession :: !DaemonSession  }-- | Run steps over the session as 'daemonOperation' does, then stop any-- activity the daemon started and did not stop, however the operation-- ended: a failed build's activity has no stop of its own.  The stop is-- made while the operation holds the session, so it never stops an-- activity of another operation on the same store.operate :: StoreSession -> ClientT IO a -> IO (Either DaemonOpFailure a)operate session = daemonOperation (ssSession session) (stopOpenActivities (ssRelay session))-- | The operations of a store through a session.daemonOps :: DaemonStoreConfig -> StoreSession -> StoreOps IOdaemonOps config session =  StoreOps    { soQueries = StoreQueries {sqValidPaths = validAmong session, sqReferences = referencesOf session},      soAddEvalObjects = addEvalObjects config session,      soAddSourceTree = addSourceTree session,      soBuild = buildRequested session,      soCheck = \drv -> buildThrough session [DerivedBuilt drv AllOutputs] Proto.BuildCheck,      soAddOutLinkRoot = makeOutLinkRoot (dscFileDir config) (outLinkRooting session),      soEvalWrites = AddedAsMade (MadeOps {moAdd = addEvalWrite session, moHold = holdPath session})    }-- | Build the outputs each request names, none being asked of the daemon-- for a request that names none.buildRequested :: StoreSession -> [(StorePath, Set Text)] -> IO (Either BuildStop ())buildRequested session requests = case targets of  [] -> pure (Right ())  _ -> buildThrough session targets Proto.BuildNormal  where    targets = [DerivedBuilt drv spec | (drv, names) <- requests, Just spec <- [namedOutputs (Set.map OutputName names)]]-- | Ask the daemon to build, in a mode: the stop a failure is.buildThrough :: StoreSession -> [DerivedPath] -> Proto.BuildMode -> IO (Either BuildStop ())buildThrough session targets mode = first buildStop <$> operate session (buildPaths targets mode)-- | A failed operation as the stop a build reports: the daemon's message-- and status, or the reason the connection failed with the status of-- every other stop.buildStop :: DaemonOpFailure -> BuildStopbuildStop = \case  DaemonRefused refusal -> BuildStop (daemonErrorText refusal) (fromIntegral (errExitStatus refusal))  LinkFailed reason -> BuildStop reason connectionFailedStatus-- | The status a build that could not ask the daemon reports.connectionFailedStatus :: IntconnectionFailedStatus = 1-- | How an out-link is rooted through the daemon: its path rooted for the-- connection while the link is made, and the link's absolute spelling-- recorded as an indirect root.outLinkRooting :: StoreSession -> LinkRootingoutLinkRooting session =  LinkRooting    { lrHold = holdPath session,      lrRecord = \bytes -> first opFailureText <$> operate session (addIndirectRoot bytes)    }-- | Which of the paths the daemon holds, asking it nothing when there are-- none.validAmong :: StoreSession -> Set StorePath -> IO (Set StorePath)validAmong session paths  | Set.null paths = pure Set.empty  | otherwise = operate session (queryValidPaths paths NoSubstitute) >>= either (ioError . userError . T.unpack . opFailureText) pure-- | The references the daemon records for a path, none for one it does-- not hold.referencesOf :: StoreSession -> StorePath -> IO (Either Text (Set StorePath))referencesOf session path = either (Left . opFailureText) (Right . maybe Set.empty upiReferences) <$> operate session (queryPathInfo path)-- | Keep a path from collection for the connection's life.holdPath :: StoreSession -> StorePath -> IO (Either Text ())holdPath session path = first opFailureText <$> operate session (addTempRoot path)-- | An operation's answer, or the text of why it failed.viaDaemon :: StoreSession -> ClientT IO a -> ExceptT Text IO aviaDaemon session = withExceptT opFailureText . ExceptT . operate session-- | Add what evaluation made and named, as 'soAddEvalObjects' says:-- nothing at all asks nothing of the daemon, and neither do the trees-- evaluation wrote, which the daemon took as they were made.  Each source-- and derivation is held before the daemon is asked which it has, since-- those it has are not sent.  The sources are sent, then the derivations-- in 'derivationAddOrder', each one the daemon does not hold, until the-- first fails.addEvalObjects :: DaemonStoreConfig -> StoreSession -> EvalObjects -> IO (Either Text ())addEvalObjects config session objects  | nothingToAdd objects = pure (Right ())  | otherwise = runExceptT $ do      derivations <- liftEither (derivationAddOrder (eoDerivations objects))      let sources = Map.toAscList (eoSources objects)          candidates = map fst sources <> [path | (path, _, _) <- derivations]      unless (null candidates) $ do        valid <- viaDaemon session (traverse_ addTempRoot candidates *> queryValidPaths (Set.fromList candidates) NoSubstitute)        sensitivity <- liftIO (probeCaseSensitivity (unStoreDir (dscFileDir config)))        for_ sources $ \(path, srcText) -> unless (Set.member path valid) (addSource config session sensitivity path srcText)        for_ derivations $ \(path, drv, aterm) -> unless (Set.member path valid) (addDerivation session path drv aterm)-- | Send the copy of a path evaluation named, as a NAR of the tree its-- text names, under the case-hack evaluation read it with.  A tree that-- cannot be read fails the add with the failed access's words, whether-- it fails as the walk plans the archive or as the upload pulls a file.addSource :: DaemonStoreConfig -> StoreSession -> CaseSensitivity -> StorePath -> Text -> ExceptT Text IO ()addSource config session sensitivity path srcText = do  let request = AddToStoreRequest (TE.encodeUtf8 (spName path)) narMethod Set.empty NoRepair      source = storeTextToFilePath (dscFileDir config) srcText  added <- liftIO (try (ExecBit.withNarSource (pathCaseHack sensitivity srcText) source (operate session . addToStore request)))  info <- liftEither (either (Left . walkFailureText) (first opFailureText) added)  when (vpiPath info /= path) $    throwError ("refusing to register " <> storePathToText defaultStoreDir path <> ": " <> srcText <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate")-- | Send a derivation's ATerm as a text that refers to what the-- derivation refers to.addDerivation :: StoreSession -> StorePath -> Derivation -> ByteString -> ExceptT Text IO ()addDerivation session path drv aterm = do  let request = AddToStoreRequest (TE.encodeUtf8 (spName path)) textMethod (Set.fromList (drvReferences drv)) NoRepair  source <- liftIO (chunkSource [aterm])  info <- viaDaemon session (addToStore request source)  when (vpiPath info /= path) $ throwError (madeAnotherPath (vpiPath info) path)-- | Add a tree, given as its NAR, as the path its SHA-256, the name and-- the references make.addSourceTree :: StoreSession -> Text -> Set StorePath -> NAR.NarEntry -> IO (Either Text StorePath)addSourceTree session name refs entry = runExceptT $ do  let nar = NAR.serialise entry  expected <- liftEither (first badStorePathText (makeSourcePath name (sha256Digest nar) refs))  source <- liftIO (chunkSource [nar])  info <- viaDaemon session (addToStore (AddToStoreRequest (TE.encodeUtf8 name) narMethod refs NoRepair) source)  expected <$ when (vpiPath info /= expected) (throwError (madeAnotherPath (vpiPath info) expected))-- | Add a tree as evaluation makes it, answering the path the daemon-- made.addEvalWrite :: StoreSession -> EvalWrite -> IO (Either Text StorePath)addEvalWrite session write = do  source <- chunkSource [evalWriteContents write]  bimap opFailureText vpiPath <$> operate session (addToStore (evalWriteRequest write) source)-- | A chunk source over chunks, as an upload is given: each call answers-- the next chunk, and then an empty one, for ever.chunkSource :: [ByteString] -> IO (IO ByteString)chunkSource chunks = do  remaining <- newIORef chunks  pure (atomicModifyIORef' remaining (\case [] -> ([], BS.empty); next : rest -> (rest, next)))-- ----------------------------------------------------------------------------- What is sent-- ----------------------------------------------------------------------------- | The spellings upstream's client sends an add's method in: a text-- hashed with SHA-256, a NAR hashed with it, and a file's bytes hashed-- with it.textMethod, narMethod, flatMethod :: ByteStringtextMethod = "text:sha256"narMethod = "fixed:r:sha256"flatMethod = "fixed:sha256"-- | The add that sends a tree evaluation made: its name, the method its-- kind names, and the references a text has.  Nothing is repaired.evalWriteRequest :: EvalWrite -> AddToStoreRequestevalWriteRequest = \case  TextWrite name refs _ -> request name textMethod refs  FlatWrite name _ -> request name flatMethod Set.empty  NarWrite name _ -> request name narMethod Set.empty  where    request name method refs = AddToStoreRequest (TE.encodeUtf8 name) method refs NoRepair-- | The derivations an evaluation recorded, parsed and in the order to-- add them: each after every derivation of the map that it refers to, as-- a daemon needs each reference valid first.  A derivation visits what-- it refers to, sources and input derivations, before itself, the keys-- and references in ascending order, and each is placed once, so a cycle,-- which no evaluation makes, ends.  A key that names no store path, and-- an ATerm that does not parse, are the reason it is refused.derivationAddOrder :: Map Text ByteString -> Either Text [(StorePath, Derivation, ByteString)]derivationAddOrder recorded = do  parsed <- traverse parseRecorded (Map.toAscList recorded)  let known = Map.fromList [(path, (drv, aterm)) | (path, drv, aterm) <- parsed]  pure (reverse (snd (foldl' (visit known) (Set.empty, []) (Map.keys known))))  where    parseRecorded (key, aterm) = case parseStorePath defaultStoreDir key of      Nothing -> Left ("no store path: " <> key)      Just path -> either (\err -> Left ("the recorded .drv for " <> key <> " does not parse: " <> err)) (\drv -> Right (path, drv, aterm)) (fromATerm aterm)-- | Place a derivation after what it refers to, given the derivations-- known and the paths placed so far with the order they were placed in,-- latest first.visit :: Map StorePath (Derivation, ByteString) -> (Set StorePath, [(StorePath, Derivation, ByteString)]) -> StorePath -> (Set StorePath, [(StorePath, Derivation, ByteString)])visit known (placed, order) path  | Set.member path placed = (placed, order)  | Just (drv, aterm) <- Map.lookup path known =      let (placedAfter, orderAfter) = foldl' (visit known) (Set.insert path placed, order) (Set.toAscList (Set.fromList (drvReferences drv)))       in (placedAfter, (path, drv, aterm) : orderAfter)  | otherwise = (placed, order)-- ----------------------------------------------------------------------------- What is said of a failure-- ----------------------------------------------------------------------------- | A connection that cannot be made, given the reason the operating-- system gives, as upstream words it ('Nix.Daemon.Dial.connectFailureText').connectFailureText :: DaemonAddress -> Text -> TextconnectFailureText address = Dial.connectFailureText (shown (daemonAddressPath address))-- | A handshake that fails, as upstream words it: the store's name and-- the daemon's message, or the reason the connection failed or the client-- refused to go on.openFailureText :: DaemonAddress -> ClientFailure -> TextopenFailureText address failure = "cannot open connection to remote store '" <> daemonStoreName address <> "': error: " <> failureText failure-- | What every operation after a connection failed to open fails with, as-- upstream words it.previouslyFailedText :: DaemonAddress -> TextpreviouslyFailedText address = "opening a connection to remote store '" <> daemonStoreName address <> "' previously failed"-- | Why a step of the client failed: the daemon's message, or the reason-- the connection failed or the client refused to go on.failureText :: ClientFailure -> TextfailureText = \case  DaemonFailed refusal -> daemonErrorText refusal  NotSent why -> why  ConnectionLost why -> why-- | A failed access of the walk of a local tree as the words of the-- access that failed: the entry, what was done to it and the operating-- system's reason.walkFailureText :: NAR.NarWalkError -> TextwalkFailureText = T.pack . displayException-- | Bytes shown in a message, any that are not UTF-8 replaced.shown :: ByteString -> Textshown = TE.decodeUtf8Lenient