Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Provides an interface for querying data from the nix store.
//!
//! - [`DbConnection`] is a direct connection to the underlying sqlite database.
//! - [`CommandBackend`] uses nix commands to interact with the store.
mod db;
pub mod nix_command;
mod queries;
// Make the test db available for the rest of the crate.
#[cfg(test)] pub(crate) mod test_utils;

use std::{
  fmt::Display,
  path::Path,
};

pub use db::DbConnection;
use eyre::{
  Result,
  eyre,
};
pub use nix_command::CommandBackend;
use size::Size;
use tracing::warn;

use crate::StorePath;

/// The normal database connection
pub const DATABASE_PATH: &str = "file:/nix/var/nix/db/db.sqlite";
/// A backup database connection that can access the database
/// even in a read-only environment
///
/// This might produce incorrect results as the connection is not guaranteed
/// to be the only one accessing the database. (There might be e.g. a
/// `nixos-rebuild` modifying the database)
pub const DATABASE_PATH_IMMUTABLE: &str =
  "file:/nix/var/nix/db/db.sqlite?immutable=1";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StorePathInfo {
  path:     StorePath,
  nar_size: Size,
}

impl StorePathInfo {
  #[must_use]
  pub const fn new(path: StorePath, nar_size: Size) -> Self {
    Self { path, nar_size }
  }

  #[must_use]
  pub const fn path(&self) -> &StorePath {
    &self.path
  }

  #[must_use]
  pub const fn nar_size(&self) -> Size {
    self.nar_size
  }
}

/// Defines an interface for interacting with a Nix database.
///
/// This allows us to construct a backend that can fall back
/// to e.g. shell commands should something go wrong.
pub trait StoreBackend: Display {
  /// Opens any resources required by the backend.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend cannot be connected.
  fn connect(&mut self) -> Result<()>;
  /// Returns whether this backend is currently connected.
  fn connected(&self) -> bool;
  /// Closes resources held by the backend.
  ///
  /// # Errors
  ///
  /// Returns an error if resources cannot be closed cleanly.
  fn close(&mut self) -> Result<()>;
  /// Queries the closure size for a Nix store path.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend query fails or the size cannot be read.
  fn query_closure_size(&self, path: &Path) -> Result<Size> {
    Ok(Size::from_bytes(
      self
        .query_closure_path_info(path)?
        .iter()
        .map(|info| info.nar_size().bytes())
        .sum::<i64>(),
    ))
  }
  /// Queries derivations selected by a system profile.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend query fails.
  fn query_system_derivations(&self, system: &Path) -> Result<Vec<StorePath>>;
  /// Queries all dependencies of a store path.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend query fails.
  fn query_dependents(&self, path: &Path) -> Result<Vec<StorePath>>;
  /// Queries all dependencies of a store path with their NAR sizes.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend query fails or path information cannot be
  /// read.
  fn query_closure_path_info(&self, path: &Path) -> Result<Vec<StorePathInfo>>;
}

/// combines multiple store backends by falling back to the next one if the
/// current one fails.
///
/// Queries try connected backends in order.
pub struct CombinedStoreBackend {
  /// The underlying store backend implementations.
  backends: Vec<Box<dyn StoreBackend>>,
}

impl CombinedStoreBackend {
  #[must_use]
  pub fn new(backends: Vec<Box<dyn StoreBackend>>) -> Self {
    Self { backends }
  }

  #[must_use]
  pub fn for_correctness(force_correctness: bool) -> Self {
    if force_correctness {
      Self::default_correct()
    } else {
      Self::default_fast()
    }
  }

  pub(crate) fn query_with_correctness<T>(
    force_correctness: bool,
    query: impl FnOnce(&Self) -> Result<T>,
  ) -> Result<T> {
    let mut backend = Self::for_correctness(force_correctness);
    backend.connect()?;

    let result = query(&backend);
    let close_result = backend.close();

    match result {
      Ok(value) => {
        close_result?;
        Ok(value)
      },
      Err(error) => Err(error),
    }
  }

  /// Returns a backend that is focused on performance and availability.
  ///
  /// This first tries the regular sqlite database, then falls back to opening
  /// it with `immutable=1`, and finally falls back to Nix commands.
  #[must_use]
  pub fn default_fast() -> Self {
    Self::new(vec![
      Box::new(DbConnection::new(DATABASE_PATH)),
      Box::new(DbConnection::new(DATABASE_PATH_IMMUTABLE)),
      Box::new(CommandBackend::default()),
    ])
  }

