bunsen 0.42.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
//! What a resource cache holds, and removing it.
use alloc::fmt;
use core::str::FromStr;
use std::{
    fs,
    path::{
        Path,
        PathBuf,
    },
    time::SystemTime,
};

use crate::{
    data::resources::{
        RESOURCES_DIR,
        ResourceCache,
        cache::FETCHING_DIR,
    },
    errors::{
        BunsenError,
        BunsenResult,
        sys_at,
    },
};

/// A file in a [`ResourceCache`]:
/// `<cache>/resources/<name>/<pin>/<file>`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CachedFile {
    /// The name it is cached under: a catalog resource's full name
    /// (`openai/whisper/base/checkpoint`), an `hf:` repo's
    /// (`hf/openai/whisper-tiny/checkpoint`), or `given` for a path's.
    pub name: String,

    /// The directory pinning it: its SHA-256, or `.fetching` for an
    /// unpinned download not yet hashed.
    pub pin: String,

    /// Its path under the pin, without the `.partial` of an unfinished
    /// download: a file name, or a relative path (`encoder/config.json`).
    pub file: String,

    /// Where it is.
    pub path: PathBuf,

    /// Its size.
    pub bytes: u64,

    /// An unfinished download (`<file>.partial`), which a fetch resumes.
    pub partial: bool,

    /// When it came into the cache (its creation time), where the file
    /// system records it.
    pub created: Option<SystemTime>,

    /// When it was last loaded (its modification time): a load that finds
    /// it in the cache sets it ([`ResourceCache`]'s "Use"), and a download
    /// is its first use.
    pub last_used: Option<SystemTime>,
}

/// Which of a [`ResourceCache`]'s files: every one, or those whose name is
/// under a name.
///
/// Parsed from `""` (every file) or a `/`-separated name: `qwen` selects
/// every Qwen resource, `openai/whisper/base` one build's, `hf` every file
/// fetched from the Hub off the catalog.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CacheSelector {
    /// The name the files' names are under, or every file.
    pub prefix: Option<String>,
}

impl CacheSelector {
    /// Whether a file cached under `name` is selected: the name is the
    /// prefix, or under it.
    pub fn matches(
        &self,
        name: &str,
    ) -> bool {
        self.prefix.as_deref().is_none_or(|p| {
            name == p
                || name
                    .strip_prefix(p)
                    .is_some_and(|rest| rest.starts_with('/'))
        })
    }
}

impl FromStr for CacheSelector {
    type Err = BunsenError;

    /// # Errors
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal) for an empty
    /// segment.
    fn from_str(s: &str) -> BunsenResult<Self> {
        if s.is_empty() {
            return Ok(Self::default());
        }
        if s.split('/').any(str::is_empty) {
            return Err(BunsenError::illegal(format!(
                "cache selector {s:?}: expected a `/`-separated name, with no empty segment"
            )));
        }
        Ok(Self {
            prefix: Some(s.to_string()),
        })
    }
}

impl fmt::Display for CacheSelector {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        match &self.prefix {
            None => write!(f, "every resource"),
            Some(prefix) => write!(f, "{prefix}"),
        }
    }
}

