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