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