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