1use std::collections::BTreeMap;
17use std::sync::Arc;
18
19use async_trait::async_trait;
20use engenho_store::{
21 StoreMesh,
22 command::{Reason, ResourceCommand},
23};
24use engenho_substrate::{
25 DerivationCacheBackend, Drv, DrvHash, NarBlob, NarHash, OutputPath, Realisation,
26};
27use serde_json::json;
28use thiserror::Error;
29use tokio::sync::Mutex;
30use tracing::debug;
31
32use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
33use crate::drv::DrvController;
34use crate::effect::Effect;
35use crate::error::ControllerError;
36
37#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct BuildResult {
41 pub realisations: Vec<Realisation>,
43 pub nars: Vec<NarBlob>,
45}
46
47#[derive(Debug, Clone, Error)]
49pub enum BuildError {
50 #[error("backend: {0}")]
52 Backend(String),
53 #[error("invalid drv: {0}")]
55 InvalidDrv(String),
56}
57
58engenho_substrate::impl_error_kind! {
59 BuildError {
60 (Backend(_)) => "backend",
61 (InvalidDrv(_)) => "invalid_drv",
62 }
63}
64
65#[async_trait]
67pub trait BuildBackend: Send + Sync {
68 fn name(&self) -> &'static str;
70
71 async fn build(&self, drv: &Drv) -> Result<BuildResult, BuildError>;
77}
78
79#[derive(Default, Clone)]
86pub struct FakeBuildBackend {
87 inner: Arc<Mutex<FakeBuildState>>,
88}
89
90#[derive(Default)]
91struct FakeBuildState {
92 builds: Vec<DrvHash>,
93 fail_with: Option<String>,
95}
96
97impl FakeBuildBackend {
98 #[must_use]
100 pub fn new() -> Self {
101 Self::default()
102 }
103
104 pub async fn builds(&self) -> Vec<DrvHash> {
106 self.inner.lock().await.builds.clone()
107 }
108
109 pub async fn fail_next(&self, msg: impl Into<String>) {
111 self.inner.lock().await.fail_with = Some(msg.into());
112 }
113}
114
115#[async_trait]
116impl BuildBackend for FakeBuildBackend {
117 fn name(&self) -> &'static str {
118 "fake"
119 }
120
121 async fn build(&self, drv: &Drv) -> Result<BuildResult, BuildError> {
122 let mut state = self.inner.lock().await;
123 state.builds.push(drv.drv_hash.clone());
124 if let Some(msg) = state.fail_with.take() {
125 return Err(BuildError::Backend(msg));
126 }
127 let outputs: Vec<String> = if drv.outputs.is_empty() {
129 vec!["out".into()]
130 } else {
131 drv.outputs.keys().cloned().collect()
132 };
133 let mut realisations = Vec::with_capacity(outputs.len());
134 let mut nars = Vec::with_capacity(outputs.len());
135 for name in outputs {
136 let synthetic_bytes = format!("nar:{}:{name}", drv.drv_hash.to_hex()).into_bytes();
137 let nar = NarBlob::from_bytes(synthetic_bytes);
138 realisations.push(Realisation {
139 drv_hash: drv.drv_hash.clone(),
140 output_name: name.clone(),
141 output_path: OutputPath::new(format!(
142 "/nix/store/{}-{name}",
143 &drv.drv_hash.to_hex()[..16]
144 )),
145 nar_hash: Some(nar.hash().clone()),
146 });
147 nars.push(nar);
148 }
149 Ok(BuildResult { realisations, nars })
150 }
151}
152
153pub struct DrvBuildController {
159 store: Arc<StoreMesh>,
160 cache: Arc<dyn DerivationCacheBackend>,
161 builder: Arc<dyn BuildBackend>,
162 namespace: Option<String>,
163}
164
165impl DrvBuildController {
166 #[must_use]
168 pub fn new(
169 store: Arc<StoreMesh>,
170 cache: Arc<dyn DerivationCacheBackend>,
171 builder: Arc<dyn BuildBackend>,
172 namespace: Option<String>,
173 ) -> Self {
174 Self {
175 store,
176 cache,
177 builder,
178 namespace,
179 }
180 }
181
182 pub async fn ingest(
188 cache: &Arc<dyn DerivationCacheBackend>,
189 result: &BuildResult,
190 ) -> Result<(), ControllerError> {
191 for nar in &result.nars {
192 cache
193 .put_nar(nar)
194 .await
195 .map_err(|e| ControllerError::Internal(e.to_string()))?;
196 }
197 for r in &result.realisations {
198 cache
199 .put_realisation(r)
200 .await
201 .map_err(|e| ControllerError::Internal(e.to_string()))?;
202 }
203 Ok(())
204 }
205}
206
207#[async_trait]
208impl Controller for DrvBuildController {
209 fn name(&self) -> &'static str {
210 "drv-build"
211 }
212
213 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
214 let drs = self
215 .store
216 .list("engenho.io", "v1", "Derivation", self.namespace.as_deref())
217 .await;
218 let mut report = ReconcileReport::default();
219 report.objects_examined = drs.len();
220
221 for (cr_key, cr_value) in &drs {
222 let phase = cr_value
224 .get("status")
225 .and_then(|s| s.get("phase"))
226 .and_then(|p| p.as_str());
227 if phase != Some("Pending") {
228 continue;
229 }
230 let hash_str = cr_value
231 .get("spec")
232 .and_then(|s| s.get("drvHash"))
233 .and_then(|h| h.as_str());
234 let Some(hash_str) = hash_str else {
235 report.objects_skipped += 1;
236 continue;
237 };
238 let Some(hash) = DrvController::parse_drv_hash(hash_str) else {
239 report.objects_skipped += 1;
240 continue;
241 };
242
243 let drv = if let Some(d) = self
245 .cache
246 .get_drv(&hash)
247 .await
248 .map_err(|e| ControllerError::Internal(e.to_string()))?
249 {
250 d
251 } else {
252 debug!(drv_hash = %hash_str, "DrvBuild: drv not in cache");
253 continue;
254 };
255
256 let result = match self.builder.build(&drv).await {
258 Ok(r) => r,
259 Err(e) => {
260 let applied = self
262 .store
263 .propose(ResourceCommand::patch(
264 cr_key.clone(),
265 json!({
266 "status": {
267 "phase": "BuildFailed",
268 "message": e.to_string(),
269 }
270 }),
271 Reason::Controller,
272 ))
273 .await?;
274 report.record(Effect::of(applied.op));
275 continue;
276 }
277 };
278
279 let ingested = Effect::applied(Self::ingest(&self.cache, &result).await)?;
282 report.record(ingested);
283 }
284 Ok(report.into())
285 }
286}
287
288impl BuildResult {
290 #[must_use]
292 pub fn empty() -> Self {
293 Self {
294 realisations: Vec::new(),
295 nars: Vec::new(),
296 }
297 }
298
299 #[must_use]
301 pub fn single_output(
302 drv_hash: DrvHash,
303 output_name: impl Into<String>,
304 output_path: OutputPath,
305 nar_bytes: Vec<u8>,
306 ) -> Self {
307 let nar = NarBlob::from_bytes(nar_bytes);
308 let realisation = Realisation {
309 drv_hash,
310 output_name: output_name.into(),
311 output_path,
312 nar_hash: Some(nar.hash().clone()),
313 };
314 Self {
315 realisations: vec![realisation],
316 nars: vec![nar],
317 }
318 }
319
320 #[must_use]
322 pub fn nar_index(&self) -> BTreeMap<String, NarHash> {
323 self.realisations
324 .iter()
325 .filter_map(|r| {
326 r.nar_hash
327 .as_ref()
328 .map(|h| (r.output_name.clone(), h.clone()))
329 })
330 .collect()
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337 use engenho_substrate::MemoryDerivationCache;
338
339 fn sample_drv() -> Drv {
340 Drv::synthetic(DrvHash::from_bytes(b"sample"), "x86_64-linux")
341 }
342
343 fn cache_arc(c: MemoryDerivationCache) -> Arc<dyn DerivationCacheBackend> {
344 Arc::new(c)
345 }
346
347 #[tokio::test]
348 async fn fake_backend_records_build_calls() {
349 let b = FakeBuildBackend::new();
350 let drv = sample_drv();
351 b.build(&drv).await.unwrap();
352 assert_eq!(b.builds().await.len(), 1);
353 assert_eq!(b.builds().await[0], drv.drv_hash);
354 }
355
356 #[tokio::test]
357 async fn fake_backend_produces_single_out_when_no_outputs_declared() {
358 let b = FakeBuildBackend::new();
359 let r = b.build(&sample_drv()).await.unwrap();
360 assert_eq!(r.realisations.len(), 1);
361 assert_eq!(r.realisations[0].output_name, "out");
362 assert_eq!(r.nars.len(), 1);
363 }
364
365 #[tokio::test]
366 async fn fake_backend_respects_declared_outputs() {
367 let mut drv = sample_drv();
368 drv.outputs.insert("out".into(), OutputPath::new(""));
369 drv.outputs.insert("dev".into(), OutputPath::new(""));
370 let b = FakeBuildBackend::new();
371 let r = b.build(&drv).await.unwrap();
372 assert_eq!(r.realisations.len(), 2);
373 let names: Vec<_> = r.realisations.iter().map(|r| &r.output_name).collect();
374 assert!(names.iter().any(|n| n.as_str() == "out"));
375 assert!(names.iter().any(|n| n.as_str() == "dev"));
376 }
377
378 #[tokio::test]
379 async fn fake_backend_nar_hashes_match_payload() {
380 let b = FakeBuildBackend::new();
381 let r = b.build(&sample_drv()).await.unwrap();
382 for nar in &r.nars {
383 let actual = NarHash::from_bytes(nar.bytes());
384 assert_eq!(&actual, nar.hash());
385 }
386 }
387
388 #[tokio::test]
389 async fn fake_backend_fail_next_surfaces_error() {
390 let b = FakeBuildBackend::new();
391 b.fail_next("oops").await;
392 let err = b.build(&sample_drv()).await.unwrap_err();
393 assert_eq!(err.kind(), "backend");
394 }
395
396 #[tokio::test]
397 async fn ingest_writes_nars_and_realisations() {
398 let cache = cache_arc(MemoryDerivationCache::new());
399 let drv = sample_drv();
400 let result = BuildResult::single_output(
401 drv.drv_hash.clone(),
402 "out",
403 OutputPath::new("/nix/store/abc-out"),
404 b"hello-nar".to_vec(),
405 );
406 DrvBuildController::ingest(&cache, &result).await.unwrap();
407 let nar = cache.get_nar(result.nars[0].hash()).await.unwrap();
408 assert!(nar.is_some());
409 let list = cache.list_realisations(&drv.drv_hash).await.unwrap();
410 assert_eq!(list.len(), 1);
411 }
412
413 #[test]
414 fn build_result_single_output_builds_typed_realisation() {
415 let drv_hash = DrvHash::from_bytes(b"x");
416 let r = BuildResult::single_output(
417 drv_hash.clone(),
418 "out",
419 OutputPath::new("/nix/store/a-out"),
420 b"nar-bytes".to_vec(),
421 );
422 assert_eq!(r.realisations.len(), 1);
423 assert_eq!(r.realisations[0].drv_hash, drv_hash);
424 assert_eq!(r.realisations[0].output_name, "out");
425 assert_eq!(r.nars.len(), 1);
426 assert_eq!(r.realisations[0].nar_hash.as_ref(), Some(r.nars[0].hash()));
427 }
428
429 #[test]
430 fn build_result_empty_is_zero_sized() {
431 let r = BuildResult::empty();
432 assert!(r.realisations.is_empty());
433 assert!(r.nars.is_empty());
434 }
435
436 #[test]
437 fn build_result_nar_index_maps_output_to_hash() {
438 let drv_hash = DrvHash::from_bytes(b"x");
439 let r = BuildResult::single_output(
440 drv_hash,
441 "out",
442 OutputPath::new("/nix/store/a"),
443 b"nar".to_vec(),
444 );
445 let idx = r.nar_index();
446 assert_eq!(idx.len(), 1);
447 assert!(idx.contains_key("out"));
448 }
449
450 #[test]
451 fn build_error_kinds_are_stable() {
452 assert_eq!(BuildError::Backend("x".into()).kind(), "backend");
453 assert_eq!(BuildError::InvalidDrv("x".into()).kind(), "invalid_drv");
454 }
455
456 #[test]
457 fn fake_backend_name_is_stable() {
458 assert_eq!(FakeBuildBackend::new().name(), "fake");
459 }
460
461 #[test]
462 fn controller_name_is_stable() {
463 struct F;
464 #[async_trait]
465 impl Controller for F {
466 fn name(&self) -> &'static str {
467 "drv-build"
468 }
469 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
470 Ok(ReconcileReport::default().into())
471 }
472 }
473 assert_eq!(F.name(), "drv-build");
474 }
475}