Skip to main content

nsh_engine/
cache.rs

1//! Where an app's caches are kept and how much each keeps
2//! ([`CacheOptions`], [`crate::EngineConfig::cache`]). The engine opens
3//! them for the app it runs: each cache in `<root>/<app id>/<kind>`, so
4//! apps never share one. Today the one kind is the images an app
5//! downloads ([`nsh_core::image::DiskCache`], `images`).
6
7use std::path::PathBuf;
8
9pub use nsh_core::ByteSize;
10
11/// Where an app's caches are kept and how much each keeps. The default:
12/// the system's cache directory, each cache at its default size.
13#[derive(Debug, Clone, Default, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct CacheOptions {
16    /// The root of the app's caches: each in `<root>/<app id>/<kind>`.
17    pub location: CacheLocation,
18    /// The images the app downloads, kept as the server sent them
19    /// (`images`).
20    pub images: CachePolicy,
21}
22
23impl CacheOptions {
24    /// Caches in `location`, each at its default size.
25    pub fn at(location: CacheLocation) -> Self {
26        Self {
27            location,
28            ..Self::default()
29        }
30    }
31
32    /// No cache on disk.
33    pub fn off() -> Self {
34        Self::at(CacheLocation::Off)
35    }
36
37    /// These options with `images` for the images the app downloads.
38    #[must_use]
39    pub fn with_images(mut self, images: CachePolicy) -> Self {
40        self.images = images;
41        self
42    }
43}
44
45/// The root directory of an app's caches.
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum CacheLocation {
49    /// The system's cache directory: Caches on Apple platforms (`nsh` in
50    /// it in an embedding iOS app), `%LOCALAPPDATA%` on Windows,
51    /// `$XDG_CACHE_HOME` (`~/.cache`) on Linux, `nsh` in the Context's
52    /// cache directory on Android. The system may clear it for space.
53    #[default]
54    System,
55    /// A directory of the embedding app's choosing.
56    Dir(PathBuf),
57    /// Nothing is cached on disk.
58    Off,
59}
60
61/// How much one cache keeps.
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum CachePolicy {
65    /// Its default size (the images': 256 MiB,
66    /// [`nsh_core::image::DEFAULT_DISK_CACHE_SIZE`]).
67    #[default]
68    Default,
69    /// At most this much; past it the least recently used entries go.
70    MaxSize(ByteSize),
71    /// Not kept on disk.
72    Off,
73}
74
75impl CacheOptions {
76    /// The directory of the `kind` cache of app `app_id` (`None`: none on
77    /// disk), `System` resolved to [`crate::storage`]'s system cache
78    /// directory.
79    #[cfg(not(target_arch = "wasm32"))]
80    pub(crate) fn dir(&self, app_id: Option<&str>, kind: &str) -> Option<PathBuf> {
81        let root = match &self.location {
82            CacheLocation::System => crate::storage::cache_dir()?,
83            CacheLocation::Dir(dir) => dir.clone(),
84            CacheLocation::Off => return None,
85        };
86        Some(root.join(crate::app_dir_name(app_id)).join(kind))
87    }
88
89    /// The disk cache of the images app `app_id` downloads, if it keeps one.
90    #[cfg(not(target_arch = "wasm32"))]
91    pub(crate) fn open_images(&self, app_id: Option<&str>) -> Option<nsh_core::image::DiskCache> {
92        let size = match self.images {
93            CachePolicy::Default => nsh_core::image::DEFAULT_DISK_CACHE_SIZE,
94            CachePolicy::MaxSize(size) => size,
95            CachePolicy::Off => return None,
96        };
97        nsh_core::image::DiskCache::open(self.dir(app_id, "images")?, size)
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use std::path::Path;
104
105    use super::*;
106
107    #[test]
108    fn caches_live_in_their_apps_directory() {
109        let options = CacheOptions::at(CacheLocation::Dir("/c".into()));
110        let images = options.open_images(Some("com.example.chat")).unwrap();
111        assert_eq!(images.dir(), Path::new("/c/com.example.chat/images"));
112        assert_eq!(images.max_size(), ByteSize::mib(256));
113        // An id that is no directory name stays in the root.
114        let odd = options.open_images(Some("a/b")).unwrap();
115        assert_eq!(odd.dir(), Path::new("/c/default/images"));
116        let small = options
117            .clone()
118            .with_images(CachePolicy::MaxSize(ByteSize::mib(8)));
119        assert_eq!(
120            small.open_images(None).unwrap().max_size(),
121            ByteSize::mib(8)
122        );
123        assert!(
124            options
125                .clone()
126                .with_images(CachePolicy::Off)
127                .open_images(None)
128                .is_none()
129        );
130        assert!(
131            options
132                .with_images(CachePolicy::MaxSize(ByteSize::ZERO))
133                .open_images(None)
134                .is_none()
135        );
136        assert!(CacheOptions::off().open_images(None).is_none());
137    }
138}