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