Unverified Commit 8882653a authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: Use Arc<PathMap> and Box<Path> to make InvalidatorMap slightly more efficient (#95987)

Addresses
https://github.com/vercel/next.js/pull/95951/changes#r3617631291

- We often already have an `Arc<PathBuf>` here.
- The data stored in the queue is temporary, so the slight extra size of
`Arc<PathBuf>` is fine, and saving the clone is nice.
- The other references to the `Arc<PathBuf>` are not long-lived, so
convert it into a `Box<Path>` once it goes into the locked map.
parent 5639c4ec
use std::{
collections::BTreeMap,
path::PathBuf,
sync::{LockResult, Mutex, MutexGuard},
path::{Path, PathBuf},
sync::{Arc, LockResult, Mutex, MutexGuard},
};
use concurrent_queue::ConcurrentQueue;
use rustc_hash::FxHashSet;
use turbo_tasks::Invalidator;
pub type LockedInvalidatorMap = BTreeMap<PathBuf, FxHashSet<Invalidator>>;
pub type LockedInvalidatorMap = BTreeMap<Box<Path>, FxHashSet<Invalidator>>;
pub struct InvalidatorMap {
queue: ConcurrentQueue<(PathBuf, Invalidator)>,
queue: ConcurrentQueue<(Arc<PathBuf>, Invalidator)>,
map: Mutex<LockedInvalidatorMap>,
}
......@@ -32,12 +32,20 @@ impl InvalidatorMap {
pub fn lock(&self) -> LockResult<MutexGuard<'_, LockedInvalidatorMap>> {
let mut guard = self.map.lock()?;
while let Ok((key, value)) = self.queue.pop() {
guard.entry(key).or_default().insert(value);
if let Some(invalidators) = guard.get_mut(key.as_path()) {
invalidators.insert(value);
} else {
let key = match Arc::try_unwrap(key) {
Ok(key) => key.into_boxed_path(),
Err(key) => Box::from(key.as_path()),
};
guard.insert(key, FxHashSet::from_iter([value]));
}
}
Ok(guard)
}
pub fn insert(&self, key: PathBuf, invalidator: Invalidator) {
pub fn insert(&self, key: Arc<PathBuf>, invalidator: Invalidator) {
self.queue.push((key, invalidator)).unwrap_or_else(|err| {
let (key, ..) = err.into_inner();
// PushError<T> is not Debug
......
......@@ -359,9 +359,9 @@ impl DiskFileSystemInner {
/// registers the path as an invalidator for the current task,
/// has to be called within a turbo-tasks function
async fn register_read_invalidator(&self, path: &Path) -> Result<()> {
async fn register_read_invalidator(&self, path: &Arc<PathBuf>) -> Result<()> {
if let Some(invalidator) = turbo_tasks::get_invalidator() {
self.invalidator_map.insert(path.to_owned(), invalidator);
self.invalidator_map.insert(path.clone(), invalidator);
self.watcher
.ensure_watched_file(path, self.root_path())
.await?;
......@@ -390,10 +390,9 @@ impl DiskFileSystemInner {
/// registers the path as an invalidator for the current task,
/// has to be called within a turbo-tasks function
async fn register_dir_invalidator(&self, path: &Path) -> Result<()> {
async fn register_dir_invalidator(&self, path: &Arc<PathBuf>) -> Result<()> {
if let Some(invalidator) = turbo_tasks::get_invalidator() {
self.dir_invalidator_map
.insert(path.to_owned(), invalidator);
self.dir_invalidator_map.insert(path.clone(), invalidator);
self.watcher
.ensure_watched_dir(path, self.root_path())
.await?;
......@@ -507,7 +506,7 @@ impl DiskFileSystemInner {
}
for path in parent_dirs_to_invalidate {
if let Some(path_invalidators) = dir_invalidator_map.remove(&path) {
if let Some(path_invalidators) = dir_invalidator_map.remove(path.as_path()) {
let reason_for_path = reason(&path);
invalidators.extend(
path_invalidators
......@@ -901,12 +900,12 @@ impl FileSystem for DiskFileSystem {
if self.inner.is_path_denied(&fs_path) {
return Ok(RawDirectoryContent::not_found());
}
let full_path = self.to_sys_path_raw(&fs_path);
let full_path = Arc::new(self.to_sys_path_raw(&fs_path));
self.inner.register_dir_invalidator(&full_path).await?;
// we use the sync std function here as it's a lot faster (600%) in node-file-trace
let read_dir = match retry_blocking(|| std::fs::read_dir(&full_path))
let read_dir = match retry_blocking(|| std::fs::read_dir(&*full_path))
.instrument(tracing::info_span!("read directory", name = ?full_path))
.concurrency_limited(&self.inner.read_semaphore)
.await
......
use std::{
borrow::Borrow,
collections::{BTreeMap, BTreeSet, btree_map, btree_set},
ops::Bound,
path::{Path, PathBuf},
};
/// A thin wrapper around [`BTreeMap<PathBuf, V>`] that provides efficient extraction of child
/// paths.
/// A thin wrapper around a path-keyed [`BTreeMap`] (e.g. `BTreeMap<Box<Path>, V>`) that provides
/// efficient extraction of child paths.
///
/// In the future, this may use a more efficient representation, like a radix tree or trie.
pub trait OrderedPathMapExt<V> {
pub trait OrderedPathMapExt<K, V> {
fn extract_path_with_children<'a>(
&'a mut self,
path: &'a Path,
) -> PathMapExtractPathWithChildren<'a, V>;
) -> PathMapExtractPathWithChildren<'a, K, V>;
}
impl<V> OrderedPathMapExt<V> for BTreeMap<PathBuf, V> {
impl<K: Borrow<Path> + Ord, V> OrderedPathMapExt<K, V> for BTreeMap<K, V> {
/// Iterates over and removes `path` and all of its children.
fn extract_path_with_children<'a>(
&'a mut self,
path: &'a Path,
) -> PathMapExtractPathWithChildren<'a, V> {
) -> PathMapExtractPathWithChildren<'a, K, V> {
PathMapExtractPathWithChildren {
cursor: self.lower_bound_mut(Bound::Included(path)),
parent_path: path,
......@@ -28,13 +29,13 @@ impl<V> OrderedPathMapExt<V> for BTreeMap<PathBuf, V> {
}
}
pub struct PathMapExtractPathWithChildren<'a, V> {
cursor: btree_map::CursorMut<'a, PathBuf, V>,
pub struct PathMapExtractPathWithChildren<'a, K, V> {
cursor: btree_map::CursorMut<'a, K, V>,
parent_path: &'a Path,
}
impl<V> Iterator for PathMapExtractPathWithChildren<'_, V> {
type Item = (PathBuf, V);
impl<K: Borrow<Path> + Ord, V> Iterator for PathMapExtractPathWithChildren<'_, K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<Self::Item> {
// this simple implementation works because `Path` implements `Ord` (and `starts_with`)
......@@ -43,7 +44,7 @@ impl<V> Iterator for PathMapExtractPathWithChildren<'_, V> {
if self
.cursor
.peek_next()
.is_none_or(|(k, _v)| !k.starts_with(self.parent_path))
.is_none_or(|(k, _v)| !k.borrow().starts_with(self.parent_path))
{
return None;
}
......
......@@ -794,7 +794,7 @@ fn invalidate_path(
paths: impl Iterator<Item = PathBuf>,
) {
for path in paths {
if let Some(invalidators) = invalidator_map.remove(&path) {
if let Some(invalidators) = invalidator_map.remove(path.as_path()) {
invalidators
.into_iter()
.for_each(|i| invalidate(inner, turbo_tasks, report_invalidation_reason, &path, i));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment