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