Skip to main content

smriti/
bootstrap.rs

1//! Runtime bootstrap checks and setup helpers.
2
3use std::io::Write;
4use std::path::{Path, PathBuf};
5
6use futures::StreamExt;
7use sha2::{Digest, Sha256};
8use zip::read::ZipArchive;
9
10const MAX_ASSET_PACK_FILES: usize = 1_000;
11const MAX_ASSET_PACK_DOWNLOAD_BYTES: u64 = 1024 * 1024 * 1024;
12const MAX_ASSET_PACK_EXPANDED_BYTES: u64 = 2 * 1024 * 1024 * 1024;
13
14#[cfg(target_os = "windows")]
15pub const SETUP_ASSETS_HINT: &str =
16    "powershell -ExecutionPolicy Bypass -File scripts\\setup_assets.ps1";
17
18#[cfg(not(target_os = "windows"))]
19pub const SETUP_ASSETS_HINT: &str = "./scripts/setup_assets.sh";
20
21pub const ASSET_PACK_URL_DEFAULT: &str = concat!(
22    "https://github.com/ChivukulaVirinchi/photovault/releases/download/v",
23    env!("CARGO_PKG_VERSION"),
24    "/Smriti-Assets.zip"
25);
26const ASSET_PACK_LATEST_URL: &str =
27    "https://github.com/ChivukulaVirinchi/photovault/releases/latest/download/Smriti-Assets.zip";
28
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum AssetFeature {
32    #[default]
33    All,
34    Faces,
35    Visual,
36    Places,
37}
38
39impl AssetFeature {
40    pub fn needs_pack(self, health: &AssetHealth) -> bool {
41        match self {
42            Self::All => health.missing_any(),
43            Self::Faces => health.missing_face_models || health.missing_onnx_runtime,
44            Self::Visual => health.missing_onnx_runtime,
45            Self::Places => health.missing_geonames_db,
46        }
47    }
48
49    fn archive_name(self) -> &'static str {
50        match self {
51            Self::All => "Smriti-Assets.zip",
52            Self::Faces => "Smriti-Faces.zip",
53            Self::Visual => "Smriti-Runtime.zip",
54            Self::Places => "Smriti-Places.zip",
55        }
56    }
57}
58
59/// Probe only on an explicit setup surface, never on the startup path.
60/// Older releases have only the combined archive; disclose its real size.
61pub async fn asset_download_source(feature: AssetFeature) -> Result<(String, u64), String> {
62    let client = reqwest::Client::builder()
63        .connect_timeout(std::time::Duration::from_secs(10))
64        .timeout(std::time::Duration::from_secs(20))
65        .build()
66        .map_err(|e| e.to_string())?;
67    let mut urls = Vec::new();
68    if feature != AssetFeature::All {
69        urls.push(ASSET_PACK_URL_DEFAULT.replace("Smriti-Assets.zip", feature.archive_name()));
70        urls.push(ASSET_PACK_LATEST_URL.replace("Smriti-Assets.zip", feature.archive_name()));
71    }
72    urls.push(asset_pack_url());
73    urls.push(ASSET_PACK_LATEST_URL.to_string());
74    for url in urls {
75        if let Ok(response) = client.head(&url).send().await {
76            if response.status().is_success() {
77                if let Some(size) = response
78                    .headers()
79                    .get(reqwest::header::CONTENT_LENGTH)
80                    .and_then(|value| value.to_str().ok())
81                    .and_then(|value| value.parse::<u64>().ok())
82                    .filter(|n| *n > 0 && *n <= MAX_ASSET_PACK_DOWNLOAD_BYTES)
83                {
84                    return Ok((url, size));
85                }
86            }
87        }
88    }
89    Err("Couldn't check the download size. Check your internet connection and retry.".into())
90}
91
92#[derive(Debug, Clone, Default)]
93pub struct AssetHealth {
94    pub missing_face_models: bool,
95    pub missing_onnx_runtime: bool,
96    pub missing_geonames_db: bool,
97}
98
99impl AssetHealth {
100    pub fn missing_any(&self) -> bool {
101        self.missing_face_models || self.missing_onnx_runtime || self.missing_geonames_db
102    }
103
104    pub fn summary(&self) -> String {
105        let mut missing = Vec::new();
106        if self.missing_face_models {
107            missing.push("face models");
108        }
109        if self.missing_onnx_runtime {
110            missing.push("ONNX runtime");
111        }
112        if self.missing_geonames_db {
113            missing.push("GeoNames database");
114        }
115        if missing.is_empty() {
116            "All optional assets are installed.".to_string()
117        } else {
118            format!("Missing: {}", missing.join(", "))
119        }
120    }
121}
122
123#[cfg(target_os = "windows")]
124const ORT_LIB_NAME: &str = "onnxruntime.dll";
125#[cfg(target_os = "macos")]
126const ORT_LIB_NAME: &str = "libonnxruntime.dylib";
127#[cfg(not(any(target_os = "windows", target_os = "macos")))]
128const ORT_LIB_NAME: &str = "libonnxruntime.so";
129fn ort_platform_dir() -> Option<&'static str> {
130    #[cfg(target_os = "windows")]
131    return Some("windows");
132    #[cfg(target_os = "linux")]
133    return Some("linux");
134    #[cfg(target_os = "macos")]
135    return Some("macos");
136    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
137    return None;
138}
139
140const MIN_BINARY_ASSET_BYTES: u64 = 1024 * 1024;
141
142fn usable_binary_asset(path: &Path) -> bool {
143    std::fs::metadata(path)
144        .is_ok_and(|metadata| metadata.is_file() && metadata.len() >= MIN_BINARY_ASSET_BYTES)
145}
146
147fn runtime_file_name_matches(name: &str) -> bool {
148    #[cfg(target_os = "macos")]
149    {
150        name.starts_with("libonnxruntime") && name.ends_with(".dylib")
151    }
152    #[cfg(not(target_os = "macos"))]
153    {
154        name.starts_with(ORT_LIB_NAME)
155    }
156}
157
158pub fn project_root() -> PathBuf {
159    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
160}
161
162pub fn default_asset_install_dir() -> PathBuf {
163    dirs::data_dir()
164        .unwrap_or_else(|| PathBuf::from("."))
165        .join("smriti")
166        .join("assets")
167}
168
169/// Pre-rename install dir, kept as a secondary lookup so users who
170/// installed assets under the old "photovault" path keep working
171/// after the upgrade. Removed in a future release.
172fn legacy_asset_install_dir() -> PathBuf {
173    dirs::data_dir()
174        .unwrap_or_else(|| PathBuf::from("."))
175        .join("photovault")
176        .join("assets")
177}
178
179pub fn asset_pack_url() -> String {
180    // Read SMRITI_* first, fall back to the legacy PHOTOVAULT_*
181    // env name for one release worth of grace.
182    std::env::var("SMRITI_ASSET_PACK_URL")
183        .or_else(|_| std::env::var("PHOTOVAULT_ASSET_PACK_URL"))
184        .unwrap_or_else(|_| ASSET_PACK_URL_DEFAULT.to_string())
185}
186
187fn find_runtime_in_dir(dir: &Path) -> Option<PathBuf> {
188    let direct = dir.join(ORT_LIB_NAME);
189    if usable_binary_asset(&direct) {
190        return Some(direct);
191    }
192
193    let entries = std::fs::read_dir(dir).ok()?;
194    for entry in entries.flatten() {
195        let path = entry.path();
196        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
197            if runtime_file_name_matches(name) && usable_binary_asset(&path) {
198                return Some(path);
199            }
200        }
201    }
202
203    None
204}
205
206pub fn onnx_runtime_path() -> Option<PathBuf> {
207    for root in candidate_asset_roots() {
208        if let Some(path) = onnx_runtime_path_in_root(&root) {
209            return Some(path);
210        }
211    }
212    None
213}
214
215fn onnx_runtime_path_in_root(root: &Path) -> Option<PathBuf> {
216    let candidate = root.join("libs").join("onnxruntime");
217    if let Some(path) = find_runtime_in_dir(&candidate) {
218        return Some(path);
219    }
220    if let Some(platform_dir) = ort_platform_dir() {
221        return find_runtime_in_dir(&candidate.join(platform_dir));
222    }
223    None
224}
225
226pub fn onnx_runtime_install_path() -> PathBuf {
227    let base = default_asset_install_dir().join("libs").join("onnxruntime");
228    if let Some(platform_dir) = ort_platform_dir() {
229        base.join(platform_dir).join(ORT_LIB_NAME)
230    } else {
231        base.join(ORT_LIB_NAME)
232    }
233}
234
235pub fn onnx_runtime_exists() -> bool {
236    onnx_runtime_path().is_some()
237}
238
239pub fn geonames_db_exists() -> bool {
240    crate::db::geonames::geonames_db_exists()
241}
242
243pub fn asset_health() -> AssetHealth {
244    AssetHealth {
245        missing_face_models: !has_face_models(),
246        missing_onnx_runtime: !onnx_runtime_exists(),
247        missing_geonames_db: !geonames_db_exists(),
248    }
249}
250
251fn asset_health_in_root(root: &Path) -> AssetHealth {
252    let model_dir = root.join("models");
253    let detector = model_dir.join("scrfd_10g_bnkps.onnx");
254    let embedder = model_dir.join(crate::config::AppConfig::load().face_embedder_model);
255    AssetHealth {
256        missing_face_models: !usable_binary_asset(&detector) || !usable_binary_asset(&embedder),
257        missing_onnx_runtime: onnx_runtime_path_in_root(root).is_none(),
258        missing_geonames_db: !crate::db::geonames::geonames_db_is_current(
259            &root.join("data").join("geonames.db"),
260        ),
261    }
262}
263
264fn candidate_asset_roots() -> Vec<PathBuf> {
265    let mut roots = Vec::new();
266
267    roots.push(default_asset_install_dir());
268    // Legacy fallback so users with assets installed under the old
269    // PhotoVault path keep working through the rename.
270    roots.push(legacy_asset_install_dir());
271
272    if let Ok(from_env) = std::env::var("SMRITI_ASSET_DIR") {
273        roots.push(PathBuf::from(from_env));
274    }
275    if let Ok(from_env) = std::env::var("PHOTOVAULT_ASSET_DIR") {
276        roots.push(PathBuf::from(from_env));
277    }
278
279    if let Ok(exe) = std::env::current_exe() {
280        if let Some(exe_dir) = exe.parent() {
281            // Portable/AppImage layout
282            roots.push(exe_dir.to_path_buf());
283            // Debian install layout: /usr/bin/<name> -> /usr/lib/<name>
284            roots.push(exe_dir.join("..").join("lib").join("smriti"));
285            // Legacy install path under the old name.
286            roots.push(exe_dir.join("..").join("lib").join("photovault"));
287            // `cargo tauri dev` runs the binary from target/debug/.
288            // Walk up two levels to land on the workspace root, where
289            // the dev tree's `libs/` and `models/` actually live.
290            roots.push(exe_dir.join("..").join(".."));
291        }
292    }
293    // `cargo tauri dev` sets CWD to src-tauri/. Walk up so the
294    // workspace root's libs/ + models/ are reachable.
295    if let Some(parent) = std::env::current_dir()
296        .ok()
297        .as_deref()
298        .and_then(|p| p.parent())
299    {
300        roots.push(parent.to_path_buf());
301    }
302
303    roots.push(project_root());
304    roots.push(PathBuf::from("/usr/lib/smriti"));
305    roots.push(PathBuf::from("/usr/lib/photovault")); // legacy
306
307    roots
308}
309
310pub fn asset_roots() -> Vec<PathBuf> {
311    candidate_asset_roots()
312}
313
314pub fn model_dir() -> PathBuf {
315    select_face_model_dir(
316        &candidate_asset_roots(),
317        &crate::config::AppConfig::load().face_embedder_model,
318    )
319    .unwrap_or_else(|| project_root().join("models"))
320}
321
322fn select_face_model_dir(roots: &[PathBuf], embedder: &str) -> Option<PathBuf> {
323    let find = |require_embedder: bool| {
324        roots
325            .iter()
326            .map(|root| root.join("models"))
327            .find(|directory| {
328                usable_binary_asset(&directory.join("scrfd_10g_bnkps.onnx"))
329                    && (!require_embedder || usable_binary_asset(&directory.join(embedder)))
330            })
331    };
332    find(true).or_else(|| find(false))
333}
334
335pub fn detector_model_path() -> PathBuf {
336    model_dir().join("scrfd_10g_bnkps.onnx")
337}
338
339pub fn embedder_model_path() -> PathBuf {
340    model_dir().join(crate::config::AppConfig::load().face_embedder_model)
341}
342
343pub fn has_face_models() -> bool {
344    usable_binary_asset(&detector_model_path()) && usable_binary_asset(&embedder_model_path())
345}
346
347pub fn face_processing_assets_available() -> bool {
348    let config = crate::config::AppConfig::load();
349    onnx_runtime_exists()
350        && usable_binary_asset(&detector_model_path())
351        && (usable_binary_asset(&embedder_model_path())
352            || (config.face_gpu_bridge_enabled && config.face_gpu_bridge_url.is_some()))
353}
354
355pub async fn install_feature_assets<F>(
356    feature: AssetFeature,
357    mut progress: F,
358    cancel: Option<&std::sync::atomic::AtomicBool>,
359) -> Result<String, String>
360where
361    F: FnMut(u64, Option<u64>) + Send,
362{
363    let install_root = default_asset_install_dir();
364    let install_parent = install_root
365        .parent()
366        .ok_or_else(|| "Asset install path has no parent directory".to_string())?;
367    std::fs::create_dir_all(install_parent).map_err(|e| {
368        format!(
369            "Failed creating asset parent dir {}: {}",
370            install_parent.display(),
371            e
372        )
373    })?;
374
375    // Honour SMRITI_* env vars first, fall back to legacy PHOTOVAULT_*
376    // for one release worth of grace.
377    let local_path = std::env::var("SMRITI_ASSET_PACK_PATH")
378        .or_else(|_| std::env::var("PHOTOVAULT_ASSET_PACK_PATH"))
379        .ok();
380    let (archive_path, remove_archive_after) = if let Some(local_path) = local_path {
381        let path = PathBuf::from(&local_path);
382        let metadata = std::fs::metadata(&path).map_err(|e| {
383            format!(
384                "Failed to read SMRITI_ASSET_PACK_PATH {}: {}",
385                local_path, e
386            )
387        })?;
388        if !metadata.is_file() || metadata.len() > MAX_ASSET_PACK_DOWNLOAD_BYTES {
389            return Err("Local asset pack is not a file or exceeds the 1 GiB limit".to_string());
390        }
391        (path, false)
392    } else {
393        let primary_url = if feature == AssetFeature::All {
394            asset_pack_url()
395        } else {
396            asset_download_source(feature).await?.0
397        };
398        let fallback_url = std::env::var("SMRITI_ASSET_PACK_FALLBACK_URL")
399            .or_else(|_| std::env::var("PHOTOVAULT_ASSET_PACK_FALLBACK_URL"))
400            .unwrap_or_else(|_| ASSET_PACK_LATEST_URL.to_string());
401
402        let download_path = install_parent.join(format!(
403            ".smriti-assets-download-{}.zip",
404            std::process::id()
405        ));
406        let client = reqwest::Client::builder()
407            .connect_timeout(std::time::Duration::from_secs(20))
408            .timeout(std::time::Duration::from_secs(30 * 60))
409            .build()
410            .map_err(|error| format!("Failed creating asset download client: {error}"))?;
411        let mut last_error = None;
412        let mut downloaded = false;
413        for url in [primary_url.as_str(), fallback_url.as_str()] {
414            let response = match client.get(url).send().await {
415                Ok(r) => r,
416                Err(e) => {
417                    last_error = Some(format!("request error from {}: {}", url, e));
418                    continue;
419                }
420            };
421
422            if !response.status().is_success() {
423                last_error = Some(format!("HTTP {} from {}", response.status(), url));
424                continue;
425            }
426
427            if response
428                .content_length()
429                .is_some_and(|length| length > MAX_ASSET_PACK_DOWNLOAD_BYTES)
430            {
431                last_error = Some(format!("asset pack from {} exceeds 1 GiB", url));
432                continue;
433            }
434
435            let mut output = match std::fs::File::create(&download_path) {
436                Ok(file) => file,
437                Err(error) => {
438                    last_error = Some(format!("cannot create download file: {}", error));
439                    break;
440                }
441            };
442            let total = response.content_length();
443            let mut stream = response.bytes_stream();
444            let mut hasher = Sha256::new();
445            let mut written = 0_u64;
446            let mut last_progress = std::time::Instant::now();
447            let mut stream_error = None;
448            while let Some(chunk) = stream.next().await {
449                if cancel.is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)) {
450                    drop(output);
451                    let _ = std::fs::remove_file(&download_path);
452                    return Err("Setup cancelled. You can retry when ready.".into());
453                }
454                let chunk = match chunk {
455                    Ok(chunk) => chunk,
456                    Err(error) => {
457                        stream_error = Some(format!("body read error from {}: {}", url, error));
458                        break;
459                    }
460                };
461                written = written.saturating_add(chunk.len() as u64);
462                if written > MAX_ASSET_PACK_DOWNLOAD_BYTES {
463                    stream_error = Some(format!("asset pack from {} exceeds 1 GiB", url));
464                    break;
465                }
466                if let Err(error) = output.write_all(&chunk) {
467                    stream_error = Some(format!("download write failed: {}", error));
468                    break;
469                }
470                hasher.update(&chunk);
471                if last_progress.elapsed() >= std::time::Duration::from_millis(150) {
472                    progress(written, total);
473                    last_progress = std::time::Instant::now();
474                }
475            }
476            drop(output);
477            if let Some(error) = stream_error {
478                last_error = Some(error);
479                let _ = std::fs::remove_file(&download_path);
480                continue;
481            }
482            if written == 0 {
483                last_error = Some(format!("empty response from {}", url));
484                let _ = std::fs::remove_file(&download_path);
485                continue;
486            }
487            // The pack carries a native library and ML models that will be
488            // loaded into the process: never install one that doesn't match
489            // the SHA256SUMS published with the same release.
490            let actual = format!("{:x}", hasher.finalize());
491            if let Err(error) = verify_release_checksum(&client, url, &actual).await {
492                last_error = Some(error);
493                let _ = std::fs::remove_file(&download_path);
494                continue;
495            }
496            progress(written, total);
497            downloaded = true;
498            break;
499        }
500
501        if !downloaded {
502            tracing::warn!(
503                "Asset pack download failed: {}",
504                last_error.unwrap_or_default()
505            );
506            return Err(
507                "Couldn't download or verify feature files. Check your internet connection and retry.".into(),
508            );
509        }
510        (download_path, true)
511    };
512
513    if cancel.is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)) {
514        if remove_archive_after {
515            let _ = std::fs::remove_file(&archive_path);
516        }
517        return Err("Setup cancelled. You can retry when ready.".into());
518    }
519
520    let install_root_for_worker = install_root.clone();
521    let install_parent_for_worker = install_parent.to_path_buf();
522    tokio::task::spawn_blocking(move || {
523        install_downloaded_asset_pack(
524            &archive_path,
525            remove_archive_after,
526            &install_root_for_worker,
527            &install_parent_for_worker,
528            feature,
529        )
530    })
531    .await
532    .map_err(|error| format!("Asset installation worker failed: {error}"))??;
533
534    Ok(format!("Assets installed to {}", install_root.display()))
535}
536
537/// Check `actual_sha256` against the `SHA256SUMS` file that sits next to
538/// `url` in the same GitHub release.
539async fn verify_release_checksum(
540    client: &reqwest::Client,
541    url: &str,
542    actual_sha256: &str,
543) -> Result<(), String> {
544    let (base, file_name) = url
545        .rsplit_once('/')
546        .ok_or_else(|| format!("cannot derive checksum location from {url}"))?;
547    let sums_url = format!("{base}/SHA256SUMS");
548    let body = client
549        .get(&sums_url)
550        .send()
551        .await
552        .and_then(|response| response.error_for_status())
553        .map_err(|error| format!("checksum list unavailable at {sums_url}: {error}"))?
554        .text()
555        .await
556        .map_err(|error| format!("checksum list unreadable at {sums_url}: {error}"))?;
557    let expected = crate::services::self_replace::parse_sha256sums(&body, file_name)
558        .ok_or_else(|| format!("{sums_url} has no entry for {file_name}"))?;
559    if expected.eq_ignore_ascii_case(actual_sha256) {
560        Ok(())
561    } else {
562        Err(format!(
563            "checksum mismatch for {url}: expected {expected}, got {actual_sha256}"
564        ))
565    }
566}
567
568fn install_downloaded_asset_pack(
569    archive_path: &Path,
570    remove_archive_after: bool,
571    install_root: &Path,
572    install_parent: &Path,
573    feature: AssetFeature,
574) -> Result<(), String> {
575    let nonce = std::time::SystemTime::now()
576        .duration_since(std::time::UNIX_EPOCH)
577        .map(|duration| duration.as_nanos())
578        .unwrap_or(0);
579    let staging = install_parent.join(format!(
580        ".smriti-assets-installing-{}-{nonce}",
581        std::process::id()
582    ));
583    if staging.exists() {
584        std::fs::remove_dir_all(&staging)
585            .map_err(|e| format!("Failed clearing stale asset staging directory: {e}"))?;
586    }
587    std::fs::create_dir_all(&staging)
588        .map_err(|e| format!("Failed creating asset staging directory: {e}"))?;
589
590    let install_result: Result<(), String> = (|| {
591        extract_asset_archive(archive_path, &staging)?;
592        prepare_staged_feature_pack(&staging, feature)?;
593        // A legacy combined archive may contain other features. Install only
594        // what was requested and missing; never replace a runtime DLL in use.
595        let health = asset_health();
596        for (directory, needed) in [
597            (
598                "libs",
599                matches!(
600                    feature,
601                    AssetFeature::All | AssetFeature::Faces | AssetFeature::Visual
602                ) && health.missing_onnx_runtime,
603            ),
604            (
605                "models",
606                matches!(feature, AssetFeature::All | AssetFeature::Faces)
607                    && health.missing_face_models,
608            ),
609            (
610                "data",
611                matches!(feature, AssetFeature::All | AssetFeature::Places)
612                    && health.missing_geonames_db,
613            ),
614        ] {
615            if needed {
616                merge_asset_tree(&staging.join(directory), &install_root.join(directory))?;
617            }
618        }
619        Ok(())
620    })();
621
622    let cleanup_result = std::fs::remove_dir_all(&staging);
623    if remove_archive_after {
624        let _ = std::fs::remove_file(archive_path);
625    }
626    install_result?;
627    if let Err(error) = cleanup_result {
628        tracing::warn!(
629            "Assets installed, but staging cleanup failed at {}: {}",
630            staging.display(),
631            error
632        );
633    }
634
635    Ok(())
636}
637
638#[cfg(test)]
639fn prepare_staged_asset_pack(staging: &Path) -> Result<(), String> {
640    prepare_staged_feature_pack(staging, AssetFeature::All)
641}
642
643fn prepare_staged_feature_pack(staging: &Path, feature: AssetFeature) -> Result<(), String> {
644    // v0.3.1's published pack accidentally contained GeoNames source text
645    // but no geonames.db. Repair that pack locally so one-click setup works
646    // for existing releases as well as corrected future ones.
647    let staged_geonames = staging.join("data").join("geonames.db");
648    if matches!(feature, AssetFeature::All | AssetFeature::Places)
649        && !crate::db::geonames::geonames_db_is_current(&staged_geonames)
650    {
651        let cities = staging.join("data").join("cities1000.txt");
652        let countries = staging.join("data").join("country_codes.txt");
653        if cities.is_file() && countries.is_file() {
654            crate::db::geonames::build_geonames_db(staging)?;
655        }
656    }
657
658    // Validate this download itself. Looking across all candidate roots could
659    // let an old development asset mask an incomplete release archive.
660    let health = asset_health_in_root(staging);
661    if feature.needs_pack(&health) {
662        return Err(format!(
663            "Downloaded asset pack is incomplete. {}",
664            health.summary()
665        ));
666    }
667    Ok(())
668}
669
670fn extract_asset_archive(archive_path: &Path, destination: &Path) -> Result<(), String> {
671    let reader = std::fs::File::open(archive_path)
672        .map_err(|e| format!("Failed opening downloaded asset zip: {}", e))?;
673    let mut archive = ZipArchive::new(reader).map_err(|e| format!("Invalid asset zip: {}", e))?;
674    if archive.len() > MAX_ASSET_PACK_FILES {
675        return Err(format!(
676            "Asset zip contains too many entries ({}; maximum {})",
677            archive.len(),
678            MAX_ASSET_PACK_FILES
679        ));
680    }
681
682    let mut expanded_bytes = 0_u64;
683    for i in 0..archive.len() {
684        let mut file = archive
685            .by_index(i)
686            .map_err(|e| format!("Failed reading zip entry {}: {}", i, e))?;
687        expanded_bytes = expanded_bytes
688            .checked_add(file.size())
689            .ok_or_else(|| "Asset zip expanded size overflow".to_string())?;
690        if expanded_bytes > MAX_ASSET_PACK_EXPANDED_BYTES {
691            return Err("Asset zip expands beyond the 2 GiB safety limit".to_string());
692        }
693        let enclosed = file.enclosed_name().ok_or_else(|| {
694            format!(
695                "Unsafe path in zip entry: {}",
696                String::from_utf8_lossy(file.name_raw())
697            )
698        })?;
699
700        let out_path = destination.join(enclosed);
701        if file.is_dir() {
702            std::fs::create_dir_all(&out_path)
703                .map_err(|e| format!("Failed creating directory {}: {}", out_path.display(), e))?;
704            continue;
705        }
706
707        if let Some(parent) = out_path.parent() {
708            std::fs::create_dir_all(parent).map_err(|e| {
709                format!(
710                    "Failed creating parent directory {}: {}",
711                    parent.display(),
712                    e
713                )
714            })?;
715        }
716
717        let mut out = std::fs::File::create(&out_path)
718            .map_err(|e| format!("Failed creating {}: {}", out_path.display(), e))?;
719        std::io::copy(&mut file, &mut out)
720            .map_err(|e| format!("Failed writing {}: {}", out_path.display(), e))?;
721    }
722    Ok(())
723}
724
725fn merge_asset_tree(source: &Path, destination: &Path) -> Result<(), String> {
726    std::fs::create_dir_all(destination)
727        .map_err(|e| format!("Failed creating {}: {}", destination.display(), e))?;
728    for entry in std::fs::read_dir(source)
729        .map_err(|e| format!("Failed reading {}: {}", source.display(), e))?
730    {
731        let entry = entry.map_err(|e| format!("Failed reading asset entry: {}", e))?;
732        let source_path = entry.path();
733        let destination_path = destination.join(entry.file_name());
734        if entry
735            .file_type()
736            .map_err(|e| format!("Failed reading asset file type: {}", e))?
737            .is_dir()
738        {
739            merge_asset_tree(&source_path, &destination_path)?;
740        } else {
741            let temp_path = destination_path.with_extension("smriti-installing");
742            std::fs::copy(&source_path, &temp_path).map_err(|e| {
743                format!(
744                    "Failed staging asset {} to {}: {}",
745                    source_path.display(),
746                    temp_path.display(),
747                    e
748                )
749            })?;
750            if destination_path.exists() {
751                std::fs::remove_file(&destination_path).map_err(|e| {
752                    format!(
753                        "Failed replacing asset {}: {}",
754                        destination_path.display(),
755                        e
756                    )
757                })?;
758            }
759            std::fs::rename(&temp_path, &destination_path).map_err(|e| {
760                format!(
761                    "Failed installing asset {}: {}",
762                    destination_path.display(),
763                    e
764                )
765            })?;
766        }
767    }
768    Ok(())
769}
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774
775    #[test]
776    fn resolves_runtime_from_asset_pack_platform_subdir() {
777        let temp = tempfile::tempdir().expect("tempdir");
778        let runtime_dir = if let Some(platform_dir) = ort_platform_dir() {
779            temp.path()
780                .join("libs")
781                .join("onnxruntime")
782                .join(platform_dir)
783        } else {
784            temp.path().join("libs").join("onnxruntime")
785        };
786        std::fs::create_dir_all(&runtime_dir).expect("runtime dir");
787        let runtime = runtime_dir.join(ORT_LIB_NAME);
788        std::fs::write(&runtime, vec![0_u8; MIN_BINARY_ASSET_BYTES as usize])
789            .expect("runtime marker");
790
791        assert_eq!(onnx_runtime_path_in_root(temp.path()), Some(runtime));
792    }
793
794    #[test]
795    fn runtime_install_path_matches_asset_pack_layout() {
796        let path = onnx_runtime_install_path();
797        let suffix = if let Some(platform_dir) = ort_platform_dir() {
798            PathBuf::from("libs")
799                .join("onnxruntime")
800                .join(platform_dir)
801                .join(ORT_LIB_NAME)
802        } else {
803            PathBuf::from("libs").join("onnxruntime").join(ORT_LIB_NAME)
804        };
805
806        assert!(path.ends_with(suffix));
807    }
808
809    #[test]
810    fn default_asset_pack_matches_running_app_version() {
811        assert!(ASSET_PACK_URL_DEFAULT.contains(&format!(
812            "/v{}/Smriti-Assets.zip",
813            env!("CARGO_PKG_VERSION")
814        )));
815    }
816
817    #[test]
818    fn feature_setup_checks_only_required_assets() {
819        let mut health = AssetHealth {
820            missing_face_models: true,
821            missing_onnx_runtime: false,
822            missing_geonames_db: true,
823        };
824        assert!(AssetFeature::All.needs_pack(&health));
825        assert!(AssetFeature::Faces.needs_pack(&health));
826        assert!(AssetFeature::Places.needs_pack(&health));
827        assert!(!AssetFeature::Visual.needs_pack(&health));
828        health.missing_face_models = false;
829        assert!(!AssetFeature::Faces.needs_pack(&health));
830        health.missing_onnx_runtime = true;
831        assert!(AssetFeature::Faces.needs_pack(&health));
832        assert!(AssetFeature::Visual.needs_pack(&health));
833    }
834
835    #[test]
836    fn incomplete_model_directory_does_not_mask_installed_faces() {
837        let temp = tempfile::tempdir().unwrap();
838        let incomplete = temp.path().join("incomplete");
839        let installed = temp.path().join("installed");
840        std::fs::create_dir_all(incomplete.join("models/semantic")).unwrap();
841        std::fs::create_dir_all(installed.join("models")).unwrap();
842        let marker = vec![0_u8; MIN_BINARY_ASSET_BYTES as usize];
843        std::fs::write(installed.join("models/scrfd_10g_bnkps.onnx"), &marker).unwrap();
844        std::fs::write(installed.join("models/embedder.onnx"), marker).unwrap();
845        assert_eq!(
846            select_face_model_dir(&[incomplete, installed.clone()], "embedder.onnx"),
847            Some(installed.join("models"))
848        );
849    }
850
851    #[test]
852    fn places_pack_does_not_require_models_or_runtime() {
853        let temp = tempfile::tempdir().expect("tempdir");
854        assert!(prepare_staged_feature_pack(temp.path(), AssetFeature::Places).is_err());
855        let data = temp.path().join("data");
856        std::fs::create_dir_all(&data).unwrap();
857        std::fs::write(data.join("country_codes.txt"), "ZZ\tTest Country\n").unwrap();
858        let cities = (1..=1_001).map(|id| format!(
859            "{id}\tCity {id}\tCity {id}\t\t1.0\t2.0\tP\tPPL\tZZ\t\t\t\t\t\t{id}\t\t\tUTC\t2026-01-01\n"
860        )).collect::<String>();
861        std::fs::write(data.join("cities1000.txt"), cities).unwrap();
862        prepare_staged_feature_pack(temp.path(), AssetFeature::Places).unwrap();
863        assert!(prepare_staged_feature_pack(temp.path(), AssetFeature::Faces).is_err());
864    }
865
866    #[test]
867    fn rejects_truncated_runtime_files() {
868        let temp = tempfile::tempdir().expect("tempdir");
869        let runtime_dir = temp.path().join("libs").join("onnxruntime");
870        std::fs::create_dir_all(&runtime_dir).expect("runtime dir");
871        std::fs::write(runtime_dir.join(ORT_LIB_NAME), b"download error page")
872            .expect("runtime marker");
873
874        assert_eq!(onnx_runtime_path_in_root(temp.path()), None);
875    }
876
877    #[test]
878    fn repairs_published_pack_with_geonames_sources_but_no_database() {
879        let temp = tempfile::tempdir().expect("tempdir");
880        let root = temp.path();
881        let data = root.join("data");
882        let models = root.join("models");
883        let runtime_dir = if let Some(platform_dir) = ort_platform_dir() {
884            root.join("libs").join("onnxruntime").join(platform_dir)
885        } else {
886            root.join("libs").join("onnxruntime")
887        };
888        std::fs::create_dir_all(&data).expect("data");
889        std::fs::create_dir_all(&models).expect("models");
890        std::fs::create_dir_all(&runtime_dir).expect("runtime");
891        std::fs::write(data.join("country_codes.txt"), "ZZ\tTest Country\n").expect("countries");
892        let mut cities = String::new();
893        for id in 1..=1_001 {
894            cities.push_str(&format!(
895                "{id}\tCity {id}\tCity {id}\t\t1.0\t2.0\tP\tPPL\tZZ\t\t\t\t\t\t{id}\t\t\tUTC\t2026-01-01\n"
896            ));
897        }
898        std::fs::write(data.join("cities1000.txt"), cities).expect("cities");
899        let marker = vec![0_u8; MIN_BINARY_ASSET_BYTES as usize];
900        std::fs::write(models.join("scrfd_10g_bnkps.onnx"), &marker).expect("detector");
901        std::fs::write(models.join("adaface_ir101_webface12m.onnx"), &marker).expect("embedder");
902        std::fs::write(runtime_dir.join(ORT_LIB_NAME), marker).expect("runtime");
903
904        prepare_staged_asset_pack(root).expect("repair and validate pack");
905
906        assert!(crate::db::geonames::geonames_db_is_current(
907            &data.join("geonames.db")
908        ));
909    }
910}