bunsen 0.23.0

bunsen is a batteries included common library for burn
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
//! # Disk Cache Management

use std::{
    fs,
    path::{
        Path,
        PathBuf,
    },
};

use downloader::{
    Download,
    Downloader,
};

use crate::{
    data::cache::{
        BUNSEN_CACHE_CONFIG,
        path_utils,
    },
    errors::{
        BunsenError,
        BunsenResult,
    },
};

/// Environment variable key to override the default cache directory.
pub const BUNSEN_CACHE_DIR: &str = "BUNSEN_CACHE_DIR";
/// Environment variable key to override the default data directory.
pub const BUNSEN_DATA_DIR: &str = "BUNSEN_DATA_DIR";

/// Options for [`BunsenDiskCache`].
#[derive(Clone, Default, Debug)]
pub struct BunsenDiskCacheOptions {
    /// Optional path to the cache directory.
    pub cache_dir: Option<PathBuf>,

    /// Optional path to the data directory.
    pub data_dir: Option<PathBuf>,

    /// Optional [`Downloader`] builder.
    pub downloader: Option<fn() -> Downloader>,
}

impl BunsenDiskCacheOptions {
    /// Sets the cache directory.
    pub fn with_cache_dir<P: AsRef<Path>>(
        mut self,
        cache_dir: Option<P>,
    ) -> Self {
        self.cache_dir = cache_dir.map(|p| p.as_ref().to_path_buf());
        self
    }

    /// Sets the data directory.
    pub fn with_data_dir<P: AsRef<Path>>(
        mut self,
        data_dir: Option<P>,
    ) -> Self {
        self.data_dir = data_dir.map(|p| p.as_ref().to_path_buf());
        self
    }

    /// Sets the downloader builder.
    pub fn with_downloader(
        mut self,
        downloader: Option<fn() -> Downloader>,
    ) -> Self {
        self.downloader = downloader;
        self
    }
}

/// Disk cache for downloaded files.
///
/// Leverages [`Downloader`] for downloading files,
/// and [`PathResolver`](`super::PathResolver`) for resolving cache and data
/// paths appropriate for a user/system combo, and any environment overrides.
pub struct BunsenDiskCache {
    /// Cache directory.
    cache_dir: PathBuf,

    /// Data directory.
    data_dir: PathBuf,

    /// Connection pool for downloading files.
    downloader: Downloader,
}

impl Default for BunsenDiskCache {
    fn default() -> Self {
        Self::new(BunsenDiskCacheOptions::default()).unwrap()
    }
}

impl BunsenDiskCache {
    /// Constructs a new [`BunsenDiskCache`].
    pub fn new(options: BunsenDiskCacheOptions) -> BunsenResult<Self> {
        let cache_dir = BUNSEN_CACHE_CONFIG
            .resolve_cache_dir(options.cache_dir)
            .ok_or(BunsenError::ResourceNotFound(
                "failed to resolve cache directory".to_string(),
            ))?;

        let data_dir = BUNSEN_CACHE_CONFIG
            .resolve_data_dir(options.data_dir)
            .ok_or(BunsenError::ResourceNotFound(
                "failed to resolve data directory".to_string(),
            ))?;

        let downloader = match options.downloader {
            Some(builder) => builder(),
            None => Downloader::builder()
                .build()
                .map_err(BunsenError::external)?,
        };

        Ok(Self {
            cache_dir,
            data_dir,
            downloader,
        })
    }

    /// Returns the cache directory.
    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    /// Returns the data directory.
    pub fn data_dir(&self) -> &Path {
        &self.data_dir
    }

    /// Returns the downloader.
    pub fn downloader(&self) -> &Downloader {
        &self.downloader
    }

