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