zebra_network/config/
cache_dir.rs

1//! Cache directory configuration for zebra-network.
2
3use std::path::{Path, PathBuf};
4
5use zebra_chain::{common::default_cache_dir, parameters::Network};
6
7/// A cache directory config field.
8///
9/// This cache directory configuration field is optional.
10/// It defaults to being enabled with the default config path,
11/// but also allows a custom path to be set.
12#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
13#[serde(untagged)]
14pub enum CacheDir {
15    /// Whether the cache directory is enabled with the default path (`true`),
16    /// or disabled (`false`).
17    IsEnabled(bool),
18
19    /// Enable the cache directory and use a custom path.
20    CustomPath(PathBuf),
21}
22
23impl From<bool> for CacheDir {
24    fn from(value: bool) -> Self {
25        CacheDir::IsEnabled(value)
26    }
27}
28
29impl From<PathBuf> for CacheDir {
30    fn from(value: PathBuf) -> Self {
31        CacheDir::CustomPath(value)
32    }
33}
34
35impl CacheDir {
36    /// Returns a `CacheDir` enabled with the default path.
37    pub fn default_path() -> Self {
38        Self::IsEnabled(true)
39    }
40
41    /// Returns a disabled `CacheDir`.
42    pub fn disabled() -> Self {
43        Self::IsEnabled(false)
44    }
45
46    /// Returns a custom `CacheDir` enabled with `path`.
47    pub fn custom_path(path: impl AsRef<Path>) -> Self {
48        Self::CustomPath(path.as_ref().to_owned())
49    }
50
51    /// Returns `true` if this `CacheDir` is enabled with the default or a custom path.
52    pub fn is_enabled(&self) -> bool {
53        match self {
54            CacheDir::IsEnabled(is_enabled) => *is_enabled,
55            CacheDir::CustomPath(_) => true,
56        }
57    }
58
59    /// Returns the peer cache file path for `network`, if enabled.
60    pub fn peer_cache_file_path(&self, network: &Network) -> Option<PathBuf> {
61        Some(
62            self.cache_dir()?
63                .join("network")
64                .join(format!("{}.peers", network.lowercase_name())),
65        )
66    }
67
68    /// Returns the `zebra-network` base cache directory, if enabled.
69    pub fn cache_dir(&self) -> Option<PathBuf> {
70        match self {
71            Self::IsEnabled(is_enabled) => is_enabled.then(default_cache_dir),
72            Self::CustomPath(cache_dir) => Some(cache_dir.to_owned()),
73        }
74    }
75}
76
77impl Default for CacheDir {
78    fn default() -> Self {
79        Self::default_path()
80    }
81}