  /// Returns a backend that is focused solely on absolutely guaranteeing
  /// correct results if the regular sqlite database cannot be opened.
  ///
  /// Note that [`DATABASE_PATH_IMMUTABLE`] is not used here, since opening
  /// the database can lead to undefined results (also silently with no errors)
  /// if the database is actually modified while opened.
  #[must_use]
  pub fn default_correct() -> Self {
    Self::new(vec![
      Box::new(DbConnection::new(DATABASE_PATH)),
      Box::new(CommandBackend::default()),
    ])
  }

  // tries to execute a query until it succeeds or all connected backends have
  // been tried
  fn fallback_query<F, Ret>(&self, query: F, path: &Path) -> Result<Ret>
  where
    F: Fn(&dyn StoreBackend, &Path) -> Result<Ret>,
  {
    let mut combined_err: Option<eyre::Report> = None;
    // attempt to cycle through backends until a successful query is made
    for (i, backend) in self.backends.iter().enumerate() {
      if !backend.connected() {
        warn!(
          "Skipping backend {i} ({backend}) in query {path:?}: not connected"
        );
        continue;
      }
      let res = query(backend.as_ref(), path);
      match res {
        Ok(_) => return res,
        Err(err) => {
          warn!(
            "Failed to query path {path:?} on current backend {backend} \
             ({i}): {}",
            &err
          );
          combined_err = match combined_err {
            Some(combined) => Some(combined.wrap_err(err)),
            None => Some(err),
          };
        },
      }
    }
    warn!("All store backends for path {path:?} failed");
    Err(combined_err.unwrap_or_else(|| eyre!("No internal stores to query.")))
  }
}

impl Display for CombinedStoreBackend {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "CombinedStoreBackend({} backends)", self.backends.len())
  }
}

impl Default for CombinedStoreBackend {
  fn default() -> Self {
    Self::default_fast()
  }
}

impl StoreBackend for CombinedStoreBackend {
  /// connects to all backends. Returns an error if all backends fail
  fn connect(&mut self) -> Result<()> {
    tracing::debug!(
      backend_count = self.backends.len(),
      "connecting to store backends"
    );
    let mut combined_err: Option<eyre::Report> = None;
    let mut connected_count = 0;
    // connect, collecting the errors as we go
    for (i, backend) in self.backends.iter_mut().enumerate() {
      tracing::trace!(backend_index = i, backend = %backend, "attempting to connect to backend");
      if let Err(err) = backend.connect() {
        warn!(
          "Unable to connect to store backend {i}: {backend}, trying next. \
           (error: {err})"
        );
        combined_err = match combined_err {
          Some(combined) => Some(combined.wrap_err(err)),
          None => Some(err),
        }
      } else {
        connected_count += 1;
        tracing::debug!(backend_index = i, backend = %backend, "backend connected successfully");
      }
    }
    tracing::info!(
      connected_count = connected_count,
      total_count = self.backends.len(),
      "backend connection complete"
    );
    let any_succeeded = self.backends.iter().any(|f| f.connected());
    // warn about encountered errors, even though there are fallbacks
    if let Some(err) = &combined_err
      && any_succeeded
    {
      warn!("Some backends failed to connect: {err}");
    }
    if any_succeeded {
      Ok(())
    } else {
      combined_err =
        combined_err.map(|err| err.wrap_err("All backends failed to connect."));
      Err(combined_err.unwrap_or_else(|| eyre!("No backends to connect to.")))
    }
  }

  /// True if any backend is connected.
  fn connected(&self) -> bool {
    self.backends.iter().any(|backend| backend.connected())
  }

  /// Closes all connected backends.
  ///
  /// If some fail to close, the combined error is returned.
  fn close(&mut self) -> Result<()> {
    let mut combined_err: Option<eyre::Report> = None;
    for (i, backend) in self.backends.iter_mut().enumerate() {
      if backend.connected()
        && let Err(err) = backend.close()
      {
        warn!("Unable to close store backend {i}: {backend}. (error: {err})");
        combined_err = match combined_err {
          Some(combined) => Some(combined.wrap_err(err)),
          None => Some(err),
        };
      }
    }
    combined_err.map_or_else(
      || Ok(()),
      |err| Err(err.wrap_err("One or more backends failed to close.")),
    )
  }

  fn query_system_derivations(&self, system: &Path) -> Result<Vec<StorePath>> {
    self.fallback_query(
      |backend, system| backend.query_system_derivations(system),
      system,
    )
  }

  fn query_dependents(&self, path: &Path) -> Result<Vec<StorePath>> {
    self.fallback_query(|backend, path| backend.query_dependents(path), path)
  }

  fn query_closure_path_info(&self, path: &Path) -> Result<Vec<StorePathInfo>> {
    self.fallback_query(
      |backend, path| backend.query_closure_path_info(path),
      path,
    )
  }
}

#[cfg(test)]
mod test {
  use std::{
    cell::RefCell,
    fmt,
  };

  use super::*;

