Skip to main content

nix_daemon/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3use std::{
4    collections::BTreeMap,
5    io::{Error, Result},
6    sync::Arc,
7};
8
9use nix_compat::{
10    derivation::{OutputName, UnverifiedDerivation},
11    derived_path::DerivedPath,
12    nix_daemon::{
13        NixDaemonIO,
14        types::{
15            BuildMode, BuildResult, KeyedBuildResult, NarHash, QueryMissingResult,
16            UnkeyedValidPathInfo, ValidPathInfo,
17        },
18    },
19    nixbase32,
20    nixhash::CAHashMode,
21    store_path::{StorePath, build_ca_path},
22};
23use snix_build::buildservice::BuildService;
24use snix_build_glue::build_state::BuildState;
25use snix_castore::{blob_engine::BlobEngine, directoryservice::DirectoryService};
26use snix_store::{
27    nar::{NarCalculationService, ingest_nar_and_hash},
28    path_info::PathInfo,
29    pathinfoservice::PathInfoService,
30};
31use tracing::{instrument, warn};
32use url::Url;
33
34#[allow(dead_code)]
35pub struct SnixDaemon {
36    build_state: Arc<BuildState>,
37}
38
39impl SnixDaemon {
40    pub fn new(
41        blob_engine: Arc<dyn BlobEngine>,
42        directory_service: Arc<dyn DirectoryService>,
43        path_info_service: Arc<dyn PathInfoService>,
44        nar_calculation_service: Arc<dyn NarCalculationService>,
45        build_service: Arc<dyn BuildService>,
46        hashed_mirrors: Vec<Url>,
47    ) -> Self {
48        let build_state = Arc::new(BuildState::new(
49            blob_engine,
50            directory_service,
51            path_info_service,
52            nar_calculation_service,
53            build_service,
54            hashed_mirrors,
55        ));
56        Self { build_state }
57    }
58}
59
60/// Implements [NixDaemonIO] backed by snix services.
61impl NixDaemonIO for SnixDaemon {
62    #[instrument(skip_all, fields(path), level = "debug", ret(Debug))]
63    async fn query_path_info(&self, path: &StorePath) -> Result<Option<UnkeyedValidPathInfo>> {
64        let path_info_service = self.build_state.path_info_service.clone();
65        if let Some(path_info) = path_info_service
66            .get(*path.digest())
67            .await
68            .map_err(std::io::Error::other)?
69            && path_info.store_path.name() == path.name()
70        {
71            return Ok(Some(into_unkeyed_path_info(path_info)));
72        }
73        Ok(None)
74    }
75
76    #[instrument(skip_all, fields(hash=nix_compat::nixbase32::encode(hash)), level = "debug", ret(Debug))]
77    async fn query_path_from_hash_part(&self, hash: &[u8]) -> Result<Option<UnkeyedValidPathInfo>> {
78        let digest = hash
79            .try_into()
80            .map_err(|_| Error::other("invalid digest length"))?;
81        match self
82            .build_state
83            .path_info_service
84            .get(digest)
85            .await
86            .map_err(std::io::Error::other)?
87        {
88            Some(path_info) => Ok(Some(into_unkeyed_path_info(path_info))),
89            None => Ok(None),
90        }
91    }
92
93    #[instrument(skip_all, fields(request), level = "debug", ret(Debug))]
94    async fn add_to_store_nar<R>(
95        &self,
96        info: ValidPathInfo,
97        reader: &mut R,
98        _repair: bool,
99        _dont_check_sigs: bool,
100    ) -> Result<()>
101    where
102        R: tokio::io::AsyncRead + Send + Unpin,
103    {
104        let (root_node, nar_sha256, nar_size) = ingest_nar_and_hash(
105            self.build_state.blob_engine.clone(),
106            &self.build_state.directory_service,
107            reader,
108            &info.info.ca,
109        )
110        .await
111        .map_err(|e| Error::other(e.to_string()))?;
112
113        if nar_size != info.info.nar_size || nar_sha256 != *info.info.nar_hash {
114            warn!(
115                nar_hash.expected = nixbase32::encode(&*info.info.nar_hash),
116                nar_hash.actual = nixbase32::encode(&nar_sha256),
117                "nar hash mismatch"
118            );
119            return Err(Error::other(
120                "ingested nar ended up different from what was specified in the request",
121            ));
122        }
123
124        if let Some(cahash) = &info.info.ca {
125            let actual_path = build_ca_path(
126                info.path.name(),
127                cahash.mode() == CAHashMode::Nar,
128                &cahash.hash(),
129                info.info.references.iter().map(|p| p.as_ref()),
130                false,
131            );
132
133            if actual_path != info.path.as_ref() {
134                return Err(Error::other("path mismatch"));
135            }
136        }
137
138        let path_info = PathInfo {
139            store_path: info.path,
140            node: root_node,
141            references: info.info.references,
142            nar_size,
143            nar_sha256,
144            signatures: info.info.signatures,
145            deriver: info.info.deriver,
146            ca: info.info.ca,
147        };
148        self.build_state
149            .path_info_service
150            .put(path_info)
151            .await
152            .map_err(|e| Error::other(e.to_string()))?;
153        Ok(())
154    }
155
156    async fn nar_from_path(
157        &self,
158        path: &StorePath,
159    ) -> std::io::Result<Box<dyn tokio::io::AsyncBufRead + Unpin + Send>> {
160        let path_info = self
161            .build_state
162            .path_info_service
163            .get(*path.digest())
164            .await
165            .map_err(std::io::Error::other)?
166            .ok_or_else(|| std::io::Error::other("unknown store path"))?;
167
168        let blob_engine = self.build_state.blob_engine.clone();
169        let directory_service = self.build_state.directory_service.clone();
170
171        Ok(Box::new(
172            snix_store::nar::Reader::new(&path_info.node, blob_engine, directory_service)
173                .await
174                .map_err(std::io::Error::other)?,
175        ))
176    }
177
178    async fn build_paths(&self, _derived_paths: Vec<DerivedPath>, _mode: BuildMode) -> Result<()> {
179        Ok(())
180    }
181
182    async fn build_paths_with_results(
183        &self,
184        _derived_paths: Vec<DerivedPath>,
185        _mode: BuildMode,
186    ) -> Result<Vec<KeyedBuildResult>> {
187        Err(std::io::Error::other(
188            "Operation BuildPathsWithResults is not implemented",
189        ))
190    }
191    async fn build_derivation(
192        &self,
193        _drv_path: StorePath,
194        _derivation: UnverifiedDerivation,
195        _mode: BuildMode,
196    ) -> std::io::Result<BuildResult> {
197        Err(std::io::Error::other(
198            "Operation BuildDerivation is not implemented",
199        ))
200    }
201
202    async fn query_missing(&self, _derived_paths: Vec<DerivedPath>) -> Result<QueryMissingResult> {
203        Err(std::io::Error::other(
204            "Operation QueryMissing is not implemented",
205        ))
206    }
207
208    async fn query_derivation_output_map(
209        &self,
210        _drv_path: &StorePath,
211    ) -> Result<BTreeMap<OutputName, Option<StorePath>>> {
212        Err(std::io::Error::other(
213            "Operation QueryDerivationOutputMap is not implemented",
214        ))
215    }
216
217    async fn add_temp_root(&self, path: &StorePath) -> std::io::Result<()> {
218        warn!(
219            "Would create a temp GC root for {} but snix do not support those yet",
220            &path
221        );
222        Ok(())
223    }
224
225    async fn add_indirect_root(&self, path: &str) -> std::io::Result<()> {
226        warn!(
227            "Would create a indirect GC root for {} but snix do not support those yet",
228            &path
229        );
230        Ok(())
231    }
232}
233
234// PathInfo lives in the snix-store crate, but does not depend on nix-compat's wire feature,
235// while UnkeyedValidPathInfo is only available if that feature is enabled. To avoid complexity
236// we manually convert as opposed to creating a From<PathInfo>.
237fn into_unkeyed_path_info(info: PathInfo) -> UnkeyedValidPathInfo {
238    UnkeyedValidPathInfo {
239        deriver: info.deriver,
240        nar_hash: NarHash::from_digest(info.nar_sha256),
241        references: info.references,
242        registration_time: 0,
243        nar_size: info.nar_size,
244        ultimate: false,
245        signatures: info.signatures,
246        ca: info.ca,
247    }
248}