|
| 1 | +use crate::diagnostics::ExtractionStep; |
| 2 | +use crate::parallel::WORKER_STACK_SIZE; |
| 3 | +use ra_ap_project_model::ProjectManifest; |
| 4 | +use std::sync::Arc; |
| 5 | +use std::thread::JoinHandle; |
| 6 | +use std::time::Instant; |
| 7 | +use tracing::{error, warn}; |
| 8 | + |
| 9 | +type Loaded<W> = (Option<W>, ExtractionStep); |
| 10 | + |
| 11 | +/// Workspaces loaded from manifests, keeping the `capacity` most recently used ones so that they |
| 12 | +/// need not be reloaded when extracting dependencies. Optionally, the manifest that is going to be |
| 13 | +/// requested next is loaded in the background meanwhile. At most `capacity + 1` workspaces are |
| 14 | +/// held at any time. |
| 15 | +pub struct LoadedWorkspaces<'m, W, L> { |
| 16 | + /// Most recently used last. |
| 17 | + loaded: Vec<(&'m ProjectManifest, W)>, |
| 18 | + prefetched: Option<(&'m ProjectManifest, JoinHandle<Loaded<W>>)>, |
| 19 | + load: Arc<L>, |
| 20 | + capacity: usize, |
| 21 | + prefetch: bool, |
| 22 | +} |
| 23 | + |
| 24 | +impl<'m, W, L> LoadedWorkspaces<'m, W, L> |
| 25 | +where |
| 26 | + W: Send + 'static, |
| 27 | + L: Fn(&ProjectManifest) -> Option<W> + Send + Sync + 'static, |
| 28 | +{ |
| 29 | + pub fn new(capacity: usize, prefetch: bool, load: L) -> Self { |
| 30 | + assert!(capacity > 0); |
| 31 | + Self { |
| 32 | + loaded: Vec::with_capacity(capacity), |
| 33 | + prefetched: None, |
| 34 | + load: Arc::new(load), |
| 35 | + capacity, |
| 36 | + prefetch, |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + pub fn contains(&self, manifest: &ProjectManifest) -> bool { |
| 41 | + self.loaded.iter().any(|(m, _)| *m == manifest) |
| 42 | + } |
| 43 | + |
| 44 | + /// Returns the workspace of `manifest`, loading it unless still loaded, or `None` if it cannot |
| 45 | + /// be loaded. Then starts loading `next` in the background, if prefetching is enabled. |
| 46 | + pub fn get( |
| 47 | + &mut self, |
| 48 | + manifest: &'m ProjectManifest, |
| 49 | + next: Option<&'m ProjectManifest>, |
| 50 | + steps: &mut Vec<ExtractionStep>, |
| 51 | + ) -> Option<&W> { |
| 52 | + let found = if let Some(index) = self.loaded.iter().position(|(m, _)| *m == manifest) { |
| 53 | + let entry = self.loaded.remove(index); |
| 54 | + self.loaded.push(entry); |
| 55 | + true |
| 56 | + } else { |
| 57 | + let prefetched = self.take_prefetched(manifest, steps); |
| 58 | + let (workspace, step) = prefetched.unwrap_or_else(|| load_timed(&*self.load, manifest)); |
| 59 | + steps.push(step); |
| 60 | + workspace.is_some_and(|workspace| { |
| 61 | + // evict before starting the next prefetch to bound the number of workspaces held |
| 62 | + if self.loaded.len() == self.capacity { |
| 63 | + self.loaded.remove(0); |
| 64 | + } |
| 65 | + self.loaded.push((manifest, workspace)); |
| 66 | + true |
| 67 | + }) |
| 68 | + }; |
| 69 | + if let Some(next) = next { |
| 70 | + self.start_prefetch(next); |
| 71 | + } |
| 72 | + let (_, workspace) = self.loaded.last().filter(|_| found)?; |
| 73 | + Some(workspace) |
| 74 | + } |
| 75 | + |
| 76 | + fn take_prefetched( |
| 77 | + &mut self, |
| 78 | + manifest: &ProjectManifest, |
| 79 | + steps: &mut Vec<ExtractionStep>, |
| 80 | + ) -> Option<Loaded<W>> { |
| 81 | + let (prefetched, handle) = self.prefetched.take()?; |
| 82 | + let loaded = handle |
| 83 | + .join() |
| 84 | + .unwrap_or_else(|e| std::panic::resume_unwind(e)); |
| 85 | + if prefetched == manifest { |
| 86 | + return Some(loaded); |
| 87 | + } |
| 88 | + warn!("discarding {prefetched}, loaded in the background instead of {manifest}"); |
| 89 | + steps.push(loaded.1); |
| 90 | + None |
| 91 | + } |
| 92 | + |
| 93 | + fn start_prefetch(&mut self, next: &'m ProjectManifest) { |
| 94 | + if !self.prefetch || self.prefetched.is_some() || self.contains(next) { |
| 95 | + return; |
| 96 | + } |
| 97 | + let load = Arc::clone(&self.load); |
| 98 | + let manifest = next.clone(); |
| 99 | + match std::thread::Builder::new() |
| 100 | + .stack_size(WORKER_STACK_SIZE) |
| 101 | + .spawn(move || load_timed(&*load, &manifest)) |
| 102 | + { |
| 103 | + Ok(handle) => self.prefetched = Some((next, handle)), |
| 104 | + // `next` is then loaded when requested |
| 105 | + Err(e) => warn!("cannot load {next} in the background: {e}"), |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +impl<W, L> Drop for LoadedWorkspaces<'_, W, L> { |
| 111 | + fn drop(&mut self) { |
| 112 | + // do not leave cargo or proc-macro server processes behind |
| 113 | + if let Some((manifest, handle)) = self.prefetched.take() |
| 114 | + && handle.join().is_err() |
| 115 | + { |
| 116 | + error!("loading {manifest} in the background panicked"); |
| 117 | + } |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +fn load_timed<W>( |
| 122 | + load: &impl Fn(&ProjectManifest) -> Option<W>, |
| 123 | + manifest: &ProjectManifest, |
| 124 | +) -> Loaded<W> { |
| 125 | + let before = Instant::now(); |
| 126 | + let ret = load(manifest); |
| 127 | + (ret, ExtractionStep::load_manifest(before, manifest)) |
| 128 | +} |
| 129 | + |
| 130 | +#[cfg(test)] |
| 131 | +mod tests { |
| 132 | + use super::*; |
| 133 | + use std::sync::Mutex; |
| 134 | + use std::sync::atomic::{AtomicUsize, Ordering}; |
| 135 | + |
| 136 | + #[derive(Default)] |
| 137 | + struct Stats { |
| 138 | + loads: Mutex<Vec<String>>, |
| 139 | + live: AtomicUsize, |
| 140 | + peak: AtomicUsize, |
| 141 | + } |
| 142 | + |
| 143 | + struct Workspace(String, Arc<Stats>); |
| 144 | + |
| 145 | + impl Drop for Workspace { |
| 146 | + fn drop(&mut self) { |
| 147 | + self.1.live.fetch_sub(1, Ordering::SeqCst); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + fn manifests(names: &[&str]) -> Vec<ProjectManifest> { |
| 152 | + let root = crate::cwd().unwrap(); |
| 153 | + names |
| 154 | + .iter() |
| 155 | + .map(|name| ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml"))) |
| 156 | + .collect::<Result<_, _>>() |
| 157 | + .unwrap() |
| 158 | + } |
| 159 | + |
| 160 | + /// Loads workspaces named after their directory, failing for `broken`. |
| 161 | + fn loader(stats: &Arc<Stats>) -> impl Fn(&ProjectManifest) -> Option<Workspace> + use<> { |
| 162 | + let stats = Arc::clone(stats); |
| 163 | + move |manifest| { |
| 164 | + let name = manifest.manifest_path().parent().file_name()?.to_owned(); |
| 165 | + // test threads are named, background loading ones are not |
| 166 | + let background = std::thread::current().name().is_none(); |
| 167 | + let entry = format!("{name}{}", if background { " (background)" } else { "" }); |
| 168 | + stats.loads.lock().unwrap().push(entry); |
| 169 | + if name == "broken" { |
| 170 | + return None; |
| 171 | + } |
| 172 | + let live = stats.live.fetch_add(1, Ordering::SeqCst) + 1; |
| 173 | + stats.peak.fetch_max(live, Ordering::SeqCst); |
| 174 | + Some(Workspace(name, Arc::clone(&stats))) |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + #[test] |
| 179 | + fn reuses_most_recently_used_workspaces() { |
| 180 | + let stats = Arc::default(); |
| 181 | + let [a, b, c, broken]: &[_; 4] = &manifests(&["a", "b", "c", "broken"]).try_into().unwrap(); |
| 182 | + let mut loaded = LoadedWorkspaces::new(2, false, loader(&stats)); |
| 183 | + let mut steps = Vec::new(); |
| 184 | + for manifest in [a, b, a, c, b, broken, broken] { |
| 185 | + let got = loaded.get(manifest, None, &mut steps).map(|w| w.0.clone()); |
| 186 | + assert_eq!(got.is_some(), manifest != broken); |
| 187 | + } |
| 188 | + // `c` evicts `b`, the least recently used; failed loads are not kept |
| 189 | + assert_eq!( |
| 190 | + *stats.loads.lock().unwrap(), |
| 191 | + ["a", "b", "c", "b", "broken", "broken"] |
| 192 | + ); |
| 193 | + assert_eq!(steps.len(), 6); |
| 194 | + assert!(loaded.contains(c) && loaded.contains(b) && !loaded.contains(a)); |
| 195 | + } |
| 196 | + |
| 197 | + #[test] |
| 198 | + fn prefetches_next_workspace_within_bound() { |
| 199 | + let stats = Arc::default(); |
| 200 | + let all = manifests(&["a", "b", "broken", "c", "d"]); |
| 201 | + let mut loaded = LoadedWorkspaces::new(2, true, loader(&stats)); |
| 202 | + let mut steps = Vec::new(); |
| 203 | + for (i, manifest) in all.iter().enumerate() { |
| 204 | + let got = loaded.get(manifest, all.get(i + 1), &mut steps); |
| 205 | + assert_eq!(got.is_some(), i != 2); |
| 206 | + } |
| 207 | + assert_eq!( |
| 208 | + *stats.loads.lock().unwrap(), |
| 209 | + [ |
| 210 | + "a", |
| 211 | + "b (background)", |
| 212 | + "broken (background)", |
| 213 | + "c (background)", |
| 214 | + "d (background)" |
| 215 | + ] |
| 216 | + ); |
| 217 | + assert_eq!(steps.len(), 5); |
| 218 | + assert!(stats.peak.load(Ordering::SeqCst) <= 3); |
| 219 | + drop(loaded); |
| 220 | + assert_eq!(stats.live.load(Ordering::SeqCst), 0); |
| 221 | + } |
| 222 | +} |
0 commit comments