use super::album_generator::AlbumGenerator;
use crate::testing_prelude::*;
use std::sync::Mutex;
#[expect(
clippy::type_complexity,
reason = "type alias would obscure cache structure"
)]
static ALBUM_CACHE: LazyLock<Mutex<HashMap<String, Arc<OnceCell<Result<AlbumConfig, String>>>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
pub struct AlbumProvider;
impl AlbumProvider {
pub async fn get(format: SampleFormat) -> AlbumConfig {
Self::get_advanced(AlbumConfig::with_format(format)).await
}
#[expect(
clippy::panic,
reason = "sample generation is unrecoverable. clear message is rendered"
)]
pub async fn get_advanced(config: AlbumConfig) -> AlbumConfig {
let key = config.dir_name();
let cell = {
let mut map = ALBUM_CACHE
.lock()
.expect("album cache mutex should not be poisoned");
Arc::clone(map.entry(key).or_insert_with(|| Arc::new(OnceCell::new())))
};
cell.get_or_init(|| async {
let source_dir = SAMPLE_SOURCES_DIR.join(config.dir_name());
if !is_generated(&source_dir) {
AlbumGenerator::generate_files(&config, &source_dir)
.await
.map_err(|e| e.render())?;
mark_generated(&source_dir)?;
}
Ok(config)
})
.await
.clone()
.unwrap_or_else(|e| panic!("Sample generation failed\n{e}"))
}
}
fn is_generated(dir: &Path) -> bool {
dir.join(".generated").exists()
}
fn mark_generated(dir: &Path) -> Result<(), String> {
let path = dir.join(".generated");
File::create(&path).map_err(|e| format!("failed to create {}: {e}", path.display()))?;
Ok(())
}