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