    /// Loads a file from a specified path or downloads it if it does not exist.
    ///
    /// # Arguments
    /// * `context`: A slice of `C` containing path-related context used in
    ///   determining the cache location. These paths are combined to build the
    ///   cached file's location.
    /// * `urls`: A slice of string references specifying the URLs to download
    ///   the file from if it is not already cached.
    /// * `download`: A boolean flag indicating whether to attempt downloading
    ///   the file from the provided URLs if it does not already exist in the
    ///   cache.
    ///
    /// # Returns
    /// * Returns a [`PathBuf`] pointing to the cached file if it exists or is
    ///   successfully downloaded.
    /// * Returns an error if the file is not found in the cache and downloading
    ///   is not allowed or fails.
    ///
    /// # Errors
    /// * Returns an error if the cached file does not exist and `download` is
    ///   `false`.
    /// * Returns an error if the downloading process fails.
    fn _load_resource<P, C, S>(
        &mut self,
        root: &P,
        context: &[C],
        urls: &[S],
        download: bool,
        // TODO: hash: Option<&str>,
    ) -> BunsenResult<PathBuf>
    where
        P: AsRef<Path>,
        C: AsRef<Path>,
        S: AsRef<str>,
    {
        let urls: Vec<_> = urls.iter().map(|s| s.as_ref()).collect();
        let mut dl = Download::new_mirrored(&urls);
        let file_name = dl.file_name.clone();
        let path = path_utils::extend_path(root, context, &file_name);
        dl.file_name = path.clone();

        if path.exists() {
            return Ok(path);
        }

        if !download {
            return Err(BunsenError::ResourceNotFound(format!(
                "cached file not found: {}",
                path.display()
            )));
        }

        fs::create_dir_all(path.parent().unwrap()).map_err(BunsenError::external)?;

        self.downloader
            .download(&[dl])
            .map_err(BunsenError::external)?;

        Ok(path)
    }

    /// Returns the cache path for the given key.
    ///
    /// * Does not check that the path exists.
    /// * Does not initialize the containing directories.
    ///
    /// # Arguments
    /// * `context` - prefix dirs, inserted between `self.cache_dir` and `file`.
    /// * `file` - the final file name.
    pub fn cache_path<C, F>(
        &self,
        context: &[C],
        file: F,
    ) -> PathBuf
    where
        C: AsRef<Path>,
        F: AsRef<Path>,
    {
        path_utils::extend_path(&self.cache_dir, context, file)
    }

    /// Returns the data path for the given key.
    ///
    /// * Does not check that the path exists.
    /// * Does not initialize the containing directories.
    ///
    /// # Arguments
    /// * `context` - prefix dirs, inserted between `self.cache_dir` and `file`.
    /// * `file` - the final file name.
    pub fn data_path<C, F>(
        &self,
        context: &[C],
        file: F,
    ) -> PathBuf
    where
        C: AsRef<Path>,
        F: AsRef<Path>,
    {
        path_utils::extend_path(&self.data_dir, context, file)
    }

    /// Loads a cached file from a specified path or downloads it if it does not
    /// exist.
    ///
    /// # Arguments
    /// * `context`: A slice of `C` containing path-related context used in
    ///   determining the cache location. These paths are combined to build the
    ///   cached file's location.
    /// * `urls`: A slice of string references specifying the URLs to download
    ///   the file from if it is not already cached.
    /// * `download`: A boolean flag indicating whether to attempt downloading
    ///   the file from the provided URLs if it does not already exist in the
    ///   cache.
    ///
    /// # Returns
    /// * Returns a [`PathBuf`] pointing to the cached file if it exists or is
    ///   successfully downloaded.
    /// * Returns an error if the file is not found in the cache and downloading
    ///   is not allowed or fails.
    ///
    /// # Errors
    /// * Returns an error if the cached file does not exist and `download` is
    ///   `false`.
    /// * Returns an error if the downloading process fails.
    pub fn load_cached_path<C, S>(
        &mut self,
        context: &[C],
        urls: &[S],
        download: bool,
        // TODO: hash: Option<&str>,
    ) -> BunsenResult<PathBuf>
    where
        C: AsRef<Path>,
        S: AsRef<str>,
    {
        let root = self.cache_dir.clone();
        self._load_resource(&root, context, urls, download)
    }

    /// Loads a data file from a specified path or downloads it if it does not
    /// exist.
    ///
    /// # Arguments
    /// * `context`: A slice of `C` containing path-related context used in
    ///   determining the cache location. These paths are combined to build the
    ///   data file's location.
    /// * `urls`: A slice of string references specifying the URLs to download
    ///   the file from if it is not already data.
    /// * `download`: A boolean flag indicating whether to attempt downloading
    ///   the file from the provided URLs if it does not already exist in the
    ///   cache.
    ///
    /// # Returns
    /// * Returns a [`PathBuf`] pointing to the data file if it exists or is
    ///   successfully downloaded.
    /// * Returns an error if the file is not found in the cache and downloading
    ///   is not allowed or fails.
    ///
    /// # Errors
    /// * Returns an error if the data file does not exist and `download` is
    ///   `false`.
    /// * Returns an error if the downloading process fails.
    pub fn load_data_path<C, S>(
        &mut self,
        context: &[C],
        urls: &[S],
        download: bool,
        // TODO: hash: Option<&str>,
    ) -> BunsenResult<PathBuf>
    where
        C: AsRef<Path>,
        S: AsRef<str>,
    {
        let root = self.cache_dir.clone();
        self._load_resource(&root, context, urls, download)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        env,
        path::PathBuf,
    };

