This commit is contained in:
Max Brunsfeld 2023-08-02 12:15:06 -07:00
parent 61a6892b8c
commit a9de73739a
8 changed files with 289 additions and 100 deletions

View File

@ -1,13 +1,17 @@
use crate::{Client, Subscription, User, UserStore}; use crate::{Client, Subscription, User, UserStore};
use anyhow::Result; use anyhow::Result;
use collections::HashMap;
use futures::Future; use futures::Future;
use gpui::{AsyncAppContext, Entity, ModelContext, ModelHandle, Task}; use gpui::{AsyncAppContext, Entity, ModelContext, ModelHandle, Task};
use rpc::{proto, TypedEnvelope}; use rpc::{proto, TypedEnvelope};
use std::sync::Arc; use std::sync::Arc;
type ChannelId = u64;
pub struct ChannelStore { pub struct ChannelStore {
channels: Vec<Arc<Channel>>, channels: Vec<Arc<Channel>>,
channel_invitations: Vec<Arc<Channel>>, channel_invitations: Vec<Arc<Channel>>,
channel_participants: HashMap<ChannelId, Vec<ChannelId>>,
client: Arc<Client>, client: Arc<Client>,
user_store: ModelHandle<UserStore>, user_store: ModelHandle<UserStore>,
_rpc_subscription: Subscription, _rpc_subscription: Subscription,
@ -15,9 +19,9 @@ pub struct ChannelStore {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct Channel { pub struct Channel {
pub id: u64, pub id: ChannelId,
pub name: String, pub name: String,
pub parent_id: Option<u64>, pub parent_id: Option<ChannelId>,
pub depth: usize, pub depth: usize,
} }
@ -37,6 +41,7 @@ impl ChannelStore {
Self { Self {
channels: vec![], channels: vec![],
channel_invitations: vec![], channel_invitations: vec![],
channel_participants: Default::default(),
client, client,
user_store, user_store,
_rpc_subscription: rpc_subscription, _rpc_subscription: rpc_subscription,
@ -51,15 +56,15 @@ impl ChannelStore {
&self.channel_invitations &self.channel_invitations
} }
pub fn channel_for_id(&self, channel_id: u64) -> Option<Arc<Channel>> { pub fn channel_for_id(&self, channel_id: ChannelId) -> Option<Arc<Channel>> {
self.channels.iter().find(|c| c.id == channel_id).cloned() self.channels.iter().find(|c| c.id == channel_id).cloned()
} }
pub fn create_channel( pub fn create_channel(
&self, &self,
name: &str, name: &str,
parent_id: Option<u64>, parent_id: Option<ChannelId>,
) -> impl Future<Output = Result<u64>> { ) -> impl Future<Output = Result<ChannelId>> {
let client = self.client.clone(); let client = self.client.clone();
let name = name.to_owned(); let name = name.to_owned();
async move { async move {
@ -72,7 +77,7 @@ impl ChannelStore {
pub fn invite_member( pub fn invite_member(
&self, &self,
channel_id: u64, channel_id: ChannelId,
user_id: u64, user_id: u64,
admin: bool, admin: bool,
) -> impl Future<Output = Result<()>> { ) -> impl Future<Output = Result<()>> {
@ -91,7 +96,7 @@ impl ChannelStore {
pub fn respond_to_channel_invite( pub fn respond_to_channel_invite(
&mut self, &mut self,
channel_id: u64, channel_id: ChannelId,
accept: bool, accept: bool,
) -> impl Future<Output = Result<()>> { ) -> impl Future<Output = Result<()>> {
let client = self.client.clone(); let client = self.client.clone();
@ -107,7 +112,7 @@ impl ChannelStore {
false false
} }
pub fn remove_channel(&self, channel_id: u64) -> impl Future<Output = Result<()>> { pub fn remove_channel(&self, channel_id: ChannelId) -> impl Future<Output = Result<()>> {
let client = self.client.clone(); let client = self.client.clone();
async move { async move {
client.request(proto::RemoveChannel { channel_id }).await?; client.request(proto::RemoveChannel { channel_id }).await?;
@ -117,7 +122,7 @@ impl ChannelStore {
pub fn remove_member( pub fn remove_member(
&self, &self,
channel_id: u64, channel_id: ChannelId,
user_id: u64, user_id: u64,
cx: &mut ModelContext<Self>, cx: &mut ModelContext<Self>,
) -> Task<Result<()>> { ) -> Task<Result<()>> {
@ -126,13 +131,13 @@ impl ChannelStore {
pub fn channel_members( pub fn channel_members(
&self, &self,
channel_id: u64, channel_id: ChannelId,
cx: &mut ModelContext<Self>, cx: &mut ModelContext<Self>,
) -> Task<Result<Vec<Arc<User>>>> { ) -> Task<Result<Vec<Arc<User>>>> {
todo!() todo!()
} }
pub fn add_guest_channel(&self, channel_id: u64) -> Task<Result<()>> { pub fn add_guest_channel(&self, channel_id: ChannelId) -> Task<Result<()>> {
todo!() todo!()
} }

View File

@ -212,7 +212,13 @@ impl Database {
.map(|participant| participant.user_id), .map(|participant| participant.user_id),
); );
let room = self.get_room(room_id, &tx).await?; let (channel_id, room) = self.get_channel_room(room_id, &tx).await?;
let channel_members = if let Some(channel_id) = channel_id {
self.get_channel_members_internal(channel_id, &tx).await?
} else {
Vec::new()
};
// Delete the room if it becomes empty. // Delete the room if it becomes empty.
if room.participants.is_empty() { if room.participants.is_empty() {
project::Entity::delete_many() project::Entity::delete_many()
@ -224,6 +230,8 @@ impl Database {
Ok(RefreshedRoom { Ok(RefreshedRoom {
room, room,
channel_id,
channel_members,
stale_participant_user_ids, stale_participant_user_ids,
canceled_calls_to_user_ids, canceled_calls_to_user_ids,
}) })
@ -1178,7 +1186,7 @@ impl Database {
user_id: UserId, user_id: UserId,
connection: ConnectionId, connection: ConnectionId,
live_kit_room: &str, live_kit_room: &str,
) -> Result<ChannelRoom> { ) -> Result<proto::Room> {
self.transaction(|tx| async move { self.transaction(|tx| async move {
let room = room::ActiveModel { let room = room::ActiveModel {
live_kit_room: ActiveValue::set(live_kit_room.into()), live_kit_room: ActiveValue::set(live_kit_room.into()),
@ -1217,7 +1225,7 @@ impl Database {
calling_connection: ConnectionId, calling_connection: ConnectionId,
called_user_id: UserId, called_user_id: UserId,
initial_project_id: Option<ProjectId>, initial_project_id: Option<ProjectId>,
) -> Result<RoomGuard<(ChannelRoom, proto::IncomingCall)>> { ) -> Result<RoomGuard<(proto::Room, proto::IncomingCall)>> {
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
room_participant::ActiveModel { room_participant::ActiveModel {
room_id: ActiveValue::set(room_id), room_id: ActiveValue::set(room_id),
@ -1246,7 +1254,7 @@ impl Database {
&self, &self,
room_id: RoomId, room_id: RoomId,
called_user_id: UserId, called_user_id: UserId,
) -> Result<RoomGuard<ChannelRoom>> { ) -> Result<RoomGuard<proto::Room>> {
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
room_participant::Entity::delete_many() room_participant::Entity::delete_many()
.filter( .filter(
@ -1266,7 +1274,7 @@ impl Database {
&self, &self,
expected_room_id: Option<RoomId>, expected_room_id: Option<RoomId>,
user_id: UserId, user_id: UserId,
) -> Result<Option<RoomGuard<ChannelRoom>>> { ) -> Result<Option<RoomGuard<proto::Room>>> {
self.optional_room_transaction(|tx| async move { self.optional_room_transaction(|tx| async move {
let mut filter = Condition::all() let mut filter = Condition::all()
.add(room_participant::Column::UserId.eq(user_id)) .add(room_participant::Column::UserId.eq(user_id))
@ -1303,7 +1311,7 @@ impl Database {
room_id: RoomId, room_id: RoomId,
calling_connection: ConnectionId, calling_connection: ConnectionId,
called_user_id: UserId, called_user_id: UserId,
) -> Result<RoomGuard<ChannelRoom>> { ) -> Result<RoomGuard<proto::Room>> {
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
let participant = room_participant::Entity::find() let participant = room_participant::Entity::find()
.filter( .filter(
@ -1340,7 +1348,7 @@ impl Database {
user_id: UserId, user_id: UserId,
channel_id: Option<ChannelId>, channel_id: Option<ChannelId>,
connection: ConnectionId, connection: ConnectionId,
) -> Result<RoomGuard<ChannelRoom>> { ) -> Result<RoomGuard<JoinRoom>> {
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
if let Some(channel_id) = channel_id { if let Some(channel_id) = channel_id {
channel_member::Entity::find() channel_member::Entity::find()
@ -1396,7 +1404,16 @@ impl Database {
} }
let room = self.get_room(room_id, &tx).await?; let room = self.get_room(room_id, &tx).await?;
Ok(room) let channel_members = if let Some(channel_id) = channel_id {
self.get_channel_members_internal(channel_id, &tx).await?
} else {
Vec::new()
};
Ok(JoinRoom {
room,
channel_id,
channel_members,
})
}) })
.await .await
} }
@ -1690,9 +1707,18 @@ impl Database {
}); });
} }
let room = self.get_room(room_id, &tx).await?; let (channel_id, room) = self.get_channel_room(room_id, &tx).await?;
let channel_members = if let Some(channel_id) = channel_id {
self.get_channel_members_internal(channel_id, &tx).await?
} else {
Vec::new()
};
Ok(RejoinedRoom { Ok(RejoinedRoom {
room, room,
channel_id,
channel_members,
rejoined_projects, rejoined_projects,
reshared_projects, reshared_projects,
}) })
@ -1833,7 +1859,7 @@ impl Database {
.exec(&*tx) .exec(&*tx)
.await?; .await?;
let room = self.get_room(room_id, &tx).await?; let (channel_id, room) = self.get_channel_room(room_id, &tx).await?;
let deleted = if room.participants.is_empty() { let deleted = if room.participants.is_empty() {
let result = room::Entity::delete_by_id(room_id) let result = room::Entity::delete_by_id(room_id)
.filter(room::Column::ChannelId.is_null()) .filter(room::Column::ChannelId.is_null())
@ -1844,8 +1870,15 @@ impl Database {
false false
}; };
let channel_members = if let Some(channel_id) = channel_id {
self.get_channel_members_internal(channel_id, &tx).await?
} else {
Vec::new()
};
let left_room = LeftRoom { let left_room = LeftRoom {
room, room,
channel_id,
channel_members,
left_projects, left_projects,
canceled_calls_to_user_ids, canceled_calls_to_user_ids,
deleted, deleted,
@ -1868,7 +1901,7 @@ impl Database {
project_id: ProjectId, project_id: ProjectId,
leader_connection: ConnectionId, leader_connection: ConnectionId,
follower_connection: ConnectionId, follower_connection: ConnectionId,
) -> Result<RoomGuard<ChannelRoom>> { ) -> Result<RoomGuard<proto::Room>> {
let room_id = self.room_id_for_project(project_id).await?; let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
follower::ActiveModel { follower::ActiveModel {
@ -1898,7 +1931,7 @@ impl Database {
project_id: ProjectId, project_id: ProjectId,
leader_connection: ConnectionId, leader_connection: ConnectionId,
follower_connection: ConnectionId, follower_connection: ConnectionId,
) -> Result<RoomGuard<ChannelRoom>> { ) -> Result<RoomGuard<proto::Room>> {
let room_id = self.room_id_for_project(project_id).await?; let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
follower::Entity::delete_many() follower::Entity::delete_many()
@ -1930,7 +1963,7 @@ impl Database {
room_id: RoomId, room_id: RoomId,
connection: ConnectionId, connection: ConnectionId,
location: proto::ParticipantLocation, location: proto::ParticipantLocation,
) -> Result<RoomGuard<ChannelRoom>> { ) -> Result<RoomGuard<proto::Room>> {
self.room_transaction(room_id, |tx| async { self.room_transaction(room_id, |tx| async {
let tx = tx; let tx = tx;
let location_kind; let location_kind;
@ -2042,8 +2075,16 @@ impl Database {
}), }),
}) })
} }
async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
let (_, room) = self.get_channel_room(room_id, tx).await?;
Ok(room)
}
async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<ChannelRoom> { async fn get_channel_room(
&self,
room_id: RoomId,
tx: &DatabaseTransaction,
) -> Result<(Option<ChannelId>, proto::Room)> {
let db_room = room::Entity::find_by_id(room_id) let db_room = room::Entity::find_by_id(room_id)
.one(tx) .one(tx)
.await? .await?
@ -2147,6 +2188,28 @@ impl Database {
}); });
} }
Ok((
db_room.channel_id,
proto::Room {
id: db_room.id.to_proto(),
live_kit_room: db_room.live_kit_room,
participants: participants.into_values().collect(),
pending_participants,
followers,
},
))
}
async fn get_channel_members_for_room(
&self,
room_id: RoomId,
tx: &DatabaseTransaction,
) -> Result<Vec<UserId>> {
let db_room = room::Model {
id: room_id,
..Default::default()
};
let channel_users = let channel_users =
if let Some(channel) = db_room.find_related(channel::Entity).one(tx).await? { if let Some(channel) = db_room.find_related(channel::Entity).one(tx).await? {
self.get_channel_members_internal(channel.id, tx).await? self.get_channel_members_internal(channel.id, tx).await?
@ -2154,16 +2217,7 @@ impl Database {
Vec::new() Vec::new()
}; };
Ok(ChannelRoom { Ok(channel_users)
room: proto::Room {
id: db_room.id.to_proto(),
live_kit_room: db_room.live_kit_room,
participants: participants.into_values().collect(),
pending_participants,
followers,
},
channel_participants: channel_users,
})
} }
// projects // projects
@ -2193,7 +2247,7 @@ impl Database {
room_id: RoomId, room_id: RoomId,
connection: ConnectionId, connection: ConnectionId,
worktrees: &[proto::WorktreeMetadata], worktrees: &[proto::WorktreeMetadata],
) -> Result<RoomGuard<(ProjectId, ChannelRoom)>> { ) -> Result<RoomGuard<(ProjectId, proto::Room)>> {
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
let participant = room_participant::Entity::find() let participant = room_participant::Entity::find()
.filter( .filter(
@ -2264,7 +2318,7 @@ impl Database {
&self, &self,
project_id: ProjectId, project_id: ProjectId,
connection: ConnectionId, connection: ConnectionId,
) -> Result<RoomGuard<(ChannelRoom, Vec<ConnectionId>)>> { ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
let room_id = self.room_id_for_project(project_id).await?; let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?; let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
@ -2291,7 +2345,7 @@ impl Database {
project_id: ProjectId, project_id: ProjectId,
connection: ConnectionId, connection: ConnectionId,
worktrees: &[proto::WorktreeMetadata], worktrees: &[proto::WorktreeMetadata],
) -> Result<RoomGuard<(ChannelRoom, Vec<ConnectionId>)>> { ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
let room_id = self.room_id_for_project(project_id).await?; let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
let project = project::Entity::find_by_id(project_id) let project = project::Entity::find_by_id(project_id)
@ -2868,7 +2922,7 @@ impl Database {
&self, &self,
project_id: ProjectId, project_id: ProjectId,
connection: ConnectionId, connection: ConnectionId,
) -> Result<RoomGuard<(ChannelRoom, LeftProject)>> { ) -> Result<RoomGuard<(proto::Room, LeftProject)>> {
let room_id = self.room_id_for_project(project_id).await?; let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move { self.room_transaction(room_id, |tx| async move {
let result = project_collaborator::Entity::delete_many() let result = project_collaborator::Entity::delete_many()
@ -3342,7 +3396,10 @@ impl Database {
.await .await
} }
pub async fn get_channels(&self, user_id: UserId) -> Result<Vec<Channel>> { pub async fn get_channels(
&self,
user_id: UserId,
) -> Result<(Vec<Channel>, HashMap<ChannelId, Vec<UserId>>)> {
self.transaction(|tx| async move { self.transaction(|tx| async move {
let tx = tx; let tx = tx;
@ -3379,7 +3436,31 @@ impl Database {
drop(rows); drop(rows);
Ok(channels) #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
enum QueryUserIdsAndChannelIds {
ChannelId,
UserId,
}
let mut participants = room_participant::Entity::find()
.inner_join(room::Entity)
.filter(room::Column::ChannelId.is_in(channels.iter().map(|c| c.id)))
.select_only()
.column(room::Column::ChannelId)
.column(room_participant::Column::UserId)
.into_values::<_, QueryUserIdsAndChannelIds>()
.stream(&*tx)
.await?;
let mut participant_map: HashMap<ChannelId, Vec<UserId>> = HashMap::default();
while let Some(row) = participants.next().await {
let row: (ChannelId, UserId) = row?;
participant_map.entry(row.0).or_default().push(row.1)
}
drop(participants);
Ok((channels, participant_map))
}) })
.await .await
} }
@ -3523,7 +3604,7 @@ impl Database {
.await .await
} }
pub async fn get_channel_room(&self, channel_id: ChannelId) -> Result<RoomId> { pub async fn room_id_for_channel(&self, channel_id: ChannelId) -> Result<RoomId> {
self.transaction(|tx| async move { self.transaction(|tx| async move {
let tx = tx; let tx = tx;
let room = channel::Model { let room = channel::Model {
@ -3932,29 +4013,19 @@ id_type!(ServerId);
id_type!(SignupId); id_type!(SignupId);
id_type!(UserId); id_type!(UserId);
pub struct ChannelRoom { #[derive(Clone)]
pub struct JoinRoom {
pub room: proto::Room, pub room: proto::Room,
pub channel_participants: Vec<UserId>, pub channel_id: Option<ChannelId>,
} pub channel_members: Vec<UserId>,
impl Deref for ChannelRoom {
type Target = proto::Room;
fn deref(&self) -> &Self::Target {
&self.room
}
}
impl DerefMut for ChannelRoom {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.room
}
} }
pub struct RejoinedRoom { pub struct RejoinedRoom {
pub room: ChannelRoom, pub room: proto::Room,
pub rejoined_projects: Vec<RejoinedProject>, pub rejoined_projects: Vec<RejoinedProject>,
pub reshared_projects: Vec<ResharedProject>, pub reshared_projects: Vec<ResharedProject>,
pub channel_id: Option<ChannelId>,
pub channel_members: Vec<UserId>,
} }
pub struct ResharedProject { pub struct ResharedProject {
@ -3989,14 +4060,18 @@ pub struct RejoinedWorktree {
} }
pub struct LeftRoom { pub struct LeftRoom {
pub room: ChannelRoom, pub room: proto::Room,
pub channel_id: Option<ChannelId>,
pub channel_members: Vec<UserId>,
pub left_projects: HashMap<ProjectId, LeftProject>, pub left_projects: HashMap<ProjectId, LeftProject>,
pub canceled_calls_to_user_ids: Vec<UserId>, pub canceled_calls_to_user_ids: Vec<UserId>,
pub deleted: bool, pub deleted: bool,
} }
pub struct RefreshedRoom { pub struct RefreshedRoom {
pub room: ChannelRoom, pub room: proto::Room,
pub channel_id: Option<ChannelId>,
pub channel_members: Vec<UserId>,
pub stale_participant_user_ids: Vec<UserId>, pub stale_participant_user_ids: Vec<UserId>,
pub canceled_calls_to_user_ids: Vec<UserId>, pub canceled_calls_to_user_ids: Vec<UserId>,
} }

View File

@ -1,7 +1,7 @@
use super::{ChannelId, RoomId}; use super::{ChannelId, RoomId};
use sea_orm::entity::prelude::*; use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)] #[derive(Clone, Default, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "rooms")] #[sea_orm(table_name = "rooms")]
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]

View File

@ -951,7 +951,7 @@ test_both_dbs!(test_channels_postgres, test_channels_sqlite, db, {
.await .await
.unwrap(); .unwrap();
let channels = db.get_channels(a_id).await.unwrap(); let (channels, _) = db.get_channels(a_id).await.unwrap();
assert_eq!( assert_eq!(
channels, channels,
@ -1047,10 +1047,10 @@ test_both_dbs!(
.create_root_channel("channel_1", "1", user_1) .create_root_channel("channel_1", "1", user_1)
.await .await
.unwrap(); .unwrap();
let room_1 = db.get_channel_room(channel_1).await.unwrap(); let room_1 = db.room_id_for_channel(channel_1).await.unwrap();
// can join a room with membership to its channel // can join a room with membership to its channel
let room = db let joined_room = db
.join_room( .join_room(
room_1, room_1,
user_1, user_1,
@ -1059,9 +1059,9 @@ test_both_dbs!(
) )
.await .await
.unwrap(); .unwrap();
assert_eq!(room.participants.len(), 1); assert_eq!(joined_room.room.participants.len(), 1);
drop(room); drop(joined_room);
// cannot join a room without membership to its channel // cannot join a room without membership to its channel
assert!(db assert!(db
.join_room( .join_room(

View File

@ -2,7 +2,7 @@ mod connection_pool;
use crate::{ use crate::{
auth, auth,
db::{self, ChannelId, ChannelRoom, Database, ProjectId, RoomId, ServerId, User, UserId}, db::{self, ChannelId, Database, ProjectId, RoomId, ServerId, User, UserId},
executor::Executor, executor::Executor,
AppState, Result, AppState, Result,
}; };
@ -296,6 +296,15 @@ impl Server {
"refreshed room" "refreshed room"
); );
room_updated(&refreshed_room.room, &peer); room_updated(&refreshed_room.room, &peer);
if let Some(channel_id) = refreshed_room.channel_id {
channel_updated(
channel_id,
&refreshed_room.room,
&refreshed_room.channel_members,
&peer,
&*pool.lock(),
);
}
contacts_to_update contacts_to_update
.extend(refreshed_room.stale_participant_user_ids.iter().copied()); .extend(refreshed_room.stale_participant_user_ids.iter().copied());
contacts_to_update contacts_to_update
@ -517,7 +526,7 @@ impl Server {
this.app_state.db.set_user_connected_once(user_id, true).await?; this.app_state.db.set_user_connected_once(user_id, true).await?;
} }
let (contacts, invite_code, channels, channel_invites) = future::try_join4( let (contacts, invite_code, (channels, channel_participants), channel_invites) = future::try_join4(
this.app_state.db.get_contacts(user_id), this.app_state.db.get_contacts(user_id),
this.app_state.db.get_invite_code_for_user(user_id), this.app_state.db.get_invite_code_for_user(user_id),
this.app_state.db.get_channels(user_id), this.app_state.db.get_channels(user_id),
@ -528,7 +537,7 @@ impl Server {
let mut pool = this.connection_pool.lock(); let mut pool = this.connection_pool.lock();
pool.add_connection(connection_id, user_id, user.admin); pool.add_connection(connection_id, user_id, user.admin);
this.peer.send(connection_id, build_initial_contacts_update(contacts, &pool))?; this.peer.send(connection_id, build_initial_contacts_update(contacts, &pool))?;
this.peer.send(connection_id, build_initial_channels_update(channels, channel_invites))?; this.peer.send(connection_id, build_initial_channels_update(channels, channel_participants, channel_invites))?;
if let Some((code, count)) = invite_code { if let Some((code, count)) = invite_code {
this.peer.send(connection_id, proto::UpdateInviteInfo { this.peer.send(connection_id, proto::UpdateInviteInfo {
@ -921,8 +930,8 @@ async fn join_room(
.await .await
.join_room(room_id, session.user_id, None, session.connection_id) .join_room(room_id, session.user_id, None, session.connection_id)
.await?; .await?;
room_updated(&room, &session.peer); room_updated(&room.room, &session.peer);
room.clone() room.room.clone()
}; };
for connection_id in session for connection_id in session
@ -971,6 +980,9 @@ async fn rejoin_room(
response: Response<proto::RejoinRoom>, response: Response<proto::RejoinRoom>,
session: Session, session: Session,
) -> Result<()> { ) -> Result<()> {
let room;
let channel_id;
let channel_members;
{ {
let mut rejoined_room = session let mut rejoined_room = session
.db() .db()
@ -1132,6 +1144,21 @@ async fn rejoin_room(
)?; )?;
} }
} }
room = mem::take(&mut rejoined_room.room);
channel_id = rejoined_room.channel_id;
channel_members = mem::take(&mut rejoined_room.channel_members);
}
//TODO: move this into the room guard
if let Some(channel_id) = channel_id {
channel_updated(
channel_id,
&room,
&channel_members,
&session.peer,
&*session.connection_pool().await,
);
} }
update_user_contacts(session.user_id, &session).await?; update_user_contacts(session.user_id, &session).await?;
@ -2202,9 +2229,9 @@ async fn invite_channel_member(
} }
async fn remove_channel_member( async fn remove_channel_member(
request: proto::RemoveChannelMember, _request: proto::RemoveChannelMember,
response: Response<proto::RemoveChannelMember>, _response: Response<proto::RemoveChannelMember>,
session: Session, _session: Session,
) -> Result<()> { ) -> Result<()> {
Ok(()) Ok(())
} }
@ -2247,11 +2274,11 @@ async fn join_channel(
) -> Result<()> { ) -> Result<()> {
let channel_id = ChannelId::from_proto(request.channel_id); let channel_id = ChannelId::from_proto(request.channel_id);
{ let joined_room = {
let db = session.db().await; let db = session.db().await;
let room_id = db.get_channel_room(channel_id).await?; let room_id = db.room_id_for_channel(channel_id).await?;
let room = db let joined_room = db
.join_room( .join_room(
room_id, room_id,
session.user_id, session.user_id,
@ -2262,7 +2289,10 @@ async fn join_channel(
let live_kit_connection_info = session.live_kit_client.as_ref().and_then(|live_kit| { let live_kit_connection_info = session.live_kit_client.as_ref().and_then(|live_kit| {
let token = live_kit let token = live_kit
.room_token(&room.live_kit_room, &session.user_id.to_string()) .room_token(
&joined_room.room.live_kit_room,
&session.user_id.to_string(),
)
.trace_err()?; .trace_err()?;
Some(LiveKitConnectionInfo { Some(LiveKitConnectionInfo {
@ -2272,12 +2302,25 @@ async fn join_channel(
}); });
response.send(proto::JoinRoomResponse { response.send(proto::JoinRoomResponse {
room: Some(room.clone()), room: Some(joined_room.room.clone()),
live_kit_connection_info, live_kit_connection_info,
})?; })?;
room_updated(&room, &session.peer); room_updated(&joined_room.room, &session.peer);
}
joined_room.clone()
};
// TODO - do this while still holding the room guard,
// currently there's a possible race condition if someone joins the channel
// after we've dropped the lock but before we finish sending these updates
channel_updated(
channel_id,
&joined_room.room,
&joined_room.channel_members,
&session.peer,
&*session.connection_pool().await,
);
update_user_contacts(session.user_id, &session).await?; update_user_contacts(session.user_id, &session).await?;
@ -2356,6 +2399,7 @@ fn to_tungstenite_message(message: AxumMessage) -> TungsteniteMessage {
fn build_initial_channels_update( fn build_initial_channels_update(
channels: Vec<db::Channel>, channels: Vec<db::Channel>,
channel_participants: HashMap<db::ChannelId, Vec<UserId>>,
channel_invites: Vec<db::Channel>, channel_invites: Vec<db::Channel>,
) -> proto::UpdateChannels { ) -> proto::UpdateChannels {
let mut update = proto::UpdateChannels::default(); let mut update = proto::UpdateChannels::default();
@ -2426,10 +2470,7 @@ fn contact_for_user(
} }
} }
fn room_updated(room: &ChannelRoom, peer: &Peer, pool: &ConnectionPool) { fn room_updated(room: &proto::Room, peer: &Peer) {
let channel_ids = &room.channel_participants;
let room = &room.room;
broadcast( broadcast(
None, None,
room.participants room.participants
@ -2444,17 +2485,41 @@ fn room_updated(room: &ChannelRoom, peer: &Peer, pool: &ConnectionPool) {
) )
}, },
); );
}
fn channel_updated(
channel_id: ChannelId,
room: &proto::Room,
channel_members: &[UserId],
peer: &Peer,
pool: &ConnectionPool,
) {
let participants = room
.participants
.iter()
.map(|p| p.user_id)
.collect::<Vec<_>>();
broadcast( broadcast(
None, None,
channel_ids channel_members
.iter() .iter()
.filter(|user_id| {
!room
.participants
.iter()
.any(|p| p.user_id == user_id.to_proto())
})
.flat_map(|user_id| pool.user_connection_ids(*user_id)), .flat_map(|user_id| pool.user_connection_ids(*user_id)),
|peer_id| { |peer_id| {
peer.send( peer.send(
peer_id.into(), peer_id.into(),
proto::RoomUpdated { proto::UpdateChannels {
room: Some(room.clone()), channel_participants: vec![proto::ChannelParticipants {
channel_id: channel_id.to_proto(),
participant_user_ids: participants.clone(),
}],
..Default::default()
}, },
) )
}, },
@ -2502,6 +2567,10 @@ async fn leave_room_for_session(session: &Session) -> Result<()> {
let canceled_calls_to_user_ids; let canceled_calls_to_user_ids;
let live_kit_room; let live_kit_room;
let delete_live_kit_room; let delete_live_kit_room;
let room;
let channel_members;
let channel_id;
if let Some(mut left_room) = session.db().await.leave_room(session.connection_id).await? { if let Some(mut left_room) = session.db().await.leave_room(session.connection_id).await? {
contacts_to_update.insert(session.user_id); contacts_to_update.insert(session.user_id);
@ -2509,19 +2578,30 @@ async fn leave_room_for_session(session: &Session) -> Result<()> {
project_left(project, session); project_left(project, session);
} }
{
let connection_pool = session.connection_pool().await;
room_updated(&left_room.room, &session.peer, &connection_pool);
}
room_id = RoomId::from_proto(left_room.room.id); room_id = RoomId::from_proto(left_room.room.id);
canceled_calls_to_user_ids = mem::take(&mut left_room.canceled_calls_to_user_ids); canceled_calls_to_user_ids = mem::take(&mut left_room.canceled_calls_to_user_ids);
live_kit_room = mem::take(&mut left_room.room.live_kit_room); live_kit_room = mem::take(&mut left_room.room.live_kit_room);
delete_live_kit_room = left_room.deleted; delete_live_kit_room = left_room.deleted;
room = mem::take(&mut left_room.room);
channel_members = mem::take(&mut left_room.channel_members);
channel_id = left_room.channel_id;
room_updated(&room, &session.peer);
} else { } else {
return Ok(()); return Ok(());
} }
// TODO - do this while holding the room guard.
if let Some(channel_id) = channel_id {
channel_updated(
channel_id,
&room,
&channel_members,
&session.peer,
&*session.connection_pool().await,
);
}
{ {
let pool = session.connection_pool().await; let pool = session.connection_pool().await;
for canceled_user_id in canceled_calls_to_user_ids { for canceled_user_id in canceled_calls_to_user_ids {

View File

@ -66,7 +66,7 @@ async fn test_basic_channels(
) )
}); });
// Client B now sees that they are in channel A. // Client B now sees that they are a member channel A.
client_b client_b
.channel_store() .channel_store()
.update(cx_b, |channels, _| { .update(cx_b, |channels, _| {
@ -110,14 +110,20 @@ async fn test_channel_room(
deterministic: Arc<Deterministic>, deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext, cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext, cx_b: &mut TestAppContext,
cx_c: &mut TestAppContext,
) { ) {
deterministic.forbid_parking(); deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await; let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await; let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await; let client_b = server.create_client(cx_b, "user_b").await;
let client_c = server.create_client(cx_b, "user_c").await;
let zed_id = server let zed_id = server
.make_channel("zed", (&client_a, cx_a), &mut [(&client_b, cx_b)]) .make_channel(
"zed",
(&client_a, cx_a),
&mut [(&client_b, cx_b), (&client_c, cx_c)],
)
.await; .await;
let active_call_a = cx_a.read(ActiveCall::global); let active_call_a = cx_a.read(ActiveCall::global);
@ -128,11 +134,26 @@ async fn test_channel_room(
.await .await
.unwrap(); .unwrap();
// TODO Test that B and C sees A in the channel room
client_b.channel_store().read_with(cx_b, |channels, _| {
assert_eq!(
channels.channels(),
&[Arc::new(Channel {
id: zed_id,
name: "zed".to_string(),
parent_id: None,
depth: 0,
})]
)
});
active_call_b active_call_b
.update(cx_b, |active_call, cx| active_call.join_channel(zed_id, cx)) .update(cx_b, |active_call, cx| active_call.join_channel(zed_id, cx))
.await .await
.unwrap(); .unwrap();
// TODO Test that C sees A and B in the channel room
deterministic.run_until_parked(); deterministic.run_until_parked();
let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone()); let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
@ -162,12 +183,14 @@ async fn test_channel_room(
.await .await
.unwrap(); .unwrap();
// TODO Make sure that C sees A leave
active_call_b active_call_b
.update(cx_b, |active_call, cx| active_call.hang_up(cx)) .update(cx_b, |active_call, cx| active_call.hang_up(cx))
.await .await
.unwrap(); .unwrap();
// Make sure room exists? // TODO Make sure that C sees B leave
active_call_a active_call_a
.update(cx_a, |active_call, cx| active_call.join_channel(zed_id, cx)) .update(cx_a, |active_call, cx| active_call.join_channel(zed_id, cx))

View File

@ -136,8 +136,8 @@ message Envelope {
RemoveChannelMember remove_channel_member = 122; RemoveChannelMember remove_channel_member = 122;
RespondToChannelInvite respond_to_channel_invite = 123; RespondToChannelInvite respond_to_channel_invite = 123;
UpdateChannels update_channels = 124; UpdateChannels update_channels = 124;
JoinChannel join_channel = 125; JoinChannel join_channel = 126;
RemoveChannel remove_channel = 126; RemoveChannel remove_channel = 127;
} }
} }
@ -870,6 +870,12 @@ message UpdateChannels {
repeated uint64 remove_channels = 2; repeated uint64 remove_channels = 2;
repeated Channel channel_invitations = 3; repeated Channel channel_invitations = 3;
repeated uint64 remove_channel_invitations = 4; repeated uint64 remove_channel_invitations = 4;
repeated ChannelParticipants channel_participants = 5;
}
message ChannelParticipants {
uint64 channel_id = 1;
repeated uint64 participant_user_ids = 2;
} }
message JoinChannel { message JoinChannel {

View File

@ -244,7 +244,7 @@ messages!(
(UpdateWorktreeSettings, Foreground), (UpdateWorktreeSettings, Foreground),
(UpdateDiffBase, Foreground), (UpdateDiffBase, Foreground),
(GetPrivateUserInfo, Foreground), (GetPrivateUserInfo, Foreground),
(GetPrivateUserInfoResponse, Foreground), (GetPrivateUserInfoResponse, Foreground)
); );
request_messages!( request_messages!(