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