use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
sync::{Mutex, MutexGuard, OnceLock},
};
pub fn test_model_path(model_id: &str) -> PathBuf {
static RESOLVED: OnceLock<Mutex<HashMap<String, PathBuf>>> = OnceLock::new();
let mut resolved = lock(RESOLVED.get_or_init(Mutex::default));
if let Some(path) = resolved.get(model_id) {
return path.clone();
}
let target_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target");
let path = find_existing_model(&target_dir, model_id)
.unwrap_or_else(|| download_model(model_id, &target_dir));
resolved.insert(model_id.to_owned(), path.clone());
path
}
pub fn license_key() -> String {
std::env::var("AIC_SDK_LICENSE")
.expect("AIC_SDK_LICENSE environment variable must be set for tests")
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|err| err.into_inner())
}
fn find_existing_model(target_dir: &Path, model_id: &str) -> Option<PathBuf> {
let prefix = model_id.replace(['-', '.'], "_");
fs::read_dir(target_dir).ok()?.flatten().find_map(|entry| {
let path = entry.path();
let matches = path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with(&prefix))
&& path.extension().is_some_and(|ext| ext == "aicmodel")
&& path.is_file();
matches.then_some(path)
})
}
#[cfg(feature = "download-model")]
fn download_model(model_id: &str, target_dir: &Path) -> PathBuf {
aic_sdk::Model::download(model_id, target_dir)
.unwrap_or_else(|err| panic!("failed to download model `{model_id}`: {err}"))
}
#[cfg(not(feature = "download-model"))]
fn download_model(model_id: &str, target_dir: &Path) -> PathBuf {
panic!(
"model `{model_id}` not found in {} and the `download-model` feature is disabled",
target_dir.display()
)
}