Get the server and integration tests compiling

This commit is contained in:
Max Brunsfeld 2021-12-20 16:30:29 -08:00
parent 466a377e1d
commit 55910c0d79
8 changed files with 840 additions and 665 deletions

View file

@ -8,7 +8,9 @@ use clock::ReplicaId;
use collections::HashMap; use collections::HashMap;
use futures::Future; use futures::Future;
use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet}; use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
use gpui::{AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task}; use gpui::{
AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task,
};
use language::{Buffer, DiagnosticEntry, LanguageRegistry}; use language::{Buffer, DiagnosticEntry, LanguageRegistry};
use lsp::DiagnosticSeverity; use lsp::DiagnosticSeverity;
use postage::{prelude::Stream, watch}; use postage::{prelude::Stream, watch};
@ -42,6 +44,7 @@ enum ProjectClientState {
_maintain_remote_id_task: Task<Option<()>>, _maintain_remote_id_task: Task<Option<()>>,
}, },
Remote { Remote {
sharing_has_stopped: bool,
remote_id: u64, remote_id: u64,
replica_id: ReplicaId, replica_id: ReplicaId,
}, },
@ -106,59 +109,61 @@ pub struct ProjectEntry {
impl Project { impl Project {
pub fn local( pub fn local(
languages: Arc<LanguageRegistry>,
client: Arc<Client>, client: Arc<Client>,
user_store: ModelHandle<UserStore>, user_store: ModelHandle<UserStore>,
languages: Arc<LanguageRegistry>,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
cx: &mut ModelContext<Self>, cx: &mut MutableAppContext,
) -> Self { ) -> ModelHandle<Self> {
let (remote_id_tx, remote_id_rx) = watch::channel(); cx.add_model(|cx: &mut ModelContext<Self>| {
let _maintain_remote_id_task = cx.spawn_weak({ let (remote_id_tx, remote_id_rx) = watch::channel();
let rpc = client.clone(); let _maintain_remote_id_task = cx.spawn_weak({
move |this, mut cx| { let rpc = client.clone();
async move { move |this, mut cx| {
let mut status = rpc.status(); async move {
while let Some(status) = status.recv().await { let mut status = rpc.status();
if let Some(this) = this.upgrade(&cx) { while let Some(status) = status.recv().await {
let remote_id = if let client::Status::Connected { .. } = status { if let Some(this) = this.upgrade(&cx) {
let response = rpc.request(proto::RegisterProject {}).await?; let remote_id = if let client::Status::Connected { .. } = status {
Some(response.project_id) let response = rpc.request(proto::RegisterProject {}).await?;
} else { Some(response.project_id)
None } else {
}; None
this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx)); };
this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx));
}
} }
Ok(())
} }
Ok(()) .log_err()
} }
.log_err() });
}
});
Self { Self {
worktrees: Default::default(), worktrees: Default::default(),
collaborators: Default::default(), collaborators: Default::default(),
client_state: ProjectClientState::Local { client_state: ProjectClientState::Local {
is_shared: false, is_shared: false,
remote_id_tx, remote_id_tx,
remote_id_rx, remote_id_rx,
_maintain_remote_id_task, _maintain_remote_id_task,
}, },
subscriptions: Vec::new(), subscriptions: Vec::new(),
active_worktree: None, active_worktree: None,
active_entry: None, active_entry: None,
languages, languages,
client, client,
user_store, user_store,
fs, fs,
} }
})
} }
pub async fn open_remote( pub async fn remote(
remote_id: u64, remote_id: u64,
languages: Arc<LanguageRegistry>,
client: Arc<Client>, client: Arc<Client>,
user_store: ModelHandle<UserStore>, user_store: ModelHandle<UserStore>,
languages: Arc<LanguageRegistry>,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
cx: &mut AsyncAppContext, cx: &mut AsyncAppContext,
) -> Result<ModelHandle<Self>> { ) -> Result<ModelHandle<Self>> {
@ -211,6 +216,7 @@ impl Project {
user_store, user_store,
fs, fs,
subscriptions: vec![ subscriptions: vec![
client.subscribe_to_entity(remote_id, cx, Self::handle_unshare_project),
client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator), client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator), client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
client.subscribe_to_entity(remote_id, cx, Self::handle_share_worktree), client.subscribe_to_entity(remote_id, cx, Self::handle_share_worktree),
@ -221,6 +227,7 @@ impl Project {
], ],
client, client,
client_state: ProjectClientState::Remote { client_state: ProjectClientState::Remote {
sharing_has_stopped: false,
remote_id, remote_id,
replica_id, replica_id,
}, },
@ -252,6 +259,27 @@ impl Project {
} }
} }
pub fn next_remote_id(&self) -> impl Future<Output = u64> {
let mut id = None;
let mut watch = None;
match &self.client_state {
ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
}
async move {
if let Some(id) = id {
return id;
}
let mut watch = watch.unwrap();
loop {
if let Some(Some(id)) = watch.recv().await {
return id;
}
}
}
}
pub fn replica_id(&self) -> ReplicaId { pub fn replica_id(&self) -> ReplicaId {
match &self.client_state { match &self.client_state {
ProjectClientState::Local { .. } => 0, ProjectClientState::Local { .. } => 0,
@ -277,7 +305,7 @@ impl Project {
pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> { pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
let rpc = self.client.clone(); let rpc = self.client.clone();
cx.spawn(|this, mut cx| async move { cx.spawn(|this, mut cx| async move {
let remote_id = this.update(&mut cx, |this, _| { let project_id = this.update(&mut cx, |this, _| {
if let ProjectClientState::Local { if let ProjectClientState::Local {
is_shared, is_shared,
remote_id_rx, remote_id_rx,
@ -285,25 +313,22 @@ impl Project {
} = &mut this.client_state } = &mut this.client_state
{ {
*is_shared = true; *is_shared = true;
Ok(*remote_id_rx.borrow()) remote_id_rx
.borrow()
.ok_or_else(|| anyhow!("no project id"))
} else { } else {
Err(anyhow!("can't share a remote project")) Err(anyhow!("can't share a remote project"))
} }
})?; })?;
let remote_id = remote_id.ok_or_else(|| anyhow!("no project id"))?; rpc.send(proto::ShareProject { project_id }).await?;
rpc.send(proto::ShareProject {
project_id: remote_id,
})
.await?;
this.update(&mut cx, |this, cx| { this.update(&mut cx, |this, cx| {
for worktree in &this.worktrees { for worktree in &this.worktrees {
worktree.update(cx, |worktree, cx| { worktree.update(cx, |worktree, cx| {
worktree worktree
.as_local_mut() .as_local_mut()
.unwrap() .unwrap()
.share(remote_id, cx) .share(project_id, cx)
.detach(); .detach();
}); });
} }
@ -312,6 +337,41 @@ impl Project {
}) })
} }
pub fn unshare(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
let rpc = self.client.clone();
cx.spawn(|this, mut cx| async move {
let project_id = this.update(&mut cx, |this, _| {
if let ProjectClientState::Local {
is_shared,
remote_id_rx,
..
} = &mut this.client_state
{
*is_shared = true;
remote_id_rx
.borrow()
.ok_or_else(|| anyhow!("no project id"))
} else {
Err(anyhow!("can't share a remote project"))
}
})?;
rpc.send(proto::UnshareProject { project_id }).await?;
Ok(())
})
}
pub fn is_read_only(&self) -> bool {
match &self.client_state {
ProjectClientState::Local { .. } => false,
ProjectClientState::Remote {
sharing_has_stopped,
..
} => *sharing_has_stopped,
}
}
pub fn open_buffer( pub fn open_buffer(
&self, &self,
path: ProjectPath, path: ProjectPath,
@ -333,14 +393,14 @@ impl Project {
pub fn add_local_worktree( pub fn add_local_worktree(
&mut self, &mut self,
abs_path: &Path, abs_path: impl AsRef<Path>,
cx: &mut ModelContext<Self>, cx: &mut ModelContext<Self>,
) -> Task<Result<ModelHandle<Worktree>>> { ) -> Task<Result<ModelHandle<Worktree>>> {
let fs = self.fs.clone(); let fs = self.fs.clone();
let client = self.client.clone(); let client = self.client.clone();
let user_store = self.user_store.clone(); let user_store = self.user_store.clone();
let languages = self.languages.clone(); let languages = self.languages.clone();
let path = Arc::from(abs_path); let path = Arc::from(abs_path.as_ref());
cx.spawn(|project, mut cx| async move { cx.spawn(|project, mut cx| async move {
let worktree = let worktree =
Worktree::open_local(client.clone(), user_store, path, fs, languages, &mut cx) Worktree::open_local(client.clone(), user_store, path, fs, languages, &mut cx)
@ -352,10 +412,12 @@ impl Project {
}); });
if let Some(project_id) = remote_project_id { if let Some(project_id) = remote_project_id {
let worktree_id = worktree.id() as u64;
let register_message = worktree.update(&mut cx, |worktree, _| { let register_message = worktree.update(&mut cx, |worktree, _| {
let worktree = worktree.as_local_mut().unwrap(); let worktree = worktree.as_local_mut().unwrap();
proto::RegisterWorktree { proto::RegisterWorktree {
project_id, project_id,
worktree_id,
root_name: worktree.root_name().to_string(), root_name: worktree.root_name().to_string(),
authorized_logins: worktree.authorized_logins(), authorized_logins: worktree.authorized_logins(),
} }
@ -432,6 +494,25 @@ impl Project {
// RPC message handlers // RPC message handlers
fn handle_unshare_project(
&mut self,
_: TypedEnvelope<proto::UnshareProject>,
_: Arc<Client>,
cx: &mut ModelContext<Self>,
) -> Result<()> {
if let ProjectClientState::Remote {
sharing_has_stopped,
..
} = &mut self.client_state
{
*sharing_has_stopped = true;
cx.notify();
Ok(())
} else {
unreachable!()
}
}
fn handle_add_collaborator( fn handle_add_collaborator(
&mut self, &mut self,
mut envelope: TypedEnvelope<proto::AddProjectCollaborator>, mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
@ -812,6 +893,6 @@ mod tests {
let client = client::Client::new(); let client = client::Client::new();
let http_client = FakeHttpClient::new(|_| async move { Ok(ServerResponse::new(404)) }); let http_client = FakeHttpClient::new(|_| async move { Ok(ServerResponse::new(404)) });
let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx)); let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
cx.add_model(|cx| Project::local(languages, client, user_store, fs, cx)) cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
} }
} }

View file

@ -617,18 +617,18 @@ mod tests {
) )
.await; .await;
let project = cx.add_model(|cx| { let project = cx.update(|cx| {
Project::local( Project::local(
params.languages.clone(),
params.client.clone(), params.client.clone(),
params.user_store.clone(), params.user_store.clone(),
params.languages.clone(),
params.fs.clone(), params.fs.clone(),
cx, cx,
) )
}); });
let root1 = project let root1 = project
.update(&mut cx, |project, cx| { .update(&mut cx, |project, cx| {
project.add_local_worktree("/root1".as_ref(), cx) project.add_local_worktree("/root1", cx)
}) })
.await .await
.unwrap(); .unwrap();
@ -637,7 +637,7 @@ mod tests {
.await; .await;
let root2 = project let root2 = project
.update(&mut cx, |project, cx| { .update(&mut cx, |project, cx| {
project.add_local_worktree("/root2".as_ref(), cx) project.add_local_worktree("/root2", cx)
}) })
.await .await
.unwrap(); .unwrap();

View file

@ -96,8 +96,9 @@ message LeaveProject {
message RegisterWorktree { message RegisterWorktree {
uint64 project_id = 1; uint64 project_id = 1;
string root_name = 2; uint64 worktree_id = 2;
repeated string authorized_logins = 3; string root_name = 3;
repeated string authorized_logins = 4;
} }
message UnregisterWorktree { message UnregisterWorktree {

View file

@ -186,6 +186,7 @@ entity_messages!(
SaveBuffer, SaveBuffer,
ShareWorktree, ShareWorktree,
UnregisterWorktree, UnregisterWorktree,
UnshareProject,
UpdateBuffer, UpdateBuffer,
UpdateWorktree, UpdateWorktree,
); );

View file

@ -443,7 +443,9 @@ impl Db {
macro_rules! id_type { macro_rules! id_type {
($name:ident) => { ($name:ident) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, sqlx::Type, Serialize)] #[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, sqlx::Type, Serialize,
)]
#[sqlx(transparent)] #[sqlx(transparent)]
#[serde(transparent)] #[serde(transparent)]
pub struct $name(pub i32); pub struct $name(pub i32);

File diff suppressed because it is too large Load diff

View file

@ -11,7 +11,7 @@ pub struct Store {
projects: HashMap<u64, Project>, projects: HashMap<u64, Project>,
visible_projects_by_user_id: HashMap<UserId, HashSet<u64>>, visible_projects_by_user_id: HashMap<UserId, HashSet<u64>>,
channels: HashMap<ChannelId, Channel>, channels: HashMap<ChannelId, Channel>,
next_worktree_id: u64, next_project_id: u64,
} }
struct ConnectionState { struct ConnectionState {
@ -24,19 +24,19 @@ pub struct Project {
pub host_connection_id: ConnectionId, pub host_connection_id: ConnectionId,
pub host_user_id: UserId, pub host_user_id: UserId,
pub share: Option<ProjectShare>, pub share: Option<ProjectShare>,
worktrees: HashMap<u64, Worktree>, pub worktrees: HashMap<u64, Worktree>,
} }
pub struct Worktree { pub struct Worktree {
pub authorized_user_ids: Vec<UserId>, pub authorized_user_ids: Vec<UserId>,
pub root_name: String, pub root_name: String,
pub share: Option<WorktreeShare>,
} }
#[derive(Default)] #[derive(Default)]
pub struct ProjectShare { pub struct ProjectShare {
pub guests: HashMap<ConnectionId, (ReplicaId, UserId)>, pub guests: HashMap<ConnectionId, (ReplicaId, UserId)>,
pub active_replica_ids: HashSet<ReplicaId>, pub active_replica_ids: HashSet<ReplicaId>,
pub worktrees: HashMap<u64, WorktreeShare>,
} }
pub struct WorktreeShare { pub struct WorktreeShare {
@ -57,9 +57,9 @@ pub struct RemovedConnectionState {
pub contact_ids: HashSet<UserId>, pub contact_ids: HashSet<UserId>,
} }
pub struct JoinedWorktree<'a> { pub struct JoinedProject<'a> {
pub replica_id: ReplicaId, pub replica_id: ReplicaId,
pub worktree: &'a Worktree, pub project: &'a Project,
} }
pub struct UnsharedWorktree { pub struct UnsharedWorktree {
@ -67,7 +67,7 @@ pub struct UnsharedWorktree {
pub authorized_user_ids: Vec<UserId>, pub authorized_user_ids: Vec<UserId>,
} }
pub struct LeftWorktree { pub struct LeftProject {
pub connection_ids: Vec<ConnectionId>, pub connection_ids: Vec<ConnectionId>,
pub authorized_user_ids: Vec<UserId>, pub authorized_user_ids: Vec<UserId>,
} }
@ -114,17 +114,17 @@ impl Store {
} }
let mut result = RemovedConnectionState::default(); let mut result = RemovedConnectionState::default();
for worktree_id in connection.worktrees.clone() { for project_id in connection.projects.clone() {
if let Ok(worktree) = self.unregister_worktree(worktree_id, connection_id) { if let Some((project, authorized_user_ids)) =
self.unregister_project(project_id, connection_id)
{
result.contact_ids.extend(authorized_user_ids);
result.hosted_projects.insert(project_id, project);
} else if let Some(project) = self.leave_project(connection_id, project_id) {
result result
.contact_ids .guest_project_ids
.extend(worktree.authorized_user_ids.iter().copied()); .insert(project_id, project.connection_ids);
result.hosted_worktrees.insert(worktree_id, worktree); result.contact_ids.extend(project.authorized_user_ids);
} else if let Some(worktree) = self.leave_worktree(connection_id, worktree_id) {
result
.guest_worktree_ids
.insert(worktree_id, worktree.connection_ids);
result.contact_ids.extend(worktree.authorized_user_ids);
} }
} }
@ -191,7 +191,7 @@ impl Store {
let project = &self.projects[project_id]; let project = &self.projects[project_id];
let mut guests = HashSet::default(); let mut guests = HashSet::default();
if let Ok(share) = worktree.share() { if let Ok(share) = project.share() {
for guest_connection_id in share.guests.keys() { for guest_connection_id in share.guests.keys() {
if let Ok(user_id) = self.user_id_for_connection(*guest_connection_id) { if let Ok(user_id) = self.user_id_for_connection(*guest_connection_id) {
guests.insert(user_id.to_proto()); guests.insert(user_id.to_proto());
@ -200,6 +200,12 @@ impl Store {
} }
if let Ok(host_user_id) = self.user_id_for_connection(project.host_connection_id) { if let Ok(host_user_id) = self.user_id_for_connection(project.host_connection_id) {
let mut worktree_root_names = project
.worktrees
.values()
.map(|worktree| worktree.root_name.clone())
.collect::<Vec<_>>();
worktree_root_names.sort_unstable();
contacts contacts
.entry(host_user_id) .entry(host_user_id)
.or_insert_with(|| proto::Contact { .or_insert_with(|| proto::Contact {
@ -209,11 +215,7 @@ impl Store {
.projects .projects
.push(proto::ProjectMetadata { .push(proto::ProjectMetadata {
id: *project_id, id: *project_id,
worktree_root_names: project worktree_root_names,
.worktrees
.iter()
.map(|worktree| worktree.root_name.clone())
.collect(),
is_shared: project.share.is_some(), is_shared: project.share.is_some(),
guests: guests.into_iter().collect(), guests: guests.into_iter().collect(),
}); });
@ -268,7 +270,20 @@ impl Store {
} }
} }
pub fn unregister_project(&mut self, project_id: u64) { pub fn unregister_project(
&mut self,
project_id: u64,
connection_id: ConnectionId,
) -> Option<(Project, Vec<UserId>)> {
match self.projects.entry(project_id) {
hash_map::Entry::Occupied(e) => {
if e.get().host_connection_id != connection_id {
return None;
}
}
hash_map::Entry::Vacant(_) => return None,
}
todo!() todo!()
} }
@ -277,7 +292,7 @@ impl Store {
project_id: u64, project_id: u64,
worktree_id: u64, worktree_id: u64,
acting_connection_id: ConnectionId, acting_connection_id: ConnectionId,
) -> tide::Result<Worktree> { ) -> tide::Result<(Worktree, Vec<ConnectionId>)> {
let project = self let project = self
.projects .projects
.get_mut(&project_id) .get_mut(&project_id)
@ -291,31 +306,25 @@ impl Store {
.remove(&worktree_id) .remove(&worktree_id)
.ok_or_else(|| anyhow!("no such worktree"))?; .ok_or_else(|| anyhow!("no such worktree"))?;
if let Some(connection) = self.connections.get_mut(&project.host_connection_id) { let mut guest_connection_ids = Vec::new();
connection.worktrees.remove(&worktree_id); if let Some(share) = &project.share {
} guest_connection_ids.extend(share.guests.keys());
if let Some(share) = &worktree.share {
for connection_id in share.guests.keys() {
if let Some(connection) = self.connections.get_mut(connection_id) {
connection.worktrees.remove(&worktree_id);
}
}
} }
for authorized_user_id in &worktree.authorized_user_ids { for authorized_user_id in &worktree.authorized_user_ids {
if let Some(visible_worktrees) = self if let Some(visible_projects) =
.visible_worktrees_by_user_id self.visible_projects_by_user_id.get_mut(authorized_user_id)
.get_mut(&authorized_user_id)
{ {
visible_worktrees.remove(&worktree_id); if !project.has_authorized_user_id(*authorized_user_id) {
visible_projects.remove(&project_id);
}
} }
} }
#[cfg(test)] #[cfg(test)]
self.check_invariants(); self.check_invariants();
Ok(worktree) Ok((worktree, guest_connection_ids))
} }
pub fn share_project(&mut self, project_id: u64, connection_id: ConnectionId) -> bool { pub fn share_project(&mut self, project_id: u64, connection_id: ConnectionId) -> bool {
@ -328,47 +337,27 @@ impl Store {
false false
} }
pub fn share_worktree( pub fn unshare_project(
&mut self, &mut self,
project_id: u64, project_id: u64,
worktree_id: u64,
connection_id: ConnectionId,
entries: HashMap<u64, proto::Entry>,
) -> Option<Vec<UserId>> {
if let Some(project) = self.projects.get_mut(&project_id) {
if project.host_connection_id == connection_id {
if let Some(share) = project.share.as_mut() {
share
.worktrees
.insert(worktree_id, WorktreeShare { entries });
return Some(project.authorized_user_ids());
}
}
}
None
}
pub fn unshare_worktree(
&mut self,
worktree_id: u64,
acting_connection_id: ConnectionId, acting_connection_id: ConnectionId,
) -> tide::Result<UnsharedWorktree> { ) -> tide::Result<UnsharedWorktree> {
let worktree = if let Some(worktree) = self.worktrees.get_mut(&worktree_id) { let project = if let Some(project) = self.projects.get_mut(&project_id) {
worktree project
} else { } else {
return Err(anyhow!("no such worktree"))?; return Err(anyhow!("no such project"))?;
}; };
if worktree.host_connection_id != acting_connection_id { if project.host_connection_id != acting_connection_id {
return Err(anyhow!("not your worktree"))?; return Err(anyhow!("not your project"))?;
} }
let connection_ids = worktree.connection_ids(); let connection_ids = project.connection_ids();
let authorized_user_ids = worktree.authorized_user_ids.clone(); let authorized_user_ids = project.authorized_user_ids();
if let Some(share) = worktree.share.take() { if let Some(share) = project.share.take() {
for connection_id in share.guests.into_keys() { for connection_id in share.guests.into_keys() {
if let Some(connection) = self.connections.get_mut(&connection_id) { if let Some(connection) = self.connections.get_mut(&connection_id) {
connection.worktrees.remove(&worktree_id); connection.projects.remove(&project_id);
} }
} }
@ -380,34 +369,51 @@ impl Store {
authorized_user_ids, authorized_user_ids,
}) })
} else { } else {
Err(anyhow!("worktree is not shared"))? Err(anyhow!("project is not shared"))?
} }
} }
pub fn join_worktree( pub fn share_worktree(
&mut self,
project_id: u64,
worktree_id: u64,
connection_id: ConnectionId,
entries: HashMap<u64, proto::Entry>,
) -> Option<Vec<UserId>> {
let project = self.projects.get_mut(&project_id)?;
let worktree = project.worktrees.get_mut(&worktree_id)?;
if project.host_connection_id == connection_id && project.share.is_some() {
worktree.share = Some(WorktreeShare { entries });
Some(project.authorized_user_ids())
} else {
None
}
}
pub fn join_project(
&mut self, &mut self,
connection_id: ConnectionId, connection_id: ConnectionId,
user_id: UserId, user_id: UserId,
worktree_id: u64, project_id: u64,
) -> tide::Result<JoinedWorktree> { ) -> tide::Result<JoinedProject> {
let connection = self let connection = self
.connections .connections
.get_mut(&connection_id) .get_mut(&connection_id)
.ok_or_else(|| anyhow!("no such connection"))?; .ok_or_else(|| anyhow!("no such connection"))?;
let worktree = self let project = self
.worktrees .projects
.get_mut(&worktree_id) .get_mut(&project_id)
.and_then(|worktree| { .and_then(|project| {
if worktree.authorized_user_ids.contains(&user_id) { if project.has_authorized_user_id(user_id) {
Some(worktree) Some(project)
} else { } else {
None None
} }
}) })
.ok_or_else(|| anyhow!("no such worktree"))?; .ok_or_else(|| anyhow!("no such project"))?;
let share = worktree.share_mut()?; let share = project.share_mut()?;
connection.worktrees.insert(worktree_id); connection.projects.insert(project_id);
let mut replica_id = 1; let mut replica_id = 1;
while share.active_replica_ids.contains(&replica_id) { while share.active_replica_ids.contains(&replica_id) {
@ -419,33 +425,33 @@ impl Store {
#[cfg(test)] #[cfg(test)]
self.check_invariants(); self.check_invariants();
Ok(JoinedWorktree { Ok(JoinedProject {
replica_id, replica_id,
worktree: &self.worktrees[&worktree_id], project: &self.projects[&project_id],
}) })
} }
pub fn leave_worktree( pub fn leave_project(
&mut self, &mut self,
connection_id: ConnectionId, connection_id: ConnectionId,
worktree_id: u64, project_id: u64,
) -> Option<LeftWorktree> { ) -> Option<LeftProject> {
let worktree = self.worktrees.get_mut(&worktree_id)?; let project = self.projects.get_mut(&project_id)?;
let share = worktree.share.as_mut()?; let share = project.share.as_mut()?;
let (replica_id, _) = share.guests.remove(&connection_id)?; let (replica_id, _) = share.guests.remove(&connection_id)?;
share.active_replica_ids.remove(&replica_id); share.active_replica_ids.remove(&replica_id);
if let Some(connection) = self.connections.get_mut(&connection_id) { if let Some(connection) = self.connections.get_mut(&connection_id) {
connection.worktrees.remove(&worktree_id); connection.projects.remove(&project_id);
} }
let connection_ids = worktree.connection_ids(); let connection_ids = project.connection_ids();
let authorized_user_ids = worktree.authorized_user_ids.clone(); let authorized_user_ids = project.authorized_user_ids();
#[cfg(test)] #[cfg(test)]
self.check_invariants(); self.check_invariants();
Some(LeftWorktree { Some(LeftProject {
connection_ids, connection_ids,
authorized_user_ids, authorized_user_ids,
}) })
@ -454,115 +460,75 @@ impl Store {
pub fn update_worktree( pub fn update_worktree(
&mut self, &mut self,
connection_id: ConnectionId, connection_id: ConnectionId,
project_id: u64,
worktree_id: u64, worktree_id: u64,
removed_entries: &[u64], removed_entries: &[u64],
updated_entries: &[proto::Entry], updated_entries: &[proto::Entry],
) -> tide::Result<Vec<ConnectionId>> { ) -> Option<Vec<ConnectionId>> {
let worktree = self.write_worktree(worktree_id, connection_id)?; let project = self.write_project(project_id, connection_id)?;
let share = worktree.share_mut()?; let share = project.worktrees.get_mut(&worktree_id)?.share.as_mut()?;
for entry_id in removed_entries { for entry_id in removed_entries {
share.entries.remove(&entry_id); share.entries.remove(&entry_id);
} }
for entry in updated_entries { for entry in updated_entries {
share.entries.insert(entry.id, entry.clone()); share.entries.insert(entry.id, entry.clone());
} }
Ok(worktree.connection_ids()) Some(project.connection_ids())
} }
pub fn worktree_host_connection_id( pub fn project_connection_ids(
&self, &self,
connection_id: ConnectionId, project_id: u64,
worktree_id: u64, acting_connection_id: ConnectionId,
) -> tide::Result<ConnectionId> { ) -> Option<Vec<ConnectionId>> {
Ok(self Some(
.read_worktree(worktree_id, connection_id)? self.read_project(project_id, acting_connection_id)?
.host_connection_id) .connection_ids(),
} )
pub fn worktree_guest_connection_ids(
&self,
connection_id: ConnectionId,
worktree_id: u64,
) -> tide::Result<Vec<ConnectionId>> {
Ok(self
.read_worktree(worktree_id, connection_id)?
.share()?
.guests
.keys()
.copied()
.collect())
}
pub fn worktree_connection_ids(
&self,
connection_id: ConnectionId,
worktree_id: u64,
) -> tide::Result<Vec<ConnectionId>> {
Ok(self
.read_worktree(worktree_id, connection_id)?
.connection_ids())
} }
pub fn channel_connection_ids(&self, channel_id: ChannelId) -> Option<Vec<ConnectionId>> { pub fn channel_connection_ids(&self, channel_id: ChannelId) -> Option<Vec<ConnectionId>> {
Some(self.channels.get(&channel_id)?.connection_ids()) Some(self.channels.get(&channel_id)?.connection_ids())
} }
fn read_worktree( pub fn read_project(&self, project_id: u64, connection_id: ConnectionId) -> Option<&Project> {
&self, let project = self.projects.get(&project_id)?;
worktree_id: u64, if project.host_connection_id == connection_id
connection_id: ConnectionId, || project.share.as_ref()?.guests.contains_key(&connection_id)
) -> tide::Result<&Worktree> {
let worktree = self
.worktrees
.get(&worktree_id)
.ok_or_else(|| anyhow!("worktree not found"))?;
if worktree.host_connection_id == connection_id
|| worktree.share()?.guests.contains_key(&connection_id)
{ {
Ok(worktree) Some(project)
} else { } else {
Err(anyhow!( None
"{} is not a member of worktree {}",
connection_id,
worktree_id
))?
} }
} }
fn write_worktree( fn write_project(
&mut self, &mut self,
worktree_id: u64, project_id: u64,
connection_id: ConnectionId, connection_id: ConnectionId,
) -> tide::Result<&mut Worktree> { ) -> Option<&mut Project> {
let worktree = self let project = self.projects.get_mut(&project_id)?;
.worktrees if project.host_connection_id == connection_id
.get_mut(&worktree_id) || project.share.as_ref()?.guests.contains_key(&connection_id)
.ok_or_else(|| anyhow!("worktree not found"))?;
if worktree.host_connection_id == connection_id
|| worktree
.share
.as_ref()
.map_or(false, |share| share.guests.contains_key(&connection_id))
{ {
Ok(worktree) Some(project)
} else { } else {
Err(anyhow!( None
"{} is not a member of worktree {}",
connection_id,
worktree_id
))?
} }
} }
#[cfg(test)] #[cfg(test)]
fn check_invariants(&self) { fn check_invariants(&self) {
for (connection_id, connection) in &self.connections { for (connection_id, connection) in &self.connections {
for worktree_id in &connection.worktrees { for project_id in &connection.projects {
let worktree = &self.worktrees.get(&worktree_id).unwrap(); let project = &self.projects.get(&project_id).unwrap();
if worktree.host_connection_id != *connection_id { if project.host_connection_id != *connection_id {
assert!(worktree.share().unwrap().guests.contains_key(connection_id)); assert!(project
.share
.as_ref()
.unwrap()
.guests
.contains_key(connection_id));
} }
} }
for channel_id in &connection.channels { for channel_id in &connection.channels {
@ -585,22 +551,22 @@ impl Store {
} }
} }
for (worktree_id, worktree) in &self.worktrees { for (project_id, project) in &self.projects {
let host_connection = self.connections.get(&worktree.host_connection_id).unwrap(); let host_connection = self.connections.get(&project.host_connection_id).unwrap();
assert!(host_connection.worktrees.contains(worktree_id)); assert!(host_connection.projects.contains(project_id));
for authorized_user_ids in &worktree.authorized_user_ids { for authorized_user_ids in project.authorized_user_ids() {
let visible_worktree_ids = self let visible_project_ids = self
.visible_worktrees_by_user_id .visible_projects_by_user_id
.get(authorized_user_ids) .get(&authorized_user_ids)
.unwrap(); .unwrap();
assert!(visible_worktree_ids.contains(worktree_id)); assert!(visible_project_ids.contains(project_id));
} }
if let Some(share) = &worktree.share { if let Some(share) = &project.share {
for guest_connection_id in share.guests.keys() { for guest_connection_id in share.guests.keys() {
let guest_connection = self.connections.get(guest_connection_id).unwrap(); let guest_connection = self.connections.get(guest_connection_id).unwrap();
assert!(guest_connection.worktrees.contains(worktree_id)); assert!(guest_connection.projects.contains(project_id));
} }
assert_eq!(share.active_replica_ids.len(), share.guests.len(),); assert_eq!(share.active_replica_ids.len(), share.guests.len(),);
assert_eq!( assert_eq!(
@ -614,10 +580,10 @@ impl Store {
} }
} }
for (user_id, visible_worktree_ids) in &self.visible_worktrees_by_user_id { for (user_id, visible_project_ids) in &self.visible_projects_by_user_id {
for worktree_id in visible_worktree_ids { for project_id in visible_project_ids {
let worktree = self.worktrees.get(worktree_id).unwrap(); let project = self.projects.get(project_id).unwrap();
assert!(worktree.authorized_user_ids.contains(user_id)); assert!(project.authorized_user_ids().contains(user_id));
} }
} }
@ -630,7 +596,33 @@ impl Store {
} }
} }
impl Worktree { impl Project {
pub fn has_authorized_user_id(&self, user_id: UserId) -> bool {
self.worktrees
.values()
.any(|worktree| worktree.authorized_user_ids.contains(&user_id))
}
pub fn authorized_user_ids(&self) -> Vec<UserId> {
let mut ids = self
.worktrees
.values()
.flat_map(|worktree| worktree.authorized_user_ids.iter())
.copied()
.collect::<Vec<_>>();
ids.sort_unstable();
ids.dedup();
ids
}
pub fn guest_connection_ids(&self) -> Vec<ConnectionId> {
if let Some(share) = &self.share {
share.guests.keys().copied().collect()
} else {
Vec::new()
}
}
pub fn connection_ids(&self) -> Vec<ConnectionId> { pub fn connection_ids(&self) -> Vec<ConnectionId> {
if let Some(share) = &self.share { if let Some(share) = &self.share {
share share

View file

@ -391,15 +391,13 @@ pub struct Workspace {
impl Workspace { impl Workspace {
pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self { pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
let project = cx.add_model(|cx| { let project = Project::local(
Project::local( params.client.clone(),
params.languages.clone(), params.user_store.clone(),
params.client.clone(), params.languages.clone(),
params.user_store.clone(), params.fs.clone(),
params.fs.clone(), cx,
cx, );
)
});
cx.observe(&project, |_, _, cx| cx.notify()).detach(); cx.observe(&project, |_, _, cx| cx.notify()).detach();
let pane = cx.add_view(|_| Pane::new(params.settings.clone())); let pane = cx.add_view(|_| Pane::new(params.settings.clone()));