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