1#[cfg(any(test, feature = "test-support"))]
2pub mod test;
3
4mod proxy;
5pub mod telemetry;
6pub mod user;
7pub mod zed_urls;
8
9use anyhow::{Context as _, Result, anyhow};
10use async_tungstenite::tungstenite::{
11 client::IntoClientRequest,
12 error::Error as WebsocketError,
13 http::{HeaderValue, Request, StatusCode},
14};
15use clock::SystemClock;
16use cloud_api_client::CloudApiClient;
17use cloud_api_client::websocket_protocol::MessageToClient;
18use credentials_provider::CredentialsProvider;
19use feature_flags::FeatureFlagAppExt as _;
20use futures::{
21 AsyncReadExt, FutureExt, SinkExt, Stream, StreamExt, TryFutureExt as _, TryStreamExt,
22 channel::oneshot, future::BoxFuture,
23};
24use gpui::{App, AsyncApp, Entity, Global, Task, WeakEntity, actions};
25use http_client::{HttpClient, HttpClientWithUrl, http};
26use parking_lot::RwLock;
27use postage::watch;
28use proxy::connect_proxy_stream;
29use rand::prelude::*;
30use release_channel::{AppVersion, ReleaseChannel};
31use rpc::proto::{AnyTypedEnvelope, EnvelopedMessage, PeerId, RequestMessage};
32use schemars::JsonSchema;
33use serde::{Deserialize, Serialize};
34use settings::{Settings, SettingsSources};
35use std::{
36 any::TypeId,
37 convert::TryFrom,
38 fmt::Write as _,
39 future::Future,
40 marker::PhantomData,
41 path::PathBuf,
42 sync::{
43 Arc, LazyLock, Weak,
44 atomic::{AtomicU64, Ordering},
45 },
46 time::{Duration, Instant},
47};
48use std::{cmp, pin::Pin};
49use telemetry::Telemetry;
50use thiserror::Error;
51use tokio::net::TcpStream;
52use url::Url;
53use util::{ConnectionResult, ResultExt};
54
55pub use rpc::*;
56pub use telemetry_events::Event;
57pub use user::*;
58
59static ZED_SERVER_URL: LazyLock<Option<String>> =
60 LazyLock::new(|| std::env::var("ZED_SERVER_URL").ok());
61static ZED_RPC_URL: LazyLock<Option<String>> = LazyLock::new(|| std::env::var("ZED_RPC_URL").ok());
62
63pub static IMPERSONATE_LOGIN: LazyLock<Option<String>> = LazyLock::new(|| {
64 std::env::var("ZED_IMPERSONATE")
65 .ok()
66 .and_then(|s| if s.is_empty() { None } else { Some(s) })
67});
68
69pub static ADMIN_API_TOKEN: LazyLock<Option<String>> = LazyLock::new(|| {
70 std::env::var("ZED_ADMIN_API_TOKEN")
71 .ok()
72 .and_then(|s| if s.is_empty() { None } else { Some(s) })
73});
74
75pub static ZED_APP_PATH: LazyLock<Option<PathBuf>> =
76 LazyLock::new(|| std::env::var("ZED_APP_PATH").ok().map(PathBuf::from));
77
78pub static ZED_ALWAYS_ACTIVE: LazyLock<bool> =
79 LazyLock::new(|| std::env::var("ZED_ALWAYS_ACTIVE").is_ok_and(|e| !e.is_empty()));
80
81pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(500);
82pub const MAX_RECONNECTION_DELAY: Duration = Duration::from_secs(30);
83pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(20);
84
85actions!(
86 client,
87 [
88 /// Signs in to Zed account.
89 SignIn,
90 /// Signs out of Zed account.
91 SignOut,
92 /// Reconnects to the collaboration server.
93 Reconnect
94 ]
95);
96
97#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
98pub struct ClientSettingsContent {
99 server_url: Option<String>,
100}
101
102#[derive(Deserialize)]
103pub struct ClientSettings {
104 pub server_url: String,
105}
106
107impl Settings for ClientSettings {
108 const KEY: Option<&'static str> = None;
109
110 type FileContent = ClientSettingsContent;
111
112 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
113 let mut result = sources.json_merge::<Self>()?;
114 if let Some(server_url) = &*ZED_SERVER_URL {
115 result.server_url.clone_from(server_url)
116 }
117 Ok(result)
118 }
119
120 fn import_from_vscode(_vscode: &settings::VsCodeSettings, _current: &mut Self::FileContent) {}
121}
122
123#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
124pub struct ProxySettingsContent {
125 proxy: Option<String>,
126}
127
128#[derive(Deserialize, Default)]
129pub struct ProxySettings {
130 pub proxy: Option<String>,
131}
132
133impl Settings for ProxySettings {
134 const KEY: Option<&'static str> = None;
135
136 type FileContent = ProxySettingsContent;
137
138 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
139 Ok(Self {
140 proxy: sources
141 .user
142 .or(sources.server)
143 .and_then(|value| value.proxy.clone())
144 .or(sources.default.proxy.clone()),
145 })
146 }
147
148 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
149 vscode.string_setting("http.proxy", &mut current.proxy);
150 }
151}
152
153pub fn init_settings(cx: &mut App) {
154 TelemetrySettings::register(cx);
155 ClientSettings::register(cx);
156 ProxySettings::register(cx);
157}
158
159pub fn init(client: &Arc<Client>, cx: &mut App) {
160 let client = Arc::downgrade(client);
161 cx.on_action({
162 let client = client.clone();
163 move |_: &SignIn, cx| {
164 if let Some(client) = client.upgrade() {
165 cx.spawn(async move |cx| client.sign_in_with_optional_connect(true, cx).await)
166 .detach_and_log_err(cx);
167 }
168 }
169 });
170
171 cx.on_action({
172 let client = client.clone();
173 move |_: &SignOut, cx| {
174 if let Some(client) = client.upgrade() {
175 cx.spawn(async move |cx| {
176 client.sign_out(cx).await;
177 })
178 .detach();
179 }
180 }
181 });
182
183 cx.on_action({
184 let client = client;
185 move |_: &Reconnect, cx| {
186 if let Some(client) = client.upgrade() {
187 cx.spawn(async move |cx| {
188 client.reconnect(cx);
189 })
190 .detach();
191 }
192 }
193 });
194}
195
196pub type MessageToClientHandler = Box<dyn Fn(&MessageToClient, &mut App) + Send + Sync + 'static>;
197
198struct GlobalClient(Arc<Client>);
199
200impl Global for GlobalClient {}
201
202pub struct Client {
203 id: AtomicU64,
204 peer: Arc<Peer>,
205 http: Arc<HttpClientWithUrl>,
206 cloud_client: Arc<CloudApiClient>,
207 telemetry: Arc<Telemetry>,
208 credentials_provider: ClientCredentialsProvider,
209 state: RwLock<ClientState>,
210 handler_set: parking_lot::Mutex<ProtoMessageHandlerSet>,
211 message_to_client_handlers: parking_lot::Mutex<Vec<MessageToClientHandler>>,
212
213 #[allow(clippy::type_complexity)]
214 #[cfg(any(test, feature = "test-support"))]
215 authenticate:
216 RwLock<Option<Box<dyn 'static + Send + Sync + Fn(&AsyncApp) -> Task<Result<Credentials>>>>>,
217
218 #[allow(clippy::type_complexity)]
219 #[cfg(any(test, feature = "test-support"))]
220 establish_connection: RwLock<
221 Option<
222 Box<
223 dyn 'static
224 + Send
225 + Sync
226 + Fn(
227 &Credentials,
228 &AsyncApp,
229 ) -> Task<Result<Connection, EstablishConnectionError>>,
230 >,
231 >,
232 >,
233
234 #[cfg(any(test, feature = "test-support"))]
235 rpc_url: RwLock<Option<Url>>,
236}
237
238#[derive(Error, Debug)]
239pub enum EstablishConnectionError {
240 #[error("upgrade required")]
241 UpgradeRequired,
242 #[error("unauthorized")]
243 Unauthorized,
244 #[error("{0}")]
245 Other(#[from] anyhow::Error),
246 #[error("{0}")]
247 InvalidHeaderValue(#[from] async_tungstenite::tungstenite::http::header::InvalidHeaderValue),
248 #[error("{0}")]
249 Io(#[from] std::io::Error),
250 #[error("{0}")]
251 Websocket(#[from] async_tungstenite::tungstenite::http::Error),
252}
253
254impl From<WebsocketError> for EstablishConnectionError {
255 fn from(error: WebsocketError) -> Self {
256 if let WebsocketError::Http(response) = &error {
257 match response.status() {
258 StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
259 StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
260 _ => {}
261 }
262 }
263 EstablishConnectionError::Other(error.into())
264 }
265}
266
267impl EstablishConnectionError {
268 pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
269 Self::Other(error.into())
270 }
271}
272
273#[derive(Copy, Clone, Debug, PartialEq)]
274pub enum Status {
275 SignedOut,
276 UpgradeRequired,
277 Authenticating,
278 Authenticated,
279 AuthenticationError,
280 Connecting,
281 ConnectionError,
282 Connected {
283 peer_id: PeerId,
284 connection_id: ConnectionId,
285 },
286 ConnectionLost,
287 Reauthenticating,
288 Reconnecting,
289 ReconnectionError {
290 next_reconnection: Instant,
291 },
292}
293
294impl Status {
295 pub fn is_connected(&self) -> bool {
296 matches!(self, Self::Connected { .. })
297 }
298
299 pub fn is_signing_in(&self) -> bool {
300 matches!(
301 self,
302 Self::Authenticating | Self::Reauthenticating | Self::Connecting | Self::Reconnecting
303 )
304 }
305
306 pub fn is_signed_out(&self) -> bool {
307 matches!(self, Self::SignedOut | Self::UpgradeRequired)
308 }
309}
310
311struct ClientState {
312 credentials: Option<Credentials>,
313 status: (watch::Sender<Status>, watch::Receiver<Status>),
314 _reconnect_task: Option<Task<()>>,
315}
316
317#[derive(Clone, Debug, Eq, PartialEq)]
318pub struct Credentials {
319 pub user_id: u64,
320 pub access_token: String,
321}
322
323impl Credentials {
324 pub fn authorization_header(&self) -> String {
325 format!("{} {}", self.user_id, self.access_token)
326 }
327}
328
329pub struct ClientCredentialsProvider {
330 provider: Arc<dyn CredentialsProvider>,
331}
332
333impl ClientCredentialsProvider {
334 pub fn new(cx: &App) -> Self {
335 Self {
336 provider: <dyn CredentialsProvider>::global(cx),
337 }
338 }
339
340 fn server_url(&self, cx: &AsyncApp) -> Result<String> {
341 cx.update(|cx| ClientSettings::get_global(cx).server_url.clone())
342 }
343
344 /// Reads the credentials from the provider.
345 fn read_credentials<'a>(
346 &'a self,
347 cx: &'a AsyncApp,
348 ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
349 async move {
350 if IMPERSONATE_LOGIN.is_some() {
351 return None;
352 }
353
354 let server_url = self.server_url(cx).ok()?;
355 let (user_id, access_token) = self
356 .provider
357 .read_credentials(&server_url, cx)
358 .await
359 .log_err()
360 .flatten()?;
361
362 Some(Credentials {
363 user_id: user_id.parse().ok()?,
364 access_token: String::from_utf8(access_token).ok()?,
365 })
366 }
367 .boxed_local()
368 }
369
370 /// Writes the credentials to the provider.
371 fn write_credentials<'a>(
372 &'a self,
373 user_id: u64,
374 access_token: String,
375 cx: &'a AsyncApp,
376 ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
377 async move {
378 let server_url = self.server_url(cx)?;
379 self.provider
380 .write_credentials(
381 &server_url,
382 &user_id.to_string(),
383 access_token.as_bytes(),
384 cx,
385 )
386 .await
387 }
388 .boxed_local()
389 }
390
391 /// Deletes the credentials from the provider.
392 fn delete_credentials<'a>(
393 &'a self,
394 cx: &'a AsyncApp,
395 ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
396 async move {
397 let server_url = self.server_url(cx)?;
398 self.provider.delete_credentials(&server_url, cx).await
399 }
400 .boxed_local()
401 }
402}
403
404impl Default for ClientState {
405 fn default() -> Self {
406 Self {
407 credentials: None,
408 status: watch::channel_with(Status::SignedOut),
409 _reconnect_task: None,
410 }
411 }
412}
413
414pub enum Subscription {
415 Entity {
416 client: Weak<Client>,
417 id: (TypeId, u64),
418 },
419 Message {
420 client: Weak<Client>,
421 id: TypeId,
422 },
423}
424
425impl Drop for Subscription {
426 fn drop(&mut self) {
427 match self {
428 Subscription::Entity { client, id } => {
429 if let Some(client) = client.upgrade() {
430 let mut state = client.handler_set.lock();
431 let _ = state.entities_by_type_and_remote_id.remove(id);
432 }
433 }
434 Subscription::Message { client, id } => {
435 if let Some(client) = client.upgrade() {
436 let mut state = client.handler_set.lock();
437 let _ = state.entity_types_by_message_type.remove(id);
438 let _ = state.message_handlers.remove(id);
439 }
440 }
441 }
442 }
443}
444
445pub struct PendingEntitySubscription<T: 'static> {
446 client: Arc<Client>,
447 remote_id: u64,
448 _entity_type: PhantomData<T>,
449 consumed: bool,
450}
451
452impl<T: 'static> PendingEntitySubscription<T> {
453 pub fn set_entity(mut self, entity: &Entity<T>, cx: &AsyncApp) -> Subscription {
454 self.consumed = true;
455 let mut handlers = self.client.handler_set.lock();
456 let id = (TypeId::of::<T>(), self.remote_id);
457 let Some(EntityMessageSubscriber::Pending(messages)) =
458 handlers.entities_by_type_and_remote_id.remove(&id)
459 else {
460 unreachable!()
461 };
462
463 handlers.entities_by_type_and_remote_id.insert(
464 id,
465 EntityMessageSubscriber::Entity {
466 handle: entity.downgrade().into(),
467 },
468 );
469 drop(handlers);
470 for message in messages {
471 let client_id = self.client.id();
472 let type_name = message.payload_type_name();
473 let sender_id = message.original_sender_id();
474 log::debug!(
475 "handling queued rpc message. client_id:{}, sender_id:{:?}, type:{}",
476 client_id,
477 sender_id,
478 type_name
479 );
480 self.client.handle_message(message, cx);
481 }
482 Subscription::Entity {
483 client: Arc::downgrade(&self.client),
484 id,
485 }
486 }
487}
488
489impl<T: 'static> Drop for PendingEntitySubscription<T> {
490 fn drop(&mut self) {
491 if !self.consumed {
492 let mut state = self.client.handler_set.lock();
493 if let Some(EntityMessageSubscriber::Pending(messages)) = state
494 .entities_by_type_and_remote_id
495 .remove(&(TypeId::of::<T>(), self.remote_id))
496 {
497 for message in messages {
498 log::info!("unhandled message {}", message.payload_type_name());
499 }
500 }
501 }
502 }
503}
504
505#[derive(Copy, Clone, Deserialize, Debug)]
506pub struct TelemetrySettings {
507 pub diagnostics: bool,
508 pub metrics: bool,
509}
510
511/// Control what info is collected by Zed.
512#[derive(Default, Clone, Serialize, Deserialize, JsonSchema, Debug)]
513pub struct TelemetrySettingsContent {
514 /// Send debug info like crash reports.
515 ///
516 /// Default: true
517 pub diagnostics: Option<bool>,
518 /// Send anonymized usage data like what languages you're using Zed with.
519 ///
520 /// Default: true
521 pub metrics: Option<bool>,
522}
523
524impl settings::Settings for TelemetrySettings {
525 const KEY: Option<&'static str> = Some("telemetry");
526
527 type FileContent = TelemetrySettingsContent;
528
529 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
530 sources.json_merge()
531 }
532
533 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
534 vscode.enum_setting("telemetry.telemetryLevel", &mut current.metrics, |s| {
535 Some(s == "all")
536 });
537 vscode.enum_setting("telemetry.telemetryLevel", &mut current.diagnostics, |s| {
538 Some(matches!(s, "all" | "error" | "crash"))
539 });
540 // we could translate telemetry.telemetryLevel, but just because users didn't want
541 // to send microsoft telemetry doesn't mean they don't want to send it to zed. their
542 // all/error/crash/off correspond to combinations of our "diagnostics" and "metrics".
543 }
544}
545
546impl Client {
547 pub fn new(
548 clock: Arc<dyn SystemClock>,
549 http: Arc<HttpClientWithUrl>,
550 cx: &mut App,
551 ) -> Arc<Self> {
552 Arc::new(Self {
553 id: AtomicU64::new(0),
554 peer: Peer::new(0),
555 telemetry: Telemetry::new(clock, http.clone(), cx),
556 cloud_client: Arc::new(CloudApiClient::new(http.clone())),
557 http,
558 credentials_provider: ClientCredentialsProvider::new(cx),
559 state: Default::default(),
560 handler_set: Default::default(),
561 message_to_client_handlers: parking_lot::Mutex::new(Vec::new()),
562
563 #[cfg(any(test, feature = "test-support"))]
564 authenticate: Default::default(),
565 #[cfg(any(test, feature = "test-support"))]
566 establish_connection: Default::default(),
567 #[cfg(any(test, feature = "test-support"))]
568 rpc_url: RwLock::default(),
569 })
570 }
571
572 pub fn production(cx: &mut App) -> Arc<Self> {
573 let clock = Arc::new(clock::RealSystemClock);
574 let http = Arc::new(HttpClientWithUrl::new_url(
575 cx.http_client(),
576 &ClientSettings::get_global(cx).server_url,
577 cx.http_client().proxy().cloned(),
578 ));
579 Self::new(clock, http, cx)
580 }
581
582 pub fn id(&self) -> u64 {
583 self.id.load(Ordering::SeqCst)
584 }
585
586 pub fn http_client(&self) -> Arc<HttpClientWithUrl> {
587 self.http.clone()
588 }
589
590 pub fn cloud_client(&self) -> Arc<CloudApiClient> {
591 self.cloud_client.clone()
592 }
593
594 pub fn set_id(&self, id: u64) -> &Self {
595 self.id.store(id, Ordering::SeqCst);
596 self
597 }
598
599 #[cfg(any(test, feature = "test-support"))]
600 pub fn teardown(&self) {
601 let mut state = self.state.write();
602 state._reconnect_task.take();
603 self.handler_set.lock().clear();
604 self.peer.teardown();
605 }
606
607 #[cfg(any(test, feature = "test-support"))]
608 pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
609 where
610 F: 'static + Send + Sync + Fn(&AsyncApp) -> Task<Result<Credentials>>,
611 {
612 *self.authenticate.write() = Some(Box::new(authenticate));
613 self
614 }
615
616 #[cfg(any(test, feature = "test-support"))]
617 pub fn override_establish_connection<F>(&self, connect: F) -> &Self
618 where
619 F: 'static
620 + Send
621 + Sync
622 + Fn(&Credentials, &AsyncApp) -> Task<Result<Connection, EstablishConnectionError>>,
623 {
624 *self.establish_connection.write() = Some(Box::new(connect));
625 self
626 }
627
628 #[cfg(any(test, feature = "test-support"))]
629 pub fn override_rpc_url(&self, url: Url) -> &Self {
630 *self.rpc_url.write() = Some(url);
631 self
632 }
633
634 pub fn global(cx: &App) -> Arc<Self> {
635 cx.global::<GlobalClient>().0.clone()
636 }
637 pub fn set_global(client: Arc<Client>, cx: &mut App) {
638 cx.set_global(GlobalClient(client))
639 }
640
641 pub fn user_id(&self) -> Option<u64> {
642 self.state
643 .read()
644 .credentials
645 .as_ref()
646 .map(|credentials| credentials.user_id)
647 }
648
649 pub fn peer_id(&self) -> Option<PeerId> {
650 if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
651 Some(*peer_id)
652 } else {
653 None
654 }
655 }
656
657 pub fn status(&self) -> watch::Receiver<Status> {
658 self.state.read().status.1.clone()
659 }
660
661 fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncApp) {
662 log::info!("set status on client {}: {:?}", self.id(), status);
663 let mut state = self.state.write();
664 *state.status.0.borrow_mut() = status;
665
666 match status {
667 Status::Connected { .. } => {
668 state._reconnect_task = None;
669 }
670 Status::ConnectionLost => {
671 let client = self.clone();
672 state._reconnect_task = Some(cx.spawn(async move |cx| {
673 #[cfg(any(test, feature = "test-support"))]
674 let mut rng = StdRng::seed_from_u64(0);
675 #[cfg(not(any(test, feature = "test-support")))]
676 let mut rng = StdRng::from_entropy();
677
678 let mut delay = INITIAL_RECONNECTION_DELAY;
679 loop {
680 match client.connect(true, cx).await {
681 ConnectionResult::Timeout => {
682 log::error!("client connect attempt timed out")
683 }
684 ConnectionResult::ConnectionReset => {
685 log::error!("client connect attempt reset")
686 }
687 ConnectionResult::Result(r) => {
688 if let Err(error) = r {
689 log::error!("failed to connect: {error}");
690 } else {
691 break;
692 }
693 }
694 }
695
696 if matches!(
697 *client.status().borrow(),
698 Status::AuthenticationError | Status::ConnectionError
699 ) {
700 client.set_status(
701 Status::ReconnectionError {
702 next_reconnection: Instant::now() + delay,
703 },
704 cx,
705 );
706 let jitter =
707 Duration::from_millis(rng.gen_range(0..delay.as_millis() as u64));
708 cx.background_executor().timer(delay + jitter).await;
709 delay = cmp::min(delay * 2, MAX_RECONNECTION_DELAY);
710 } else {
711 break;
712 }
713 }
714 }));
715 }
716 Status::SignedOut | Status::UpgradeRequired => {
717 self.telemetry.set_authenticated_user_info(None, false);
718 state._reconnect_task.take();
719 }
720 _ => {}
721 }
722 }
723
724 pub fn subscribe_to_entity<T>(
725 self: &Arc<Self>,
726 remote_id: u64,
727 ) -> Result<PendingEntitySubscription<T>>
728 where
729 T: 'static,
730 {
731 let id = (TypeId::of::<T>(), remote_id);
732
733 let mut state = self.handler_set.lock();
734 anyhow::ensure!(
735 !state.entities_by_type_and_remote_id.contains_key(&id),
736 "already subscribed to entity"
737 );
738
739 state
740 .entities_by_type_and_remote_id
741 .insert(id, EntityMessageSubscriber::Pending(Default::default()));
742
743 Ok(PendingEntitySubscription {
744 client: self.clone(),
745 remote_id,
746 consumed: false,
747 _entity_type: PhantomData,
748 })
749 }
750
751 #[track_caller]
752 pub fn add_message_handler<M, E, H, F>(
753 self: &Arc<Self>,
754 entity: WeakEntity<E>,
755 handler: H,
756 ) -> Subscription
757 where
758 M: EnvelopedMessage,
759 E: 'static,
760 H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
761 F: 'static + Future<Output = Result<()>>,
762 {
763 self.add_message_handler_impl(entity, move |entity, message, _, cx| {
764 handler(entity, message, cx)
765 })
766 }
767
768 fn add_message_handler_impl<M, E, H, F>(
769 self: &Arc<Self>,
770 entity: WeakEntity<E>,
771 handler: H,
772 ) -> Subscription
773 where
774 M: EnvelopedMessage,
775 E: 'static,
776 H: 'static
777 + Sync
778 + Fn(Entity<E>, TypedEnvelope<M>, AnyProtoClient, AsyncApp) -> F
779 + Send
780 + Sync,
781 F: 'static + Future<Output = Result<()>>,
782 {
783 let message_type_id = TypeId::of::<M>();
784 let mut state = self.handler_set.lock();
785 state
786 .entities_by_message_type
787 .insert(message_type_id, entity.into());
788
789 let prev_handler = state.message_handlers.insert(
790 message_type_id,
791 Arc::new(move |subscriber, envelope, client, cx| {
792 let subscriber = subscriber.downcast::<E>().unwrap();
793 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
794 handler(subscriber, *envelope, client, cx).boxed_local()
795 }),
796 );
797 if prev_handler.is_some() {
798 let location = std::panic::Location::caller();
799 panic!(
800 "{}:{} registered handler for the same message {} twice",
801 location.file(),
802 location.line(),
803 std::any::type_name::<M>()
804 );
805 }
806
807 Subscription::Message {
808 client: Arc::downgrade(self),
809 id: message_type_id,
810 }
811 }
812
813 pub fn add_request_handler<M, E, H, F>(
814 self: &Arc<Self>,
815 entity: WeakEntity<E>,
816 handler: H,
817 ) -> Subscription
818 where
819 M: RequestMessage,
820 E: 'static,
821 H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
822 F: 'static + Future<Output = Result<M::Response>>,
823 {
824 self.add_message_handler_impl(entity, move |handle, envelope, this, cx| {
825 Self::respond_to_request(envelope.receipt(), handler(handle, envelope, cx), this)
826 })
827 }
828
829 async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
830 receipt: Receipt<T>,
831 response: F,
832 client: AnyProtoClient,
833 ) -> Result<()> {
834 match response.await {
835 Ok(response) => {
836 client.send_response(receipt.message_id, response)?;
837 Ok(())
838 }
839 Err(error) => {
840 client.send_response(receipt.message_id, error.to_proto())?;
841 Err(error)
842 }
843 }
844 }
845
846 pub async fn has_credentials(&self, cx: &AsyncApp) -> bool {
847 self.credentials_provider
848 .read_credentials(cx)
849 .await
850 .is_some()
851 }
852
853 pub async fn sign_in(
854 self: &Arc<Self>,
855 try_provider: bool,
856 cx: &AsyncApp,
857 ) -> Result<Credentials> {
858 if self.status().borrow().is_signed_out() {
859 self.set_status(Status::Authenticating, cx);
860 } else {
861 self.set_status(Status::Reauthenticating, cx);
862 }
863
864 let mut credentials = None;
865
866 let old_credentials = self.state.read().credentials.clone();
867 if let Some(old_credentials) = old_credentials
868 && self.validate_credentials(&old_credentials, cx).await?
869 {
870 credentials = Some(old_credentials);
871 }
872
873 if credentials.is_none()
874 && try_provider
875 && let Some(stored_credentials) = self.credentials_provider.read_credentials(cx).await
876 {
877 if self.validate_credentials(&stored_credentials, cx).await? {
878 credentials = Some(stored_credentials);
879 } else {
880 self.credentials_provider
881 .delete_credentials(cx)
882 .await
883 .log_err();
884 }
885 }
886
887 if credentials.is_none() {
888 let mut status_rx = self.status();
889 let _ = status_rx.next().await;
890 futures::select_biased! {
891 authenticate = self.authenticate(cx).fuse() => {
892 match authenticate {
893 Ok(creds) => {
894 if IMPERSONATE_LOGIN.is_none() {
895 self.credentials_provider
896 .write_credentials(creds.user_id, creds.access_token.clone(), cx)
897 .await
898 .log_err();
899 }
900
901 credentials = Some(creds);
902 },
903 Err(err) => {
904 self.set_status(Status::AuthenticationError, cx);
905 return Err(err);
906 }
907 }
908 }
909 _ = status_rx.next().fuse() => {
910 return Err(anyhow!("authentication canceled"));
911 }
912 }
913 }
914
915 let credentials = credentials.unwrap();
916 self.set_id(credentials.user_id);
917 self.cloud_client
918 .set_credentials(credentials.user_id as u32, credentials.access_token.clone());
919 self.state.write().credentials = Some(credentials.clone());
920 self.set_status(Status::Authenticated, cx);
921
922 Ok(credentials)
923 }
924
925 async fn validate_credentials(
926 self: &Arc<Self>,
927 credentials: &Credentials,
928 cx: &AsyncApp,
929 ) -> Result<bool> {
930 match self
931 .cloud_client
932 .validate_credentials(credentials.user_id as u32, &credentials.access_token)
933 .await
934 {
935 Ok(valid) => Ok(valid),
936 Err(err) => {
937 self.set_status(Status::AuthenticationError, cx);
938 Err(anyhow!("failed to validate credentials: {}", err))
939 }
940 }
941 }
942
943 /// Establishes a WebSocket connection with Cloud for receiving updates from the server.
944 async fn connect_to_cloud(self: &Arc<Self>, cx: &AsyncApp) -> Result<()> {
945 let connect_task = cx.update({
946 let cloud_client = self.cloud_client.clone();
947 move |cx| cloud_client.connect(cx)
948 })??;
949 let connection = connect_task.await?;
950
951 let (mut messages, task) = cx.update(|cx| connection.spawn(cx))?;
952 task.detach();
953
954 cx.spawn({
955 let this = self.clone();
956 async move |cx| {
957 while let Some(message) = messages.next().await {
958 if let Some(message) = message.log_err() {
959 this.handle_message_to_client(message, cx);
960 }
961 }
962 }
963 })
964 .detach();
965
966 Ok(())
967 }
968
969 /// Performs a sign-in and also (optionally) connects to Collab.
970 ///
971 /// Only Zed staff automatically connect to Collab.
972 pub async fn sign_in_with_optional_connect(
973 self: &Arc<Self>,
974 try_provider: bool,
975 cx: &AsyncApp,
976 ) -> Result<()> {
977 // Don't try to sign in again if we're already connected to Collab, as it will temporarily disconnect us.
978 if self.status().borrow().is_connected() {
979 return Ok(());
980 }
981
982 let (is_staff_tx, is_staff_rx) = oneshot::channel::<bool>();
983 let mut is_staff_tx = Some(is_staff_tx);
984 cx.update(|cx| {
985 cx.on_flags_ready(move |state, _cx| {
986 if let Some(is_staff_tx) = is_staff_tx.take() {
987 is_staff_tx.send(state.is_staff).log_err();
988 }
989 })
990 .detach();
991 })
992 .log_err();
993
994 let credentials = self.sign_in(try_provider, cx).await?;
995
996 self.connect_to_cloud(cx).await.log_err();
997
998 cx.update(move |cx| {
999 cx.spawn({
1000 let client = self.clone();
1001 async move |cx| {
1002 let is_staff = is_staff_rx.await?;
1003 if is_staff {
1004 match client.connect_with_credentials(credentials, cx).await {
1005 ConnectionResult::Timeout => Err(anyhow!("connection timed out")),
1006 ConnectionResult::ConnectionReset => Err(anyhow!("connection reset")),
1007 ConnectionResult::Result(result) => {
1008 result.context("client auth and connect")
1009 }
1010 }
1011 } else {
1012 Ok(())
1013 }
1014 }
1015 })
1016 .detach_and_log_err(cx);
1017 })
1018 .log_err();
1019
1020 Ok(())
1021 }
1022
1023 pub async fn connect(
1024 self: &Arc<Self>,
1025 try_provider: bool,
1026 cx: &AsyncApp,
1027 ) -> ConnectionResult<()> {
1028 let was_disconnected = match *self.status().borrow() {
1029 Status::SignedOut | Status::Authenticated => true,
1030 Status::ConnectionError
1031 | Status::ConnectionLost
1032 | Status::Authenticating
1033 | Status::AuthenticationError
1034 | Status::Reauthenticating
1035 | Status::ReconnectionError { .. } => false,
1036 Status::Connected { .. } | Status::Connecting | Status::Reconnecting => {
1037 return ConnectionResult::Result(Ok(()));
1038 }
1039 Status::UpgradeRequired => {
1040 return ConnectionResult::Result(
1041 Err(EstablishConnectionError::UpgradeRequired)
1042 .context("client auth and connect"),
1043 );
1044 }
1045 };
1046 let credentials = match self.sign_in(try_provider, cx).await {
1047 Ok(credentials) => credentials,
1048 Err(err) => return ConnectionResult::Result(Err(err)),
1049 };
1050
1051 if was_disconnected {
1052 self.set_status(Status::Connecting, cx);
1053 } else {
1054 self.set_status(Status::Reconnecting, cx);
1055 }
1056
1057 self.connect_with_credentials(credentials, cx).await
1058 }
1059
1060 async fn connect_with_credentials(
1061 self: &Arc<Self>,
1062 credentials: Credentials,
1063 cx: &AsyncApp,
1064 ) -> ConnectionResult<()> {
1065 let mut timeout =
1066 futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
1067 futures::select_biased! {
1068 connection = self.establish_connection(&credentials, cx).fuse() => {
1069 match connection {
1070 Ok(conn) => {
1071 futures::select_biased! {
1072 result = self.set_connection(conn, cx).fuse() => {
1073 match result.context("client auth and connect") {
1074 Ok(()) => ConnectionResult::Result(Ok(())),
1075 Err(err) => {
1076 self.set_status(Status::ConnectionError, cx);
1077 ConnectionResult::Result(Err(err))
1078 },
1079 }
1080 },
1081 _ = timeout => {
1082 self.set_status(Status::ConnectionError, cx);
1083 ConnectionResult::Timeout
1084 }
1085 }
1086 }
1087 Err(EstablishConnectionError::Unauthorized) => {
1088 self.set_status(Status::ConnectionError, cx);
1089 ConnectionResult::Result(Err(EstablishConnectionError::Unauthorized).context("client auth and connect"))
1090 }
1091 Err(EstablishConnectionError::UpgradeRequired) => {
1092 self.set_status(Status::UpgradeRequired, cx);
1093 ConnectionResult::Result(Err(EstablishConnectionError::UpgradeRequired).context("client auth and connect"))
1094 }
1095 Err(error) => {
1096 self.set_status(Status::ConnectionError, cx);
1097 ConnectionResult::Result(Err(error).context("client auth and connect"))
1098 }
1099 }
1100 }
1101 _ = &mut timeout => {
1102 self.set_status(Status::ConnectionError, cx);
1103 ConnectionResult::Timeout
1104 }
1105 }
1106 }
1107
1108 async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncApp) -> Result<()> {
1109 let executor = cx.background_executor();
1110 log::debug!("add connection to peer");
1111 let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
1112 let executor = executor.clone();
1113 move |duration| executor.timer(duration)
1114 });
1115 let handle_io = executor.spawn(handle_io);
1116
1117 let peer_id = async {
1118 log::debug!("waiting for server hello");
1119 let message = incoming.next().await.context("no hello message received")?;
1120 log::debug!("got server hello");
1121 let hello_message_type_name = message.payload_type_name().to_string();
1122 let hello = message
1123 .into_any()
1124 .downcast::<TypedEnvelope<proto::Hello>>()
1125 .map_err(|_| {
1126 anyhow!(
1127 "invalid hello message received: {:?}",
1128 hello_message_type_name
1129 )
1130 })?;
1131 let peer_id = hello.payload.peer_id.context("invalid peer id")?;
1132 Ok(peer_id)
1133 };
1134
1135 let peer_id = match peer_id.await {
1136 Ok(peer_id) => peer_id,
1137 Err(error) => {
1138 self.peer.disconnect(connection_id);
1139 return Err(error);
1140 }
1141 };
1142
1143 log::debug!(
1144 "set status to connected (connection id: {:?}, peer id: {:?})",
1145 connection_id,
1146 peer_id
1147 );
1148 self.set_status(
1149 Status::Connected {
1150 peer_id,
1151 connection_id,
1152 },
1153 cx,
1154 );
1155
1156 cx.spawn({
1157 let this = self.clone();
1158 async move |cx| {
1159 while let Some(message) = incoming.next().await {
1160 this.handle_message(message, cx);
1161 // Don't starve the main thread when receiving lots of messages at once.
1162 smol::future::yield_now().await;
1163 }
1164 }
1165 })
1166 .detach();
1167
1168 cx.spawn({
1169 let this = self.clone();
1170 async move |cx| match handle_io.await {
1171 Ok(()) => {
1172 if *this.status().borrow()
1173 == (Status::Connected {
1174 connection_id,
1175 peer_id,
1176 })
1177 {
1178 this.set_status(Status::SignedOut, cx);
1179 }
1180 }
1181 Err(err) => {
1182 log::error!("connection error: {:?}", err);
1183 this.set_status(Status::ConnectionLost, cx);
1184 }
1185 }
1186 })
1187 .detach();
1188
1189 Ok(())
1190 }
1191
1192 fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1193 #[cfg(any(test, feature = "test-support"))]
1194 if let Some(callback) = self.authenticate.read().as_ref() {
1195 return callback(cx);
1196 }
1197
1198 self.authenticate_with_browser(cx)
1199 }
1200
1201 fn establish_connection(
1202 self: &Arc<Self>,
1203 credentials: &Credentials,
1204 cx: &AsyncApp,
1205 ) -> Task<Result<Connection, EstablishConnectionError>> {
1206 #[cfg(any(test, feature = "test-support"))]
1207 if let Some(callback) = self.establish_connection.read().as_ref() {
1208 return callback(credentials, cx);
1209 }
1210
1211 self.establish_websocket_connection(credentials, cx)
1212 }
1213
1214 fn rpc_url(
1215 &self,
1216 http: Arc<HttpClientWithUrl>,
1217 release_channel: Option<ReleaseChannel>,
1218 ) -> impl Future<Output = Result<url::Url>> + use<> {
1219 #[cfg(any(test, feature = "test-support"))]
1220 let url_override = self.rpc_url.read().clone();
1221
1222 async move {
1223 #[cfg(any(test, feature = "test-support"))]
1224 if let Some(url) = url_override {
1225 return Ok(url);
1226 }
1227
1228 if let Some(url) = &*ZED_RPC_URL {
1229 return Url::parse(url).context("invalid rpc url");
1230 }
1231
1232 let mut url = http.build_url("/rpc");
1233 if let Some(preview_param) =
1234 release_channel.and_then(|channel| channel.release_query_param())
1235 {
1236 url += "?";
1237 url += preview_param;
1238 }
1239
1240 let response = http.get(&url, Default::default(), false).await?;
1241 anyhow::ensure!(
1242 response.status().is_redirection(),
1243 "unexpected /rpc response status {}",
1244 response.status()
1245 );
1246 let collab_url = response
1247 .headers()
1248 .get("Location")
1249 .context("missing location header in /rpc response")?
1250 .to_str()
1251 .map_err(EstablishConnectionError::other)?
1252 .to_string();
1253 Url::parse(&collab_url).with_context(|| format!("parsing collab rpc url {collab_url}"))
1254 }
1255 }
1256
1257 fn establish_websocket_connection(
1258 self: &Arc<Self>,
1259 credentials: &Credentials,
1260 cx: &AsyncApp,
1261 ) -> Task<Result<Connection, EstablishConnectionError>> {
1262 let release_channel = cx
1263 .update(|cx| ReleaseChannel::try_global(cx))
1264 .ok()
1265 .flatten();
1266 let app_version = cx
1267 .update(|cx| AppVersion::global(cx).to_string())
1268 .ok()
1269 .unwrap_or_default();
1270
1271 let http = self.http.clone();
1272 let proxy = http.proxy().cloned();
1273 let user_agent = http.user_agent().cloned();
1274 let credentials = credentials.clone();
1275 let rpc_url = self.rpc_url(http, release_channel);
1276 let system_id = self.telemetry.system_id();
1277 let metrics_id = self.telemetry.metrics_id();
1278 cx.spawn(async move |cx| {
1279 use HttpOrHttps::*;
1280
1281 #[derive(Debug)]
1282 enum HttpOrHttps {
1283 Http,
1284 Https,
1285 }
1286
1287 let mut rpc_url = rpc_url.await?;
1288 let url_scheme = match rpc_url.scheme() {
1289 "https" => Https,
1290 "http" => Http,
1291 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1292 };
1293 let rpc_host = rpc_url
1294 .host_str()
1295 .zip(rpc_url.port_or_known_default())
1296 .context("missing host in rpc url")?;
1297
1298 let stream = {
1299 let handle = cx.update(|cx| gpui_tokio::Tokio::handle(cx)).ok().unwrap();
1300 let _guard = handle.enter();
1301 match proxy {
1302 Some(proxy) => connect_proxy_stream(&proxy, rpc_host).await?,
1303 None => Box::new(TcpStream::connect(rpc_host).await?),
1304 }
1305 };
1306
1307 log::info!("connected to rpc endpoint {}", rpc_url);
1308
1309 rpc_url
1310 .set_scheme(match url_scheme {
1311 Https => "wss",
1312 Http => "ws",
1313 })
1314 .unwrap();
1315
1316 // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1317 // for us from the RPC URL.
1318 //
1319 // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1320 let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1321
1322 // We then modify the request to add our desired headers.
1323 let request_headers = request.headers_mut();
1324 request_headers.insert(
1325 http::header::AUTHORIZATION,
1326 HeaderValue::from_str(&credentials.authorization_header())?,
1327 );
1328 request_headers.insert(
1329 "x-zed-protocol-version",
1330 HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1331 );
1332 request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1333 request_headers.insert(
1334 "x-zed-release-channel",
1335 HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1336 );
1337 if let Some(user_agent) = user_agent {
1338 request_headers.insert(http::header::USER_AGENT, user_agent);
1339 }
1340 if let Some(system_id) = system_id {
1341 request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1342 }
1343 if let Some(metrics_id) = metrics_id {
1344 request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1345 }
1346
1347 let (stream, _) = async_tungstenite::tokio::client_async_tls_with_connector_and_config(
1348 request,
1349 stream,
1350 Some(Arc::new(http_client_tls::tls_config()).into()),
1351 None,
1352 )
1353 .await?;
1354
1355 Ok(Connection::new(
1356 stream
1357 .map_err(|error| anyhow!(error))
1358 .sink_map_err(|error| anyhow!(error)),
1359 ))
1360 })
1361 }
1362
1363 pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1364 let http = self.http.clone();
1365 let this = self.clone();
1366 cx.spawn(async move |cx| {
1367 let background = cx.background_executor().clone();
1368
1369 let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1370 cx.update(|cx| {
1371 cx.spawn(async move |cx| {
1372 let url = open_url_rx.await?;
1373 cx.update(|cx| cx.open_url(&url))
1374 })
1375 .detach_and_log_err(cx);
1376 })
1377 .log_err();
1378
1379 let credentials = background
1380 .clone()
1381 .spawn(async move {
1382 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1383 // zed server to encrypt the user's access token, so that it can'be intercepted by
1384 // any other app running on the user's device.
1385 let (public_key, private_key) =
1386 rpc::auth::keypair().expect("failed to generate keypair for auth");
1387 let public_key_string = String::try_from(public_key)
1388 .expect("failed to serialize public key for auth");
1389
1390 if let Some((login, token)) =
1391 IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1392 {
1393 eprintln!("authenticate as admin {login}, {token}");
1394
1395 return this
1396 .authenticate_as_admin(http, login.clone(), token.clone())
1397 .await;
1398 }
1399
1400 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1401 let server =
1402 tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1403 let port = server.server_addr().port();
1404
1405 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1406 // that the user is signing in from a Zed app running on the same device.
1407 let mut url = http.build_url(&format!(
1408 "/native_app_signin?native_app_port={}&native_app_public_key={}",
1409 port, public_key_string
1410 ));
1411
1412 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1413 log::info!("impersonating user @{}", impersonate_login);
1414 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1415 }
1416
1417 open_url_tx.send(url).log_err();
1418
1419 #[derive(Deserialize)]
1420 struct CallbackParams {
1421 pub user_id: String,
1422 pub access_token: String,
1423 }
1424
1425 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1426 // access token from the query params.
1427 //
1428 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1429 // custom URL scheme instead of this local HTTP server.
1430 let (user_id, access_token) = background
1431 .spawn(async move {
1432 for _ in 0..100 {
1433 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1434 let path = req.url();
1435 let url = Url::parse(&format!("http://example.com{}", path))
1436 .context("failed to parse login notification url")?;
1437 let callback_params: CallbackParams =
1438 serde_urlencoded::from_str(url.query().unwrap_or_default())
1439 .context(
1440 "failed to parse sign-in callback query parameters",
1441 )?;
1442
1443 let post_auth_url =
1444 http.build_url("/native_app_signin_succeeded");
1445 req.respond(
1446 tiny_http::Response::empty(302).with_header(
1447 tiny_http::Header::from_bytes(
1448 &b"Location"[..],
1449 post_auth_url.as_bytes(),
1450 )
1451 .unwrap(),
1452 ),
1453 )
1454 .context("failed to respond to login http request")?;
1455 return Ok((
1456 callback_params.user_id,
1457 callback_params.access_token,
1458 ));
1459 }
1460 }
1461
1462 anyhow::bail!("didn't receive login redirect");
1463 })
1464 .await?;
1465
1466 let access_token = private_key
1467 .decrypt_string(&access_token)
1468 .context("failed to decrypt access token")?;
1469
1470 Ok(Credentials {
1471 user_id: user_id.parse()?,
1472 access_token,
1473 })
1474 })
1475 .await?;
1476
1477 cx.update(|cx| cx.activate(true))?;
1478 Ok(credentials)
1479 })
1480 }
1481
1482 async fn authenticate_as_admin(
1483 self: &Arc<Self>,
1484 http: Arc<HttpClientWithUrl>,
1485 login: String,
1486 api_token: String,
1487 ) -> Result<Credentials> {
1488 #[derive(Serialize)]
1489 struct ImpersonateUserBody {
1490 github_login: String,
1491 }
1492
1493 #[derive(Deserialize)]
1494 struct ImpersonateUserResponse {
1495 user_id: u64,
1496 access_token: String,
1497 }
1498
1499 let url = self
1500 .http
1501 .build_zed_cloud_url("/internal/users/impersonate", &[])?;
1502 let request = Request::post(url.as_str())
1503 .header("Content-Type", "application/json")
1504 .header("Authorization", format!("Bearer {api_token}"))
1505 .body(
1506 serde_json::to_string(&ImpersonateUserBody {
1507 github_login: login,
1508 })?
1509 .into(),
1510 )?;
1511
1512 let mut response = http.send(request).await?;
1513 let mut body = String::new();
1514 response.body_mut().read_to_string(&mut body).await?;
1515 anyhow::ensure!(
1516 response.status().is_success(),
1517 "admin user request failed {} - {}",
1518 response.status().as_u16(),
1519 body,
1520 );
1521 let response: ImpersonateUserResponse = serde_json::from_str(&body)?;
1522
1523 Ok(Credentials {
1524 user_id: response.user_id,
1525 access_token: response.access_token,
1526 })
1527 }
1528
1529 pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1530 self.state.write().credentials = None;
1531 self.cloud_client.clear_credentials();
1532 self.disconnect(cx);
1533
1534 if self.has_credentials(cx).await {
1535 self.credentials_provider
1536 .delete_credentials(cx)
1537 .await
1538 .log_err();
1539 }
1540 }
1541
1542 pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1543 self.peer.teardown();
1544 self.set_status(Status::SignedOut, cx);
1545 }
1546
1547 pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1548 self.peer.teardown();
1549 self.set_status(Status::ConnectionLost, cx);
1550 }
1551
1552 fn connection_id(&self) -> Result<ConnectionId> {
1553 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1554 Ok(connection_id)
1555 } else {
1556 anyhow::bail!("not connected");
1557 }
1558 }
1559
1560 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1561 log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1562 self.peer.send(self.connection_id()?, message)
1563 }
1564
1565 pub fn request<T: RequestMessage>(
1566 &self,
1567 request: T,
1568 ) -> impl Future<Output = Result<T::Response>> + use<T> {
1569 self.request_envelope(request)
1570 .map_ok(|envelope| envelope.payload)
1571 }
1572
1573 pub fn request_stream<T: RequestMessage>(
1574 &self,
1575 request: T,
1576 ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1577 let client_id = self.id.load(Ordering::SeqCst);
1578 log::debug!(
1579 "rpc request start. client_id:{}. name:{}",
1580 client_id,
1581 T::NAME
1582 );
1583 let response = self
1584 .connection_id()
1585 .map(|conn_id| self.peer.request_stream(conn_id, request));
1586 async move {
1587 let response = response?.await;
1588 log::debug!(
1589 "rpc request finish. client_id:{}. name:{}",
1590 client_id,
1591 T::NAME
1592 );
1593 response
1594 }
1595 }
1596
1597 pub fn request_envelope<T: RequestMessage>(
1598 &self,
1599 request: T,
1600 ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
1601 let client_id = self.id();
1602 log::debug!(
1603 "rpc request start. client_id:{}. name:{}",
1604 client_id,
1605 T::NAME
1606 );
1607 let response = self
1608 .connection_id()
1609 .map(|conn_id| self.peer.request_envelope(conn_id, request));
1610 async move {
1611 let response = response?.await;
1612 log::debug!(
1613 "rpc request finish. client_id:{}. name:{}",
1614 client_id,
1615 T::NAME
1616 );
1617 response
1618 }
1619 }
1620
1621 pub fn request_dynamic(
1622 &self,
1623 envelope: proto::Envelope,
1624 request_type: &'static str,
1625 ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
1626 let client_id = self.id();
1627 log::debug!(
1628 "rpc request start. client_id:{}. name:{}",
1629 client_id,
1630 request_type
1631 );
1632 let response = self
1633 .connection_id()
1634 .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1635 async move {
1636 let response = response?.await;
1637 log::debug!(
1638 "rpc request finish. client_id:{}. name:{}",
1639 client_id,
1640 request_type
1641 );
1642 Ok(response?.0)
1643 }
1644 }
1645
1646 fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1647 let sender_id = message.sender_id();
1648 let request_id = message.message_id();
1649 let type_name = message.payload_type_name();
1650 let original_sender_id = message.original_sender_id();
1651
1652 if let Some(future) = ProtoMessageHandlerSet::handle_message(
1653 &self.handler_set,
1654 message,
1655 self.clone().into(),
1656 cx.clone(),
1657 ) {
1658 let client_id = self.id();
1659 log::debug!(
1660 "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1661 client_id,
1662 original_sender_id,
1663 type_name
1664 );
1665 cx.spawn(async move |_| match future.await {
1666 Ok(()) => {
1667 log::debug!(
1668 "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1669 client_id,
1670 original_sender_id,
1671 type_name
1672 );
1673 }
1674 Err(error) => {
1675 log::error!(
1676 "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1677 client_id,
1678 original_sender_id,
1679 type_name,
1680 error
1681 );
1682 }
1683 })
1684 .detach();
1685 } else {
1686 log::info!("unhandled message {}", type_name);
1687 self.peer
1688 .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1689 .log_err();
1690 }
1691 }
1692
1693 pub fn add_message_to_client_handler(
1694 self: &Arc<Client>,
1695 handler: impl Fn(&MessageToClient, &mut App) + Send + Sync + 'static,
1696 ) {
1697 self.message_to_client_handlers
1698 .lock()
1699 .push(Box::new(handler));
1700 }
1701
1702 fn handle_message_to_client(self: &Arc<Client>, message: MessageToClient, cx: &AsyncApp) {
1703 cx.update(|cx| {
1704 for handler in self.message_to_client_handlers.lock().iter() {
1705 handler(&message, cx);
1706 }
1707 })
1708 .ok();
1709 }
1710
1711 pub fn telemetry(&self) -> &Arc<Telemetry> {
1712 &self.telemetry
1713 }
1714}
1715
1716impl ProtoClient for Client {
1717 fn request(
1718 &self,
1719 envelope: proto::Envelope,
1720 request_type: &'static str,
1721 ) -> BoxFuture<'static, Result<proto::Envelope>> {
1722 self.request_dynamic(envelope, request_type).boxed()
1723 }
1724
1725 fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1726 log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1727 let connection_id = self.connection_id()?;
1728 self.peer.send_dynamic(connection_id, envelope)
1729 }
1730
1731 fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1732 log::debug!(
1733 "rpc respond. client_id:{}, name:{}",
1734 self.id(),
1735 message_type
1736 );
1737 let connection_id = self.connection_id()?;
1738 self.peer.send_dynamic(connection_id, envelope)
1739 }
1740
1741 fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1742 &self.handler_set
1743 }
1744
1745 fn is_via_collab(&self) -> bool {
1746 true
1747 }
1748}
1749
1750/// prefix for the zed:// url scheme
1751pub const ZED_URL_SCHEME: &str = "zed";
1752
1753/// Parses the given link into a Zed link.
1754///
1755/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1756/// Returns [`None`] otherwise.
1757pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1758 let server_url = &ClientSettings::get_global(cx).server_url;
1759 if let Some(stripped) = link
1760 .strip_prefix(server_url)
1761 .and_then(|result| result.strip_prefix('/'))
1762 {
1763 return Some(stripped);
1764 }
1765 if let Some(stripped) = link
1766 .strip_prefix(ZED_URL_SCHEME)
1767 .and_then(|result| result.strip_prefix("://"))
1768 {
1769 return Some(stripped);
1770 }
1771
1772 None
1773}
1774
1775#[cfg(test)]
1776mod tests {
1777 use super::*;
1778 use crate::test::{FakeServer, parse_authorization_header};
1779
1780 use clock::FakeSystemClock;
1781 use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1782 use http_client::FakeHttpClient;
1783 use parking_lot::Mutex;
1784 use proto::TypedEnvelope;
1785 use settings::SettingsStore;
1786 use std::future;
1787
1788 #[gpui::test(iterations = 10)]
1789 async fn test_reconnection(cx: &mut TestAppContext) {
1790 init_test(cx);
1791 let user_id = 5;
1792 let client = cx.update(|cx| {
1793 Client::new(
1794 Arc::new(FakeSystemClock::new()),
1795 FakeHttpClient::with_404_response(),
1796 cx,
1797 )
1798 });
1799 let server = FakeServer::for_client(user_id, &client, cx).await;
1800 let mut status = client.status();
1801 assert!(matches!(
1802 status.next().await,
1803 Some(Status::Connected { .. })
1804 ));
1805 assert_eq!(server.auth_count(), 1);
1806
1807 server.forbid_connections();
1808 server.disconnect();
1809 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1810
1811 server.allow_connections();
1812 cx.executor().advance_clock(Duration::from_secs(10));
1813 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1814 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1815
1816 server.forbid_connections();
1817 server.disconnect();
1818 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1819
1820 // Clear cached credentials after authentication fails
1821 server.roll_access_token();
1822 server.allow_connections();
1823 cx.executor().run_until_parked();
1824 cx.executor().advance_clock(Duration::from_secs(10));
1825 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1826 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1827 }
1828
1829 #[gpui::test(iterations = 10)]
1830 async fn test_auth_failure_during_reconnection(cx: &mut TestAppContext) {
1831 init_test(cx);
1832 let http_client = FakeHttpClient::with_200_response();
1833 let client =
1834 cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client.clone(), cx));
1835 let server = FakeServer::for_client(42, &client, cx).await;
1836 let mut status = client.status();
1837 assert!(matches!(
1838 status.next().await,
1839 Some(Status::Connected { .. })
1840 ));
1841 assert_eq!(server.auth_count(), 1);
1842
1843 // Simulate an auth failure during reconnection.
1844 http_client
1845 .as_fake()
1846 .replace_handler(|_, _request| async move {
1847 Ok(http_client::Response::builder()
1848 .status(503)
1849 .body("".into())
1850 .unwrap())
1851 });
1852 server.disconnect();
1853 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1854
1855 // Restore the ability to authenticate.
1856 http_client
1857 .as_fake()
1858 .replace_handler(|_, _request| async move {
1859 Ok(http_client::Response::builder()
1860 .status(200)
1861 .body("".into())
1862 .unwrap())
1863 });
1864 cx.executor().advance_clock(Duration::from_secs(10));
1865 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1866 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1867 }
1868
1869 #[gpui::test(iterations = 10)]
1870 async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1871 init_test(cx);
1872 let user_id = 5;
1873 let client = cx.update(|cx| {
1874 Client::new(
1875 Arc::new(FakeSystemClock::new()),
1876 FakeHttpClient::with_404_response(),
1877 cx,
1878 )
1879 });
1880 let mut status = client.status();
1881
1882 // Time out when client tries to connect.
1883 client.override_authenticate(move |cx| {
1884 cx.background_spawn(async move {
1885 Ok(Credentials {
1886 user_id,
1887 access_token: "token".into(),
1888 })
1889 })
1890 });
1891 client.override_establish_connection(|_, cx| {
1892 cx.background_spawn(async move {
1893 future::pending::<()>().await;
1894 unreachable!()
1895 })
1896 });
1897 let auth_and_connect = cx.spawn({
1898 let client = client.clone();
1899 |cx| async move { client.connect(false, &cx).await }
1900 });
1901 executor.run_until_parked();
1902 assert!(matches!(status.next().await, Some(Status::Connecting)));
1903
1904 executor.advance_clock(CONNECTION_TIMEOUT);
1905 assert!(matches!(status.next().await, Some(Status::ConnectionError)));
1906 auth_and_connect.await.into_response().unwrap_err();
1907
1908 // Allow the connection to be established.
1909 let server = FakeServer::for_client(user_id, &client, cx).await;
1910 assert!(matches!(
1911 status.next().await,
1912 Some(Status::Connected { .. })
1913 ));
1914
1915 // Disconnect client.
1916 server.forbid_connections();
1917 server.disconnect();
1918 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1919
1920 // Time out when re-establishing the connection.
1921 server.allow_connections();
1922 client.override_establish_connection(|_, cx| {
1923 cx.background_spawn(async move {
1924 future::pending::<()>().await;
1925 unreachable!()
1926 })
1927 });
1928 executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1929 assert!(matches!(status.next().await, Some(Status::Reconnecting)));
1930
1931 executor.advance_clock(CONNECTION_TIMEOUT);
1932 assert!(matches!(
1933 status.next().await,
1934 Some(Status::ReconnectionError { .. })
1935 ));
1936 }
1937
1938 #[gpui::test(iterations = 10)]
1939 async fn test_reauthenticate_only_if_unauthorized(cx: &mut TestAppContext) {
1940 init_test(cx);
1941 let auth_count = Arc::new(Mutex::new(0));
1942 let http_client = FakeHttpClient::create(|_request| async move {
1943 Ok(http_client::Response::builder()
1944 .status(200)
1945 .body("".into())
1946 .unwrap())
1947 });
1948 let client =
1949 cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client.clone(), cx));
1950 client.override_authenticate({
1951 let auth_count = auth_count.clone();
1952 move |cx| {
1953 let auth_count = auth_count.clone();
1954 cx.background_spawn(async move {
1955 *auth_count.lock() += 1;
1956 Ok(Credentials {
1957 user_id: 1,
1958 access_token: auth_count.lock().to_string(),
1959 })
1960 })
1961 }
1962 });
1963
1964 let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1965 assert_eq!(*auth_count.lock(), 1);
1966 assert_eq!(credentials.access_token, "1");
1967
1968 // If credentials are still valid, signing in doesn't trigger authentication.
1969 let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1970 assert_eq!(*auth_count.lock(), 1);
1971 assert_eq!(credentials.access_token, "1");
1972
1973 // If the server is unavailable, signing in doesn't trigger authentication.
1974 http_client
1975 .as_fake()
1976 .replace_handler(|_, _request| async move {
1977 Ok(http_client::Response::builder()
1978 .status(503)
1979 .body("".into())
1980 .unwrap())
1981 });
1982 client.sign_in(false, &cx.to_async()).await.unwrap_err();
1983 assert_eq!(*auth_count.lock(), 1);
1984
1985 // If credentials became invalid, signing in triggers authentication.
1986 http_client
1987 .as_fake()
1988 .replace_handler(|_, request| async move {
1989 let credentials = parse_authorization_header(&request).unwrap();
1990 if credentials.access_token == "2" {
1991 Ok(http_client::Response::builder()
1992 .status(200)
1993 .body("".into())
1994 .unwrap())
1995 } else {
1996 Ok(http_client::Response::builder()
1997 .status(401)
1998 .body("".into())
1999 .unwrap())
2000 }
2001 });
2002 let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
2003 assert_eq!(*auth_count.lock(), 2);
2004 assert_eq!(credentials.access_token, "2");
2005 }
2006
2007 #[gpui::test(iterations = 10)]
2008 async fn test_authenticating_more_than_once(
2009 cx: &mut TestAppContext,
2010 executor: BackgroundExecutor,
2011 ) {
2012 init_test(cx);
2013 let auth_count = Arc::new(Mutex::new(0));
2014 let dropped_auth_count = Arc::new(Mutex::new(0));
2015 let client = cx.update(|cx| {
2016 Client::new(
2017 Arc::new(FakeSystemClock::new()),
2018 FakeHttpClient::with_404_response(),
2019 cx,
2020 )
2021 });
2022 client.override_authenticate({
2023 let auth_count = auth_count.clone();
2024 let dropped_auth_count = dropped_auth_count.clone();
2025 move |cx| {
2026 let auth_count = auth_count.clone();
2027 let dropped_auth_count = dropped_auth_count.clone();
2028 cx.background_spawn(async move {
2029 *auth_count.lock() += 1;
2030 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
2031 future::pending::<()>().await;
2032 unreachable!()
2033 })
2034 }
2035 });
2036
2037 let _authenticate = cx.spawn({
2038 let client = client.clone();
2039 move |cx| async move { client.connect(false, &cx).await }
2040 });
2041 executor.run_until_parked();
2042 assert_eq!(*auth_count.lock(), 1);
2043 assert_eq!(*dropped_auth_count.lock(), 0);
2044
2045 let _authenticate = cx.spawn(|cx| async move { client.connect(false, &cx).await });
2046 executor.run_until_parked();
2047 assert_eq!(*auth_count.lock(), 2);
2048 assert_eq!(*dropped_auth_count.lock(), 1);
2049 }
2050
2051 #[gpui::test]
2052 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
2053 init_test(cx);
2054 let user_id = 5;
2055 let client = cx.update(|cx| {
2056 Client::new(
2057 Arc::new(FakeSystemClock::new()),
2058 FakeHttpClient::with_404_response(),
2059 cx,
2060 )
2061 });
2062 let server = FakeServer::for_client(user_id, &client, cx).await;
2063
2064 let (done_tx1, done_rx1) = smol::channel::unbounded();
2065 let (done_tx2, done_rx2) = smol::channel::unbounded();
2066 AnyProtoClient::from(client.clone()).add_entity_message_handler(
2067 move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, cx| {
2068 match entity.read_with(&cx, |entity, _| entity.id).unwrap() {
2069 1 => done_tx1.try_send(()).unwrap(),
2070 2 => done_tx2.try_send(()).unwrap(),
2071 _ => unreachable!(),
2072 }
2073 async { Ok(()) }
2074 },
2075 );
2076 let entity1 = cx.new(|_| TestEntity {
2077 id: 1,
2078 subscription: None,
2079 });
2080 let entity2 = cx.new(|_| TestEntity {
2081 id: 2,
2082 subscription: None,
2083 });
2084 let entity3 = cx.new(|_| TestEntity {
2085 id: 3,
2086 subscription: None,
2087 });
2088
2089 let _subscription1 = client
2090 .subscribe_to_entity(1)
2091 .unwrap()
2092 .set_entity(&entity1, &cx.to_async());
2093 let _subscription2 = client
2094 .subscribe_to_entity(2)
2095 .unwrap()
2096 .set_entity(&entity2, &cx.to_async());
2097 // Ensure dropping a subscription for the same entity type still allows receiving of
2098 // messages for other entity IDs of the same type.
2099 let subscription3 = client
2100 .subscribe_to_entity(3)
2101 .unwrap()
2102 .set_entity(&entity3, &cx.to_async());
2103 drop(subscription3);
2104
2105 server.send(proto::JoinProject {
2106 project_id: 1,
2107 committer_name: None,
2108 committer_email: None,
2109 });
2110 server.send(proto::JoinProject {
2111 project_id: 2,
2112 committer_name: None,
2113 committer_email: None,
2114 });
2115 done_rx1.recv().await.unwrap();
2116 done_rx2.recv().await.unwrap();
2117 }
2118
2119 #[gpui::test]
2120 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
2121 init_test(cx);
2122 let user_id = 5;
2123 let client = cx.update(|cx| {
2124 Client::new(
2125 Arc::new(FakeSystemClock::new()),
2126 FakeHttpClient::with_404_response(),
2127 cx,
2128 )
2129 });
2130 let server = FakeServer::for_client(user_id, &client, cx).await;
2131
2132 let entity = cx.new(|_| TestEntity::default());
2133 let (done_tx1, _done_rx1) = smol::channel::unbounded();
2134 let (done_tx2, done_rx2) = smol::channel::unbounded();
2135 let subscription1 = client.add_message_handler(
2136 entity.downgrade(),
2137 move |_, _: TypedEnvelope<proto::Ping>, _| {
2138 done_tx1.try_send(()).unwrap();
2139 async { Ok(()) }
2140 },
2141 );
2142 drop(subscription1);
2143 let _subscription2 = client.add_message_handler(
2144 entity.downgrade(),
2145 move |_, _: TypedEnvelope<proto::Ping>, _| {
2146 done_tx2.try_send(()).unwrap();
2147 async { Ok(()) }
2148 },
2149 );
2150 server.send(proto::Ping {});
2151 done_rx2.recv().await.unwrap();
2152 }
2153
2154 #[gpui::test]
2155 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
2156 init_test(cx);
2157 let user_id = 5;
2158 let client = cx.update(|cx| {
2159 Client::new(
2160 Arc::new(FakeSystemClock::new()),
2161 FakeHttpClient::with_404_response(),
2162 cx,
2163 )
2164 });
2165 let server = FakeServer::for_client(user_id, &client, cx).await;
2166
2167 let entity = cx.new(|_| TestEntity::default());
2168 let (done_tx, done_rx) = smol::channel::unbounded();
2169 let subscription = client.add_message_handler(
2170 entity.clone().downgrade(),
2171 move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
2172 entity
2173 .update(&mut cx, |entity, _| entity.subscription.take())
2174 .unwrap();
2175 done_tx.try_send(()).unwrap();
2176 async { Ok(()) }
2177 },
2178 );
2179 entity.update(cx, |entity, _| {
2180 entity.subscription = Some(subscription);
2181 });
2182 server.send(proto::Ping {});
2183 done_rx.recv().await.unwrap();
2184 }
2185
2186 #[derive(Default)]
2187 struct TestEntity {
2188 id: usize,
2189 subscription: Option<Subscription>,
2190 }
2191
2192 fn init_test(cx: &mut TestAppContext) {
2193 cx.update(|cx| {
2194 let settings_store = SettingsStore::test(cx);
2195 cx.set_global(settings_store);
2196 init_settings(cx);
2197 });
2198 }
2199}