aboutsummaryrefslogtreecommitdiff
path: root/base/src/lib.rs
blob: b97f9242436abc4dff1761f5f6190d4f93175b53 (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
#![feature(lazy_cell)]
use base64::Engine;
use jellycommon::{config::GlobalConfig, AssetLocation};
use std::{fs::File, future::Future, path::PathBuf, sync::LazyLock};
use tokio::sync::Mutex;

pub static CONF: LazyLock<GlobalConfig> = LazyLock::new(|| {
    serde_json::from_reader(
        File::open(
            std::env::args()
                .nth(1)
                .expect("First argument must specify the config.json to use."),
        )
        .unwrap(),
    )
    .unwrap()
});

pub fn cache_location(seed: &[&str]) -> (usize, AssetLocation) {
    use sha2::Digest;
    let mut d = sha2::Sha512::new();
    for s in seed {
        d.update(s.as_bytes());
        d.update(b"\0");
    }
    let d = d.finalize();
    let n = d[0] as usize | (d[1] as usize) << 8 | (d[2] as usize) << 16 | (d[3] as usize) << 24;
    let fname = base64::engine::general_purpose::URL_SAFE.encode(d);
    let fname = &fname[..22]; // about 128 bits
    (n, AssetLocation::Cache(fname.into()))
}

const CACHE_GENERATION_BUCKET_COUNT: usize = 1024;
pub static CACHE_GENERATION_LOCKS: LazyLock<[Mutex<()>; CACHE_GENERATION_BUCKET_COUNT]> =
    LazyLock::new(|| [(); CACHE_GENERATION_BUCKET_COUNT].map(|_| Mutex::new(())));

pub async fn async_cache_file<Fun, Fut>(
    seed: &[&str],
    generate: Fun,
) -> Result<AssetLocation, anyhow::Error>
where
    Fun: FnOnce(tokio::fs::File) -> Fut,
    Fut: Future<Output = Result<(), anyhow::Error>>,
{
    let (bucket, location) = cache_location(seed);
    // we need a lock even if it exists since somebody might be still in the process of writing.
    let _guard = CACHE_GENERATION_LOCKS[bucket % CACHE_GENERATION_BUCKET_COUNT].lock();
    let exists = tokio::fs::try_exists(location.path()).await?;
    if !exists {
        let f = tokio::fs::File::create(location.path()).await?;
        generate(f).await?;
    }
    drop(_guard);
    Ok(location)
}

pub fn cache_file<Fun>(seed: &[&str], mut generate: Fun) -> Result<AssetLocation, anyhow::Error>
where
    Fun: FnMut(std::fs::File) -> Result<(), anyhow::Error>,
{
    let (bucket, location) = cache_location(seed);
    // we need a lock even if it exists since somebody might be still in the process of writing.
    let _guard = CACHE_GENERATION_LOCKS[bucket % CACHE_GENERATION_BUCKET_COUNT].lock();
    let exists = location.path().exists();
    if !exists {
        let f = std::fs::File::create(location.path())?;
        generate(f)?;
    }
    drop(_guard);
    Ok(location)
}

pub trait AssetLocationExt {
    fn path(&self) -> PathBuf;
}
impl AssetLocationExt for AssetLocation {
    fn path(&self) -> PathBuf {
        match self {
            AssetLocation::Assets(p) => CONF.asset_path.join(p),
            AssetLocation::Cache(p) => CONF.cache_path.join(p),
            AssetLocation::Library(p) => CONF.library_path.join(p),
        }
    }
}