Repository navigation
Rust: Reuse the loaded workspace and load the next one in the background #23335
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+331
−35
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
46a544d
Rust: Reuse loaded workspaces and load the next one in the background
0e0ef1e
Rust: Keep only the current workspace loaded
27f4815
Rust: Update integration test steps for workspace reuse
4c9ddfe
Rust: Test that dropping loaded workspaces waits for a background load
b771b4b
Rust: Test proc macros across concurrently loaded workspaces
8f6861c
Rust: Format proc-macro workspaces test query
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,247 @@ | ||
| use crate::diagnostics::ExtractionStep; | ||
| use crate::parallel::WORKER_STACK_SIZE; | ||
| use ra_ap_project_model::ProjectManifest; | ||
| use std::sync::Arc; | ||
| use std::thread::JoinHandle; | ||
| use std::time::Instant; | ||
| use tracing::{error, warn}; | ||
|
|
||
| type Loaded<W> = (Option<W>, ExtractionStep); | ||
|
|
||
| /// The workspace loaded from the last requested manifest, kept so that it need not be reloaded | ||
| /// if requested again. Optionally, the manifest that is going to be requested next is loaded in | ||
| /// the background meanwhile, so at most two workspaces are held at any time. | ||
| pub struct LoadedWorkspaces<'m, W, L> { | ||
| current: Option<(&'m ProjectManifest, W)>, | ||
| prefetched: Option<(&'m ProjectManifest, JoinHandle<Loaded<W>>)>, | ||
| load: Arc<L>, | ||
| prefetch: bool, | ||
| } | ||
|
|
||
| impl<'m, W, L> LoadedWorkspaces<'m, W, L> | ||
| where | ||
| W: Send + 'static, | ||
| L: Fn(&ProjectManifest) -> Option<W> + Send + Sync + 'static, | ||
| { | ||
| pub fn new(prefetch: bool, load: L) -> Self { | ||
| Self { | ||
| current: None, | ||
| prefetched: None, | ||
| load: Arc::new(load), | ||
| prefetch, | ||
| } | ||
| } | ||
|
|
||
| pub fn contains(&self, manifest: &ProjectManifest) -> bool { | ||
| self.current.as_ref().is_some_and(|(m, _)| *m == manifest) | ||
| } | ||
|
|
||
| /// Returns the workspace of `manifest`, loading it unless still loaded, or `None` if it cannot | ||
| /// be loaded. Then starts loading `next` in the background, if prefetching is enabled. | ||
| pub fn get( | ||
| &mut self, | ||
| manifest: &'m ProjectManifest, | ||
| next: Option<&'m ProjectManifest>, | ||
| steps: &mut Vec<ExtractionStep>, | ||
| ) -> Option<&W> { | ||
| if !self.contains(manifest) { | ||
| let prefetched = self.take_prefetched(manifest, steps); | ||
| self.current = None; | ||
| let (workspace, step) = prefetched.unwrap_or_else(|| load_timed(&*self.load, manifest)); | ||
| steps.push(step); | ||
| self.current = workspace.map(|workspace| (manifest, workspace)); | ||
| } | ||
| if let Some(next) = next { | ||
| self.start_prefetch(next); | ||
| } | ||
| let (_, workspace) = self.current.as_ref()?; | ||
| Some(workspace) | ||
| } | ||
|
|
||
| fn take_prefetched( | ||
| &mut self, | ||
| manifest: &ProjectManifest, | ||
| steps: &mut Vec<ExtractionStep>, | ||
| ) -> Option<Loaded<W>> { | ||
| let (prefetched, handle) = self.prefetched.take()?; | ||
| let loaded = handle | ||
| .join() | ||
| .unwrap_or_else(|e| std::panic::resume_unwind(e)); | ||
| if prefetched == manifest { | ||
| return Some(loaded); | ||
| } | ||
| warn!("discarding {prefetched}, loaded in the background instead of {manifest}"); | ||
| steps.push(loaded.1); | ||
| None | ||
| } | ||
|
|
||
| fn start_prefetch(&mut self, next: &'m ProjectManifest) { | ||
| if !self.prefetch || self.prefetched.is_some() || self.contains(next) { | ||
| return; | ||
| } | ||
| let load = Arc::clone(&self.load); | ||
| let manifest = next.clone(); | ||
| match std::thread::Builder::new() | ||
| .stack_size(WORKER_STACK_SIZE) | ||
| .spawn(move || load_timed(&*load, &manifest)) | ||
|
redsun82 marked this conversation as resolved.
Resolved
|
||
| { | ||
| Ok(handle) => self.prefetched = Some((next, handle)), | ||
| // `next` is then loaded when requested | ||
| Err(e) => warn!("cannot load {next} in the background: {e}"), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<W, L> Drop for LoadedWorkspaces<'_, W, L> { | ||
| fn drop(&mut self) { | ||
| // do not leave cargo or proc-macro server processes behind | ||
| if let Some((manifest, handle)) = self.prefetched.take() | ||
| && handle.join().is_err() | ||
|
redsun82 marked this conversation as resolved.
Resolved
|
||
| { | ||
| error!("loading {manifest} in the background panicked"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn load_timed<W>( | ||
| load: &impl Fn(&ProjectManifest) -> Option<W>, | ||
| manifest: &ProjectManifest, | ||
| ) -> Loaded<W> { | ||
| let before = Instant::now(); | ||
| let ret = load(manifest); | ||
| (ret, ExtractionStep::load_manifest(before, manifest)) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use std::sync::Mutex; | ||
| use std::sync::atomic::{AtomicUsize, Ordering}; | ||
| use std::sync::mpsc::{Receiver, Sender, channel}; | ||
| use std::time::Duration; | ||
|
|
||
| struct Stats { | ||
| loads: Mutex<Vec<String>>, | ||
| live: AtomicUsize, | ||
| peak: AtomicUsize, | ||
| /// Background loads wait for a message on this, so that tests can check that `get` | ||
| /// returns while the next workspace is still loading. | ||
| gate: Mutex<Receiver<()>>, | ||
| } | ||
|
|
||
| struct Workspace(Arc<Stats>); | ||
|
|
||
| impl Drop for Workspace { | ||
| fn drop(&mut self) { | ||
| self.0.live.fetch_sub(1, Ordering::SeqCst); | ||
| } | ||
| } | ||
|
|
||
| fn stats() -> (Arc<Stats>, Sender<()>) { | ||
| let (sender, receiver) = channel(); | ||
| let stats = Stats { | ||
| loads: Mutex::default(), | ||
| live: AtomicUsize::default(), | ||
| peak: AtomicUsize::default(), | ||
| gate: Mutex::new(receiver), | ||
| }; | ||
| (Arc::new(stats), sender) | ||
| } | ||
|
|
||
| fn manifests<const N: usize>(names: [&str; N]) -> [ProjectManifest; N] { | ||
| let root = crate::cwd().unwrap(); | ||
| names.map(|name| { | ||
| ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml")).unwrap() | ||
| }) | ||
| } | ||
|
|
||
| /// Loads workspaces named after their directory, failing for `broken`. | ||
| fn loader(stats: &Arc<Stats>) -> impl Fn(&ProjectManifest) -> Option<Workspace> + use<> { | ||
| let stats = Arc::clone(stats); | ||
| move |manifest| { | ||
| let name = manifest.manifest_path().parent().file_name()?.to_owned(); | ||
| // test threads are named, background loading ones are not | ||
| let background = std::thread::current().name().is_none(); | ||
| if background { | ||
| let gate = stats.gate.lock().unwrap(); | ||
| gate.recv_timeout(Duration::from_secs(10)) | ||
| .expect("background load not released"); | ||
| } | ||
| let entry = format!("{name}{}", if background { " (background)" } else { "" }); | ||
| stats.loads.lock().unwrap().push(entry); | ||
| if name == "broken" { | ||
| return None; | ||
| } | ||
| let live = stats.live.fetch_add(1, Ordering::SeqCst) + 1; | ||
| stats.peak.fetch_max(live, Ordering::SeqCst); | ||
| Some(Workspace(Arc::clone(&stats))) | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn reuses_last_workspace() { | ||
| let (stats, _) = stats(); | ||
| let [a, b, broken] = &manifests(["a", "b", "broken"]); | ||
| let mut loaded = LoadedWorkspaces::new(false, loader(&stats)); | ||
| let mut steps = Vec::new(); | ||
| for manifest in [a, a, b, a, broken, broken] { | ||
| let got = loaded.get(manifest, None, &mut steps); | ||
| assert_eq!(got.is_some(), manifest != broken); | ||
| } | ||
| // failed loads are not kept | ||
| assert_eq!( | ||
| *stats.loads.lock().unwrap(), | ||
| ["a", "b", "a", "broken", "broken"] | ||
| ); | ||
| assert_eq!(steps.len(), 5); | ||
| assert!(!loaded.contains(a)); | ||
| assert_eq!(stats.peak.load(Ordering::SeqCst), 1); | ||
| } | ||
|
|
||
| #[test] | ||
| fn loads_next_workspace_in_background() { | ||
| let (stats, release) = stats(); | ||
| let all = manifests(["a", "b", "broken", "c", "d"]); | ||
| let mut loaded = LoadedWorkspaces::new(true, loader(&stats)); | ||
| let mut steps = Vec::new(); | ||
| for (i, manifest) in all.iter().enumerate() { | ||
| let next = all.get(i + 1); | ||
| let got = loaded.get(manifest, next, &mut steps); | ||
| assert_eq!(got.is_some(), i != 2); | ||
| if next.is_some() { | ||
| release.send(()).unwrap(); | ||
| } | ||
| } | ||
| assert_eq!( | ||
| *stats.loads.lock().unwrap(), | ||
| [ | ||
| "a", | ||
| "b (background)", | ||
| "broken (background)", | ||
| "c (background)", | ||
| "d (background)" | ||
| ] | ||
| ); | ||
| assert_eq!(steps.len(), 5); | ||
| assert_eq!(stats.peak.load(Ordering::SeqCst), 2); | ||
| drop(loaded); | ||
| assert_eq!(stats.live.load(Ordering::SeqCst), 0); | ||
| } | ||
|
|
||
| #[test] | ||
| fn drop_waits_for_background_load() { | ||
| let (stats, release) = stats(); | ||
| let [a, b] = &manifests(["a", "b"]); | ||
| let mut loaded = LoadedWorkspaces::new(true, loader(&stats)); | ||
| assert!(loaded.get(a, Some(b), &mut Vec::new()).is_some()); | ||
| let releaser = std::thread::spawn(move || { | ||
| std::thread::sleep(Duration::from_millis(100)); | ||
| release.send(()).unwrap(); | ||
| }); | ||
| drop(loaded); | ||
| assert_eq!(*stats.loads.lock().unwrap(), ["a", "b (background)"]); | ||
| assert_eq!(stats.peak.load(Ordering::SeqCst), 2); | ||
| assert_eq!(stats.live.load(Ordering::SeqCst), 0); | ||
| releaser.join().unwrap(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.