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