use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use pagesift_net::{FetchRequest, Fetcher, FetcherConfig};
use pagesift_ocr::models::{File, Hasher, Model};
const MIN_SPEED: u64 = 64 << 10;
const MIN_TIMEOUT: Duration = Duration::from_secs(60);
fn model_lock(dir: &Path) -> Arc<tokio::sync::Mutex<()>> {
static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
LOCKS
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(dir.to_owned())
.or_default()
.clone()
}
fn part_path(dir: &Path, name: &str) -> PathBuf {
static NEXT: AtomicU64 = AtomicU64::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
dir.join(format!("{name}.part.{}.{n}", std::process::id()))
}
async fn fetch_file(fetcher: &Fetcher, model: &Model, file: &File, dir: &Path) -> Result<()> {
let url = model.url(file);
let mut req = FetchRequest::new(url.clone());
req.timeout = Some(MIN_TIMEOUT.max(Duration::from_secs(file.size / MIN_SPEED)));
let mut body = fetcher
.fetch_stream(req)
.await
.with_context(|| format!("downloading {url}"))?;
if body.status != 200 {
bail!("downloading {url}: HTTP {}", body.status);
}
let part = part_path(dir, file.name);
let result = async {
let mut out =
std::fs::File::create(&part).with_context(|| format!("creating {}", part.display()))?;
let mut hash = Hasher::new(file);
while let Some(chunk) = body
.chunk()
.await
.with_context(|| format!("downloading {url}"))?
{
hash.update(&chunk);
out.write_all(&chunk)
.with_context(|| format!("writing {}", part.display()))?;
}
out.sync_all()
.with_context(|| format!("writing {}", part.display()))?;
hash.finish()
.map_err(anyhow::Error::msg)
.with_context(|| format!("checking {url}"))?;
let dest = dir.join(file.name);
std::fs::rename(&part, &dest).with_context(|| format!("moving to {}", dest.display()))
}
.await;
if result.is_err() {
let _ = std::fs::remove_file(&part);
}
result
}
pub async fn fetch(
config: &FetcherConfig,
root: &Path,
model: &Model,
mut progress: impl FnMut(&File),
) -> Result<()> {
let dir = model.dir(root);
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
let fetcher = Fetcher::new(config.clone())?;
let lock = model_lock(&dir);
let _guard = lock.lock().await;
for file in model.files {
let have = std::fs::metadata(dir.join(file.name)).is_ok_and(|m| m.len() == file.size);
if !have {
progress(file);
fetch_file(&fetcher, model, file, &dir).await?;
}
}
Ok(())
}
pub(crate) fn fetch_blocking(
config: &FetcherConfig,
root: &Path,
model: &Model,
) -> Result<(), String> {
std::thread::scope(|s| {
s.spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(fetch(config, root, model, |f| {
tracing::info!(model = model.repo, file = f.name, "downloading OCR model");
}))
.map_err(|e| format!("{e:#}"))
})
.join()
.unwrap_or_else(|_| Err("the model download thread panicked".into()))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part_paths_never_repeat() {
let dir = Path::new("/models");
assert_ne!(part_path(dir, "a"), part_path(dir, "a"));
}
#[test]
fn one_lock_per_model_directory() {
let (a, b) = (Path::new("/models/a"), Path::new("/models/b"));
assert!(Arc::ptr_eq(&model_lock(a), &model_lock(a)));
assert!(!Arc::ptr_eq(&model_lock(a), &model_lock(b)));
}
}