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