Merge pull request #1774 from zed-industries/stale-connections

Correctly handle disconnect when a different client for the same user is on a call
This commit is contained in:
Antonio Scandurra 2022-10-18 18:37:43 +01:00 committed by GitHub
commit c7a629ba6b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 284 additions and 154 deletions

View file

@ -143,11 +143,16 @@ pub enum Status {
Authenticating, Authenticating,
Connecting, Connecting,
ConnectionError, ConnectionError,
Connected { connection_id: ConnectionId }, Connected {
peer_id: PeerId,
connection_id: ConnectionId,
},
ConnectionLost, ConnectionLost,
Reauthenticating, Reauthenticating,
Reconnecting, Reconnecting,
ReconnectionError { next_reconnection: Instant }, ReconnectionError {
next_reconnection: Instant,
},
} }
impl Status { impl Status {
@ -314,6 +319,14 @@ impl Client {
.map(|credentials| credentials.user_id) .map(|credentials| credentials.user_id)
} }
pub fn peer_id(&self) -> Option<PeerId> {
if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
Some(*peer_id)
} else {
None
}
}
pub fn status(&self) -> watch::Receiver<Status> { pub fn status(&self) -> watch::Receiver<Status> {
self.state.read().status.1.clone() self.state.read().status.1.clone()
} }
@ -663,6 +676,7 @@ impl Client {
self.set_status(Status::Reconnecting, cx); self.set_status(Status::Reconnecting, cx);
} }
let mut timeout = cx.background().timer(CONNECTION_TIMEOUT).fuse();
futures::select_biased! { futures::select_biased! {
connection = self.establish_connection(&credentials, cx).fuse() => { connection = self.establish_connection(&credentials, cx).fuse() => {
match connection { match connection {
@ -671,8 +685,14 @@ impl Client {
if !read_from_keychain && IMPERSONATE_LOGIN.is_none() { if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
write_credentials_to_keychain(&credentials, cx).log_err(); write_credentials_to_keychain(&credentials, cx).log_err();
} }
self.set_connection(conn, cx);
Ok(()) futures::select_biased! {
result = self.set_connection(conn, cx).fuse() => result,
_ = timeout => {
self.set_status(Status::ConnectionError, cx);
Err(anyhow!("timed out waiting on hello message from server"))
}
}
} }
Err(EstablishConnectionError::Unauthorized) => { Err(EstablishConnectionError::Unauthorized) => {
self.state.write().credentials.take(); self.state.write().credentials.take();
@ -695,21 +715,65 @@ impl Client {
} }
} }
} }
_ = cx.background().timer(CONNECTION_TIMEOUT).fuse() => { _ = &mut timeout => {
self.set_status(Status::ConnectionError, cx); self.set_status(Status::ConnectionError, cx);
Err(anyhow!("timed out trying to establish connection")) Err(anyhow!("timed out trying to establish connection"))
} }
} }
} }
fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) { async fn set_connection(
self: &Arc<Self>,
conn: Connection,
cx: &AsyncAppContext,
) -> Result<()> {
let executor = cx.background(); let executor = cx.background();
log::info!("add connection to peer"); log::info!("add connection to peer");
let (connection_id, handle_io, mut incoming) = self let (connection_id, handle_io, mut incoming) = self
.peer .peer
.add_connection(conn, move |duration| executor.timer(duration)); .add_connection(conn, move |duration| executor.timer(duration));
log::info!("set status to connected {}", connection_id); let handle_io = cx.background().spawn(handle_io);
self.set_status(Status::Connected { connection_id }, cx);
let peer_id = async {
log::info!("waiting for server hello");
let message = incoming
.next()
.await
.ok_or_else(|| anyhow!("no hello message received"))?;
log::info!("got server hello");
let hello_message_type_name = message.payload_type_name().to_string();
let hello = message
.into_any()
.downcast::<TypedEnvelope<proto::Hello>>()
.map_err(|_| {
anyhow!(
"invalid hello message received: {:?}",
hello_message_type_name
)
})?;
Ok(PeerId(hello.payload.peer_id))
};
let peer_id = match peer_id.await {
Ok(peer_id) => peer_id,
Err(error) => {
self.peer.disconnect(connection_id);
return Err(error);
}
};
log::info!(
"set status to connected (connection id: {}, peer id: {})",
connection_id,
peer_id
);
self.set_status(
Status::Connected {
peer_id,
connection_id,
},
cx,
);
cx.foreground() cx.foreground()
.spawn({ .spawn({
let cx = cx.clone(); let cx = cx.clone();
@ -807,14 +871,18 @@ impl Client {
}) })
.detach(); .detach();
let handle_io = cx.background().spawn(handle_io);
let this = self.clone(); let this = self.clone();
let cx = cx.clone(); let cx = cx.clone();
cx.foreground() cx.foreground()
.spawn(async move { .spawn(async move {
match handle_io.await { match handle_io.await {
Ok(()) => { Ok(()) => {
if *this.status().borrow() == (Status::Connected { connection_id }) { if *this.status().borrow()
== (Status::Connected {
connection_id,
peer_id,
})
{
this.set_status(Status::SignedOut, &cx); this.set_status(Status::SignedOut, &cx);
} }
} }
@ -825,6 +893,8 @@ impl Client {
} }
}) })
.detach(); .detach();
Ok(())
} }
fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> { fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {

View file

@ -84,9 +84,19 @@ impl FakeServer {
let (connection_id, io, incoming) = let (connection_id, io, incoming) =
peer.add_test_connection(server_conn, cx.background()); peer.add_test_connection(server_conn, cx.background());
cx.background().spawn(io).detach(); cx.background().spawn(io).detach();
let mut state = state.lock(); {
state.connection_id = Some(connection_id); let mut state = state.lock();
state.incoming = Some(incoming); state.connection_id = Some(connection_id);
state.incoming = Some(incoming);
}
peer.send(
connection_id,
proto::Hello {
peer_id: connection_id.0,
},
)
.unwrap();
Ok(client_conn) Ok(client_conn)
}) })
} }