  struct MockStoreBackend {
    name:         String,
    connected:    bool,
    fail_connect: bool,
    fail_query:   bool,
    query_called: RefCell<bool>,
  }

  impl MockStoreBackend {
    fn new(name: &str, fail_connect: bool, fail_query: bool) -> Self {
      Self {
        name: name.to_string(),
        connected: false,
        fail_connect,
        fail_query,
        query_called: RefCell::new(false),
      }
    }
  }

  impl Display for MockStoreBackend {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
      write!(f, "MockStoreBackend({})", self.name)
    }
  }

  impl StoreBackend for MockStoreBackend {
    fn connect(&mut self) -> Result<()> {
      if self.fail_connect {
        Err(eyre!("Connection failed"))
      } else {
        self.connected = true;
        Ok(())
      }
    }

    fn connected(&self) -> bool {
      self.connected
    }

    fn close(&mut self) -> Result<()> {
      self.connected = false;
      Ok(())
    }

    fn query_system_derivations(
      &self,
      _system: &Path,
    ) -> Result<Vec<StorePath>> {
      *self.query_called.borrow_mut() = true;
      if self.fail_query {
        Err(eyre!("Query failed"))
      } else {
        Ok(Vec::new())
      }
    }

    fn query_dependents(&self, _path: &Path) -> Result<Vec<StorePath>> {
      *self.query_called.borrow_mut() = true;
      if self.fail_query {
        Err(eyre!("Query failed"))
      } else {
        Ok(Vec::new())
      }
    }

    fn query_closure_path_info(
      &self,
      _path: &Path,
    ) -> Result<Vec<StorePathInfo>> {
      *self.query_called.borrow_mut() = true;
      if self.fail_query {
        Err(eyre!("Query failed"))
      } else {
        Ok(vec![StorePathInfo::new(
          StorePath::try_from(
            Path::new("/nix/store/0123456789abcdefghijklmnopqrstuv-dummy")
              .to_path_buf(),
          )?,
          Size::from_bytes(100),
        )])
      }
    }
  }

  #[test]
  fn test_connect_fallback() {
    let f1 = Box::new(MockStoreBackend::new("f1", true, false));
    let f2 = Box::new(MockStoreBackend::new("f2", false, false));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2]);

    assert!(combined.connect().is_ok());
    assert!(combined.connected());
  }

  #[test]
  fn test_connect_all_fail() {
    let f1 = Box::new(MockStoreBackend::new("f1", true, false));
    let f2 = Box::new(MockStoreBackend::new("f2", true, false));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2]);

    assert!(combined.connect().is_err());
    assert!(!combined.connected());
  }

  #[test]
  fn test_query_fallback() {
    let f1 = Box::new(MockStoreBackend::new("f1", false, true));
    let f2 = Box::new(MockStoreBackend::new("f2", false, false));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2]);

    combined.connect().unwrap();

    let res = combined.query_closure_size(Path::new("/dummy"));
    assert!(res.is_ok());
    assert_eq!(res.unwrap(), Size::from_bytes(100));
  }

  #[test]
  fn test_path_query_fallback() {
    let f1 = Box::new(MockStoreBackend::new("f1", false, true));
    let f2 = Box::new(MockStoreBackend::new("f2", false, false));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2]);

    combined.connect().unwrap();

    let res = combined.query_dependents(Path::new("/dummy"));
    assert!(res.is_ok());
    assert_eq!(res.unwrap(), Vec::new());
  }

  #[test]
  fn test_query_skip_unconnected() {
    let f1 = Box::new(MockStoreBackend::new("f1", true, false));
    let f2 = Box::new(MockStoreBackend::new("f2", false, false));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2]);

    combined.connect().unwrap(); // f1 fails, f2 succeeds

    let res = combined.query_closure_size(Path::new("/dummy"));
    assert!(res.is_ok());
    assert_eq!(res.unwrap(), Size::from_bytes(100));

    let f1 = Box::new(MockStoreBackend::new("f1", true, false));
    let f2 = Box::new(MockStoreBackend::new("f2", true, false));
    let f3 = Box::new(MockStoreBackend::new("f3", false, false));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2, f3]);
    combined.connect().unwrap();

    let res = combined.query_closure_size(Path::new("/dummy"));
    assert_eq!(res.unwrap(), Size::from_bytes(100));
    assert!(combined.connect().is_ok());
    assert!(combined.connected());
  }

  #[test]
  fn test_query_all_fail() {
    let f1 = Box::new(MockStoreBackend::new("f1", false, true));
    let f2 = Box::new(MockStoreBackend::new("f2", false, true));
    let mut combined = CombinedStoreBackend::new(vec![f1, f2]);

    combined.connect().unwrap();

    let res = combined.query_closure_size(Path::new("/dummy"));
    assert!(res.is_err());
  }
}