fetch-source 0.1.2

Declare and fetch external sources programmatically
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
// A BTree maintains key order
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use derive_more::Deref;

use crate::{Artefact, Digest, Source};

const CACHE_FILE_NAME: &str = "fetch-source-cache.json";

/***
NOTE: For the special path newtypes below, we derive `Deref` as this models these types as "subtypes" of
`PathBuf` i.e. they should be able to do everything a `PathBuf` can do, and have additional semantics
at certain places in the code. They model paths that are special to the `Cache` so are only
constructed in specific places, and requiring them as arguments rather than any `PathBuf` indicates
where their special meaning to the cache matters.
***/

/// The root directory of a cache
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deref)]
pub struct CacheRoot(PathBuf);

/// The path of a cached artefact relative to the cache root
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deref)]
pub struct RelCacheDir(PathBuf);

/// The absolute path to a cached artefact
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deref)]
pub struct CacheDir(PathBuf);

impl CacheRoot {
    /// Get the absolute path to an artefact
    pub fn append(&self, relative: RelCacheDir) -> CacheDir {
        CacheDir(self.0.join(relative.0))
    }
}

/// Records data about the cached sources and where their artefacts are within a [`Cache`](Cache).
///
/// When a [`Source`] is fetched, insert its [`Artefact`] into a cache to avoid repeatedly fetching
/// the same source definition.
///
/// When fetching a source, check the cache subdirectory to use with [`CacheItems::relative_path`].
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
pub struct CacheItems {
    #[serde(flatten)]
    map: BTreeMap<Digest, Artefact>,
}

impl CacheItems {
    /// Create an empty collection.
    pub fn new() -> Self {
        Self {
            map: BTreeMap::new(),
        }
    }

    /// Retrieves a cached artefact for the given source, if it exists.
    pub fn get(&self, source: &Source) -> Option<&Artefact> {
        self.map.get(&Source::digest(source))
    }

    /// Check whether the cache contains the given source.
    pub fn contains(&self, source: &Source) -> bool {
        self.map.contains_key(&Source::digest(source))
    }

    /// Cache an artefact and return the digest of the [`Source`] which created it. Replaces any
    /// previous value for this source.
    pub fn insert(&mut self, artefact: Artefact) {
        self.map.insert(Source::digest(&artefact), artefact);
    }

    /// Removes a cached value for the given source, returning it if it existed.
    pub fn remove(&mut self, source: &Source) -> Option<Artefact> {
        self.map.remove(&Source::digest(source))
    }

    /// Returns an iterator over the cached values.
    pub fn values(&self) -> impl Iterator<Item = &Artefact> {
        self.map.values()
    }

    /// Checks if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Returns the number of cached values.
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Get the relative path for a source within a cache directory
    pub fn relative_path<S: AsRef<Source>>(&self, source: S) -> RelCacheDir {
        RelCacheDir(PathBuf::from(Source::digest(source).as_ref()))
    }
}

/// Owns [`data`](CacheItems) about cached sources and is responsible for its persistence.
#[derive(Debug)]
pub struct Cache {
    items: CacheItems,
    cache_file: PathBuf,
}

impl Cache {
    /// Normalise to the path of a cache file. The cache dir is required to be the absolute path to
    /// the cache directory. We rely on `canonicalize` to error when the path doesn't exist.
    ///
    /// Returns an IO error if the directory doesn't exist
    #[inline]
    fn normalise_cache_file<P>(cache_dir: P) -> std::io::Result<std::path::PathBuf>
    where
        P: AsRef<Path>,
    {
        Ok(cache_dir
            .as_ref()
            .to_path_buf()
            .canonicalize()?
            .join(CACHE_FILE_NAME))
    }

    /// Create a new cache at the specified file path.
    fn create_at(cache_file: PathBuf) -> Self {
        Self {
            items: CacheItems::new(),
            cache_file,
        }
    }

    /// Read the cache in the given directory.
    ///
    /// Error if the directory or cache file do not exist, of if a deserialisation error occurs
    /// when reading the cache file
    pub fn read<P>(cache_dir: P) -> Result<Self, crate::Error>
    where
        P: AsRef<Path>,
    {
        let cache_file = Self::normalise_cache_file(cache_dir)?;
        let contents = std::fs::read_to_string(&cache_file)?;
        let items: CacheItems = serde_json::from_str(&contents)?;
        Ok(Self { items, cache_file })
    }

