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