use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use futures::future::LocalBoxFuture; use gix_hash::ObjectId; use crate::error::KnotError; use crate::git::RefSnapshot; use crate::odb::{Fetched, ObjectSource, Objects}; use crate::remote::Remote; #[derive(Default)] struct Synced { objects: Objects, tips: HashSet, } thread_local! { static CACHE: RefCell>>> = RefCell::new(HashMap::new()); } pub fn cached_objects(key: &str) -> Objects { synced(key).borrow().objects.clone() } fn synced(key: &str) -> Rc> { CACHE.with(|cache| { cache .borrow_mut() .entry(key.to_string()) .or_default() .clone() }) } pub fn forget(key: &str) { CACHE.with(|cache| { cache.borrow_mut().remove(key); }); } pub struct PackSource { key: String, remote: Remote, tips: Vec, hash: gix_hash::Kind, } impl PackSource { pub fn new( key: impl Into, remote: Remote, refs: &RefSnapshot, hash: gix_hash::Kind, ) -> Self { let mut tips: Vec = refs .refs .iter() .map(|(_, target)| target.object_id()) .chain(refs.head_target.map(|target| target.object_id())) .collect(); tips.sort(); tips.dedup(); Self { key: key.into(), remote, tips, hash, } } async fn sync(&self) -> Result, KnotError> { let state = synced(&self.key); let (wants, haves): (Vec, Vec) = { let state = state.borrow(); let wants = self .tips .iter() .filter(|tip| !state.tips.contains(*tip) && !state.objects.has(tip)) .copied() .collect(); (wants, state.tips.iter().copied().collect()) }; if wants.is_empty() { return Ok(Vec::new()); } let pack = self.remote.fetch_pack(&wants, &haves).await?; let objects = state.borrow().objects.clone(); let fetched = crate::pack::unpack(&pack, self.hash, |id| objects.get(id))?; state.borrow_mut().tips.extend(self.tips.iter().copied()); Ok(fetched) } } impl ObjectSource for PackSource { fn fetch<'a>( &'a self, _ids: Vec, ) -> LocalBoxFuture<'a, Result, KnotError>> { Box::pin(self.sync()) } fn blob_size<'a>( &'a self, _id: ObjectId, ) -> LocalBoxFuture<'a, Result, KnotError>> { Box::pin(async { Ok(None) }) } }