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