1#[cfg(any(test, feature = "test-support"))]
2pub mod test;
3
4pub mod amplitude_telemetry;
5pub mod channel;
6pub mod http;
7pub mod telemetry;
8pub mod user;
9
10use amplitude_telemetry::AmplitudeTelemetry;
11use anyhow::{anyhow, Context, Result};
12use async_recursion::async_recursion;
13use async_tungstenite::tungstenite::{
14 error::Error as WebsocketError,
15 http::{Request, StatusCode},
16};
17use db::Db;
18use futures::{future::LocalBoxFuture, AsyncReadExt, FutureExt, SinkExt, StreamExt, TryStreamExt};
19use gpui::{
20 actions,
21 serde_json::{self, Value},
22 AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AnyWeakViewHandle, AppContext,
23 AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task, View, ViewContext,
24 ViewHandle,
25};
26use http::HttpClient;
27use lazy_static::lazy_static;
28use parking_lot::RwLock;
29use postage::watch;
30use rand::prelude::*;
31use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, RequestMessage};
32use serde::Deserialize;
33use settings::ReleaseChannel;
34use std::{
35 any::TypeId,
36 collections::HashMap,
37 convert::TryFrom,
38 fmt::Write as _,
39 future::Future,
40 path::PathBuf,
41 sync::{Arc, Weak},
42 time::{Duration, Instant},
43};
44use telemetry::Telemetry;
45use thiserror::Error;
46use url::Url;
47use util::{ResultExt, TryFutureExt};
48
49pub use channel::*;
50pub use rpc::*;
51pub use user::*;
52
53lazy_static! {
54 pub static ref ZED_SERVER_URL: String =
55 std::env::var("ZED_SERVER_URL").unwrap_or_else(|_| "https://zed.dev".to_string());
56 pub static ref IMPERSONATE_LOGIN: Option<String> = std::env::var("ZED_IMPERSONATE")
57 .ok()
58 .and_then(|s| if s.is_empty() { None } else { Some(s) });
59 pub static ref ADMIN_API_TOKEN: Option<String> = std::env::var("ZED_ADMIN_API_TOKEN")
60 .ok()
61 .and_then(|s| if s.is_empty() { None } else { Some(s) });
62}
63
64pub const ZED_SECRET_CLIENT_TOKEN: &str = "618033988749894";
65pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(100);
66pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
67
68actions!(client, [Authenticate]);
69
70pub fn init(client: Arc<Client>, cx: &mut MutableAppContext) {
71 cx.add_global_action({
72 let client = client.clone();
73 move |_: &Authenticate, cx| {
74 let client = client.clone();
75 cx.spawn(
76 |cx| async move { client.authenticate_and_connect(true, &cx).log_err().await },
77 )
78 .detach();
79 }
80 });
81}
82
83pub struct Client {
84 id: usize,
85 peer: Arc<Peer>,
86 http: Arc<dyn HttpClient>,
87 telemetry: Arc<Telemetry>,
88 amplitude_telemetry: Arc<AmplitudeTelemetry>,
89 state: RwLock<ClientState>,
90
91 #[allow(clippy::type_complexity)]
92 #[cfg(any(test, feature = "test-support"))]
93 authenticate: RwLock<
94 Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
95 >,
96
97 #[allow(clippy::type_complexity)]
98 #[cfg(any(test, feature = "test-support"))]
99 establish_connection: RwLock<
100 Option<
101 Box<
102 dyn 'static
103 + Send
104 + Sync
105 + Fn(
106 &Credentials,
107 &AsyncAppContext,
108 ) -> Task<Result<Connection, EstablishConnectionError>>,
109 >,
110 >,
111 >,
112}
113
114#[derive(Error, Debug)]
115pub enum EstablishConnectionError {
116 #[error("upgrade required")]
117 UpgradeRequired,
118 #[error("unauthorized")]
119 Unauthorized,
120 #[error("{0}")]
121 Other(#[from] anyhow::Error),
122 #[error("{0}")]
123 Http(#[from] http::Error),
124 #[error("{0}")]
125 Io(#[from] std::io::Error),
126 #[error("{0}")]
127 Websocket(#[from] async_tungstenite::tungstenite::http::Error),
128}
129
130impl From<WebsocketError> for EstablishConnectionError {
131 fn from(error: WebsocketError) -> Self {
132 if let WebsocketError::Http(response) = &error {
133 match response.status() {
134 StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
135 StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
136 _ => {}
137 }
138 }
139 EstablishConnectionError::Other(error.into())
140 }
141}
142
143impl EstablishConnectionError {
144 pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
145 Self::Other(error.into())
146 }
147}
148
149#[derive(Copy, Clone, Debug, Eq, PartialEq)]
150pub enum Status {
151 SignedOut,
152 UpgradeRequired,
153 Authenticating,
154 Connecting,
155 ConnectionError,
156 Connected {
157 peer_id: PeerId,
158 connection_id: ConnectionId,
159 },
160 ConnectionLost,
161 Reauthenticating,
162 Reconnecting,
163 ReconnectionError {
164 next_reconnection: Instant,
165 },
166}
167
168impl Status {
169 pub fn is_connected(&self) -> bool {
170 matches!(self, Self::Connected { .. })
171 }
172}
173
174struct ClientState {
175 credentials: Option<Credentials>,
176 status: (watch::Sender<Status>, watch::Receiver<Status>),
177 entity_id_extractors: HashMap<TypeId, fn(&dyn AnyTypedEnvelope) -> u64>,
178 _reconnect_task: Option<Task<()>>,
179 reconnect_interval: Duration,
180 entities_by_type_and_remote_id: HashMap<(TypeId, u64), AnyWeakEntityHandle>,
181 models_by_message_type: HashMap<TypeId, AnyWeakModelHandle>,
182 entity_types_by_message_type: HashMap<TypeId, TypeId>,
183 #[allow(clippy::type_complexity)]
184 message_handlers: HashMap<
185 TypeId,
186 Arc<
187 dyn Send
188 + Sync
189 + Fn(
190 AnyEntityHandle,
191 Box<dyn AnyTypedEnvelope>,
192 &Arc<Client>,
193 AsyncAppContext,
194 ) -> LocalBoxFuture<'static, Result<()>>,
195 >,
196 >,
197}
198
199enum AnyWeakEntityHandle {
200 Model(AnyWeakModelHandle),
201 View(AnyWeakViewHandle),
202}
203
204enum AnyEntityHandle {
205 Model(AnyModelHandle),
206 View(AnyViewHandle),
207}
208
209#[derive(Clone, Debug)]
210pub struct Credentials {
211 pub user_id: u64,
212 pub access_token: String,
213}
214
215impl Default for ClientState {
216 fn default() -> Self {
217 Self {
218 credentials: None,
219 status: watch::channel_with(Status::SignedOut),
220 entity_id_extractors: Default::default(),
221 _reconnect_task: None,
222 reconnect_interval: Duration::from_secs(5),
223 models_by_message_type: Default::default(),
224 entities_by_type_and_remote_id: Default::default(),
225 entity_types_by_message_type: Default::default(),
226 message_handlers: Default::default(),
227 }
228 }
229}
230
231pub enum Subscription {
232 Entity {
233 client: Weak<Client>,
234 id: (TypeId, u64),
235 },
236 Message {
237 client: Weak<Client>,
238 id: TypeId,
239 },
240}
241
242impl Drop for Subscription {
243 fn drop(&mut self) {
244 match self {
245 Subscription::Entity { client, id } => {
246 if let Some(client) = client.upgrade() {
247 let mut state = client.state.write();
248 let _ = state.entities_by_type_and_remote_id.remove(id);
249 }
250 }
251 Subscription::Message { client, id } => {
252 if let Some(client) = client.upgrade() {
253 let mut state = client.state.write();
254 let _ = state.entity_types_by_message_type.remove(id);
255 let _ = state.message_handlers.remove(id);
256 }
257 }
258 }
259 }
260}
261
262impl Client {
263 pub fn new(http: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
264 Arc::new(Self {
265 id: 0,
266 peer: Peer::new(),
267 telemetry: Telemetry::new(http.clone(), cx),
268 amplitude_telemetry: AmplitudeTelemetry::new(http.clone(), cx),
269 http,
270 state: Default::default(),
271
272 #[cfg(any(test, feature = "test-support"))]
273 authenticate: Default::default(),
274 #[cfg(any(test, feature = "test-support"))]
275 establish_connection: Default::default(),
276 })
277 }
278
279 pub fn id(&self) -> usize {
280 self.id
281 }
282
283 pub fn http_client(&self) -> Arc<dyn HttpClient> {
284 self.http.clone()
285 }
286
287 #[cfg(any(test, feature = "test-support"))]
288 pub fn set_id(&mut self, id: usize) -> &Self {
289 self.id = id;
290 self
291 }
292
293 #[cfg(any(test, feature = "test-support"))]
294 pub fn tear_down(&self) {
295 let mut state = self.state.write();
296 state._reconnect_task.take();
297 state.message_handlers.clear();
298 state.models_by_message_type.clear();
299 state.entities_by_type_and_remote_id.clear();
300 state.entity_id_extractors.clear();
301 self.peer.reset();
302 }
303
304 #[cfg(any(test, feature = "test-support"))]
305 pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
306 where
307 F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
308 {
309 *self.authenticate.write() = Some(Box::new(authenticate));
310 self
311 }
312
313 #[cfg(any(test, feature = "test-support"))]
314 pub fn override_establish_connection<F>(&self, connect: F) -> &Self
315 where
316 F: 'static
317 + Send
318 + Sync
319 + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
320 {
321 *self.establish_connection.write() = Some(Box::new(connect));
322 self
323 }
324
325 pub fn user_id(&self) -> Option<u64> {
326 self.state
327 .read()
328 .credentials
329 .as_ref()
330 .map(|credentials| credentials.user_id)
331 }
332
333 pub fn peer_id(&self) -> Option<PeerId> {
334 if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
335 Some(*peer_id)
336 } else {
337 None
338 }
339 }
340
341 pub fn status(&self) -> watch::Receiver<Status> {
342 self.state.read().status.1.clone()
343 }
344
345 fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
346 log::info!("set status on client {}: {:?}", self.id, status);
347 let mut state = self.state.write();
348 *state.status.0.borrow_mut() = status;
349
350 match status {
351 Status::Connected { .. } => {
352 state._reconnect_task = None;
353 }
354 Status::ConnectionLost => {
355 let this = self.clone();
356 let reconnect_interval = state.reconnect_interval;
357 state._reconnect_task = Some(cx.spawn(|cx| async move {
358 let mut rng = StdRng::from_entropy();
359 let mut delay = INITIAL_RECONNECTION_DELAY;
360 while let Err(error) = this.authenticate_and_connect(true, &cx).await {
361 log::error!("failed to connect {}", error);
362 if matches!(*this.status().borrow(), Status::ConnectionError) {
363 this.set_status(
364 Status::ReconnectionError {
365 next_reconnection: Instant::now() + delay,
366 },
367 &cx,
368 );
369 cx.background().timer(delay).await;
370 delay = delay
371 .mul_f32(rng.gen_range(1.0..=2.0))
372 .min(reconnect_interval);
373 } else {
374 break;
375 }
376 }
377 }));
378 }
379 Status::SignedOut | Status::UpgradeRequired => {
380 self.telemetry.set_authenticated_user_info(None, false);
381 self.amplitude_telemetry
382 .set_authenticated_user_info(None, false);
383 state._reconnect_task.take();
384 }
385 _ => {}
386 }
387 }
388
389 pub fn add_view_for_remote_entity<T: View>(
390 self: &Arc<Self>,
391 remote_id: u64,
392 cx: &mut ViewContext<T>,
393 ) -> Subscription {
394 let id = (TypeId::of::<T>(), remote_id);
395 self.state
396 .write()
397 .entities_by_type_and_remote_id
398 .insert(id, AnyWeakEntityHandle::View(cx.weak_handle().into()));
399 Subscription::Entity {
400 client: Arc::downgrade(self),
401 id,
402 }
403 }
404
405 pub fn add_model_for_remote_entity<T: Entity>(
406 self: &Arc<Self>,
407 remote_id: u64,
408 cx: &mut ModelContext<T>,
409 ) -> Subscription {
410 let id = (TypeId::of::<T>(), remote_id);
411 self.state
412 .write()
413 .entities_by_type_and_remote_id
414 .insert(id, AnyWeakEntityHandle::Model(cx.weak_handle().into()));
415 Subscription::Entity {
416 client: Arc::downgrade(self),
417 id,
418 }
419 }
420
421 pub fn add_message_handler<M, E, H, F>(
422 self: &Arc<Self>,
423 model: ModelHandle<E>,
424 handler: H,
425 ) -> Subscription
426 where
427 M: EnvelopedMessage,
428 E: Entity,
429 H: 'static
430 + Send
431 + Sync
432 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
433 F: 'static + Future<Output = Result<()>>,
434 {
435 let message_type_id = TypeId::of::<M>();
436
437 let mut state = self.state.write();
438 state
439 .models_by_message_type
440 .insert(message_type_id, model.downgrade().into());
441
442 let prev_handler = state.message_handlers.insert(
443 message_type_id,
444 Arc::new(move |handle, envelope, client, cx| {
445 let handle = if let AnyEntityHandle::Model(handle) = handle {
446 handle
447 } else {
448 unreachable!();
449 };
450 let model = handle.downcast::<E>().unwrap();
451 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
452 handler(model, *envelope, client.clone(), cx).boxed_local()
453 }),
454 );
455 if prev_handler.is_some() {
456 panic!("registered handler for the same message twice");
457 }
458
459 Subscription::Message {
460 client: Arc::downgrade(self),
461 id: message_type_id,
462 }
463 }
464
465 pub fn add_request_handler<M, E, H, F>(
466 self: &Arc<Self>,
467 model: ModelHandle<E>,
468 handler: H,
469 ) -> Subscription
470 where
471 M: RequestMessage,
472 E: Entity,
473 H: 'static
474 + Send
475 + Sync
476 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
477 F: 'static + Future<Output = Result<M::Response>>,
478 {
479 self.add_message_handler(model, move |handle, envelope, this, cx| {
480 Self::respond_to_request(
481 envelope.receipt(),
482 handler(handle, envelope, this.clone(), cx),
483 this,
484 )
485 })
486 }
487
488 pub fn add_view_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
489 where
490 M: EntityMessage,
491 E: View,
492 H: 'static
493 + Send
494 + Sync
495 + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
496 F: 'static + Future<Output = Result<()>>,
497 {
498 self.add_entity_message_handler::<M, E, _, _>(move |handle, message, client, cx| {
499 if let AnyEntityHandle::View(handle) = handle {
500 handler(handle.downcast::<E>().unwrap(), message, client, cx)
501 } else {
502 unreachable!();
503 }
504 })
505 }
506
507 pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
508 where
509 M: EntityMessage,
510 E: Entity,
511 H: 'static
512 + Send
513 + Sync
514 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
515 F: 'static + Future<Output = Result<()>>,
516 {
517 self.add_entity_message_handler::<M, E, _, _>(move |handle, message, client, cx| {
518 if let AnyEntityHandle::Model(handle) = handle {
519 handler(handle.downcast::<E>().unwrap(), message, client, cx)
520 } else {
521 unreachable!();
522 }
523 })
524 }
525
526 fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
527 where
528 M: EntityMessage,
529 E: Entity,
530 H: 'static
531 + Send
532 + Sync
533 + Fn(AnyEntityHandle, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
534 F: 'static + Future<Output = Result<()>>,
535 {
536 let model_type_id = TypeId::of::<E>();
537 let message_type_id = TypeId::of::<M>();
538
539 let mut state = self.state.write();
540 state
541 .entity_types_by_message_type
542 .insert(message_type_id, model_type_id);
543 state
544 .entity_id_extractors
545 .entry(message_type_id)
546 .or_insert_with(|| {
547 |envelope| {
548 envelope
549 .as_any()
550 .downcast_ref::<TypedEnvelope<M>>()
551 .unwrap()
552 .payload
553 .remote_entity_id()
554 }
555 });
556 let prev_handler = state.message_handlers.insert(
557 message_type_id,
558 Arc::new(move |handle, envelope, client, cx| {
559 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
560 handler(handle, *envelope, client.clone(), cx).boxed_local()
561 }),
562 );
563 if prev_handler.is_some() {
564 panic!("registered handler for the same message twice");
565 }
566 }
567
568 pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
569 where
570 M: EntityMessage + RequestMessage,
571 E: Entity,
572 H: 'static
573 + Send
574 + Sync
575 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
576 F: 'static + Future<Output = Result<M::Response>>,
577 {
578 self.add_model_message_handler(move |entity, envelope, client, cx| {
579 Self::respond_to_request::<M, _>(
580 envelope.receipt(),
581 handler(entity, envelope, client.clone(), cx),
582 client,
583 )
584 })
585 }
586
587 pub fn add_view_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
588 where
589 M: EntityMessage + RequestMessage,
590 E: View,
591 H: 'static
592 + Send
593 + Sync
594 + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
595 F: 'static + Future<Output = Result<M::Response>>,
596 {
597 self.add_view_message_handler(move |entity, envelope, client, cx| {
598 Self::respond_to_request::<M, _>(
599 envelope.receipt(),
600 handler(entity, envelope, client.clone(), cx),
601 client,
602 )
603 })
604 }
605
606 async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
607 receipt: Receipt<T>,
608 response: F,
609 client: Arc<Self>,
610 ) -> Result<()> {
611 match response.await {
612 Ok(response) => {
613 client.respond(receipt, response)?;
614 Ok(())
615 }
616 Err(error) => {
617 client.respond_with_error(
618 receipt,
619 proto::Error {
620 message: format!("{:?}", error),
621 },
622 )?;
623 Err(error)
624 }
625 }
626 }
627
628 pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
629 read_credentials_from_keychain(cx).is_some()
630 }
631
632 #[async_recursion(?Send)]
633 pub async fn authenticate_and_connect(
634 self: &Arc<Self>,
635 try_keychain: bool,
636 cx: &AsyncAppContext,
637 ) -> anyhow::Result<()> {
638 let was_disconnected = match *self.status().borrow() {
639 Status::SignedOut => true,
640 Status::ConnectionError
641 | Status::ConnectionLost
642 | Status::Authenticating { .. }
643 | Status::Reauthenticating { .. }
644 | Status::ReconnectionError { .. } => false,
645 Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
646 return Ok(())
647 }
648 Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
649 };
650
651 if was_disconnected {
652 self.set_status(Status::Authenticating, cx);
653 } else {
654 self.set_status(Status::Reauthenticating, cx)
655 }
656
657 let mut read_from_keychain = false;
658 let mut credentials = self.state.read().credentials.clone();
659 if credentials.is_none() && try_keychain {
660 credentials = read_credentials_from_keychain(cx);
661 read_from_keychain = credentials.is_some();
662 if read_from_keychain {
663 self.report_event("read credentials from keychain", Default::default());
664 }
665 }
666 if credentials.is_none() {
667 let mut status_rx = self.status();
668 let _ = status_rx.next().await;
669 futures::select_biased! {
670 authenticate = self.authenticate(cx).fuse() => {
671 match authenticate {
672 Ok(creds) => credentials = Some(creds),
673 Err(err) => {
674 self.set_status(Status::ConnectionError, cx);
675 return Err(err);
676 }
677 }
678 }
679 _ = status_rx.next().fuse() => {
680 return Err(anyhow!("authentication canceled"));
681 }
682 }
683 }
684 let credentials = credentials.unwrap();
685
686 if was_disconnected {
687 self.set_status(Status::Connecting, cx);
688 } else {
689 self.set_status(Status::Reconnecting, cx);
690 }
691
692 let mut timeout = cx.background().timer(CONNECTION_TIMEOUT).fuse();
693 futures::select_biased! {
694 connection = self.establish_connection(&credentials, cx).fuse() => {
695 match connection {
696 Ok(conn) => {
697 self.state.write().credentials = Some(credentials.clone());
698 if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
699 write_credentials_to_keychain(&credentials, cx).log_err();
700 }
701
702 futures::select_biased! {
703 result = self.set_connection(conn, cx).fuse() => result,
704 _ = timeout => {
705 self.set_status(Status::ConnectionError, cx);
706 Err(anyhow!("timed out waiting on hello message from server"))
707 }
708 }
709 }
710 Err(EstablishConnectionError::Unauthorized) => {
711 self.state.write().credentials.take();
712 if read_from_keychain {
713 cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
714 self.set_status(Status::SignedOut, cx);
715 self.authenticate_and_connect(false, cx).await
716 } else {
717 self.set_status(Status::ConnectionError, cx);
718 Err(EstablishConnectionError::Unauthorized)?
719 }
720 }
721 Err(EstablishConnectionError::UpgradeRequired) => {
722 self.set_status(Status::UpgradeRequired, cx);
723 Err(EstablishConnectionError::UpgradeRequired)?
724 }
725 Err(error) => {
726 self.set_status(Status::ConnectionError, cx);
727 Err(error)?
728 }
729 }
730 }
731 _ = &mut timeout => {
732 self.set_status(Status::ConnectionError, cx);
733 Err(anyhow!("timed out trying to establish connection"))
734 }
735 }
736 }
737
738 async fn set_connection(
739 self: &Arc<Self>,
740 conn: Connection,
741 cx: &AsyncAppContext,
742 ) -> Result<()> {
743 let executor = cx.background();
744 log::info!("add connection to peer");
745 let (connection_id, handle_io, mut incoming) = self
746 .peer
747 .add_connection(conn, move |duration| executor.timer(duration));
748 let handle_io = cx.background().spawn(handle_io);
749
750 let peer_id = async {
751 log::info!("waiting for server hello");
752 let message = incoming
753 .next()
754 .await
755 .ok_or_else(|| anyhow!("no hello message received"))?;
756 log::info!("got server hello");
757 let hello_message_type_name = message.payload_type_name().to_string();
758 let hello = message
759 .into_any()
760 .downcast::<TypedEnvelope<proto::Hello>>()
761 .map_err(|_| {
762 anyhow!(
763 "invalid hello message received: {:?}",
764 hello_message_type_name
765 )
766 })?;
767 Ok(PeerId(hello.payload.peer_id))
768 };
769
770 let peer_id = match peer_id.await {
771 Ok(peer_id) => peer_id,
772 Err(error) => {
773 self.peer.disconnect(connection_id);
774 return Err(error);
775 }
776 };
777
778 log::info!(
779 "set status to connected (connection id: {}, peer id: {})",
780 connection_id,
781 peer_id
782 );
783 self.set_status(
784 Status::Connected {
785 peer_id,
786 connection_id,
787 },
788 cx,
789 );
790 cx.foreground()
791 .spawn({
792 let cx = cx.clone();
793 let this = self.clone();
794 async move {
795 let mut message_id = 0_usize;
796 while let Some(message) = incoming.next().await {
797 let mut state = this.state.write();
798 message_id += 1;
799 let type_name = message.payload_type_name();
800 let payload_type_id = message.payload_type_id();
801 let sender_id = message.original_sender_id().map(|id| id.0);
802
803 let model = state
804 .models_by_message_type
805 .get(&payload_type_id)
806 .and_then(|model| model.upgrade(&cx))
807 .map(AnyEntityHandle::Model)
808 .or_else(|| {
809 let entity_type_id =
810 *state.entity_types_by_message_type.get(&payload_type_id)?;
811 let entity_id = state
812 .entity_id_extractors
813 .get(&message.payload_type_id())
814 .map(|extract_entity_id| {
815 (extract_entity_id)(message.as_ref())
816 })?;
817
818 let entity = state
819 .entities_by_type_and_remote_id
820 .get(&(entity_type_id, entity_id))?;
821 if let Some(entity) = entity.upgrade(&cx) {
822 Some(entity)
823 } else {
824 state
825 .entities_by_type_and_remote_id
826 .remove(&(entity_type_id, entity_id));
827 None
828 }
829 });
830
831 let model = if let Some(model) = model {
832 model
833 } else {
834 log::info!("unhandled message {}", type_name);
835 continue;
836 };
837
838 if let Some(handler) = state.message_handlers.get(&payload_type_id).cloned()
839 {
840 drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
841 let future = handler(model, message, &this, cx.clone());
842
843 let client_id = this.id;
844 log::debug!(
845 "rpc message received. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
846 client_id,
847 message_id,
848 sender_id,
849 type_name
850 );
851 cx.foreground()
852 .spawn(async move {
853 match future.await {
854 Ok(()) => {
855 log::debug!(
856 "rpc message handled. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
857 client_id,
858 message_id,
859 sender_id,
860 type_name
861 );
862 }
863 Err(error) => {
864 log::error!(
865 "error handling message. client_id:{}, message_id:{}, sender_id:{:?}, type:{}, error:{:?}",
866 client_id,
867 message_id,
868 sender_id,
869 type_name,
870 error
871 );
872 }
873 }
874 })
875 .detach();
876 } else {
877 log::info!("unhandled message {}", type_name);
878 }
879
880 // Don't starve the main thread when receiving lots of messages at once.
881 smol::future::yield_now().await;
882 }
883 }
884 })
885 .detach();
886
887 let this = self.clone();
888 let cx = cx.clone();
889 cx.foreground()
890 .spawn(async move {
891 match handle_io.await {
892 Ok(()) => {
893 if *this.status().borrow()
894 == (Status::Connected {
895 connection_id,
896 peer_id,
897 })
898 {
899 this.set_status(Status::SignedOut, &cx);
900 }
901 }
902 Err(err) => {
903 log::error!("connection error: {:?}", err);
904 this.set_status(Status::ConnectionLost, &cx);
905 }
906 }
907 })
908 .detach();
909
910 Ok(())
911 }
912
913 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
914 #[cfg(any(test, feature = "test-support"))]
915 if let Some(callback) = self.authenticate.read().as_ref() {
916 return callback(cx);
917 }
918
919 self.authenticate_with_browser(cx)
920 }
921
922 fn establish_connection(
923 self: &Arc<Self>,
924 credentials: &Credentials,
925 cx: &AsyncAppContext,
926 ) -> Task<Result<Connection, EstablishConnectionError>> {
927 #[cfg(any(test, feature = "test-support"))]
928 if let Some(callback) = self.establish_connection.read().as_ref() {
929 return callback(credentials, cx);
930 }
931
932 self.establish_websocket_connection(credentials, cx)
933 }
934
935 async fn get_rpc_url(http: Arc<dyn HttpClient>, is_preview: bool) -> Result<Url> {
936 let preview_param = if is_preview { "?preview=1" } else { "" };
937 let url = format!("{}/rpc{preview_param}", *ZED_SERVER_URL);
938 let response = http.get(&url, Default::default(), false).await?;
939
940 // Normally, ZED_SERVER_URL is set to the URL of zed.dev website.
941 // The website's /rpc endpoint redirects to a collab server's /rpc endpoint,
942 // which requires authorization via an HTTP header.
943 //
944 // For testing purposes, ZED_SERVER_URL can also set to the direct URL of
945 // of a collab server. In that case, a request to the /rpc endpoint will
946 // return an 'unauthorized' response.
947 let collab_url = if response.status().is_redirection() {
948 response
949 .headers()
950 .get("Location")
951 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
952 .to_str()
953 .map_err(EstablishConnectionError::other)?
954 .to_string()
955 } else if response.status() == StatusCode::UNAUTHORIZED {
956 url
957 } else {
958 Err(anyhow!(
959 "unexpected /rpc response status {}",
960 response.status()
961 ))?
962 };
963
964 Url::parse(&collab_url).context("invalid rpc url")
965 }
966
967 fn establish_websocket_connection(
968 self: &Arc<Self>,
969 credentials: &Credentials,
970 cx: &AsyncAppContext,
971 ) -> Task<Result<Connection, EstablishConnectionError>> {
972 let is_preview = cx.read(|cx| {
973 if cx.has_global::<ReleaseChannel>() {
974 *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview
975 } else {
976 false
977 }
978 });
979
980 let request = Request::builder()
981 .header(
982 "Authorization",
983 format!("{} {}", credentials.user_id, credentials.access_token),
984 )
985 .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION);
986
987 let http = self.http.clone();
988 cx.background().spawn(async move {
989 let mut rpc_url = Self::get_rpc_url(http, is_preview).await?;
990 let rpc_host = rpc_url
991 .host_str()
992 .zip(rpc_url.port_or_known_default())
993 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
994 let stream = smol::net::TcpStream::connect(rpc_host).await?;
995
996 log::info!("connected to rpc endpoint {}", rpc_url);
997
998 match rpc_url.scheme() {
999 "https" => {
1000 rpc_url.set_scheme("wss").unwrap();
1001 let request = request.uri(rpc_url.as_str()).body(())?;
1002 let (stream, _) =
1003 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
1004 Ok(Connection::new(
1005 stream
1006 .map_err(|error| anyhow!(error))
1007 .sink_map_err(|error| anyhow!(error)),
1008 ))
1009 }
1010 "http" => {
1011 rpc_url.set_scheme("ws").unwrap();
1012 let request = request.uri(rpc_url.as_str()).body(())?;
1013 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1014 Ok(Connection::new(
1015 stream
1016 .map_err(|error| anyhow!(error))
1017 .sink_map_err(|error| anyhow!(error)),
1018 ))
1019 }
1020 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1021 }
1022 })
1023 }
1024
1025 pub fn authenticate_with_browser(
1026 self: &Arc<Self>,
1027 cx: &AsyncAppContext,
1028 ) -> Task<Result<Credentials>> {
1029 let platform = cx.platform();
1030 let executor = cx.background();
1031 let telemetry = self.telemetry.clone();
1032 let amplitude_telemetry = self.amplitude_telemetry.clone();
1033 let http = self.http.clone();
1034 executor.clone().spawn(async move {
1035 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1036 // zed server to encrypt the user's access token, so that it can'be intercepted by
1037 // any other app running on the user's device.
1038 let (public_key, private_key) =
1039 rpc::auth::keypair().expect("failed to generate keypair for auth");
1040 let public_key_string =
1041 String::try_from(public_key).expect("failed to serialize public key for auth");
1042
1043 if let Some((login, token)) = IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref()) {
1044 return Self::authenticate_as_admin(http, login.clone(), token.clone()).await;
1045 }
1046
1047 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1048 let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1049 let port = server.server_addr().port();
1050
1051 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1052 // that the user is signing in from a Zed app running on the same device.
1053 let mut url = format!(
1054 "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
1055 *ZED_SERVER_URL, port, public_key_string
1056 );
1057
1058 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1059 log::info!("impersonating user @{}", impersonate_login);
1060 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1061 }
1062
1063 platform.open_url(&url);
1064
1065 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1066 // access token from the query params.
1067 //
1068 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1069 // custom URL scheme instead of this local HTTP server.
1070 let (user_id, access_token) = executor
1071 .spawn(async move {
1072 for _ in 0..100 {
1073 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1074 let path = req.url();
1075 let mut user_id = None;
1076 let mut access_token = None;
1077 let url = Url::parse(&format!("http://example.com{}", path))
1078 .context("failed to parse login notification url")?;
1079 for (key, value) in url.query_pairs() {
1080 if key == "access_token" {
1081 access_token = Some(value.to_string());
1082 } else if key == "user_id" {
1083 user_id = Some(value.to_string());
1084 }
1085 }
1086
1087 let post_auth_url =
1088 format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
1089 req.respond(
1090 tiny_http::Response::empty(302).with_header(
1091 tiny_http::Header::from_bytes(
1092 &b"Location"[..],
1093 post_auth_url.as_bytes(),
1094 )
1095 .unwrap(),
1096 ),
1097 )
1098 .context("failed to respond to login http request")?;
1099 return Ok((
1100 user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
1101 access_token
1102 .ok_or_else(|| anyhow!("missing access_token parameter"))?,
1103 ));
1104 }
1105 }
1106
1107 Err(anyhow!("didn't receive login redirect"))
1108 })
1109 .await?;
1110
1111 let access_token = private_key
1112 .decrypt_string(&access_token)
1113 .context("failed to decrypt access token")?;
1114 platform.activate(true);
1115
1116 telemetry.report_event("authenticate with browser", Default::default());
1117 amplitude_telemetry.report_event("authenticate with browser", Default::default());
1118
1119 Ok(Credentials {
1120 user_id: user_id.parse()?,
1121 access_token,
1122 })
1123 })
1124 }
1125
1126 async fn authenticate_as_admin(
1127 http: Arc<dyn HttpClient>,
1128 login: String,
1129 mut api_token: String,
1130 ) -> Result<Credentials> {
1131 #[derive(Deserialize)]
1132 struct AuthenticatedUserResponse {
1133 user: User,
1134 }
1135
1136 #[derive(Deserialize)]
1137 struct User {
1138 id: u64,
1139 }
1140
1141 // Use the collab server's admin API to retrieve the id
1142 // of the impersonated user.
1143 let mut url = Self::get_rpc_url(http.clone(), false).await?;
1144 url.set_path("/user");
1145 url.set_query(Some(&format!("github_login={login}")));
1146 let request = Request::get(url.as_str())
1147 .header("Authorization", format!("token {api_token}"))
1148 .body("".into())?;
1149
1150 let mut response = http.send(request).await?;
1151 let mut body = String::new();
1152 response.body_mut().read_to_string(&mut body).await?;
1153 if !response.status().is_success() {
1154 Err(anyhow!(
1155 "admin user request failed {} - {}",
1156 response.status().as_u16(),
1157 body,
1158 ))?;
1159 }
1160 let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1161
1162 // Use the admin API token to authenticate as the impersonated user.
1163 api_token.insert_str(0, "ADMIN_TOKEN:");
1164 Ok(Credentials {
1165 user_id: response.user.id,
1166 access_token: api_token,
1167 })
1168 }
1169
1170 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
1171 let conn_id = self.connection_id()?;
1172 self.peer.disconnect(conn_id);
1173 self.set_status(Status::SignedOut, cx);
1174 Ok(())
1175 }
1176
1177 fn connection_id(&self) -> Result<ConnectionId> {
1178 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1179 Ok(connection_id)
1180 } else {
1181 Err(anyhow!("not connected"))
1182 }
1183 }
1184
1185 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1186 log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
1187 self.peer.send(self.connection_id()?, message)
1188 }
1189
1190 pub fn request<T: RequestMessage>(
1191 &self,
1192 request: T,
1193 ) -> impl Future<Output = Result<T::Response>> {
1194 let client_id = self.id;
1195 log::debug!(
1196 "rpc request start. client_id:{}. name:{}",
1197 client_id,
1198 T::NAME
1199 );
1200 let response = self
1201 .connection_id()
1202 .map(|conn_id| self.peer.request(conn_id, request));
1203 async move {
1204 let response = response?.await;
1205 log::debug!(
1206 "rpc request finish. client_id:{}. name:{}",
1207 client_id,
1208 T::NAME
1209 );
1210 response
1211 }
1212 }
1213
1214 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1215 log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1216 self.peer.respond(receipt, response)
1217 }
1218
1219 fn respond_with_error<T: RequestMessage>(
1220 &self,
1221 receipt: Receipt<T>,
1222 error: proto::Error,
1223 ) -> Result<()> {
1224 log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1225 self.peer.respond_with_error(receipt, error)
1226 }
1227
1228 pub fn start_telemetry(&self, db: Db) {
1229 self.telemetry.start(db.clone());
1230 self.amplitude_telemetry.start(db);
1231 }
1232
1233 pub fn report_event(&self, kind: &str, properties: Value) {
1234 self.telemetry.report_event(kind, properties.clone());
1235 self.amplitude_telemetry.report_event(kind, properties);
1236 }
1237
1238 pub fn telemetry_log_file_path(&self) -> Option<PathBuf> {
1239 self.amplitude_telemetry.log_file_path();
1240 self.telemetry.log_file_path()
1241 }
1242}
1243
1244impl AnyWeakEntityHandle {
1245 fn upgrade(&self, cx: &AsyncAppContext) -> Option<AnyEntityHandle> {
1246 match self {
1247 AnyWeakEntityHandle::Model(handle) => handle.upgrade(cx).map(AnyEntityHandle::Model),
1248 AnyWeakEntityHandle::View(handle) => handle.upgrade(cx).map(AnyEntityHandle::View),
1249 }
1250 }
1251}
1252
1253fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1254 if IMPERSONATE_LOGIN.is_some() {
1255 return None;
1256 }
1257
1258 let (user_id, access_token) = cx
1259 .platform()
1260 .read_credentials(&ZED_SERVER_URL)
1261 .log_err()
1262 .flatten()?;
1263 Some(Credentials {
1264 user_id: user_id.parse().ok()?,
1265 access_token: String::from_utf8(access_token).ok()?,
1266 })
1267}
1268
1269fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
1270 cx.platform().write_credentials(
1271 &ZED_SERVER_URL,
1272 &credentials.user_id.to_string(),
1273 credentials.access_token.as_bytes(),
1274 )
1275}
1276
1277const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
1278
1279pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1280 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1281}
1282
1283pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1284 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1285 let mut parts = path.split('/');
1286 let id = parts.next()?.parse::<u64>().ok()?;
1287 let access_token = parts.next()?;
1288 if access_token.is_empty() {
1289 return None;
1290 }
1291 Some((id, access_token.to_string()))
1292}
1293
1294#[cfg(test)]
1295mod tests {
1296 use super::*;
1297 use crate::test::{FakeHttpClient, FakeServer};
1298 use gpui::{executor::Deterministic, TestAppContext};
1299 use parking_lot::Mutex;
1300 use std::future;
1301
1302 #[gpui::test(iterations = 10)]
1303 async fn test_reconnection(cx: &mut TestAppContext) {
1304 cx.foreground().forbid_parking();
1305
1306 let user_id = 5;
1307 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1308 let server = FakeServer::for_client(user_id, &client, cx).await;
1309 let mut status = client.status();
1310 assert!(matches!(
1311 status.next().await,
1312 Some(Status::Connected { .. })
1313 ));
1314 assert_eq!(server.auth_count(), 1);
1315
1316 server.forbid_connections();
1317 server.disconnect();
1318 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1319
1320 server.allow_connections();
1321 cx.foreground().advance_clock(Duration::from_secs(10));
1322 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1323 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1324
1325 server.forbid_connections();
1326 server.disconnect();
1327 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1328
1329 // Clear cached credentials after authentication fails
1330 server.roll_access_token();
1331 server.allow_connections();
1332 cx.foreground().advance_clock(Duration::from_secs(10));
1333 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1334 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1335 }
1336
1337 #[gpui::test(iterations = 10)]
1338 async fn test_connection_timeout(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1339 deterministic.forbid_parking();
1340
1341 let user_id = 5;
1342 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1343 let mut status = client.status();
1344
1345 // Time out when client tries to connect.
1346 client.override_authenticate(move |cx| {
1347 cx.foreground().spawn(async move {
1348 Ok(Credentials {
1349 user_id,
1350 access_token: "token".into(),
1351 })
1352 })
1353 });
1354 client.override_establish_connection(|_, cx| {
1355 cx.foreground().spawn(async move {
1356 future::pending::<()>().await;
1357 unreachable!()
1358 })
1359 });
1360 let auth_and_connect = cx.spawn({
1361 let client = client.clone();
1362 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1363 });
1364 deterministic.run_until_parked();
1365 assert!(matches!(status.next().await, Some(Status::Connecting)));
1366
1367 deterministic.advance_clock(CONNECTION_TIMEOUT);
1368 assert!(matches!(
1369 status.next().await,
1370 Some(Status::ConnectionError { .. })
1371 ));
1372 auth_and_connect.await.unwrap_err();
1373
1374 // Allow the connection to be established.
1375 let server = FakeServer::for_client(user_id, &client, cx).await;
1376 assert!(matches!(
1377 status.next().await,
1378 Some(Status::Connected { .. })
1379 ));
1380
1381 // Disconnect client.
1382 server.forbid_connections();
1383 server.disconnect();
1384 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1385
1386 // Time out when re-establishing the connection.
1387 server.allow_connections();
1388 client.override_establish_connection(|_, cx| {
1389 cx.foreground().spawn(async move {
1390 future::pending::<()>().await;
1391 unreachable!()
1392 })
1393 });
1394 deterministic.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1395 assert!(matches!(
1396 status.next().await,
1397 Some(Status::Reconnecting { .. })
1398 ));
1399
1400 deterministic.advance_clock(CONNECTION_TIMEOUT);
1401 assert!(matches!(
1402 status.next().await,
1403 Some(Status::ReconnectionError { .. })
1404 ));
1405 }
1406
1407 #[gpui::test(iterations = 10)]
1408 async fn test_authenticating_more_than_once(
1409 cx: &mut TestAppContext,
1410 deterministic: Arc<Deterministic>,
1411 ) {
1412 cx.foreground().forbid_parking();
1413
1414 let auth_count = Arc::new(Mutex::new(0));
1415 let dropped_auth_count = Arc::new(Mutex::new(0));
1416 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1417 client.override_authenticate({
1418 let auth_count = auth_count.clone();
1419 let dropped_auth_count = dropped_auth_count.clone();
1420 move |cx| {
1421 let auth_count = auth_count.clone();
1422 let dropped_auth_count = dropped_auth_count.clone();
1423 cx.foreground().spawn(async move {
1424 *auth_count.lock() += 1;
1425 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1426 future::pending::<()>().await;
1427 unreachable!()
1428 })
1429 }
1430 });
1431
1432 let _authenticate = cx.spawn(|cx| {
1433 let client = client.clone();
1434 async move { client.authenticate_and_connect(false, &cx).await }
1435 });
1436 deterministic.run_until_parked();
1437 assert_eq!(*auth_count.lock(), 1);
1438 assert_eq!(*dropped_auth_count.lock(), 0);
1439
1440 let _authenticate = cx.spawn(|cx| {
1441 let client = client.clone();
1442 async move { client.authenticate_and_connect(false, &cx).await }
1443 });
1444 deterministic.run_until_parked();
1445 assert_eq!(*auth_count.lock(), 2);
1446 assert_eq!(*dropped_auth_count.lock(), 1);
1447 }
1448
1449 #[test]
1450 fn test_encode_and_decode_worktree_url() {
1451 let url = encode_worktree_url(5, "deadbeef");
1452 assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1453 assert_eq!(
1454 decode_worktree_url(&format!("\n {}\t", url)),
1455 Some((5, "deadbeef".to_string()))
1456 );
1457 assert_eq!(decode_worktree_url("not://the-right-format"), None);
1458 }
1459
1460 #[gpui::test]
1461 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1462 cx.foreground().forbid_parking();
1463
1464 let user_id = 5;
1465 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1466 let server = FakeServer::for_client(user_id, &client, cx).await;
1467
1468 let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1469 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1470 client.add_model_message_handler(
1471 move |model: ModelHandle<Model>, _: TypedEnvelope<proto::JoinProject>, _, cx| {
1472 match model.read_with(&cx, |model, _| model.id) {
1473 1 => done_tx1.try_send(()).unwrap(),
1474 2 => done_tx2.try_send(()).unwrap(),
1475 _ => unreachable!(),
1476 }
1477 async { Ok(()) }
1478 },
1479 );
1480 let model1 = cx.add_model(|_| Model {
1481 id: 1,
1482 subscription: None,
1483 });
1484 let model2 = cx.add_model(|_| Model {
1485 id: 2,
1486 subscription: None,
1487 });
1488 let model3 = cx.add_model(|_| Model {
1489 id: 3,
1490 subscription: None,
1491 });
1492
1493 let _subscription1 = model1.update(cx, |_, cx| client.add_model_for_remote_entity(1, cx));
1494 let _subscription2 = model2.update(cx, |_, cx| client.add_model_for_remote_entity(2, cx));
1495 // Ensure dropping a subscription for the same entity type still allows receiving of
1496 // messages for other entity IDs of the same type.
1497 let subscription3 = model3.update(cx, |_, cx| client.add_model_for_remote_entity(3, cx));
1498 drop(subscription3);
1499
1500 server.send(proto::JoinProject { project_id: 1 });
1501 server.send(proto::JoinProject { project_id: 2 });
1502 done_rx1.next().await.unwrap();
1503 done_rx2.next().await.unwrap();
1504 }
1505
1506 #[gpui::test]
1507 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1508 cx.foreground().forbid_parking();
1509
1510 let user_id = 5;
1511 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1512 let server = FakeServer::for_client(user_id, &client, cx).await;
1513
1514 let model = cx.add_model(|_| Model::default());
1515 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1516 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1517 let subscription1 = client.add_message_handler(
1518 model.clone(),
1519 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1520 done_tx1.try_send(()).unwrap();
1521 async { Ok(()) }
1522 },
1523 );
1524 drop(subscription1);
1525 let _subscription2 =
1526 client.add_message_handler(model, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1527 done_tx2.try_send(()).unwrap();
1528 async { Ok(()) }
1529 });
1530 server.send(proto::Ping {});
1531 done_rx2.next().await.unwrap();
1532 }
1533
1534 #[gpui::test]
1535 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1536 cx.foreground().forbid_parking();
1537
1538 let user_id = 5;
1539 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1540 let server = FakeServer::for_client(user_id, &client, cx).await;
1541
1542 let model = cx.add_model(|_| Model::default());
1543 let (done_tx, mut done_rx) = smol::channel::unbounded();
1544 let subscription = client.add_message_handler(
1545 model.clone(),
1546 move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1547 model.update(&mut cx, |model, _| model.subscription.take());
1548 done_tx.try_send(()).unwrap();
1549 async { Ok(()) }
1550 },
1551 );
1552 model.update(cx, |model, _| {
1553 model.subscription = Some(subscription);
1554 });
1555 server.send(proto::Ping {});
1556 done_rx.next().await.unwrap();
1557 }
1558
1559 #[derive(Default)]
1560 struct Model {
1561 id: usize,
1562 subscription: Option<Subscription>,
1563 }
1564
1565 impl Entity for Model {
1566 type Event = ();
1567 }
1568}