Skip to content

Commit

Permalink
Cache Build Plans in language server (#6281)
Browse files Browse the repository at this point in the history
## Description
closes #5462
related #5445

before we were recreating the build plan on every keystroke. We now
cache the result and reuse on subsequent did change events. We
invalidate the cache if there has been any modifications to the
`Forc.toml` file since the cache was created.

Here are the timings when triggering this with a did_change event on the
FUSD repo.

previous: `80.146ms`
with this change: `56µs`
  • Loading branch information
JoshuaBatty authored Jul 22, 2024
1 parent de85361 commit 0b440ea
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 15 deletions.
28 changes: 19 additions & 9 deletions sway-lsp/benches/lsp_benchmarks/compile.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,44 @@
use criterion::{black_box, criterion_group, Criterion};
use lsp_types::Url;
use std::sync::Arc;
use sway_core::{Engines, ExperimentalFlags};
use sway_lsp::core::session;
use tokio::runtime::Runtime;

const NUM_DID_CHANGE_ITERATIONS: usize = 10;

fn benchmarks(c: &mut Criterion) {
let experimental = ExperimentalFlags {
new_encoding: false,
};
let (uri, session, _) = Runtime::new()
.unwrap()
.block_on(async { black_box(super::compile_test_project().await) });

let build_plan = session
.build_plan_cache
.get_or_update(&session.sync.manifest_path(), || session::build_plan(&uri))
.unwrap();

// Load the test project
let uri = Url::from_file_path(super::benchmark_dir().join("src/main.sw")).unwrap();
let mut lsp_mode = Some(sway_core::LspConfig {
optimized_build: false,
file_versions: Default::default(),
});

let experimental = ExperimentalFlags {
new_encoding: false,
};

c.bench_function("compile", |b| {
b.iter(|| {
let engines = Engines::default();
let _ = black_box(
session::compile(&uri, &engines, None, lsp_mode.clone(), experimental).unwrap(),
session::compile(&build_plan, &engines, None, lsp_mode.clone(), experimental)
.unwrap(),
);
})
});

c.bench_function("traverse", |b| {
let engines = Engines::default();
let results = black_box(
session::compile(&uri, &engines, None, lsp_mode.clone(), experimental).unwrap(),
session::compile(&build_plan, &engines, None, lsp_mode.clone(), experimental).unwrap(),
);
let session = Arc::new(session::Session::new());
b.iter(|| {
Expand All @@ -44,7 +53,8 @@ fn benchmarks(c: &mut Criterion) {
b.iter(|| {
for _ in 0..NUM_DID_CHANGE_ITERATIONS {
let _ = black_box(
session::compile(&uri, &engines, None, lsp_mode.clone(), experimental).unwrap(),
session::compile(&build_plan, &engines, None, lsp_mode.clone(), experimental)
.unwrap(),
);
}
})
Expand Down
65 changes: 60 additions & 5 deletions sway-lsp/src/core/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::{
path::PathBuf,
sync::{atomic::AtomicBool, Arc},
time::SystemTime,
};
use sway_core::{
decl_engine::DeclEngine,
Expand Down Expand Up @@ -61,6 +62,7 @@ pub struct CompiledProgram {
pub struct Session {
token_map: TokenMap,
pub runnables: RunnableMap,
pub build_plan_cache: BuildPlanCache,
pub compiled_program: RwLock<CompiledProgram>,
pub engines: RwLock<Engines>,
pub sync: SyncWorkspace,
Expand All @@ -80,6 +82,7 @@ impl Session {
Session {
token_map: TokenMap::new(),
runnables: DashMap::new(),
build_plan_cache: BuildPlanCache::default(),
metrics: DashMap::new(),
compiled_program: RwLock::new(CompiledProgram::default()),
engines: <_>::default(),
Expand Down Expand Up @@ -228,7 +231,7 @@ impl Session {
}

/// Create a [BuildPlan] from the given [Url] appropriate for the language server.
pub(crate) fn build_plan(uri: &Url) -> Result<BuildPlan, LanguageServerError> {
pub fn build_plan(uri: &Url) -> Result<BuildPlan, LanguageServerError> {
let _p = tracing::trace_span!("build_plan").entered();
let manifest_dir = PathBuf::from(uri.path());
let manifest =
Expand All @@ -254,17 +257,16 @@ pub(crate) fn build_plan(uri: &Url) -> Result<BuildPlan, LanguageServerError> {
}

pub fn compile(
uri: &Url,
build_plan: &BuildPlan,
engines: &Engines,
retrigger_compilation: Option<Arc<AtomicBool>>,
lsp_mode: Option<LspConfig>,
experimental: sway_core::ExperimentalFlags,
) -> Result<Vec<(Option<Programs>, Handler)>, LanguageServerError> {
let _p = tracing::trace_span!("compile").entered();
let build_plan = build_plan(uri)?;
let tests_enabled = true;
pkg::check(
&build_plan,
build_plan,
BuildTarget::default(),
true,
lsp_mode,
Expand Down Expand Up @@ -382,8 +384,11 @@ pub fn parse_project(
experimental: sway_core::ExperimentalFlags,
) -> Result<(), LanguageServerError> {
let _p = tracing::trace_span!("parse_project").entered();
let build_plan = session
.build_plan_cache
.get_or_update(&session.sync.manifest_path(), || build_plan(uri))?;
let results = compile(
uri,
&build_plan,
engines,
retrigger_compilation,
lsp_mode.clone(),
Expand Down Expand Up @@ -508,6 +513,56 @@ pub(crate) fn program_id_from_path(
Ok(program_id)
}

/// A cache for storing and retrieving BuildPlan objects.
#[derive(Debug, Clone)]
pub struct BuildPlanCache {
/// The cached BuildPlan and its last update time
cache: Arc<RwLock<Option<(BuildPlan, SystemTime)>>>,
}

impl Default for BuildPlanCache {
fn default() -> Self {
Self {
cache: Arc::new(RwLock::new(None)),
}
}
}

impl BuildPlanCache {
/// Retrieves a BuildPlan from the cache or updates it if necessary.
pub fn get_or_update<F>(
&self,
manifest_path: &Option<PathBuf>,
update_fn: F,
) -> Result<BuildPlan, LanguageServerError>
where
F: FnOnce() -> Result<BuildPlan, LanguageServerError>,
{
let should_update = {
let cache = self.cache.read();
manifest_path
.as_ref()
.and_then(|path| path.metadata().ok()?.modified().ok())
.map_or(cache.is_none(), |time| {
cache.as_ref().map_or(true, |&(_, last)| time > last)
})
};

if should_update {
let new_plan = update_fn()?;
let mut cache = self.cache.write();
*cache = Some((new_plan.clone(), SystemTime::now()));
Ok(new_plan)
} else {
let cache = self.cache.read();
cache
.as_ref()
.map(|(plan, _)| plan.clone())
.ok_or(LanguageServerError::BuildPlanCacheIsEmpty)
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
2 changes: 1 addition & 1 deletion sway-lsp/src/core/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ impl SyncWorkspace {
.ok()
}

pub(crate) fn manifest_path(&self) -> Option<PathBuf> {
pub fn manifest_path(&self) -> Option<PathBuf> {
self.manifest_dir()
.map(|dir| dir.join(sway_utils::constants::MANIFEST_FILE_NAME))
.ok()
Expand Down
2 changes: 2 additions & 0 deletions sway-lsp/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub enum LanguageServerError {
// Top level errors
#[error("Failed to create build plan. {0}")]
BuildPlanFailed(anyhow::Error),
#[error("Build Plan Cache is empty")]
BuildPlanCacheIsEmpty,
#[error("Failed to compile. {0}")]
FailedToCompile(anyhow::Error),
#[error("Failed to parse document")]
Expand Down

0 comments on commit 0b440ea

Please sign in to comment.