Use rocksdb to store project paths' public/private state

This commit is contained in:
Max Brunsfeld
2022-06-02 17:38:33 -07:00
parent 724affc442
commit f7e7a7c6a7
8 changed files with 324 additions and 28 deletions
+161
View File
@@ -0,0 +1,161 @@
use anyhow::Result;
use std::path::PathBuf;
use std::sync::Arc;
pub struct Db(DbStore);
enum DbStore {
Null,
Real(rocksdb::DB),
#[cfg(any(test, feature = "test-support"))]
Fake {
data: parking_lot::Mutex<collections::HashMap<Vec<u8>, Vec<u8>>>,
},
}
impl Db {
/// Open or create a database at the given file path.
pub fn open(path: PathBuf) -> Result<Arc<Self>> {
let db = rocksdb::DB::open_default(&path)?;
Ok(Arc::new(Self(DbStore::Real(db))))
}
/// Open a null database that stores no data, for use as a fallback
/// when there is an error opening the real database.
pub fn null() -> Arc<Self> {
Arc::new(Self(DbStore::Null))
}
/// Open a fake database for testing.
#[cfg(any(test, feature = "test-support"))]
pub fn open_fake() -> Arc<Self> {
Arc::new(Self(DbStore::Fake {
data: Default::default(),
}))
}
pub fn read<K, I>(&self, keys: I) -> Result<Vec<Option<Vec<u8>>>>
where
K: AsRef<[u8]>,
I: IntoIterator<Item = K>,
{
match &self.0 {
DbStore::Real(db) => db
.multi_get(keys)
.into_iter()
.map(|e| e.map_err(Into::into))
.collect(),
DbStore::Null => Ok(keys.into_iter().map(|_| None).collect()),
#[cfg(any(test, feature = "test-support"))]
DbStore::Fake { data: db } => {
let db = db.lock();
Ok(keys
.into_iter()
.map(|key| db.get(key.as_ref()).cloned())
.collect())
}
}
}
pub fn delete<K, I>(&self, keys: I) -> Result<()>
where
K: AsRef<[u8]>,
I: IntoIterator<Item = K>,
{
match &self.0 {
DbStore::Real(db) => {
let mut batch = rocksdb::WriteBatch::default();
for key in keys {
batch.delete(key);
}
db.write(batch)?;
}
DbStore::Null => {}
#[cfg(any(test, feature = "test-support"))]
DbStore::Fake { data: db } => {
let mut db = db.lock();
for key in keys {
db.remove(key.as_ref());
}
}
}
Ok(())
}
pub fn write<K, V, I>(&self, entries: I) -> Result<()>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
I: IntoIterator<Item = (K, V)>,
{
match &self.0 {
DbStore::Real(db) => {
let mut batch = rocksdb::WriteBatch::default();
for (key, value) in entries {
batch.put(key, value);
}
db.write(batch)?;
}
DbStore::Null => {}
#[cfg(any(test, feature = "test-support"))]
DbStore::Fake { data: db } => {
let mut db = db.lock();
for (key, value) in entries {
db.insert(key.as_ref().into(), value.as_ref().into());
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempdir::TempDir;
#[gpui::test]
fn test_db() {
let dir = TempDir::new("db-test").unwrap();
let fake_db = Db::open_fake();
let real_db = Db::open(dir.path().join("test.db")).unwrap();
for db in [&real_db, &fake_db] {
assert_eq!(
db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[None, None, None]
);
db.write([("key-1", "one"), ("key-3", "three")]).unwrap();
assert_eq!(
db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[
Some("one".as_bytes().to_vec()),
None,
Some("three".as_bytes().to_vec())
]
);
db.delete(["key-3", "key-4"]).unwrap();
assert_eq!(
db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[Some("one".as_bytes().to_vec()), None, None,]
);
}
drop(real_db);
let real_db = Db::open(dir.path().join("test.db")).unwrap();
assert_eq!(
real_db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[Some("one".as_bytes().to_vec()), None, None,]
);
}
}
+68 -5
View File
@@ -1,3 +1,4 @@
mod db;
pub mod fs;
mod ignore;
mod lsp_command;
@@ -53,6 +54,7 @@ use std::{
use thiserror::Error;
use util::{post_inc, ResultExt, TryFutureExt as _};
pub use db::Db;
pub use fs::*;
pub use worktree::*;
@@ -60,8 +62,8 @@ pub trait Item: Entity {
fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
}
#[derive(Default)]
pub struct ProjectStore {
db: Arc<Db>,
projects: Vec<WeakModelHandle<Project>>,
}
@@ -533,7 +535,7 @@ impl Project {
let http_client = client::test::FakeHttpClient::with_404_response();
let client = client::Client::new(http_client.clone());
let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
let project_store = cx.add_model(|_| ProjectStore::default());
let project_store = cx.add_model(|_| ProjectStore::new(Db::open_fake()));
let project = cx.update(|cx| {
Project::local(true, client, user_store, project_store, languages, fs, cx)
});
@@ -568,6 +570,10 @@ impl Project {
self.user_store.clone()
}
pub fn project_store(&self) -> ModelHandle<ProjectStore> {
self.project_store.clone()
}
#[cfg(any(test, feature = "test-support"))]
pub fn check_invariants(&self, cx: &AppContext) {
if self.is_local() {
@@ -743,9 +749,6 @@ impl Project {
}
fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
cx.notify();
self.project_store.update(cx, |_, cx| cx.notify());
if let ProjectClientState::Local {
remote_id_rx,
public_rx,
@@ -768,6 +771,9 @@ impl Project {
})
.log_err();
}
self.project_store.update(cx, |_, cx| cx.notify());
cx.notify();
}
}
@@ -5215,6 +5221,13 @@ impl Project {
}
impl ProjectStore {
pub fn new(db: Arc<Db>) -> Self {
Self {
db,
projects: Default::default(),
}
}
pub fn projects<'a>(
&'a self,
cx: &'a AppContext,
@@ -5248,6 +5261,56 @@ impl ProjectStore {
cx.notify();
}
}
pub fn are_all_project_paths_public(
&self,
project: &Project,
cx: &AppContext,
) -> Task<Result<bool>> {
let project_path_keys = self.project_path_keys(project, cx);
let db = self.db.clone();
cx.background().spawn(async move {
let values = db.read(project_path_keys)?;
Ok(values.into_iter().all(|e| e.is_some()))
})
}
pub fn set_project_paths_public(
&self,
project: &Project,
public: bool,
cx: &AppContext,
) -> Task<Result<()>> {
let project_path_keys = self.project_path_keys(project, cx);
let db = self.db.clone();
cx.background().spawn(async move {
if public {
db.write(project_path_keys.into_iter().map(|key| (key, &[])))
} else {
db.delete(project_path_keys)
}
})
}
fn project_path_keys(&self, project: &Project, cx: &AppContext) -> Vec<String> {
project
.worktrees
.iter()
.filter_map(|worktree| {
worktree.upgrade(&cx).map(|worktree| {
format!(
"public-project-path:{}",
worktree
.read(cx)
.as_local()
.unwrap()
.abs_path()
.to_string_lossy()
)
})
})
.collect::<Vec<_>>()
}
}
impl WorktreeHandle {