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 let handler = state.message_handlers.get(&payload_type_id).cloned();
839 // Dropping the state prevents deadlocks if the handler interacts with rpc::Client.
840 // It also ensures we don't hold the lock while yielding back to the executor, as
841 // that might cause the executor thread driving this future to block indefinitely.
842 drop(state);
843
844 if let Some(handler) = handler {
845 let future = handler(model, message, &this, cx.clone());
846 let client_id = this.id;
847 log::debug!(
848 "rpc message received. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
849 client_id,
850 message_id,
851 sender_id,
852 type_name
853 );
854 cx.foreground()
855 .spawn(async move {
856 match future.await {
857 Ok(()) => {
858 log::debug!(
859 "rpc message handled. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
860 client_id,
861 message_id,
862 sender_id,
863 type_name
864 );
865 }
866 Err(error) => {
867 log::error!(
868 "error handling message. client_id:{}, message_id:{}, sender_id:{:?}, type:{}, error:{:?}",
869 client_id,
870 message_id,
871 sender_id,
872 type_name,
873 error
874 );
875 }
876 }
877 })
878 .detach();
879 } else {
880 log::info!("unhandled message {}", type_name);
881 }
882
883 // Don't starve the main thread when receiving lots of messages at once.
884 smol::future::yield_now().await;
885 }
886 }
887 })
888 .detach();
889
890 let this = self.clone();
891 let cx = cx.clone();
892 cx.foreground()
893 .spawn(async move {
894 match handle_io.await {
895 Ok(()) => {
896 if *this.status().borrow()
897 == (Status::Connected {
898 connection_id,
899 peer_id,
900 })
901 {
902 this.set_status(Status::SignedOut, &cx);
903 }
904 }
905 Err(err) => {
906 log::error!("connection error: {:?}", err);
907 this.set_status(Status::ConnectionLost, &cx);
908 }
909 }
910 })
911 .detach();
912
913 Ok(())
914 }
915
916 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
917 #[cfg(any(test, feature = "test-support"))]
918 if let Some(callback) = self.authenticate.read().as_ref() {
919 return callback(cx);
920 }
921
922 self.authenticate_with_browser(cx)
923 }
924
925 fn establish_connection(
926 self: &Arc<Self>,
927 credentials: &Credentials,
928 cx: &AsyncAppContext,
929 ) -> Task<Result<Connection, EstablishConnectionError>> {
930 #[cfg(any(test, feature = "test-support"))]
931 if let Some(callback) = self.establish_connection.read().as_ref() {
932 return callback(credentials, cx);
933 }
934
935 self.establish_websocket_connection(credentials, cx)
936 }
937
938 async fn get_rpc_url(http: Arc<dyn HttpClient>, is_preview: bool) -> Result<Url> {
939 let preview_param = if is_preview { "?preview=1" } else { "" };
940 let url = format!("{}/rpc{preview_param}", *ZED_SERVER_URL);
941 let response = http.get(&url, Default::default(), false).await?;
942
943 // Normally, ZED_SERVER_URL is set to the URL of zed.dev website.
944 // The website's /rpc endpoint redirects to a collab server's /rpc endpoint,
945 // which requires authorization via an HTTP header.
946 //
947 // For testing purposes, ZED_SERVER_URL can also set to the direct URL of
948 // of a collab server. In that case, a request to the /rpc endpoint will
949 // return an 'unauthorized' response.
950 let collab_url = if response.status().is_redirection() {
951 response
952 .headers()
953 .get("Location")
954 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
955 .to_str()
956 .map_err(EstablishConnectionError::other)?
957 .to_string()
958 } else if response.status() == StatusCode::UNAUTHORIZED {
959 url
960 } else {
961 Err(anyhow!(
962 "unexpected /rpc response status {}",
963 response.status()
964 ))?
965 };
966
967 Url::parse(&collab_url).context("invalid rpc url")
968 }
969
970 fn establish_websocket_connection(
971 self: &Arc<Self>,
972 credentials: &Credentials,
973 cx: &AsyncAppContext,
974 ) -> Task<Result<Connection, EstablishConnectionError>> {
975 let is_preview = cx.read(|cx| {
976 if cx.has_global::<ReleaseChannel>() {
977 *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview
978 } else {
979 false
980 }
981 });
982
983 let request = Request::builder()
984 .header(
985 "Authorization",
986 format!("{} {}", credentials.user_id, credentials.access_token),
987 )
988 .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION);
989
990 let http = self.http.clone();
991 cx.background().spawn(async move {
992 let mut rpc_url = Self::get_rpc_url(http, is_preview).await?;
993 let rpc_host = rpc_url
994 .host_str()
995 .zip(rpc_url.port_or_known_default())
996 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
997 let stream = smol::net::TcpStream::connect(rpc_host).await?;
998
999 log::info!("connected to rpc endpoint {}", rpc_url);
1000
1001 match rpc_url.scheme() {
1002 "https" => {
1003 rpc_url.set_scheme("wss").unwrap();
1004 let request = request.uri(rpc_url.as_str()).body(())?;
1005 let (stream, _) =
1006 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
1007 Ok(Connection::new(
1008 stream
1009 .map_err(|error| anyhow!(error))
1010 .sink_map_err(|error| anyhow!(error)),
1011 ))
1012 }
1013 "http" => {
1014 rpc_url.set_scheme("ws").unwrap();
1015 let request = request.uri(rpc_url.as_str()).body(())?;
1016 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1017 Ok(Connection::new(
1018 stream
1019 .map_err(|error| anyhow!(error))
1020 .sink_map_err(|error| anyhow!(error)),
1021 ))
1022 }
1023 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1024 }
1025 })
1026 }
1027
1028 pub fn authenticate_with_browser(
1029 self: &Arc<Self>,
1030 cx: &AsyncAppContext,
1031 ) -> Task<Result<Credentials>> {
1032 let platform = cx.platform();
1033 let executor = cx.background();
1034 let telemetry = self.telemetry.clone();
1035 let amplitude_telemetry = self.amplitude_telemetry.clone();
1036 let http = self.http.clone();
1037 executor.clone().spawn(async move {
1038 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1039 // zed server to encrypt the user's access token, so that it can'be intercepted by
1040 // any other app running on the user's device.
1041 let (public_key, private_key) =
1042 rpc::auth::keypair().expect("failed to generate keypair for auth");
1043 let public_key_string =
1044 String::try_from(public_key).expect("failed to serialize public key for auth");
1045
1046 if let Some((login, token)) = IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref()) {
1047 return Self::authenticate_as_admin(http, login.clone(), token.clone()).await;
1048 }
1049
1050 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1051 let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1052 let port = server.server_addr().port();
1053
1054 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1055 // that the user is signing in from a Zed app running on the same device.
1056 let mut url = format!(
1057 "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
1058 *ZED_SERVER_URL, port, public_key_string
1059 );
1060
1061 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1062 log::info!("impersonating user @{}", impersonate_login);
1063 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1064 }
1065
1066 platform.open_url(&url);
1067
1068 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1069 // access token from the query params.
1070 //
1071 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1072 // custom URL scheme instead of this local HTTP server.
1073 let (user_id, access_token) = executor
1074 .spawn(async move {
1075 for _ in 0..100 {
1076 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1077 let path = req.url();
1078 let mut user_id = None;
1079 let mut access_token = None;
1080 let url = Url::parse(&format!("http://example.com{}", path))
1081 .context("failed to parse login notification url")?;
1082 for (key, value) in url.query_pairs() {
1083 if key == "access_token" {
1084 access_token = Some(value.to_string());
1085 } else if key == "user_id" {
1086 user_id = Some(value.to_string());
1087 }
1088 }
1089
1090 let post_auth_url =
1091 format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
1092 req.respond(
1093 tiny_http::Response::empty(302).with_header(
1094 tiny_http::Header::from_bytes(
1095 &b"Location"[..],
1096 post_auth_url.as_bytes(),
1097 )
1098 .unwrap(),
1099 ),
1100 )
1101 .context("failed to respond to login http request")?;
1102 return Ok((
1103 user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
1104 access_token
1105 .ok_or_else(|| anyhow!("missing access_token parameter"))?,
1106 ));
1107 }
1108 }
1109
1110 Err(anyhow!("didn't receive login redirect"))
1111 })
1112 .await?;
1113
1114 let access_token = private_key
1115 .decrypt_string(&access_token)
1116 .context("failed to decrypt access token")?;
1117 platform.activate(true);
1118
1119 telemetry.report_event("authenticate with browser", Default::default());
1120 amplitude_telemetry.report_event("authenticate with browser", Default::default());
1121
1122 Ok(Credentials {
1123 user_id: user_id.parse()?,
1124 access_token,
1125 })
1126 })
1127 }
1128
1129 async fn authenticate_as_admin(
1130 http: Arc<dyn HttpClient>,
1131 login: String,
1132 mut api_token: String,
1133 ) -> Result<Credentials> {
1134 #[derive(Deserialize)]
1135 struct AuthenticatedUserResponse {
1136 user: User,
1137 }
1138
1139 #[derive(Deserialize)]
1140 struct User {
1141 id: u64,
1142 }
1143
1144 // Use the collab server's admin API to retrieve the id
1145 // of the impersonated user.
1146 let mut url = Self::get_rpc_url(http.clone(), false).await?;
1147 url.set_path("/user");
1148 url.set_query(Some(&format!("github_login={login}")));
1149 let request = Request::get(url.as_str())
1150 .header("Authorization", format!("token {api_token}"))
1151 .body("".into())?;
1152
1153 let mut response = http.send(request).await?;
1154 let mut body = String::new();
1155 response.body_mut().read_to_string(&mut body).await?;
1156 if !response.status().is_success() {
1157 Err(anyhow!(
1158 "admin user request failed {} - {}",
1159 response.status().as_u16(),
1160 body,
1161 ))?;
1162 }
1163 let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1164
1165 // Use the admin API token to authenticate as the impersonated user.
1166 api_token.insert_str(0, "ADMIN_TOKEN:");
1167 Ok(Credentials {
1168 user_id: response.user.id,
1169 access_token: api_token,
1170 })
1171 }
1172
1173 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
1174 let conn_id = self.connection_id()?;
1175 self.peer.disconnect(conn_id);
1176 self.set_status(Status::SignedOut, cx);
1177 Ok(())
1178 }
1179
1180 fn connection_id(&self) -> Result<ConnectionId> {
1181 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1182 Ok(connection_id)
1183 } else {
1184 Err(anyhow!("not connected"))
1185 }
1186 }
1187
1188 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1189 log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
1190 self.peer.send(self.connection_id()?, message)
1191 }
1192
1193 pub fn request<T: RequestMessage>(
1194 &self,
1195 request: T,
1196 ) -> impl Future<Output = Result<T::Response>> {
1197 let client_id = self.id;
1198 log::debug!(
1199 "rpc request start. client_id:{}. name:{}",
1200 client_id,
1201 T::NAME
1202 );
1203 let response = self
1204 .connection_id()
1205 .map(|conn_id| self.peer.request(conn_id, request));
1206 async move {
1207 let response = response?.await;
1208 log::debug!(
1209 "rpc request finish. client_id:{}. name:{}",
1210 client_id,
1211 T::NAME
1212 );
1213 response
1214 }
1215 }
1216
1217 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1218 log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1219 self.peer.respond(receipt, response)
1220 }
1221
1222 fn respond_with_error<T: RequestMessage>(
1223 &self,
1224 receipt: Receipt<T>,
1225 error: proto::Error,
1226 ) -> Result<()> {
1227 log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1228 self.peer.respond_with_error(receipt, error)
1229 }
1230
1231 pub fn start_telemetry(&self, db: Db) {
1232 self.telemetry.start(db.clone());
1233 self.amplitude_telemetry.start(db);
1234 }
1235
1236 pub fn report_event(&self, kind: &str, properties: Value) {
1237 self.telemetry.report_event(kind, properties.clone());
1238 self.amplitude_telemetry.report_event(kind, properties);
1239 }
1240
1241 pub fn telemetry_log_file_path(&self) -> Option<PathBuf> {
1242 self.amplitude_telemetry.log_file_path();
1243 self.telemetry.log_file_path()
1244 }
1245}
1246
1247impl AnyWeakEntityHandle {
1248 fn upgrade(&self, cx: &AsyncAppContext) -> Option<AnyEntityHandle> {
1249 match self {
1250 AnyWeakEntityHandle::Model(handle) => handle.upgrade(cx).map(AnyEntityHandle::Model),
1251 AnyWeakEntityHandle::View(handle) => handle.upgrade(cx).map(AnyEntityHandle::View),
1252 }
1253 }
1254}
1255
1256fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1257 if IMPERSONATE_LOGIN.is_some() {
1258 return None;
1259 }
1260
1261 let (user_id, access_token) = cx
1262 .platform()
1263 .read_credentials(&ZED_SERVER_URL)
1264 .log_err()
1265 .flatten()?;
1266 Some(Credentials {
1267 user_id: user_id.parse().ok()?,
1268 access_token: String::from_utf8(access_token).ok()?,
1269 })
1270}
1271
1272fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
1273 cx.platform().write_credentials(
1274 &ZED_SERVER_URL,
1275 &credentials.user_id.to_string(),
1276 credentials.access_token.as_bytes(),
1277 )
1278}
1279
1280const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
1281
1282pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1283 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1284}
1285
1286pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1287 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1288 let mut parts = path.split('/');
1289 let id = parts.next()?.parse::<u64>().ok()?;
1290 let access_token = parts.next()?;
1291 if access_token.is_empty() {
1292 return None;
1293 }
1294 Some((id, access_token.to_string()))
1295}
1296
1297#[cfg(test)]
1298mod tests {
1299 use super::*;
1300 use crate::test::{FakeHttpClient, FakeServer};
1301 use gpui::{executor::Deterministic, TestAppContext};
1302 use parking_lot::Mutex;
1303 use std::future;
1304
1305 #[gpui::test(iterations = 10)]
1306 async fn test_reconnection(cx: &mut TestAppContext) {
1307 cx.foreground().forbid_parking();
1308
1309 let user_id = 5;
1310 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1311 let server = FakeServer::for_client(user_id, &client, cx).await;
1312 let mut status = client.status();
1313 assert!(matches!(
1314 status.next().await,
1315 Some(Status::Connected { .. })
1316 ));
1317 assert_eq!(server.auth_count(), 1);
1318
1319 server.forbid_connections();
1320 server.disconnect();
1321 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1322
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(), 1); // Client reused the cached credentials when reconnecting
1327
1328 server.forbid_connections();
1329 server.disconnect();
1330 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1331
1332 // Clear cached credentials after authentication fails
1333 server.roll_access_token();
1334 server.allow_connections();
1335 cx.foreground().advance_clock(Duration::from_secs(10));
1336 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1337 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1338 }
1339
1340 #[gpui::test(iterations = 10)]
1341 async fn test_connection_timeout(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1342 deterministic.forbid_parking();
1343
1344 let user_id = 5;
1345 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1346 let mut status = client.status();
1347
1348 // Time out when client tries to connect.
1349 client.override_authenticate(move |cx| {
1350 cx.foreground().spawn(async move {
1351 Ok(Credentials {
1352 user_id,
1353 access_token: "token".into(),
1354 })
1355 })
1356 });
1357 client.override_establish_connection(|_, cx| {
1358 cx.foreground().spawn(async move {
1359 future::pending::<()>().await;
1360 unreachable!()
1361 })
1362 });
1363 let auth_and_connect = cx.spawn({
1364 let client = client.clone();
1365 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1366 });
1367 deterministic.run_until_parked();
1368 assert!(matches!(status.next().await, Some(Status::Connecting)));
1369
1370 deterministic.advance_clock(CONNECTION_TIMEOUT);
1371 assert!(matches!(
1372 status.next().await,
1373 Some(Status::ConnectionError { .. })
1374 ));
1375 auth_and_connect.await.unwrap_err();
1376
1377 // Allow the connection to be established.
1378 let server = FakeServer::for_client(user_id, &client, cx).await;
1379 assert!(matches!(
1380 status.next().await,
1381 Some(Status::Connected { .. })
1382 ));
1383
1384 // Disconnect client.
1385 server.forbid_connections();
1386 server.disconnect();
1387 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1388
1389 // Time out when re-establishing the connection.
1390 server.allow_connections();
1391 client.override_establish_connection(|_, cx| {
1392 cx.foreground().spawn(async move {
1393 future::pending::<()>().await;
1394 unreachable!()
1395 })
1396 });
1397 deterministic.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1398 assert!(matches!(
1399 status.next().await,
1400 Some(Status::Reconnecting { .. })
1401 ));
1402
1403 deterministic.advance_clock(CONNECTION_TIMEOUT);
1404 assert!(matches!(
1405 status.next().await,
1406 Some(Status::ReconnectionError { .. })
1407 ));
1408 }
1409
1410 #[gpui::test(iterations = 10)]
1411 async fn test_authenticating_more_than_once(
1412 cx: &mut TestAppContext,
1413 deterministic: Arc<Deterministic>,
1414 ) {
1415 cx.foreground().forbid_parking();
1416
1417 let auth_count = Arc::new(Mutex::new(0));
1418 let dropped_auth_count = Arc::new(Mutex::new(0));
1419 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1420 client.override_authenticate({
1421 let auth_count = auth_count.clone();
1422 let dropped_auth_count = dropped_auth_count.clone();
1423 move |cx| {
1424 let auth_count = auth_count.clone();
1425 let dropped_auth_count = dropped_auth_count.clone();
1426 cx.foreground().spawn(async move {
1427 *auth_count.lock() += 1;
1428 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1429 future::pending::<()>().await;
1430 unreachable!()
1431 })
1432 }
1433 });
1434
1435 let _authenticate = cx.spawn(|cx| {
1436 let client = client.clone();
1437 async move { client.authenticate_and_connect(false, &cx).await }
1438 });
1439 deterministic.run_until_parked();
1440 assert_eq!(*auth_count.lock(), 1);
1441 assert_eq!(*dropped_auth_count.lock(), 0);
1442
1443 let _authenticate = cx.spawn(|cx| {
1444 let client = client.clone();
1445 async move { client.authenticate_and_connect(false, &cx).await }
1446 });
1447 deterministic.run_until_parked();
1448 assert_eq!(*auth_count.lock(), 2);
1449 assert_eq!(*dropped_auth_count.lock(), 1);
1450 }
1451
1452 #[test]
1453 fn test_encode_and_decode_worktree_url() {
1454 let url = encode_worktree_url(5, "deadbeef");
1455 assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1456 assert_eq!(
1457 decode_worktree_url(&format!("\n {}\t", url)),
1458 Some((5, "deadbeef".to_string()))
1459 );
1460 assert_eq!(decode_worktree_url("not://the-right-format"), None);
1461 }
1462
1463 #[gpui::test]
1464 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1465 cx.foreground().forbid_parking();
1466
1467 let user_id = 5;
1468 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1469 let server = FakeServer::for_client(user_id, &client, cx).await;
1470
1471 let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1472 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1473 client.add_model_message_handler(
1474 move |model: ModelHandle<Model>, _: TypedEnvelope<proto::JoinProject>, _, cx| {
1475 match model.read_with(&cx, |model, _| model.id) {
1476 1 => done_tx1.try_send(()).unwrap(),
1477 2 => done_tx2.try_send(()).unwrap(),
1478 _ => unreachable!(),
1479 }
1480 async { Ok(()) }
1481 },
1482 );
1483 let model1 = cx.add_model(|_| Model {
1484 id: 1,
1485 subscription: None,
1486 });
1487 let model2 = cx.add_model(|_| Model {
1488 id: 2,
1489 subscription: None,
1490 });
1491 let model3 = cx.add_model(|_| Model {
1492 id: 3,
1493 subscription: None,
1494 });
1495
1496 let _subscription1 = model1.update(cx, |_, cx| client.add_model_for_remote_entity(1, cx));
1497 let _subscription2 = model2.update(cx, |_, cx| client.add_model_for_remote_entity(2, cx));
1498 // Ensure dropping a subscription for the same entity type still allows receiving of
1499 // messages for other entity IDs of the same type.
1500 let subscription3 = model3.update(cx, |_, cx| client.add_model_for_remote_entity(3, cx));
1501 drop(subscription3);
1502
1503 server.send(proto::JoinProject { project_id: 1 });
1504 server.send(proto::JoinProject { project_id: 2 });
1505 done_rx1.next().await.unwrap();
1506 done_rx2.next().await.unwrap();
1507 }
1508
1509 #[gpui::test]
1510 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1511 cx.foreground().forbid_parking();
1512
1513 let user_id = 5;
1514 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1515 let server = FakeServer::for_client(user_id, &client, cx).await;
1516
1517 let model = cx.add_model(|_| Model::default());
1518 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1519 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1520 let subscription1 = client.add_message_handler(
1521 model.clone(),
1522 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1523 done_tx1.try_send(()).unwrap();
1524 async { Ok(()) }
1525 },
1526 );
1527 drop(subscription1);
1528 let _subscription2 =
1529 client.add_message_handler(model, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1530 done_tx2.try_send(()).unwrap();
1531 async { Ok(()) }
1532 });
1533 server.send(proto::Ping {});
1534 done_rx2.next().await.unwrap();
1535 }
1536
1537 #[gpui::test]
1538 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1539 cx.foreground().forbid_parking();
1540
1541 let user_id = 5;
1542 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1543 let server = FakeServer::for_client(user_id, &client, cx).await;
1544
1545 let model = cx.add_model(|_| Model::default());
1546 let (done_tx, mut done_rx) = smol::channel::unbounded();
1547 let subscription = client.add_message_handler(
1548 model.clone(),
1549 move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1550 model.update(&mut cx, |model, _| model.subscription.take());
1551 done_tx.try_send(()).unwrap();
1552 async { Ok(()) }
1553 },
1554 );
1555 model.update(cx, |model, _| {
1556 model.subscription = Some(subscription);
1557 });
1558 server.send(proto::Ping {});
1559 done_rx.next().await.unwrap();
1560 }
1561
1562 #[derive(Default)]
1563 struct Model {
1564 id: usize,
1565 subscription: Option<Subscription>,
1566 }
1567
1568 impl Entity for Model {
1569 type Event = ();
1570 }
1571}