/// Whether `segment` is a SHA-256 pin: 64 lowercase hex digits.
pub(super) fn is_sha256(segment: &str) -> bool {
    segment.len() == 64
        && segment
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// The files under `dir`, at any depth, in path order; none when `dir` does
/// not exist.
pub(super) fn files_under(dir: &Path) -> BunsenResult<Vec<(PathBuf, fs::Metadata)>> {
    let mut out = Vec::new();
    if !dir.is_dir() {
        return Ok(out);
    }
    let mut stack = vec![dir.to_path_buf()];
    while let Some(at) = stack.pop() {
        for entry in fs::read_dir(&at).map_err(sys_at("read the directory", &at))? {
            let entry = entry.map_err(sys_at("read the directory", &at))?;
            let path = entry.path();
            let meta = entry
                .metadata()
                .map_err(sys_at("read the metadata of", &path))?;
            if meta.is_dir() {
                stack.push(path);
            } else if meta.is_file() {
                out.push((path, meta));
            }
        }
    }
    out.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(out)
}

impl ResourceCache {
    /// The directory holding every cached file: `<cache>/resources`.
    pub fn resources_dir(&self) -> PathBuf {
        self.cache_dir().join(RESOURCES_DIR)
    }

    /// The files the cache holds under `selector`, in path order.
    ///
    /// A file's pin is the first segment of its path that is a SHA-256, or
    /// `.fetching` for an unpinned download not yet filed under its digest;
    /// the name is what precedes it, and the file what follows. Anything
    /// else under the resources directory is not the cache's, and is not
    /// listed.
    ///
    /// # Errors
    /// A [`Sys`](crate::errors::BunsenErrorKind::Sys) error if a directory or
    /// a file's metadata cannot be read.
    pub fn cached_files(
        &self,
        selector: &CacheSelector,
    ) -> BunsenResult<Vec<CachedFile>> {
        let root = self.resources_dir();
        let mut out = Vec::new();
        for (path, meta) in files_under(&root)? {
            let Ok(relative) = path.strip_prefix(&root) else {
                continue;
            };
            let Some(segments) = relative
                .components()
                .map(|c| c.as_os_str().to_str().map(str::to_string))
                .collect::<Option<Vec<String>>>()
            else {
                continue;
            };
            let at = match segments
                .iter()
                .position(|s| is_sha256(s) || s == FETCHING_DIR)
            {
                Some(at) if at > 0 => at,
                _ => continue,
            };
            if at + 1 >= segments.len() {
                continue;
            }
            let entry = segments[..at].join("/");
            if !selector.matches(&entry) {
                continue;
            }
            let name = segments[at + 1..].join("/");
            let (file, partial) = match name.strip_suffix(".partial") {
                Some(file) => (file.to_string(), true),
                None => (name, false),
            };
            out.push(CachedFile {
                name: entry,
                pin: segments[at].clone(),
                file,
                path,
                bytes: meta.len(),
                partial,
                created: meta.created().ok(),
                last_used: meta.modified().ok(),
            });
        }
        Ok(out)
    }

    /// Removes `files` from the cache, and the directories they leave empty
    /// under its resources directory.
    ///
    /// # Returns
    /// The bytes freed.
    ///
    /// # Errors
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal), removing
    /// nothing, if a file is not under the cache's resources directory; a
    /// [`Sys`](crate::errors::BunsenErrorKind::Sys) error if one cannot be
    /// removed, after those before it were.
    pub fn remove_cached(
        &self,
        files: &[CachedFile],
    ) -> BunsenResult<u64> {
        let root = self.resources_dir();
        if let Some(stray) = files.iter().find(|f| !f.path.starts_with(&root)) {
            return Err(BunsenError::illegal(format!(
                "{} is not in the resource cache at {}",
                stray.path.display(),
                root.display()
            )));
        }
        let mut freed = 0;
        for file in files {
            fs::remove_file(&file.path).map_err(sys_at("remove", &file.path))?;
            freed += file.bytes;
            // The directories above it, up to the resources directory, while
            // each is empty.
            let mut dir = file.path.parent();
            while let Some(d) = dir.filter(|d| *d != root && d.starts_with(&root)) {
                if fs::remove_dir(d).is_err() {
                    break;
                }
                dir = d.parent();
            }
        }
        Ok(freed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::{
        cache::BunsenDiskCacheOptions,
        resources::ResourceCacheOptions,
    };

    fn cache_in(dir: &Path) -> ResourceCache {
        ResourceCache::new(
            ResourceCacheOptions::default()
                .with_disk(
                    BunsenDiskCacheOptions::default()
                        .with_cache_dir(Some(dir.join("cache")))
                        .without_transfer_observers(),
                )
                .with_offline(true),
        )
        .unwrap()
    }

    fn put(
        cache: &ResourceCache,
        rel: &str,
        bytes: usize,
    ) {
        let path = cache.resources_dir().join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, vec![0u8; bytes]).unwrap();
    }

    #[test]
    fn test_selector() {
        assert_eq!(
            "".parse::<CacheSelector>().unwrap(),
            CacheSelector::default()
        );
        let qwen: CacheSelector = "qwen".parse().unwrap();
        assert_eq!(qwen.prefix.as_deref(), Some("qwen"));
        assert!(qwen.matches("qwen") && qwen.matches("qwen/qwen3/qwen3-0.6b/checkpoint"));
        assert!(!qwen.matches("qwen3") && !qwen.matches("openai/whisper/base/checkpoint"));
        let build: CacheSelector = "openai/whisper/base".parse().unwrap();
        assert!(build.matches("openai/whisper/base/checkpoint"));
        assert!(!build.matches("openai/whisper/base.en/checkpoint"));
        assert_eq!(build.to_string(), "openai/whisper/base");
        for bad in ["/b", "a/", "a//b"] {
            assert!(bad.parse::<CacheSelector>().is_err(), "{bad}");
        }
    }

    /// Files are listed in path order, each by its name and pin (a SHA-256,
    /// or `.fetching` for an unpinned download not yet filed), selected by a
    /// name prefix, with an unfinished download marked and a relative path kept
    /// whole; removing them frees their bytes and the directories they
    /// leave empty.
    #[test]
    fn test_list_and_remove() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path());
        assert!(
            cache
                .cached_files(&CacheSelector::default())
                .unwrap()
                .is_empty()
        );

        let a = "a".repeat(64);
        let b = "b".repeat(64);
        let c = "c".repeat(64);
        let d = "d".repeat(64);
        put(
            &cache,
            &format!("openai/whisper/tiny/checkpoint/{a}/tiny.pt"),
            3,
        );
        put(
            &cache,
            &format!("openai/whisper/base/checkpoint/{b}/base.pt.partial"),
            5,
        );
        put(&cache, &format!("hf/o/r/config/{c}/config.json"), 7);
        put(
            &cache,
            &format!("laya/laya/laya/encoder_config/{d}/encoder/config.json"),
            11,
        );
        // No pin in its path: not the cache's.
        put(&cache, "openai/stray.txt", 1);
        // An unpinned download, not yet hashed.
        put(
            &cache,
            "hf/01-ai/yi/listing/.fetching/01-ai--yi--main.json.partial",
            13,
        );

        let all = cache.cached_files(&CacheSelector::default()).unwrap();
        let names: Vec<(&str, &str, bool)> = all
            .iter()
            .map(|f| (f.name.as_str(), f.file.as_str(), f.partial))
            .collect();
        assert_eq!(
            names,
            [
                ("hf/01-ai/yi/listing", "01-ai--yi--main.json", true),
                ("hf/o/r/config", "config.json", false),
                (
                    "laya/laya/laya/encoder_config",
                    "encoder/config.json",
                    false
                ),
                ("openai/whisper/base/checkpoint", "base.pt", true),
                ("openai/whisper/tiny/checkpoint", "tiny.pt", false),
            ]
        );
        assert_eq!(all[0].pin, FETCHING_DIR);
        assert_eq!(all[1].pin, c);
        assert_eq!(all[3].bytes, 5);
        assert_eq!(all[4].pin, a);

        let whisper = cache
            .cached_files(&"openai/whisper".parse().unwrap())
            .unwrap();
        assert_eq!(whisper.len(), 2);
        assert_eq!(cache.remove_cached(&whisper).unwrap(), 8);
        assert!(!cache.resources_dir().join("openai/whisper").exists());
        // The stray file keeps `openai` itself.
        assert!(cache.resources_dir().join("openai/stray.txt").exists());
        assert!(cache.resources_dir().join("hf/o/r/config").exists());

        let hf = cache.cached_files(&"hf".parse().unwrap()).unwrap();
        assert_eq!(cache.remove_cached(&hf).unwrap(), 20);
        assert!(!cache.resources_dir().join("hf").exists());
        assert_eq!(
            cache.cached_files(&CacheSelector::default()).unwrap().len(),
            1
        );

        let mut outside = all[1].clone();
        outside.path = dir.path().join("elsewhere");
        assert!(cache.remove_cached(&[outside]).is_err());
    }
}