    /// Create a new cache in the given directory.
    ///
    /// Error if the directory doesn't exist, or if there is already a cache file in this directory.
    pub fn new<P>(cache_dir: P) -> Result<Self, crate::Error>
    where
        P: AsRef<Path>,
    {
        let cache_file = Self::normalise_cache_file(&cache_dir)?;
        if cache_file.is_file() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                "Cache file already exists",
            )
            .into());
        }
        Ok(Self::create_at(cache_file))
    }

    /// Loads the cache from a JSON file in the given directory, creating a new cache if the file
    /// does not exist. Requires that `cache_dir` exists. Note that this function doesn't
    /// actually create the cache file - this happens when the cache is saved.
    ///
    /// Returns an error if `cache_dir` doesn't exist, or if a deserialisation error occurs when
    /// reading the cache file.
    pub fn load_or_create<P>(cache_dir: P) -> Result<Self, crate::Error>
    where
        P: AsRef<Path>,
    {
        let cache_file = Self::normalise_cache_file(&cache_dir)?;
        if cache_file.is_file() {
            Self::read(cache_dir)
        } else {
            Ok(Self::create_at(cache_file))
        }
    }

    /// Saves the cache in the directory where it was created.
    ///
    /// Returns an error if a serialisation or I/O error occurs.
    pub fn save(&self) -> Result<(), crate::Error> {
        let json = serde_json::to_string_pretty(&self.items)?;
        Ok(std::fs::write(&self.cache_file, json)?)
    }

    /// Get the cache file path.
    pub fn cache_file(&self) -> &Path {
        &self.cache_file
    }

    /// Get the directory of the cache file
    pub fn cache_dir(&self) -> CacheRoot {
        CacheRoot(self.cache_file.parent().unwrap().to_path_buf())
    }

    /// Calculate the absolute path where a fetched source would be stored within the cache
    pub fn cached_path(&self, source: &Source) -> CacheDir {
        self.cache_dir().append(self.items.relative_path(source))
    }

    /// Get a reference to the cache items.
    pub fn items(&self) -> &CacheItems {
        &self.items
    }

    /// Get a mutable reference to the cache items.
    pub fn items_mut(&mut self) -> &mut CacheItems {
        &mut self.items
    }

    /// Check whether the cache file exists in the given directory.
    pub fn cache_file_exists<P>(cache_dir: P) -> bool
    where
        P: AsRef<Path>,
    {
        cache_dir.as_ref().join(CACHE_FILE_NAME).is_file()
    }
}

impl IntoIterator for CacheItems {
    type Item = (Digest, Artefact);
    type IntoIter = std::collections::btree_map::IntoIter<Digest, Artefact>;

    fn into_iter(self) -> Self::IntoIter {
        self.map.into_iter()
    }
}

impl<'a> IntoIterator for &'a CacheItems {
    type Item = (&'a Digest, &'a Artefact);
    type IntoIter = std::collections::btree_map::Iter<'a, Digest, Artefact>;

    fn into_iter(self) -> Self::IntoIter {
        self.map.iter()
    }
}

impl IntoIterator for Cache {
    type Item = (Digest, Artefact);
    type IntoIter = std::collections::btree_map::IntoIter<Digest, Artefact>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

impl<'a> IntoIterator for &'a Cache {
    type Item = (&'a Digest, &'a Artefact);
    type IntoIter = std::collections::btree_map::Iter<'a, Digest, Artefact>;

