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) -> &Self {
763 self.state.write().credentials = Some(Credentials::DevServer { token });
764 self
765 }
766
767 #[async_recursion(?Send)]
768 pub async fn authenticate_and_connect(
769 self: &Arc<Self>,
770 try_keychain: bool,
771 cx: &AsyncAppContext,
772 ) -> anyhow::Result<()> {
773 let was_disconnected = match *self.status().borrow() {
774 Status::SignedOut => true,
775 Status::ConnectionError
776 | Status::ConnectionLost
777 | Status::Authenticating { .. }
778 | Status::Reauthenticating { .. }
779 | Status::ReconnectionError { .. } => false,
780 Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
781 return Ok(())
782 }
783 Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
784 };
785 if was_disconnected {
786 self.set_status(Status::Authenticating, cx);
787 } else {
788 self.set_status(Status::Reauthenticating, cx)
789 }
790
791 let mut read_from_keychain = false;
792 let mut credentials = self.state.read().credentials.clone();
793 if credentials.is_none() && try_keychain {
794 credentials = read_credentials_from_keychain(cx).await;
795 read_from_keychain = credentials.is_some();
796 }
797 if credentials.is_none() {
798 let mut status_rx = self.status();
799 let _ = status_rx.next().await;
800 futures::select_biased! {
801 authenticate = self.authenticate(cx).fuse() => {
802 match authenticate {
803 Ok(creds) => credentials = Some(creds),
804 Err(err) => {
805 self.set_status(Status::ConnectionError, cx);
806 return Err(err);
807 }
808 }
809 }
810 _ = status_rx.next().fuse() => {
811 return Err(anyhow!("authentication canceled"));
812 }
813 }
814 }
815 let credentials = credentials.unwrap();
816 if let Credentials::User { user_id, .. } = &credentials {
817 self.set_id(*user_id);
818 }
819
820 if was_disconnected {
821 self.set_status(Status::Connecting, cx);
822 } else {
823 self.set_status(Status::Reconnecting, cx);
824 }
825
826 let mut timeout =
827 futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
828 futures::select_biased! {
829 connection = self.establish_connection(&credentials, cx).fuse() => {
830 match connection {
831 Ok(conn) => {
832 self.state.write().credentials = Some(credentials.clone());
833 if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
834 if let Credentials::User{user_id, access_token} = credentials {
835 write_credentials_to_keychain(user_id, access_token, cx).await.log_err();
836 }
837 }
838
839 futures::select_biased! {
840 result = self.set_connection(conn, cx).fuse() => result,
841 _ = timeout => {
842 self.set_status(Status::ConnectionError, cx);
843 Err(anyhow!("timed out waiting on hello message from server"))
844 }
845 }
846 }
847 Err(EstablishConnectionError::Unauthorized) => {
848 self.state.write().credentials.take();
849 if read_from_keychain {
850 delete_credentials_from_keychain(cx).await.log_err();
851 self.set_status(Status::SignedOut, cx);
852 self.authenticate_and_connect(false, cx).await
853 } else {
854 self.set_status(Status::ConnectionError, cx);
855 Err(EstablishConnectionError::Unauthorized)?
856 }
857 }
858 Err(EstablishConnectionError::UpgradeRequired) => {
859 self.set_status(Status::UpgradeRequired, cx);
860 Err(EstablishConnectionError::UpgradeRequired)?
861 }
862 Err(error) => {
863 self.set_status(Status::ConnectionError, cx);
864 Err(error)?
865 }
866 }
867 }
868 _ = &mut timeout => {
869 self.set_status(Status::ConnectionError, cx);
870 Err(anyhow!("timed out trying to establish connection"))
871 }
872 }
873 }
874
875 async fn set_connection(
876 self: &Arc<Self>,
877 conn: Connection,
878 cx: &AsyncAppContext,
879 ) -> Result<()> {
880 let executor = cx.background_executor();
881 log::info!("add connection to peer");
882 let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
883 let executor = executor.clone();
884 move |duration| executor.timer(duration)
885 });
886 let handle_io = executor.spawn(handle_io);
887
888 let peer_id = async {
889 log::info!("waiting for server hello");
890 let message = incoming
891 .next()
892 .await
893 .ok_or_else(|| anyhow!("no hello message received"))?;
894 log::info!("got server hello");
895 let hello_message_type_name = message.payload_type_name().to_string();
896 let hello = message
897 .into_any()
898 .downcast::<TypedEnvelope<proto::Hello>>()
899 .map_err(|_| {
900 anyhow!(
901 "invalid hello message received: {:?}",
902 hello_message_type_name
903 )
904 })?;
905 let peer_id = hello
906 .payload
907 .peer_id
908 .ok_or_else(|| anyhow!("invalid peer id"))?;
909 Ok(peer_id)
910 };
911
912 let peer_id = match peer_id.await {
913 Ok(peer_id) => peer_id,
914 Err(error) => {
915 self.peer.disconnect(connection_id);
916 return Err(error);
917 }
918 };
919
920 log::info!(
921 "set status to connected (connection id: {:?}, peer id: {:?})",
922 connection_id,
923 peer_id
924 );
925 self.set_status(
926 Status::Connected {
927 peer_id,
928 connection_id,
929 },
930 cx,
931 );
932
933 cx.spawn({
934 let this = self.clone();
935 |cx| {
936 async move {
937 while let Some(message) = incoming.next().await {
938 this.handle_message(message, &cx);
939 // Don't starve the main thread when receiving lots of messages at once.
940 smol::future::yield_now().await;
941 }
942 }
943 }
944 })
945 .detach();
946
947 cx.spawn({
948 let this = self.clone();
949 move |cx| async move {
950 match handle_io.await {
951 Ok(()) => {
952 if *this.status().borrow()
953 == (Status::Connected {
954 connection_id,
955 peer_id,
956 })
957 {
958 this.set_status(Status::SignedOut, &cx);
959 }
960 }
961 Err(err) => {
962 log::error!("connection error: {:?}", err);
963 this.set_status(Status::ConnectionLost, &cx);
964 }
965 }
966 }
967 })
968 .detach();
969
970 Ok(())
971 }
972
973 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
974 #[cfg(any(test, feature = "test-support"))]
975 if let Some(callback) = self.authenticate.read().as_ref() {
976 return callback(cx);
977 }
978
979 self.authenticate_with_browser(cx)
980 }
981
982 fn establish_connection(
983 self: &Arc<Self>,
984 credentials: &Credentials,
985 cx: &AsyncAppContext,
986 ) -> Task<Result<Connection, EstablishConnectionError>> {
987 #[cfg(any(test, feature = "test-support"))]
988 if let Some(callback) = self.establish_connection.read().as_ref() {
989 return callback(credentials, cx);
990 }
991
992 self.establish_websocket_connection(credentials, cx)
993 }
994
995 async fn get_rpc_url(
996 http: Arc<HttpClientWithUrl>,
997 release_channel: Option<ReleaseChannel>,
998 ) -> Result<Url> {
999 if let Some(url) = &*ZED_RPC_URL {
1000 return Url::parse(url).context("invalid rpc url");
1001 }
1002
1003 let mut url = http.build_url("/rpc");
1004 if let Some(preview_param) =
1005 release_channel.and_then(|channel| channel.release_query_param())
1006 {
1007 url += "?";
1008 url += preview_param;
1009 }
1010 let response = http.get(&url, Default::default(), false).await?;
1011 let collab_url = if response.status().is_redirection() {
1012 response
1013 .headers()
1014 .get("Location")
1015 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
1016 .to_str()
1017 .map_err(EstablishConnectionError::other)?
1018 .to_string()
1019 } else {
1020 Err(anyhow!(
1021 "unexpected /rpc response status {}",
1022 response.status()
1023 ))?
1024 };
1025
1026 Url::parse(&collab_url).context("invalid rpc url")
1027 }
1028
1029 fn establish_websocket_connection(
1030 self: &Arc<Self>,
1031 credentials: &Credentials,
1032 cx: &AsyncAppContext,
1033 ) -> Task<Result<Connection, EstablishConnectionError>> {
1034 let release_channel = cx
1035 .update(|cx| ReleaseChannel::try_global(cx))
1036 .ok()
1037 .flatten();
1038 let app_version = cx
1039 .update(|cx| AppVersion::global(cx).to_string())
1040 .ok()
1041 .unwrap_or_default();
1042
1043 let request = Request::builder()
1044 .header("Authorization", credentials.authorization_header())
1045 .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION)
1046 .header("x-zed-app-version", app_version)
1047 .header(
1048 "x-zed-release-channel",
1049 release_channel.map(|r| r.dev_name()).unwrap_or("unknown"),
1050 );
1051
1052 let http = self.http.clone();
1053 cx.background_executor().spawn(async move {
1054 let mut rpc_url = Self::get_rpc_url(http, release_channel).await?;
1055 let rpc_host = rpc_url
1056 .host_str()
1057 .zip(rpc_url.port_or_known_default())
1058 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
1059 let stream = smol::net::TcpStream::connect(rpc_host).await?;
1060
1061 log::info!("connected to rpc endpoint {}", rpc_url);
1062
1063 match rpc_url.scheme() {
1064 "https" => {
1065 rpc_url.set_scheme("wss").unwrap();
1066 let request = request.uri(rpc_url.as_str()).body(())?;
1067 let (stream, _) =
1068 async_tungstenite::async_std::client_async_tls(request, stream).await?;
1069 Ok(Connection::new(
1070 stream
1071 .map_err(|error| anyhow!(error))
1072 .sink_map_err(|error| anyhow!(error)),
1073 ))
1074 }
1075 "http" => {
1076 rpc_url.set_scheme("ws").unwrap();
1077 let request = request.uri(rpc_url.as_str()).body(())?;
1078 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1079 Ok(Connection::new(
1080 stream
1081 .map_err(|error| anyhow!(error))
1082 .sink_map_err(|error| anyhow!(error)),
1083 ))
1084 }
1085 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1086 }
1087 })
1088 }
1089
1090 pub fn authenticate_with_browser(
1091 self: &Arc<Self>,
1092 cx: &AsyncAppContext,
1093 ) -> Task<Result<Credentials>> {
1094 let http = self.http.clone();
1095 cx.spawn(|cx| async move {
1096 let background = cx.background_executor().clone();
1097
1098 let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1099 cx.update(|cx| {
1100 cx.spawn(move |cx| async move {
1101 let url = open_url_rx.await?;
1102 cx.update(|cx| cx.open_url(&url))
1103 })
1104 .detach_and_log_err(cx);
1105 })
1106 .log_err();
1107
1108 let credentials = background
1109 .clone()
1110 .spawn(async move {
1111 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1112 // zed server to encrypt the user's access token, so that it can'be intercepted by
1113 // any other app running on the user's device.
1114 let (public_key, private_key) =
1115 rpc::auth::keypair().expect("failed to generate keypair for auth");
1116 let public_key_string = String::try_from(public_key)
1117 .expect("failed to serialize public key for auth");
1118
1119 if let Some((login, token)) =
1120 IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1121 {
1122 return Self::authenticate_as_admin(http, login.clone(), token.clone())
1123 .await;
1124 }
1125
1126 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1127 let server =
1128 tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1129 let port = server.server_addr().port();
1130
1131 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1132 // that the user is signing in from a Zed app running on the same device.
1133 let mut url = http.build_url(&format!(
1134 "/native_app_signin?native_app_port={}&native_app_public_key={}",
1135 port, public_key_string
1136 ));
1137
1138 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1139 log::info!("impersonating user @{}", impersonate_login);
1140 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1141 }
1142
1143 open_url_tx.send(url).log_err();
1144
1145 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1146 // access token from the query params.
1147 //
1148 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1149 // custom URL scheme instead of this local HTTP server.
1150 let (user_id, access_token) = background
1151 .spawn(async move {
1152 for _ in 0..100 {
1153 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1154 let path = req.url();
1155 let mut user_id = None;
1156 let mut access_token = None;
1157 let url = Url::parse(&format!("http://example.com{}", path))
1158 .context("failed to parse login notification url")?;
1159 for (key, value) in url.query_pairs() {
1160 if key == "access_token" {
1161 access_token = Some(value.to_string());
1162 } else if key == "user_id" {
1163 user_id = Some(value.to_string());
1164 }
1165 }
1166
1167 let post_auth_url =
1168 http.build_url("/native_app_signin_succeeded");
1169 req.respond(
1170 tiny_http::Response::empty(302).with_header(
1171 tiny_http::Header::from_bytes(
1172 &b"Location"[..],
1173 post_auth_url.as_bytes(),
1174 )
1175 .unwrap(),
1176 ),
1177 )
1178 .context("failed to respond to login http request")?;
1179 return Ok((
1180 user_id
1181 .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1182 access_token.ok_or_else(|| {
1183 anyhow!("missing access_token parameter")
1184 })?,
1185 ));
1186 }
1187 }
1188
1189 Err(anyhow!("didn't receive login redirect"))
1190 })
1191 .await?;
1192
1193 let access_token = private_key
1194 .decrypt_string(&access_token)
1195 .context("failed to decrypt access token")?;
1196
1197 Ok(Credentials::User {
1198 user_id: user_id.parse()?,
1199 access_token,
1200 })
1201 })
1202 .await?;
1203
1204 cx.update(|cx| cx.activate(true))?;
1205 Ok(credentials)
1206 })
1207 }
1208
1209 async fn authenticate_as_admin(
1210 http: Arc<HttpClientWithUrl>,
1211 login: String,
1212 mut api_token: String,
1213 ) -> Result<Credentials> {
1214 #[derive(Deserialize)]
1215 struct AuthenticatedUserResponse {
1216 user: User,
1217 }
1218
1219 #[derive(Deserialize)]
1220 struct User {
1221 id: u64,
1222 }
1223
1224 // Use the collab server's admin API to retrieve the id
1225 // of the impersonated user.
1226 let mut url = Self::get_rpc_url(http.clone(), None).await?;
1227 url.set_path("/user");
1228 url.set_query(Some(&format!("github_login={login}")));
1229 let request = Request::get(url.as_str())
1230 .header("Authorization", format!("token {api_token}"))
1231 .body("".into())?;
1232
1233 let mut response = http.send(request).await?;
1234 let mut body = String::new();
1235 response.body_mut().read_to_string(&mut body).await?;
1236 if !response.status().is_success() {
1237 Err(anyhow!(
1238 "admin user request failed {} - {}",
1239 response.status().as_u16(),
1240 body,
1241 ))?;
1242 }
1243 let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1244
1245 // Use the admin API token to authenticate as the impersonated user.
1246 api_token.insert_str(0, "ADMIN_TOKEN:");
1247 Ok(Credentials::User {
1248 user_id: response.user.id,
1249 access_token: api_token,
1250 })
1251 }
1252
1253 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1254 self.peer.teardown();
1255 self.set_status(Status::SignedOut, cx);
1256 }
1257
1258 pub fn reconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1259 self.peer.teardown();
1260 self.set_status(Status::ConnectionLost, cx);
1261 }
1262
1263 fn connection_id(&self) -> Result<ConnectionId> {
1264 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1265 Ok(connection_id)
1266 } else {
1267 Err(anyhow!("not connected"))
1268 }
1269 }
1270
1271 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1272 log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1273 self.peer.send(self.connection_id()?, message)
1274 }
1275
1276 pub fn request<T: RequestMessage>(
1277 &self,
1278 request: T,
1279 ) -> impl Future<Output = Result<T::Response>> {
1280 self.request_envelope(request)
1281 .map_ok(|envelope| envelope.payload)
1282 }
1283
1284 pub fn request_stream<T: RequestMessage>(
1285 &self,
1286 request: T,
1287 ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1288 let client_id = self.id.load(Ordering::SeqCst);
1289 log::debug!(
1290 "rpc request start. client_id:{}. name:{}",
1291 client_id,
1292 T::NAME
1293 );
1294 let response = self
1295 .connection_id()
1296 .map(|conn_id| self.peer.request_stream(conn_id, request));
1297 async move {
1298 let response = response?.await;
1299 log::debug!(
1300 "rpc request finish. client_id:{}. name:{}",
1301 client_id,
1302 T::NAME
1303 );
1304 response
1305 }
1306 }
1307
1308 pub fn request_envelope<T: RequestMessage>(
1309 &self,
1310 request: T,
1311 ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1312 let client_id = self.id();
1313 log::debug!(
1314 "rpc request start. client_id:{}. name:{}",
1315 client_id,
1316 T::NAME
1317 );
1318 let response = self
1319 .connection_id()
1320 .map(|conn_id| self.peer.request_envelope(conn_id, request));
1321 async move {
1322 let response = response?.await;
1323 log::debug!(
1324 "rpc request finish. client_id:{}. name:{}",
1325 client_id,
1326 T::NAME
1327 );
1328 response
1329 }
1330 }
1331
1332 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1333 log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1334 self.peer.respond(receipt, response)
1335 }
1336
1337 fn respond_with_error<T: RequestMessage>(
1338 &self,
1339 receipt: Receipt<T>,
1340 error: proto::Error,
1341 ) -> Result<()> {
1342 log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1343 self.peer.respond_with_error(receipt, error)
1344 }
1345
1346 fn handle_message(
1347 self: &Arc<Client>,
1348 message: Box<dyn AnyTypedEnvelope>,
1349 cx: &AsyncAppContext,
1350 ) {
1351 let mut state = self.state.write();
1352 let type_name = message.payload_type_name();
1353 let payload_type_id = message.payload_type_id();
1354 let sender_id = message.original_sender_id();
1355
1356 let mut subscriber = None;
1357
1358 if let Some(handle) = state
1359 .models_by_message_type
1360 .get(&payload_type_id)
1361 .and_then(|handle| handle.upgrade())
1362 {
1363 subscriber = Some(handle);
1364 } else if let Some((extract_entity_id, entity_type_id)) =
1365 state.entity_id_extractors.get(&payload_type_id).zip(
1366 state
1367 .entity_types_by_message_type
1368 .get(&payload_type_id)
1369 .copied(),
1370 )
1371 {
1372 let entity_id = (extract_entity_id)(message.as_ref());
1373
1374 match state
1375 .entities_by_type_and_remote_id
1376 .get_mut(&(entity_type_id, entity_id))
1377 {
1378 Some(WeakSubscriber::Pending(pending)) => {
1379 pending.push(message);
1380 return;
1381 }
1382 Some(weak_subscriber) => match weak_subscriber {
1383 WeakSubscriber::Entity { handle } => {
1384 subscriber = handle.upgrade();
1385 }
1386
1387 WeakSubscriber::Pending(_) => {}
1388 },
1389 _ => {}
1390 }
1391 }
1392
1393 let subscriber = if let Some(subscriber) = subscriber {
1394 subscriber
1395 } else {
1396 log::info!("unhandled message {}", type_name);
1397 self.peer.respond_with_unhandled_message(message).log_err();
1398 return;
1399 };
1400
1401 let handler = state.message_handlers.get(&payload_type_id).cloned();
1402 // Dropping the state prevents deadlocks if the handler interacts with rpc::Client.
1403 // It also ensures we don't hold the lock while yielding back to the executor, as
1404 // that might cause the executor thread driving this future to block indefinitely.
1405 drop(state);
1406
1407 if let Some(handler) = handler {
1408 let future = handler(subscriber, message, self, cx.clone());
1409 let client_id = self.id();
1410 log::debug!(
1411 "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1412 client_id,
1413 sender_id,
1414 type_name
1415 );
1416 cx.spawn(move |_| async move {
1417 match future.await {
1418 Ok(()) => {
1419 log::debug!(
1420 "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1421 client_id,
1422 sender_id,
1423 type_name
1424 );
1425 }
1426 Err(error) => {
1427 log::error!(
1428 "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1429 client_id,
1430 sender_id,
1431 type_name,
1432 error
1433 );
1434 }
1435 }
1436 })
1437 .detach();
1438 } else {
1439 log::info!("unhandled message {}", type_name);
1440 self.peer.respond_with_unhandled_message(message).log_err();
1441 }
1442 }
1443
1444 pub fn telemetry(&self) -> &Arc<Telemetry> {
1445 &self.telemetry
1446 }
1447}
1448
1449async fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1450 if IMPERSONATE_LOGIN.is_some() {
1451 return None;
1452 }
1453
1454 let (user_id, access_token) = cx
1455 .update(|cx| cx.read_credentials(&ClientSettings::get_global(cx).server_url))
1456 .log_err()?
1457 .await
1458 .log_err()??;
1459
1460 Some(Credentials::User {
1461 user_id: user_id.parse().ok()?,
1462 access_token: String::from_utf8(access_token).ok()?,
1463 })
1464}
1465
1466async fn write_credentials_to_keychain(
1467 user_id: u64,
1468 access_token: String,
1469 cx: &AsyncAppContext,
1470) -> Result<()> {
1471 cx.update(move |cx| {
1472 cx.write_credentials(
1473 &ClientSettings::get_global(cx).server_url,
1474 &user_id.to_string(),
1475 access_token.as_bytes(),
1476 )
1477 })?
1478 .await
1479}
1480
1481async fn delete_credentials_from_keychain(cx: &AsyncAppContext) -> Result<()> {
1482 cx.update(move |cx| cx.delete_credentials(&ClientSettings::get_global(cx).server_url))?
1483 .await
1484}
1485
1486/// prefix for the zed:// url scheme
1487pub static ZED_URL_SCHEME: &str = "zed";
1488
1489/// Parses the given link into a Zed link.
1490///
1491/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1492/// Returns [`None`] otherwise.
1493pub fn parse_zed_link<'a>(link: &'a str, cx: &AppContext) -> Option<&'a str> {
1494 let server_url = &ClientSettings::get_global(cx).server_url;
1495 if let Some(stripped) = link
1496 .strip_prefix(server_url)
1497 .and_then(|result| result.strip_prefix('/'))
1498 {
1499 return Some(stripped);
1500 }
1501 if let Some(stripped) = link
1502 .strip_prefix(ZED_URL_SCHEME)
1503 .and_then(|result| result.strip_prefix("://"))
1504 {
1505 return Some(stripped);
1506 }
1507
1508 None
1509}
1510
1511#[cfg(test)]
1512mod tests {
1513 use super::*;
1514 use crate::test::FakeServer;
1515
1516 use clock::FakeSystemClock;
1517 use gpui::{BackgroundExecutor, Context, TestAppContext};
1518 use parking_lot::Mutex;
1519 use settings::SettingsStore;
1520 use std::future;
1521 use util::http::FakeHttpClient;
1522
1523 #[gpui::test(iterations = 10)]
1524 async fn test_reconnection(cx: &mut TestAppContext) {
1525 init_test(cx);
1526 let user_id = 5;
1527 let client = cx.update(|cx| {
1528 Client::new(
1529 Arc::new(FakeSystemClock::default()),
1530 FakeHttpClient::with_404_response(),
1531 cx,
1532 )
1533 });
1534 let server = FakeServer::for_client(user_id, &client, cx).await;
1535 let mut status = client.status();
1536 assert!(matches!(
1537 status.next().await,
1538 Some(Status::Connected { .. })
1539 ));
1540 assert_eq!(server.auth_count(), 1);
1541
1542 server.forbid_connections();
1543 server.disconnect();
1544 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1545
1546 server.allow_connections();
1547 cx.executor().advance_clock(Duration::from_secs(10));
1548 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1549 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1550
1551 server.forbid_connections();
1552 server.disconnect();
1553 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1554
1555 // Clear cached credentials after authentication fails
1556 server.roll_access_token();
1557 server.allow_connections();
1558 cx.executor().run_until_parked();
1559 cx.executor().advance_clock(Duration::from_secs(10));
1560 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1561 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1562 }
1563
1564 #[gpui::test(iterations = 10)]
1565 async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1566 init_test(cx);
1567 let user_id = 5;
1568 let client = cx.update(|cx| {
1569 Client::new(
1570 Arc::new(FakeSystemClock::default()),
1571 FakeHttpClient::with_404_response(),
1572 cx,
1573 )
1574 });
1575 let mut status = client.status();
1576
1577 // Time out when client tries to connect.
1578 client.override_authenticate(move |cx| {
1579 cx.background_executor().spawn(async move {
1580 Ok(Credentials::User {
1581 user_id,
1582 access_token: "token".into(),
1583 })
1584 })
1585 });
1586 client.override_establish_connection(|_, cx| {
1587 cx.background_executor().spawn(async move {
1588 future::pending::<()>().await;
1589 unreachable!()
1590 })
1591 });
1592 let auth_and_connect = cx.spawn({
1593 let client = client.clone();
1594 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1595 });
1596 executor.run_until_parked();
1597 assert!(matches!(status.next().await, Some(Status::Connecting)));
1598
1599 executor.advance_clock(CONNECTION_TIMEOUT);
1600 assert!(matches!(
1601 status.next().await,
1602 Some(Status::ConnectionError { .. })
1603 ));
1604 auth_and_connect.await.unwrap_err();
1605
1606 // Allow the connection to be established.
1607 let server = FakeServer::for_client(user_id, &client, cx).await;
1608 assert!(matches!(
1609 status.next().await,
1610 Some(Status::Connected { .. })
1611 ));
1612
1613 // Disconnect client.
1614 server.forbid_connections();
1615 server.disconnect();
1616 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1617
1618 // Time out when re-establishing the connection.
1619 server.allow_connections();
1620 client.override_establish_connection(|_, cx| {
1621 cx.background_executor().spawn(async move {
1622 future::pending::<()>().await;
1623 unreachable!()
1624 })
1625 });
1626 executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1627 assert!(matches!(
1628 status.next().await,
1629 Some(Status::Reconnecting { .. })
1630 ));
1631
1632 executor.advance_clock(CONNECTION_TIMEOUT);
1633 assert!(matches!(
1634 status.next().await,
1635 Some(Status::ReconnectionError { .. })
1636 ));
1637 }
1638
1639 #[gpui::test(iterations = 10)]
1640 async fn test_authenticating_more_than_once(
1641 cx: &mut TestAppContext,
1642 executor: BackgroundExecutor,
1643 ) {
1644 init_test(cx);
1645 let auth_count = Arc::new(Mutex::new(0));
1646 let dropped_auth_count = Arc::new(Mutex::new(0));
1647 let client = cx.update(|cx| {
1648 Client::new(
1649 Arc::new(FakeSystemClock::default()),
1650 FakeHttpClient::with_404_response(),
1651 cx,
1652 )
1653 });
1654 client.override_authenticate({
1655 let auth_count = auth_count.clone();
1656 let dropped_auth_count = dropped_auth_count.clone();
1657 move |cx| {
1658 let auth_count = auth_count.clone();
1659 let dropped_auth_count = dropped_auth_count.clone();
1660 cx.background_executor().spawn(async move {
1661 *auth_count.lock() += 1;
1662 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1663 future::pending::<()>().await;
1664 unreachable!()
1665 })
1666 }
1667 });
1668
1669 let _authenticate = cx.spawn({
1670 let client = client.clone();
1671 move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1672 });
1673 executor.run_until_parked();
1674 assert_eq!(*auth_count.lock(), 1);
1675 assert_eq!(*dropped_auth_count.lock(), 0);
1676
1677 let _authenticate = cx.spawn({
1678 let client = client.clone();
1679 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1680 });
1681 executor.run_until_parked();
1682 assert_eq!(*auth_count.lock(), 2);
1683 assert_eq!(*dropped_auth_count.lock(), 1);
1684 }
1685
1686 #[gpui::test]
1687 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1688 init_test(cx);
1689 let user_id = 5;
1690 let client = cx.update(|cx| {
1691 Client::new(
1692 Arc::new(FakeSystemClock::default()),
1693 FakeHttpClient::with_404_response(),
1694 cx,
1695 )
1696 });
1697 let server = FakeServer::for_client(user_id, &client, cx).await;
1698
1699 let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1700 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1701 client.add_model_message_handler(
1702 move |model: Model<TestModel>, _: TypedEnvelope<proto::JoinProject>, _, mut cx| {
1703 match model.update(&mut cx, |model, _| model.id).unwrap() {
1704 1 => done_tx1.try_send(()).unwrap(),
1705 2 => done_tx2.try_send(()).unwrap(),
1706 _ => unreachable!(),
1707 }
1708 async { Ok(()) }
1709 },
1710 );
1711 let model1 = cx.new_model(|_| TestModel {
1712 id: 1,
1713 subscription: None,
1714 });
1715 let model2 = cx.new_model(|_| TestModel {
1716 id: 2,
1717 subscription: None,
1718 });
1719 let model3 = cx.new_model(|_| TestModel {
1720 id: 3,
1721 subscription: None,
1722 });
1723
1724 let _subscription1 = client
1725 .subscribe_to_entity(1)
1726 .unwrap()
1727 .set_model(&model1, &mut cx.to_async());
1728 let _subscription2 = client
1729 .subscribe_to_entity(2)
1730 .unwrap()
1731 .set_model(&model2, &mut cx.to_async());
1732 // Ensure dropping a subscription for the same entity type still allows receiving of
1733 // messages for other entity IDs of the same type.
1734 let subscription3 = client
1735 .subscribe_to_entity(3)
1736 .unwrap()
1737 .set_model(&model3, &mut cx.to_async());
1738 drop(subscription3);
1739
1740 server.send(proto::JoinProject { project_id: 1 });
1741 server.send(proto::JoinProject { project_id: 2 });
1742 done_rx1.next().await.unwrap();
1743 done_rx2.next().await.unwrap();
1744 }
1745
1746 #[gpui::test]
1747 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1748 init_test(cx);
1749 let user_id = 5;
1750 let client = cx.update(|cx| {
1751 Client::new(
1752 Arc::new(FakeSystemClock::default()),
1753 FakeHttpClient::with_404_response(),
1754 cx,
1755 )
1756 });
1757 let server = FakeServer::for_client(user_id, &client, cx).await;
1758
1759 let model = cx.new_model(|_| TestModel::default());
1760 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1761 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1762 let subscription1 = client.add_message_handler(
1763 model.downgrade(),
1764 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1765 done_tx1.try_send(()).unwrap();
1766 async { Ok(()) }
1767 },
1768 );
1769 drop(subscription1);
1770 let _subscription2 = client.add_message_handler(
1771 model.downgrade(),
1772 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1773 done_tx2.try_send(()).unwrap();
1774 async { Ok(()) }
1775 },
1776 );
1777 server.send(proto::Ping {});
1778 done_rx2.next().await.unwrap();
1779 }
1780
1781 #[gpui::test]
1782 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1783 init_test(cx);
1784 let user_id = 5;
1785 let client = cx.update(|cx| {
1786 Client::new(
1787 Arc::new(FakeSystemClock::default()),
1788 FakeHttpClient::with_404_response(),
1789 cx,
1790 )
1791 });
1792 let server = FakeServer::for_client(user_id, &client, cx).await;
1793
1794 let model = cx.new_model(|_| TestModel::default());
1795 let (done_tx, mut done_rx) = smol::channel::unbounded();
1796 let subscription = client.add_message_handler(
1797 model.clone().downgrade(),
1798 move |model: Model<TestModel>, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1799 model
1800 .update(&mut cx, |model, _| model.subscription.take())
1801 .unwrap();
1802 done_tx.try_send(()).unwrap();
1803 async { Ok(()) }
1804 },
1805 );
1806 model.update(cx, |model, _| {
1807 model.subscription = Some(subscription);
1808 });
1809 server.send(proto::Ping {});
1810 done_rx.next().await.unwrap();
1811 }
1812
1813 #[derive(Default)]
1814 struct TestModel {
1815 id: usize,
1816 subscription: Option<Subscription>,
1817 }
1818
1819 fn init_test(cx: &mut TestAppContext) {
1820 cx.update(|cx| {
1821 let settings_store = SettingsStore::test(cx);
1822 cx.set_global(settings_store);
1823 init_settings(cx);
1824 });
1825 }
1826}