View file

@ -8,7 +8,7 @@ use anyhow::anyhow;
use call::{room, ActiveCall, ParticipantLocation, Room}; use call::{room, ActiveCall, ParticipantLocation, Room};
use client::{ use client::{
self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Connection, self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Connection,
Credentials, EstablishConnectionError, User, UserStore, RECEIVE_TIMEOUT, Credentials, EstablishConnectionError, PeerId, User, UserStore, RECEIVE_TIMEOUT,
}; };
use collections::{BTreeMap, HashMap, HashSet}; use collections::{BTreeMap, HashMap, HashSet};
use editor::{ use editor::{
@ -16,7 +16,10 @@ use editor::{
ToggleCodeActions, Undo, ToggleCodeActions, Undo,
}; };
use fs::{FakeFs, Fs as _, HomeDir, LineEnding}; use fs::{FakeFs, Fs as _, HomeDir, LineEnding};
use futures::{channel::mpsc, Future, StreamExt as _}; use futures::{
channel::{mpsc, oneshot},
Future, StreamExt as _,
};
use gpui::{ use gpui::{
executor::{self, Deterministic}, executor::{self, Deterministic},
geometry::vector::vec2f, geometry::vector::vec2f,
@ -34,7 +37,6 @@ use project::{
ProjectStore, WorktreeId, ProjectStore, WorktreeId,
}; };
use rand::prelude::*; use rand::prelude::*;
use rpc::PeerId;
use serde_json::json; use serde_json::json;
use settings::{Formatter, Settings}; use settings::{Formatter, Settings};
use sqlx::types::time::OffsetDateTime; use sqlx::types::time::OffsetDateTime;
@ -385,7 +387,7 @@ async fn test_leaving_room_on_disconnection(
); );
// When user A disconnects, both client A and B clear their room on the active call. // When user A disconnects, both client A and B clear their room on the active call.
server.disconnect_client(client_a.current_user_id(cx_a)); server.disconnect_client(client_a.peer_id().unwrap());
cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT); cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
active_call_a.read_with(cx_a, |call, _| assert!(call.room().is_none())); active_call_a.read_with(cx_a, |call, _| assert!(call.room().is_none()));
active_call_b.read_with(cx_b, |call, _| assert!(call.room().is_none())); active_call_b.read_with(cx_b, |call, _| assert!(call.room().is_none()));
@ -416,7 +418,7 @@ async fn test_calls_on_multiple_connections(
let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await; let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).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_b1 = server.create_client(cx_b1, "user_b").await; let client_b1 = server.create_client(cx_b1, "user_b").await;
let _client_b2 = server.create_client(cx_b2, "user_b").await; let client_b2 = server.create_client(cx_b2, "user_b").await;
server server
.make_contacts(&mut [(&client_a, cx_a), (&client_b1, cx_b1)]) .make_contacts(&mut [(&client_a, cx_a), (&client_b1, cx_b1)])
.await; .await;
@ -468,6 +470,14 @@ async fn test_calls_on_multiple_connections(
assert!(incoming_call_b1.next().await.unwrap().is_none()); assert!(incoming_call_b1.next().await.unwrap().is_none());
assert!(incoming_call_b2.next().await.unwrap().is_none()); assert!(incoming_call_b2.next().await.unwrap().is_none());
// User B disconnects the client that is not on the call. Everything should be fine.
client_b1.disconnect(&cx_b1.to_async()).unwrap();
deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
client_b1
.authenticate_and_connect(false, &cx_b1.to_async())
.await
.unwrap();
// User B hangs up, and user A calls them again. // User B hangs up, and user A calls them again.
active_call_b2.update(cx_b2, |call, cx| call.hang_up(cx).unwrap()); active_call_b2.update(cx_b2, |call, cx| call.hang_up(cx).unwrap());
deterministic.run_until_parked(); deterministic.run_until_parked();
@ -520,11 +530,29 @@ async fn test_calls_on_multiple_connections(
assert!(incoming_call_b1.next().await.unwrap().is_some()); assert!(incoming_call_b1.next().await.unwrap().is_some());
assert!(incoming_call_b2.next().await.unwrap().is_some()); assert!(incoming_call_b2.next().await.unwrap().is_some());
// User A disconnects up, causing both connections to stop ringing. // User A disconnects, causing both connections to stop ringing.
server.disconnect_client(client_a.current_user_id(cx_a)); server.disconnect_client(client_a.peer_id().unwrap());
cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT); deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
assert!(incoming_call_b1.next().await.unwrap().is_none()); assert!(incoming_call_b1.next().await.unwrap().is_none());
assert!(incoming_call_b2.next().await.unwrap().is_none()); assert!(incoming_call_b2.next().await.unwrap().is_none());
// User A reconnects automatically, then calls user B again.
active_call_a
.update(cx_a, |call, cx| {
call.invite(client_b1.user_id().unwrap(), None, cx)
})
.await
.unwrap();
deterministic.run_until_parked();
assert!(incoming_call_b1.next().await.unwrap().is_some());
assert!(incoming_call_b2.next().await.unwrap().is_some());
// User B disconnects all clients, causing user A to no longer see a pending call for them.
server.forbid_connections();
server.disconnect_client(client_b1.peer_id().unwrap());
server.disconnect_client(client_b2.peer_id().unwrap());
deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
active_call_a.read_with(cx_a, |call, _| assert!(call.room().is_none()));
} }
#[gpui::test(iterations = 10)] #[gpui::test(iterations = 10)]
@ -582,7 +610,7 @@ async fn test_share_project(
.update(cx_b, |call, cx| call.accept_incoming(cx)) .update(cx_b, |call, cx| call.accept_incoming(cx))
.await .await
.unwrap(); .unwrap();
let client_b_peer_id = client_b.peer_id; let client_b_peer_id = client_b.peer_id().unwrap();
let project_b = client_b let project_b = client_b
.build_remote_project(initial_project.id, cx_b) .build_remote_project(initial_project.id, cx_b)
.await; .await;
@ -806,7 +834,7 @@ async fn test_host_disconnect(
assert!(cx_b.is_window_edited(workspace_b.window_id())); assert!(cx_b.is_window_edited(workspace_b.window_id()));
// Drop client A's connection. Collaborators should disappear and the project should not be shown as shared. // Drop client A's connection. Collaborators should disappear and the project should not be shown as shared.
server.disconnect_client(client_a.current_user_id(cx_a)); server.disconnect_client(client_a.peer_id().unwrap());
deterministic.advance_clock(rpc::RECEIVE_TIMEOUT); deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
project_a project_a
.condition(cx_a, |project, _| project.collaborators().is_empty()) .condition(cx_a, |project, _| project.collaborators().is_empty())
@ -849,7 +877,7 @@ async fn test_host_disconnect(
.unwrap(); .unwrap();
// Drop client A's connection again. We should still unshare it successfully. // Drop client A's connection again. We should still unshare it successfully.
server.disconnect_client(client_a.current_user_id(cx_a)); server.disconnect_client(client_a.peer_id().unwrap());
deterministic.advance_clock(rpc::RECEIVE_TIMEOUT); deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
project_a.read_with(cx_a, |project, _| assert!(!project.is_shared())); project_a.read_with(cx_a, |project, _| assert!(!project.is_shared()));
} }
@ -2150,7 +2178,7 @@ async fn test_leaving_project(
// Simulate connection loss for client C and ensure client A observes client C leaving the project. // Simulate connection loss for client C and ensure client A observes client C leaving the project.
client_c.wait_for_current_user(cx_c).await; client_c.wait_for_current_user(cx_c).await;
server.disconnect_client(client_c.current_user_id(cx_c)); server.disconnect_client(client_c.peer_id().unwrap());
cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT); cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
deterministic.run_until_parked(); deterministic.run_until_parked();
project_a.read_with(cx_a, |project, _| { project_a.read_with(cx_a, |project, _| {
@ -4313,7 +4341,7 @@ async fn test_chat_reconnection(cx_a: &mut TestAppContext, cx_b: &mut TestAppCon
// Disconnect client B, ensuring we can still access its cached channel data. // Disconnect client B, ensuring we can still access its cached channel data.
server.forbid_connections(); server.forbid_connections();
server.disconnect_client(client_b.current_user_id(cx_b)); server.disconnect_client(client_b.peer_id().unwrap());
cx_b.foreground().advance_clock(rpc::RECEIVE_TIMEOUT); cx_b.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
while !matches!( while !matches!(
status_b.next().await, status_b.next().await,
@ -4476,7 +4504,7 @@ async fn test_contacts(
] ]
); );
server.disconnect_client(client_c.current_user_id(cx_c)); server.disconnect_client(client_c.peer_id().unwrap());
server.forbid_connections(); server.forbid_connections();
deterministic.advance_clock(rpc::RECEIVE_TIMEOUT); deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
assert_eq!( assert_eq!(
@ -4716,7 +4744,7 @@ async fn test_contacts(
); );
server.forbid_connections(); server.forbid_connections();
server.disconnect_client(client_a.current_user_id(cx_a)); server.disconnect_client(client_a.peer_id().unwrap());
deterministic.advance_clock(rpc::RECEIVE_TIMEOUT); deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
assert_eq!(contacts(&client_a, cx_a), []); assert_eq!(contacts(&client_a, cx_a), []);
assert_eq!( assert_eq!(
@ -5626,6 +5654,7 @@ async fn test_random_collaboration(
let mut clients = Vec::new(); let mut clients = Vec::new();
let mut user_ids = Vec::new(); let mut user_ids = Vec::new();
let mut peer_ids = Vec::new();
let mut op_start_signals = Vec::new(); let mut op_start_signals = Vec::new();
let mut next_entity_id = 100000; let mut next_entity_id = 100000;
@ -5814,6 +5843,7 @@ async fn test_random_collaboration(
let op_start_signal = futures::channel::mpsc::unbounded(); let op_start_signal = futures::channel::mpsc::unbounded();
user_ids.push(host_user_id); user_ids.push(host_user_id);
peer_ids.push(host.peer_id().unwrap());
op_start_signals.push(op_start_signal.0); op_start_signals.push(op_start_signal.0);
clients.push(host_cx.foreground().spawn(host.simulate_host( clients.push(host_cx.foreground().spawn(host.simulate_host(
host_project, host_project,
@ -5831,7 +5861,7 @@ async fn test_random_collaboration(
let mut operations = 0; let mut operations = 0;
while operations < max_operations { while operations < max_operations {
if operations == disconnect_host_at { if operations == disconnect_host_at {
server.disconnect_client(user_ids[0]); server.disconnect_client(peer_ids[0]);
deterministic.advance_clock(RECEIVE_TIMEOUT); deterministic.advance_clock(RECEIVE_TIMEOUT);
drop(op_start_signals); drop(op_start_signals);
@ -5914,6 +5944,7 @@ async fn test_random_collaboration(
let op_start_signal = futures::channel::mpsc::unbounded(); let op_start_signal = futures::channel::mpsc::unbounded();
user_ids.push(guest_user_id); user_ids.push(guest_user_id);
peer_ids.push(guest.peer_id().unwrap());
op_start_signals.push(op_start_signal.0); op_start_signals.push(op_start_signal.0);
clients.push(guest_cx.foreground().spawn(guest.simulate_guest( clients.push(guest_cx.foreground().spawn(guest.simulate_guest(
guest_username.clone(), guest_username.clone(),
@ -5930,10 +5961,11 @@ async fn test_random_collaboration(
let guest_ix = rng.lock().gen_range(1..clients.len()); let guest_ix = rng.lock().gen_range(1..clients.len());
log::info!("Removing guest {}", user_ids[guest_ix]); log::info!("Removing guest {}", user_ids[guest_ix]);
let removed_guest_id = user_ids.remove(guest_ix); let removed_guest_id = user_ids.remove(guest_ix);
let removed_peer_id = peer_ids.remove(guest_ix);
let guest = clients.remove(guest_ix); let guest = clients.remove(guest_ix);
op_start_signals.remove(guest_ix); op_start_signals.remove(guest_ix);
server.forbid_connections(); server.forbid_connections();
server.disconnect_client(removed_guest_id); server.disconnect_client(removed_peer_id);
deterministic.advance_clock(RECEIVE_TIMEOUT); deterministic.advance_clock(RECEIVE_TIMEOUT);
deterministic.start_waiting(); deterministic.start_waiting();
log::info!("Waiting for guest {} to exit...", removed_guest_id); log::info!("Waiting for guest {} to exit...", removed_guest_id);
@ -6057,8 +6089,10 @@ async fn test_random_collaboration(
let host_buffer = host_project.read_with(&host_cx, |project, cx| { let host_buffer = host_project.read_with(&host_cx, |project, cx| {
project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| { project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| {
panic!( panic!(
"host does not have buffer for guest:{}, peer:{}, id:{}", "host does not have buffer for guest:{}, peer:{:?}, id:{}",
guest_client.username, guest_client.peer_id, buffer_id guest_client.username,
guest_client.peer_id(),
buffer_id
) )
}) })
}); });
@ -6101,7 +6135,7 @@ struct TestServer {
server: Arc<Server>, server: Arc<Server>,
foreground: Rc<executor::Foreground>, foreground: Rc<executor::Foreground>,
notifications: mpsc::UnboundedReceiver<()>, notifications: mpsc::UnboundedReceiver<()>,
connection_killers: Arc<Mutex<HashMap<UserId, Arc<AtomicBool>>>>, connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
forbid_connections: Arc<AtomicBool>, forbid_connections: Arc<AtomicBool>,
_test_db: TestDb, _test_db: TestDb,
} }
@ -6167,7 +6201,6 @@ impl TestServer {
let db = self.app_state.db.clone(); let db = self.app_state.db.clone();
let connection_killers = self.connection_killers.clone(); let connection_killers = self.connection_killers.clone();
let forbid_connections = self.forbid_connections.clone(); let forbid_connections = self.forbid_connections.clone();
let (connection_id_tx, mut connection_id_rx) = mpsc::channel(16);
Arc::get_mut(&mut client) Arc::get_mut(&mut client)
.unwrap() .unwrap()
@ -6190,7 +6223,6 @@ impl TestServer {
let connection_killers = connection_killers.clone(); let connection_killers = connection_killers.clone();
let forbid_connections = forbid_connections.clone(); let forbid_connections = forbid_connections.clone();
let client_name = client_name.clone(); let client_name = client_name.clone();
let connection_id_tx = connection_id_tx.clone();
cx.spawn(move |cx| async move { cx.spawn(move |cx| async move {
if forbid_connections.load(SeqCst) { if forbid_connections.load(SeqCst) {
Err(EstablishConnectionError::other(anyhow!( Err(EstablishConnectionError::other(anyhow!(
@ -6199,7 +6231,7 @@ impl TestServer {
} else { } else {
let (client_conn, server_conn, killed) = let (client_conn, server_conn, killed) =
Connection::in_memory(cx.background()); Connection::in_memory(cx.background());
connection_killers.lock().insert(user_id, killed); let (connection_id_tx, connection_id_rx) = oneshot::channel();
let user = db.get_user_by_id(user_id).await.unwrap().unwrap(); let user = db.get_user_by_id(user_id).await.unwrap().unwrap();
cx.background() cx.background()
.spawn(server.handle_connection( .spawn(server.handle_connection(
@ -6210,6 +6242,10 @@ impl TestServer {
cx.background(), cx.background(),
)) ))
.detach(); .detach();
let connection_id = connection_id_rx.await.unwrap();
connection_killers
.lock()
.insert(PeerId(connection_id.0), killed);
Ok(client_conn) Ok(client_conn)
} }
}) })
@ -6241,11 +6277,9 @@ impl TestServer {
.authenticate_and_connect(false, &cx.to_async()) .authenticate_and_connect(false, &cx.to_async())
.await .await
.unwrap(); .unwrap();
let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
let client = TestClient { let client = TestClient {
client, client,
peer_id,
username: name.to_string(), username: name.to_string(),
user_store, user_store,
project_store, project_store,
@ -6257,10 +6291,10 @@ impl TestServer {
client client
} }
fn disconnect_client(&self, user_id: UserId) { fn disconnect_client(&self, peer_id: PeerId) {
self.connection_killers self.connection_killers
.lock() .lock()
.remove(&user_id) .remove(&peer_id)
.unwrap() .unwrap()
.store(true, SeqCst); .store(true, SeqCst);
} }
@ -6361,7 +6395,6 @@ impl Drop for TestServer {
struct TestClient { struct TestClient {
client: Arc<Client>, client: Arc<Client>,
username: String, username: String,
pub peer_id: PeerId,
pub user_store: ModelHandle<UserStore>, pub user_store: ModelHandle<UserStore>,
pub project_store: ModelHandle<ProjectStore>, pub project_store: ModelHandle<ProjectStore>,
language_registry: Arc<LanguageRegistry>, language_registry: Arc<LanguageRegistry>,

View file

@ -24,7 +24,7 @@ use axum::{
}; };
use collections::{HashMap, HashSet}; use collections::{HashMap, HashSet};
use futures::{ use futures::{
channel::mpsc, channel::{mpsc, oneshot},
future::{self, BoxFuture}, future::{self, BoxFuture},
stream::FuturesUnordered, stream::FuturesUnordered,
FutureExt, SinkExt, StreamExt, TryStreamExt, FutureExt, SinkExt, StreamExt, TryStreamExt,
@ -348,7 +348,7 @@ impl Server {
connection: Connection, connection: Connection,
address: String, address: String,
user: User, user: User,
mut send_connection_id: Option<mpsc::Sender<ConnectionId>>, mut send_connection_id: Option<oneshot::Sender<ConnectionId>>,
executor: E, executor: E,
) -> impl Future<Output = Result<()>> { ) -> impl Future<Output = Result<()>> {
let mut this = self.clone(); let mut this = self.clone();
@ -369,9 +369,11 @@ impl Server {
}); });
tracing::info!(%user_id, %login, %connection_id, %address, "connection opened"); tracing::info!(%user_id, %login, %connection_id, %address, "connection opened");
this.peer.send(connection_id, proto::Hello { peer_id: connection_id.0 })?;
tracing::info!(%user_id, %login, %connection_id, %address, "sent hello message");
if let Some(send_connection_id) = send_connection_id.as_mut() { if let Some(send_connection_id) = send_connection_id.take() {
let _ = send_connection_id.send(connection_id).await; let _ = send_connection_id.send(connection_id);
} }
if !user.connected_once { if !user.connected_once {
@ -477,6 +479,10 @@ impl Server {
let mut contacts_to_update = HashSet::default(); let mut contacts_to_update = HashSet::default();
{ {
let mut store = self.store().await; let mut store = self.store().await;
#[cfg(test)]
let removed_connection = store.remove_connection(connection_id).unwrap();
#[cfg(not(test))]
let removed_connection = store.remove_connection(connection_id)?; let removed_connection = store.remove_connection(connection_id)?;
for project in removed_connection.hosted_projects { for project in removed_connection.hosted_projects {

View file

@ -215,11 +215,16 @@ impl Store {
let connected_user = self.connected_users.get(&user_id).unwrap(); let connected_user = self.connected_users.get(&user_id).unwrap();
if let Some(active_call) = connected_user.active_call.as_ref() { if let Some(active_call) = connected_user.active_call.as_ref() {
let room_id = active_call.room_id; let room_id = active_call.room_id;
let left_room = self.leave_room(room_id, connection_id)?; if active_call.connection_id == Some(connection_id) {
result.hosted_projects = left_room.unshared_projects; let left_room = self.leave_room(room_id, connection_id)?;
result.guest_projects = left_room.left_projects; result.hosted_projects = left_room.unshared_projects;
result.room_id = Some(room_id); result.guest_projects = left_room.left_projects;
result.canceled_call_connection_ids = left_room.canceled_call_connection_ids; result.room_id = Some(room_id);
result.canceled_call_connection_ids = left_room.canceled_call_connection_ids;
} else if connected_user.connection_ids.len() == 1 {
self.decline_call(room_id, connection_id)?;
result.room_id = Some(room_id);
}
} }
let connected_user = self.connected_users.get_mut(&user_id).unwrap(); let connected_user = self.connected_users.get_mut(&user_id).unwrap();

View file

@ -6,125 +6,130 @@ message Envelope {
optional uint32 responding_to = 2; optional uint32 responding_to = 2;
optional uint32 original_sender_id = 3; optional uint32 original_sender_id = 3;
oneof payload { oneof payload {
Ack ack = 4; Hello hello = 4;
Error error = 5; Ack ack = 5;
Ping ping = 6; Error error = 6;
Test test = 7; Ping ping = 7;
Test test = 8;
CreateRoom create_room = 8; CreateRoom create_room = 9;
CreateRoomResponse create_room_response = 9; CreateRoomResponse create_room_response = 10;
JoinRoom join_room = 10; JoinRoom join_room = 11;
JoinRoomResponse join_room_response = 11; JoinRoomResponse join_room_response = 12;
LeaveRoom leave_room = 12; LeaveRoom leave_room = 13;
Call call = 13; Call call = 14;
IncomingCall incoming_call = 14; IncomingCall incoming_call = 15;
CallCanceled call_canceled = 15; CallCanceled call_canceled = 16;
CancelCall cancel_call = 16; CancelCall cancel_call = 17;
DeclineCall decline_call = 17; DeclineCall decline_call = 18;
UpdateParticipantLocation update_participant_location = 18; UpdateParticipantLocation update_participant_location = 19;
RoomUpdated room_updated = 19; RoomUpdated room_updated = 20;
ShareProject share_project = 20; ShareProject share_project = 21;
ShareProjectResponse share_project_response = 21; ShareProjectResponse share_project_response = 22;
UnshareProject unshare_project = 22; UnshareProject unshare_project = 23;
JoinProject join_project = 23; JoinProject join_project = 24;
JoinProjectResponse join_project_response = 24; JoinProjectResponse join_project_response = 25;
LeaveProject leave_project = 25; LeaveProject leave_project = 26;
AddProjectCollaborator add_project_collaborator = 26; AddProjectCollaborator add_project_collaborator = 27;
RemoveProjectCollaborator remove_project_collaborator = 27; RemoveProjectCollaborator remove_project_collaborator = 28;
GetDefinition get_definition = 28; GetDefinition get_definition = 29;
GetDefinitionResponse get_definition_response = 29; GetDefinitionResponse get_definition_response = 30;
GetTypeDefinition get_type_definition = 30; GetTypeDefinition get_type_definition = 31;
GetTypeDefinitionResponse get_type_definition_response = 31; GetTypeDefinitionResponse get_type_definition_response = 32;
GetReferences get_references = 32; GetReferences get_references = 33;
GetReferencesResponse get_references_response = 33; GetReferencesResponse get_references_response = 34;
GetDocumentHighlights get_document_highlights = 34; GetDocumentHighlights get_document_highlights = 35;
GetDocumentHighlightsResponse get_document_highlights_response = 35; GetDocumentHighlightsResponse get_document_highlights_response = 36;
GetProjectSymbols get_project_symbols = 36; GetProjectSymbols get_project_symbols = 37;
GetProjectSymbolsResponse get_project_symbols_response = 37; GetProjectSymbolsResponse get_project_symbols_response = 38;
OpenBufferForSymbol open_buffer_for_symbol = 38; OpenBufferForSymbol open_buffer_for_symbol = 39;
OpenBufferForSymbolResponse open_buffer_for_symbol_response = 39; OpenBufferForSymbolResponse open_buffer_for_symbol_response = 40;
UpdateProject update_project = 40; UpdateProject update_project = 41;
RegisterProjectActivity register_project_activity = 41; RegisterProjectActivity register_project_activity = 42;
UpdateWorktree update_worktree = 42; UpdateWorktree update_worktree = 43;
UpdateWorktreeExtensions update_worktree_extensions = 43; UpdateWorktreeExtensions update_worktree_extensions = 44;
CreateProjectEntry create_project_entry = 44; CreateProjectEntry create_project_entry = 45;
RenameProjectEntry rename_project_entry = 45; RenameProjectEntry rename_project_entry = 46;
CopyProjectEntry copy_project_entry = 46; CopyProjectEntry copy_project_entry = 47;
DeleteProjectEntry delete_project_entry = 47; DeleteProjectEntry delete_project_entry = 48;
ProjectEntryResponse project_entry_response = 48; ProjectEntryResponse project_entry_response = 49;
UpdateDiagnosticSummary update_diagnostic_summary = 49; UpdateDiagnosticSummary update_diagnostic_summary = 50;
StartLanguageServer start_language_server = 50; StartLanguageServer start_language_server = 51;
UpdateLanguageServer update_language_server = 51; UpdateLanguageServer update_language_server = 52;
OpenBufferById open_buffer_by_id = 52; OpenBufferById open_buffer_by_id = 53;
OpenBufferByPath open_buffer_by_path = 53; OpenBufferByPath open_buffer_by_path = 54;
OpenBufferResponse open_buffer_response = 54; OpenBufferResponse open_buffer_response = 55;
CreateBufferForPeer create_buffer_for_peer = 55; CreateBufferForPeer create_buffer_for_peer = 56;
UpdateBuffer update_buffer = 56; UpdateBuffer update_buffer = 57;
UpdateBufferFile update_buffer_file = 57; UpdateBufferFile update_buffer_file = 58;
SaveBuffer save_buffer = 58; SaveBuffer save_buffer = 59;
BufferSaved buffer_saved = 59; BufferSaved buffer_saved = 60;
BufferReloaded buffer_reloaded = 60; BufferReloaded buffer_reloaded = 61;
ReloadBuffers reload_buffers = 61; ReloadBuffers reload_buffers = 62;
ReloadBuffersResponse reload_buffers_response = 62; ReloadBuffersResponse reload_buffers_response = 63;
FormatBuffers format_buffers = 63; FormatBuffers format_buffers = 64;
FormatBuffersResponse format_buffers_response = 64; FormatBuffersResponse format_buffers_response = 65;
GetCompletions get_completions = 65; GetCompletions get_completions = 66;
GetCompletionsResponse get_completions_response = 66; GetCompletionsResponse get_completions_response = 67;
ApplyCompletionAdditionalEdits apply_completion_additional_edits = 67; ApplyCompletionAdditionalEdits apply_completion_additional_edits = 68;
ApplyCompletionAdditionalEditsResponse apply_completion_additional_edits_response = 68; ApplyCompletionAdditionalEditsResponse apply_completion_additional_edits_response = 69;
GetCodeActions get_code_actions = 69; GetCodeActions get_code_actions = 70;
GetCodeActionsResponse get_code_actions_response = 70; GetCodeActionsResponse get_code_actions_response = 71;
GetHover get_hover = 71; GetHover get_hover = 72;
GetHoverResponse get_hover_response = 72; GetHoverResponse get_hover_response = 73;
ApplyCodeAction apply_code_action = 73; ApplyCodeAction apply_code_action = 74;
ApplyCodeActionResponse apply_code_action_response = 74; ApplyCodeActionResponse apply_code_action_response = 75;
PrepareRename prepare_rename = 75; PrepareRename prepare_rename = 76;
PrepareRenameResponse prepare_rename_response = 76; PrepareRenameResponse prepare_rename_response = 77;
PerformRename perform_rename = 77; PerformRename perform_rename = 78;
PerformRenameResponse perform_rename_response = 78; PerformRenameResponse perform_rename_response = 79;
SearchProject search_project = 79; SearchProject search_project = 80;
SearchProjectResponse search_project_response = 80; SearchProjectResponse search_project_response = 81;
GetChannels get_channels = 81; GetChannels get_channels = 82;
GetChannelsResponse get_channels_response = 82; GetChannelsResponse get_channels_response = 83;
JoinChannel join_channel = 83; JoinChannel join_channel = 84;
JoinChannelResponse join_channel_response = 84; JoinChannelResponse join_channel_response = 85;
LeaveChannel leave_channel = 85; LeaveChannel leave_channel = 86;
SendChannelMessage send_channel_message = 86; SendChannelMessage send_channel_message = 87;
SendChannelMessageResponse send_channel_message_response = 87; SendChannelMessageResponse send_channel_message_response = 88;
ChannelMessageSent channel_message_sent = 88; ChannelMessageSent channel_message_sent = 89;
GetChannelMessages get_channel_messages = 89; GetChannelMessages get_channel_messages = 90;
GetChannelMessagesResponse get_channel_messages_response = 90; GetChannelMessagesResponse get_channel_messages_response = 91;
UpdateContacts update_contacts = 91; UpdateContacts update_contacts = 92;
UpdateInviteInfo update_invite_info = 92; UpdateInviteInfo update_invite_info = 93;
ShowContacts show_contacts = 93; ShowContacts show_contacts = 94;
GetUsers get_users = 94; GetUsers get_users = 95;
FuzzySearchUsers fuzzy_search_users = 95; FuzzySearchUsers fuzzy_search_users = 96;
UsersResponse users_response = 96; UsersResponse users_response = 97;
RequestContact request_contact = 97; RequestContact request_contact = 98;
RespondToContactRequest respond_to_contact_request = 98; RespondToContactRequest respond_to_contact_request = 99;
RemoveContact remove_contact = 99; RemoveContact remove_contact = 100;
Follow follow = 100; Follow follow = 101;
FollowResponse follow_response = 101; FollowResponse follow_response = 102;
UpdateFollowers update_followers = 102; UpdateFollowers update_followers = 103;
Unfollow unfollow = 103; Unfollow unfollow = 104;
GetPrivateUserInfo get_private_user_info = 104; GetPrivateUserInfo get_private_user_info = 105;
GetPrivateUserInfoResponse get_private_user_info_response = 105; GetPrivateUserInfoResponse get_private_user_info_response = 106;
UpdateDiffBase update_diff_base = 106; UpdateDiffBase update_diff_base = 107;
} }
} }
// Messages // Messages
message Hello {
uint32 peer_id = 1;
}
message Ping {} message Ping {}
message Ack {} message Ack {}

View file

@ -121,6 +121,7 @@ messages!(
(GetProjectSymbols, Background), (GetProjectSymbols, Background),
(GetProjectSymbolsResponse, Background), (GetProjectSymbolsResponse, Background),
(GetUsers, Foreground), (GetUsers, Foreground),
(Hello, Foreground),
(IncomingCall, Foreground), (IncomingCall, Foreground),
(UsersResponse, Foreground), (UsersResponse, Foreground),
(JoinChannel, Foreground), (JoinChannel, Foreground),

View file

@ -6,4 +6,4 @@ pub use conn::Connection;
pub use peer::*; pub use peer::*;
mod macros; mod macros;
pub const PROTOCOL_VERSION: u32 = 37; pub const PROTOCOL_VERSION: u32 = 38;