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