    fn into_iter(self) -> Self::IntoIter {
        (&self.items).into_iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    // Helper macro for creating test caches
    macro_rules! mock_cache_at {
        ($cache_file:expr) => {{ Cache::create_at(PathBuf::from($cache_file).join(CACHE_FILE_NAME)) }};
    }

    #[test]
    fn artefact_path_is_digest() {
        // The cache should determine the path to a cached artefact relative to the cache directory,
        // where the subdirectory is the digest of the source.
        let cache = mock_cache_at! {"/foo/bar"};
        let source: Source =
            crate::build_from_json! { "tar": "www.example.com/test.tar.gz" }.unwrap();
        assert_eq!(
            PathBuf::from("/foo/bar/").join(Source::digest(&source).as_ref()),
            *cache.cached_path(&source)
        );
    }

    #[test]
    fn same_artefact_with_multiple_names_exists_once() {
        let mut cache = mock_cache_at! {"/foo/bar"};
        let artefact_1: crate::Artefact = crate::build_from_json! {
            "source": { "tar": "www.example.com/test.tar.gz" },
            "path": "AAAAAAAA",
        }
        .unwrap();
        let artefact_2: crate::Artefact = crate::build_from_json! {
            "source": { "tar": "www.example.com/test.tar.gz" },
            "path": "BBBBBBBB",
        }
        .unwrap();
        cache.items_mut().insert(artefact_1);
        cache.items_mut().insert(artefact_2);
        assert_eq!(cache.items().len(), 1);
    }

    #[test]
    fn cache_items_insert_and_get() {
        let mut items = CacheItems::new();
        let artefact: crate::Artefact = crate::build_from_json! {
            "source": { "tar": "www.example.com/test.tar.gz" },
            "path": "/some/path",
        }
        .unwrap();

        let source: Source =
            crate::build_from_json! { "tar": "www.example.com/test.tar.gz" }.unwrap();
        assert!(!items.contains(&source));

        items.insert(artefact);
        assert!(items.contains(&source));
        assert_eq!(items.len(), 1);

        let retrieved = items.get(&source).unwrap();
        assert_eq!(
            <crate::Artefact as AsRef<Path>>::as_ref(retrieved),
            Path::new("/some/path")
        );
    }

    #[test]
    fn cache_read_on_existing_dir_missing_file_fails() {
        let temp_dir = tempdir().unwrap();
        let cache_file = Cache::normalise_cache_file(&temp_dir).unwrap();
        let result = Cache::read(&temp_dir);
        assert!(!cache_file.exists(), "File shouldn't exist before test");
        assert!(result.is_err(), "Read should fail when file doesn't exist");
        assert!(
            !cache_file.exists(),
            "File shouldn't be created by `read` operation"
        );
    }

    #[test]
    fn cache_load_on_existing_dir_missing_file_gives_empty_cache() {
        let temp_dir = tempdir().unwrap();
        let cache_file = Cache::normalise_cache_file(&temp_dir).unwrap();
        assert!(!cache_file.exists(), "File shouldn't exist before test");
        let result = Cache::load_or_create(&temp_dir);
        assert!(
            result.is_ok(),
            "load_or_create should succeed when file doesn't exist"
        );
        assert!(
            !cache_file.exists(),
            "File shouldn't exist after test - only created when saved"
        );
        assert!(result.unwrap().items().is_empty());
    }

    #[test]
    fn cache_load_on_missing_dir_fails() {
        let temp_dir = std::env::temp_dir().join("1729288131-doesnt-exist-6168255555");
        assert!(
            !temp_dir.exists(),
            "The temporary directory shouldn't exist before test"
        );
        let result = Cache::load_or_create(&temp_dir);
        assert!(
            !temp_dir.exists(),
            "The temporary directory shouldn't exist after test"
        );
        assert!(
            result.is_err(),
            "load_or_create should fail when directory doesn't exist"
        );
        assert_eq!(result.unwrap_err().kind(), &crate::ErrorKind::Io);
    }

    #[test]
    fn cache_load_save_roundtrip() {
        let temp_dir = std::env::temp_dir().join("cache_test_migration");
        std::fs::create_dir_all(&temp_dir).unwrap();

        // Create and populate cache
        let mut cache = Cache::create_at(temp_dir.join(CACHE_FILE_NAME));
        let artefact: crate::Artefact = crate::build_from_json! {
            "source": { "tar": "www.example.com/test.tar.gz" },
            "path": "/some/path",
        }
        .unwrap();
        cache.items_mut().insert(artefact);

        // Save
        cache.save().unwrap();

        // Load
        let loaded_cache = Cache::load_or_create(&temp_dir).unwrap();
        assert_eq!(loaded_cache.items().len(), 1);

        let source: Source =
            crate::build_from_json! { "tar": "www.example.com/test.tar.gz" }.unwrap();
        let loaded_artefact = loaded_cache.items().get(&source).unwrap();
        assert_eq!(
            <crate::Artefact as AsRef<Path>>::as_ref(loaded_artefact),
            Path::new("/some/path")
        );

        // Clean up
        std::fs::remove_dir_all(&temp_dir).ok();
    }
}