    use serial_test::serial;

    use crate::data::cache::{
        BUNSEN_CACHE_CONFIG,
        BUNSEN_CACHE_DIR,
        BUNSEN_DATA_DIR,
        BunsenDiskCache,
        BunsenDiskCacheOptions,
    };

    #[test]
    #[serial]
    fn test_resolve_dirs() {
        let orig_cache_dir = env::var(BUNSEN_CACHE_DIR);
        let orig_data_dir = env::var(BUNSEN_CACHE_DIR);

        let pds = BUNSEN_CACHE_CONFIG
            .project_dirs()
            .expect("failed to get project dirs");

        let user_cache_dir = PathBuf::from("/tmp/bunsen/cache");
        let user_data_dir = PathBuf::from("/tmp/bunsen/data");

        let env_cache_dir = PathBuf::from("/tmp/bunsen/env_cache");
        let env_data_dir = PathBuf::from("/tmp/bunsen/env_data");

        // No env vars
        unsafe {
            env::remove_var(BUNSEN_CACHE_DIR);
            env::remove_var(BUNSEN_DATA_DIR);
        }

        let cache = BunsenDiskCache::new(
            BunsenDiskCacheOptions::default()
                .with_cache_dir(Some(user_cache_dir.clone()))
                .with_data_dir(Some(user_data_dir.clone())),
        )
        .unwrap();
        assert_eq!(&cache.cache_dir(), &user_cache_dir);
        assert_eq!(&cache.data_dir(), &user_data_dir);

        let cache = BunsenDiskCache::new(BunsenDiskCacheOptions::default()).unwrap();
        assert_eq!(&cache.cache_dir(), &pds.cache_dir().to_path_buf());
        assert_eq!(&cache.data_dir(), &pds.data_dir().to_path_buf());

        // With env var.
        unsafe {
            env::set_var(BUNSEN_CACHE_DIR, env_cache_dir.to_str().unwrap());
            env::set_var(BUNSEN_DATA_DIR, env_data_dir.to_str().unwrap());
        }

        let cache = BunsenDiskCache::new(
            BunsenDiskCacheOptions::default()
                .with_cache_dir(Some(user_cache_dir.clone()))
                .with_data_dir(Some(user_data_dir.clone())),
        )
        .unwrap();
        assert_eq!(&cache.cache_dir(), &user_cache_dir);
        assert_eq!(&cache.data_dir(), &user_data_dir);

        let cache = BunsenDiskCache::new(BunsenDiskCacheOptions::default()).unwrap();
        assert_eq!(&cache.cache_dir(), &env_cache_dir);
        assert_eq!(&cache.data_dir(), &env_data_dir);

        // restore original env var.
        match orig_cache_dir {
            Ok(original) => unsafe { env::set_var(BUNSEN_CACHE_DIR, original) },
            Err(_) => unsafe { env::remove_var(BUNSEN_CACHE_DIR) },
        }
        match orig_data_dir {
            Ok(original) => unsafe { env::set_var(BUNSEN_DATA_DIR, original) },
            Err(_) => unsafe { env::remove_var(BUNSEN_DATA_DIR) },
        }
    }

    #[test]
    fn test_data_path() {
        let cache = BunsenDiskCache::new(BunsenDiskCacheOptions::default()).unwrap();
        let path = cache.data_path(&["prefix"], "file.txt");
        assert_eq!(path, cache.data_dir.join("prefix").join("file.txt"));
    }

    #[test]
    fn test_cache_path() {
        let cache = BunsenDiskCache::new(BunsenDiskCacheOptions::default()).unwrap();
        let path = cache.cache_path(&["prefix"], "file.txt");
        assert_eq!(path, cache.cache_dir.join("prefix").join("file.txt"));
    }
}