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, Deserialize, Debug)]
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, Debug)]
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 sources.json_merge()
519 }
520
521 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
522 vscode.enum_setting("telemetry.telemetryLevel", &mut current.metrics, |s| {
523 Some(s == "all")
524 });
525 vscode.enum_setting("telemetry.telemetryLevel", &mut current.diagnostics, |s| {
526 Some(matches!(s, "all" | "error" | "crash"))
527 });
528 // we could translate telemetry.telemetryLevel, but just because users didn't want
529 // to send microsoft telemetry doesn't mean they don't want to send it to zed. their
530 // all/error/crash/off correspond to combinations of our "diagnostics" and "metrics".
531 }
532}
533
534impl Client {
535 pub fn new(
536 clock: Arc<dyn SystemClock>,
537 http: Arc<HttpClientWithUrl>,
538 cx: &mut App,
539 ) -> Arc<Self> {
540 Arc::new(Self {
541 id: AtomicU64::new(0),
542 peer: Peer::new(0),
543 telemetry: Telemetry::new(clock, http.clone(), cx),
544 http,
545 credentials_provider: ClientCredentialsProvider::new(cx),
546 state: Default::default(),
547 handler_set: Default::default(),
548
549 #[cfg(any(test, feature = "test-support"))]
550 authenticate: Default::default(),
551 #[cfg(any(test, feature = "test-support"))]
552 establish_connection: Default::default(),
553 #[cfg(any(test, feature = "test-support"))]
554 rpc_url: RwLock::default(),
555 })
556 }
557
558 pub fn production(cx: &mut App) -> Arc<Self> {
559 let clock = Arc::new(clock::RealSystemClock);
560 let http = Arc::new(HttpClientWithUrl::new_url(
561 cx.http_client(),
562 &ClientSettings::get_global(cx).server_url,
563 cx.http_client().proxy().cloned(),
564 ));
565 Self::new(clock, http, cx)
566 }
567
568 pub fn id(&self) -> u64 {
569 self.id.load(Ordering::SeqCst)
570 }
571
572 pub fn http_client(&self) -> Arc<HttpClientWithUrl> {
573 self.http.clone()
574 }
575
576 pub fn set_id(&self, id: u64) -> &Self {
577 self.id.store(id, Ordering::SeqCst);
578 self
579 }
580
581 #[cfg(any(test, feature = "test-support"))]
582 pub fn teardown(&self) {
583 let mut state = self.state.write();
584 state._reconnect_task.take();
585 self.handler_set.lock().clear();
586 self.peer.teardown();
587 }
588
589 #[cfg(any(test, feature = "test-support"))]
590 pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
591 where
592 F: 'static + Send + Sync + Fn(&AsyncApp) -> Task<Result<Credentials>>,
593 {
594 *self.authenticate.write() = Some(Box::new(authenticate));
595 self
596 }
597
598 #[cfg(any(test, feature = "test-support"))]
599 pub fn override_establish_connection<F>(&self, connect: F) -> &Self
600 where
601 F: 'static
602 + Send
603 + Sync
604 + Fn(&Credentials, &AsyncApp) -> Task<Result<Connection, EstablishConnectionError>>,
605 {
606 *self.establish_connection.write() = Some(Box::new(connect));
607 self
608 }
609
610 #[cfg(any(test, feature = "test-support"))]
611 pub fn override_rpc_url(&self, url: Url) -> &Self {
612 *self.rpc_url.write() = Some(url);
613 self
614 }
615
616 pub fn global(cx: &App) -> Arc<Self> {
617 cx.global::<GlobalClient>().0.clone()
618 }
619 pub fn set_global(client: Arc<Client>, cx: &mut App) {
620 cx.set_global(GlobalClient(client))
621 }
622
623 pub fn user_id(&self) -> Option<u64> {
624 self.state
625 .read()
626 .credentials
627 .as_ref()
628 .map(|credentials| credentials.user_id)
629 }
630
631 pub fn peer_id(&self) -> Option<PeerId> {
632 if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
633 Some(*peer_id)
634 } else {
635 None
636 }
637 }
638
639 pub fn status(&self) -> watch::Receiver<Status> {
640 self.state.read().status.1.clone()
641 }
642
643 fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncApp) {
644 log::info!("set status on client {}: {:?}", self.id(), status);
645 let mut state = self.state.write();
646 *state.status.0.borrow_mut() = status;
647
648 match status {
649 Status::Connected { .. } => {
650 state._reconnect_task = None;
651 }
652 Status::ConnectionLost => {
653 let client = self.clone();
654 state._reconnect_task = Some(cx.spawn(async move |cx| {
655 #[cfg(any(test, feature = "test-support"))]
656 let mut rng = StdRng::seed_from_u64(0);
657 #[cfg(not(any(test, feature = "test-support")))]
658 let mut rng = StdRng::from_entropy();
659
660 let mut delay = INITIAL_RECONNECTION_DELAY;
661 loop {
662 match client.authenticate_and_connect(true, &cx).await {
663 ConnectionResult::Timeout => {
664 log::error!("client connect attempt timed out")
665 }
666 ConnectionResult::ConnectionReset => {
667 log::error!("client connect attempt reset")
668 }
669 ConnectionResult::Result(r) => {
670 if let Err(error) = r {
671 log::error!("failed to connect: {error}");
672 } else {
673 break;
674 }
675 }
676 }
677
678 if matches!(*client.status().borrow(), Status::ConnectionError) {
679 client.set_status(
680 Status::ReconnectionError {
681 next_reconnection: Instant::now() + delay,
682 },
683 &cx,
684 );
685 cx.background_executor().timer(delay).await;
686 delay = delay
687 .mul_f32(rng.gen_range(0.5..=2.5))
688 .max(INITIAL_RECONNECTION_DELAY)
689 .min(MAX_RECONNECTION_DELAY);
690 } else {
691 break;
692 }
693 }
694 }));
695 }
696 Status::SignedOut | Status::UpgradeRequired => {
697 self.telemetry.set_authenticated_user_info(None, false);
698 state._reconnect_task.take();
699 }
700 _ => {}
701 }
702 }
703
704 pub fn subscribe_to_entity<T>(
705 self: &Arc<Self>,
706 remote_id: u64,
707 ) -> Result<PendingEntitySubscription<T>>
708 where
709 T: 'static,
710 {
711 let id = (TypeId::of::<T>(), remote_id);
712
713 let mut state = self.handler_set.lock();
714 anyhow::ensure!(
715 !state.entities_by_type_and_remote_id.contains_key(&id),
716 "already subscribed to entity"
717 );
718
719 state
720 .entities_by_type_and_remote_id
721 .insert(id, EntityMessageSubscriber::Pending(Default::default()));
722
723 Ok(PendingEntitySubscription {
724 client: self.clone(),
725 remote_id,
726 consumed: false,
727 _entity_type: PhantomData,
728 })
729 }
730
731 #[track_caller]
732 pub fn add_message_handler<M, E, H, F>(
733 self: &Arc<Self>,
734 entity: WeakEntity<E>,
735 handler: H,
736 ) -> Subscription
737 where
738 M: EnvelopedMessage,
739 E: 'static,
740 H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
741 F: 'static + Future<Output = Result<()>>,
742 {
743 self.add_message_handler_impl(entity, move |entity, message, _, cx| {
744 handler(entity, message, cx)
745 })
746 }
747
748 fn add_message_handler_impl<M, E, H, F>(
749 self: &Arc<Self>,
750 entity: WeakEntity<E>,
751 handler: H,
752 ) -> Subscription
753 where
754 M: EnvelopedMessage,
755 E: 'static,
756 H: 'static
757 + Sync
758 + Fn(Entity<E>, TypedEnvelope<M>, AnyProtoClient, AsyncApp) -> F
759 + Send
760 + Sync,
761 F: 'static + Future<Output = Result<()>>,
762 {
763 let message_type_id = TypeId::of::<M>();
764 let mut state = self.handler_set.lock();
765 state
766 .entities_by_message_type
767 .insert(message_type_id, entity.into());
768
769 let prev_handler = state.message_handlers.insert(
770 message_type_id,
771 Arc::new(move |subscriber, envelope, client, cx| {
772 let subscriber = subscriber.downcast::<E>().unwrap();
773 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
774 handler(subscriber, *envelope, client.clone(), cx).boxed_local()
775 }),
776 );
777 if prev_handler.is_some() {
778 let location = std::panic::Location::caller();
779 panic!(
780 "{}:{} registered handler for the same message {} twice",
781 location.file(),
782 location.line(),
783 std::any::type_name::<M>()
784 );
785 }
786
787 Subscription::Message {
788 client: Arc::downgrade(self),
789 id: message_type_id,
790 }
791 }
792
793 pub fn add_request_handler<M, E, H, F>(
794 self: &Arc<Self>,
795 entity: WeakEntity<E>,
796 handler: H,
797 ) -> Subscription
798 where
799 M: RequestMessage,
800 E: 'static,
801 H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
802 F: 'static + Future<Output = Result<M::Response>>,
803 {
804 self.add_message_handler_impl(entity, move |handle, envelope, this, cx| {
805 Self::respond_to_request(envelope.receipt(), handler(handle, envelope, cx), this)
806 })
807 }
808
809 async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
810 receipt: Receipt<T>,
811 response: F,
812 client: AnyProtoClient,
813 ) -> Result<()> {
814 match response.await {
815 Ok(response) => {
816 client.send_response(receipt.message_id, response)?;
817 Ok(())
818 }
819 Err(error) => {
820 client.send_response(receipt.message_id, error.to_proto())?;
821 Err(error)
822 }
823 }
824 }
825
826 pub async fn has_credentials(&self, cx: &AsyncApp) -> bool {
827 self.credentials_provider
828 .read_credentials(cx)
829 .await
830 .is_some()
831 }
832
833 #[async_recursion(?Send)]
834 pub async fn authenticate_and_connect(
835 self: &Arc<Self>,
836 try_provider: bool,
837 cx: &AsyncApp,
838 ) -> ConnectionResult<()> {
839 let was_disconnected = match *self.status().borrow() {
840 Status::SignedOut => true,
841 Status::ConnectionError
842 | Status::ConnectionLost
843 | Status::Authenticating { .. }
844 | Status::Reauthenticating { .. }
845 | Status::ReconnectionError { .. } => false,
846 Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
847 return ConnectionResult::Result(Ok(()));
848 }
849 Status::UpgradeRequired => {
850 return ConnectionResult::Result(
851 Err(EstablishConnectionError::UpgradeRequired)
852 .context("client auth and connect"),
853 );
854 }
855 };
856 if was_disconnected {
857 self.set_status(Status::Authenticating, cx);
858 } else {
859 self.set_status(Status::Reauthenticating, cx)
860 }
861
862 let mut read_from_provider = false;
863 let mut credentials = self.state.read().credentials.clone();
864 if credentials.is_none() && try_provider {
865 credentials = self.credentials_provider.read_credentials(cx).await;
866 read_from_provider = credentials.is_some();
867 }
868
869 if credentials.is_none() {
870 let mut status_rx = self.status();
871 let _ = status_rx.next().await;
872 futures::select_biased! {
873 authenticate = self.authenticate(cx).fuse() => {
874 match authenticate {
875 Ok(creds) => credentials = Some(creds),
876 Err(err) => {
877 self.set_status(Status::ConnectionError, cx);
878 return ConnectionResult::Result(Err(err));
879 }
880 }
881 }
882 _ = status_rx.next().fuse() => {
883 return ConnectionResult::Result(Err(anyhow!("authentication canceled")));
884 }
885 }
886 }
887 let credentials = credentials.unwrap();
888 self.set_id(credentials.user_id);
889
890 if was_disconnected {
891 self.set_status(Status::Connecting, cx);
892 } else {
893 self.set_status(Status::Reconnecting, cx);
894 }
895
896 let mut timeout =
897 futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
898 futures::select_biased! {
899 connection = self.establish_connection(&credentials, cx).fuse() => {
900 match connection {
901 Ok(conn) => {
902 self.state.write().credentials = Some(credentials.clone());
903 if !read_from_provider && IMPERSONATE_LOGIN.is_none() {
904 self.credentials_provider.write_credentials(credentials.user_id, credentials.access_token, cx).await.log_err();
905 }
906
907 futures::select_biased! {
908 result = self.set_connection(conn, cx).fuse() => ConnectionResult::Result(result.context("client auth and connect")),
909 _ = timeout => {
910 self.set_status(Status::ConnectionError, cx);
911 ConnectionResult::Timeout
912 }
913 }
914 }
915 Err(EstablishConnectionError::Unauthorized) => {
916 self.state.write().credentials.take();
917 if read_from_provider {
918 self.credentials_provider.delete_credentials(cx).await.log_err();
919 self.set_status(Status::SignedOut, cx);
920 self.authenticate_and_connect(false, cx).await
921 } else {
922 self.set_status(Status::ConnectionError, cx);
923 ConnectionResult::Result(Err(EstablishConnectionError::Unauthorized).context("client auth and connect"))
924 }
925 }
926 Err(EstablishConnectionError::UpgradeRequired) => {
927 self.set_status(Status::UpgradeRequired, cx);
928 ConnectionResult::Result(Err(EstablishConnectionError::UpgradeRequired).context("client auth and connect"))
929 }
930 Err(error) => {
931 self.set_status(Status::ConnectionError, cx);
932 ConnectionResult::Result(Err(error).context("client auth and connect"))
933 }
934 }
935 }
936 _ = &mut timeout => {
937 self.set_status(Status::ConnectionError, cx);
938 ConnectionResult::Timeout
939 }
940 }
941 }
942
943 async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncApp) -> Result<()> {
944 let executor = cx.background_executor();
945 log::debug!("add connection to peer");
946 let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
947 let executor = executor.clone();
948 move |duration| executor.timer(duration)
949 });
950 let handle_io = executor.spawn(handle_io);
951
952 let peer_id = async {
953 log::debug!("waiting for server hello");
954 let message = incoming.next().await.context("no hello message received")?;
955 log::debug!("got server hello");
956 let hello_message_type_name = message.payload_type_name().to_string();
957 let hello = message
958 .into_any()
959 .downcast::<TypedEnvelope<proto::Hello>>()
960 .map_err(|_| {
961 anyhow!(
962 "invalid hello message received: {:?}",
963 hello_message_type_name
964 )
965 })?;
966 let peer_id = hello.payload.peer_id.context("invalid peer id")?;
967 Ok(peer_id)
968 };
969
970 let peer_id = match peer_id.await {
971 Ok(peer_id) => peer_id,
972 Err(error) => {
973 self.peer.disconnect(connection_id);
974 return Err(error);
975 }
976 };
977
978 log::debug!(
979 "set status to connected (connection id: {:?}, peer id: {:?})",
980 connection_id,
981 peer_id
982 );
983 self.set_status(
984 Status::Connected {
985 peer_id,
986 connection_id,
987 },
988 cx,
989 );
990
991 cx.spawn({
992 let this = self.clone();
993 async move |cx| {
994 while let Some(message) = incoming.next().await {
995 this.handle_message(message, &cx);
996 // Don't starve the main thread when receiving lots of messages at once.
997 smol::future::yield_now().await;
998 }
999 }
1000 })
1001 .detach();
1002
1003 cx.spawn({
1004 let this = self.clone();
1005 async move |cx| match handle_io.await {
1006 Ok(()) => {
1007 if *this.status().borrow()
1008 == (Status::Connected {
1009 connection_id,
1010 peer_id,
1011 })
1012 {
1013 this.set_status(Status::SignedOut, &cx);
1014 }
1015 }
1016 Err(err) => {
1017 log::error!("connection error: {:?}", err);
1018 this.set_status(Status::ConnectionLost, &cx);
1019 }
1020 }
1021 })
1022 .detach();
1023
1024 Ok(())
1025 }
1026
1027 fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1028 #[cfg(any(test, feature = "test-support"))]
1029 if let Some(callback) = self.authenticate.read().as_ref() {
1030 return callback(cx);
1031 }
1032
1033 self.authenticate_with_browser(cx)
1034 }
1035
1036 fn establish_connection(
1037 self: &Arc<Self>,
1038 credentials: &Credentials,
1039 cx: &AsyncApp,
1040 ) -> Task<Result<Connection, EstablishConnectionError>> {
1041 #[cfg(any(test, feature = "test-support"))]
1042 if let Some(callback) = self.establish_connection.read().as_ref() {
1043 return callback(credentials, cx);
1044 }
1045
1046 self.establish_websocket_connection(credentials, cx)
1047 }
1048
1049 fn rpc_url(
1050 &self,
1051 http: Arc<HttpClientWithUrl>,
1052 release_channel: Option<ReleaseChannel>,
1053 ) -> impl Future<Output = Result<url::Url>> + use<> {
1054 #[cfg(any(test, feature = "test-support"))]
1055 let url_override = self.rpc_url.read().clone();
1056
1057 async move {
1058 #[cfg(any(test, feature = "test-support"))]
1059 if let Some(url) = url_override {
1060 return Ok(url);
1061 }
1062
1063 if let Some(url) = &*ZED_RPC_URL {
1064 return Url::parse(url).context("invalid rpc url");
1065 }
1066
1067 let mut url = http.build_url("/rpc");
1068 if let Some(preview_param) =
1069 release_channel.and_then(|channel| channel.release_query_param())
1070 {
1071 url += "?";
1072 url += preview_param;
1073 }
1074
1075 let response = http.get(&url, Default::default(), false).await?;
1076 anyhow::ensure!(
1077 response.status().is_redirection(),
1078 "unexpected /rpc response status {}",
1079 response.status()
1080 );
1081 let collab_url = response
1082 .headers()
1083 .get("Location")
1084 .context("missing location header in /rpc response")?
1085 .to_str()
1086 .map_err(EstablishConnectionError::other)?
1087 .to_string();
1088 Url::parse(&collab_url).with_context(|| format!("parsing colab rpc url {collab_url}"))
1089 }
1090 }
1091
1092 fn establish_websocket_connection(
1093 self: &Arc<Self>,
1094 credentials: &Credentials,
1095 cx: &AsyncApp,
1096 ) -> Task<Result<Connection, EstablishConnectionError>> {
1097 let release_channel = cx
1098 .update(|cx| ReleaseChannel::try_global(cx))
1099 .ok()
1100 .flatten();
1101 let app_version = cx
1102 .update(|cx| AppVersion::global(cx).to_string())
1103 .ok()
1104 .unwrap_or_default();
1105
1106 let http = self.http.clone();
1107 let proxy = http.proxy().cloned();
1108 let credentials = credentials.clone();
1109 let rpc_url = self.rpc_url(http, release_channel);
1110 let system_id = self.telemetry.system_id();
1111 let metrics_id = self.telemetry.metrics_id();
1112 cx.spawn(async move |cx| {
1113 use HttpOrHttps::*;
1114
1115 #[derive(Debug)]
1116 enum HttpOrHttps {
1117 Http,
1118 Https,
1119 }
1120
1121 let mut rpc_url = rpc_url.await?;
1122 let url_scheme = match rpc_url.scheme() {
1123 "https" => Https,
1124 "http" => Http,
1125 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1126 };
1127 let rpc_host = rpc_url
1128 .host_str()
1129 .zip(rpc_url.port_or_known_default())
1130 .context("missing host in rpc url")?;
1131
1132 let stream = {
1133 let handle = cx.update(|cx| gpui_tokio::Tokio::handle(cx)).ok().unwrap();
1134 let _guard = handle.enter();
1135 match proxy {
1136 Some(proxy) => connect_proxy_stream(&proxy, rpc_host).await?,
1137 None => Box::new(TcpStream::connect(rpc_host).await?),
1138 }
1139 };
1140
1141 log::info!("connected to rpc endpoint {}", rpc_url);
1142
1143 rpc_url
1144 .set_scheme(match url_scheme {
1145 Https => "wss",
1146 Http => "ws",
1147 })
1148 .unwrap();
1149
1150 // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1151 // for us from the RPC URL.
1152 //
1153 // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1154 let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1155
1156 // We then modify the request to add our desired headers.
1157 let request_headers = request.headers_mut();
1158 request_headers.insert(
1159 "Authorization",
1160 HeaderValue::from_str(&credentials.authorization_header())?,
1161 );
1162 request_headers.insert(
1163 "x-zed-protocol-version",
1164 HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1165 );
1166 request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1167 request_headers.insert(
1168 "x-zed-release-channel",
1169 HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1170 );
1171 if let Some(system_id) = system_id {
1172 request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1173 }
1174 if let Some(metrics_id) = metrics_id {
1175 request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1176 }
1177
1178 let (stream, _) = async_tungstenite::tokio::client_async_tls_with_connector_and_config(
1179 request,
1180 stream,
1181 Some(Arc::new(http_client_tls::tls_config()).into()),
1182 None,
1183 )
1184 .await?;
1185
1186 Ok(Connection::new(
1187 stream
1188 .map_err(|error| anyhow!(error))
1189 .sink_map_err(|error| anyhow!(error)),
1190 ))
1191 })
1192 }
1193
1194 pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1195 let http = self.http.clone();
1196 let this = self.clone();
1197 cx.spawn(async move |cx| {
1198 let background = cx.background_executor().clone();
1199
1200 let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1201 cx.update(|cx| {
1202 cx.spawn(async move |cx| {
1203 let url = open_url_rx.await?;
1204 cx.update(|cx| cx.open_url(&url))
1205 })
1206 .detach_and_log_err(cx);
1207 })
1208 .log_err();
1209
1210 let credentials = background
1211 .clone()
1212 .spawn(async move {
1213 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1214 // zed server to encrypt the user's access token, so that it can'be intercepted by
1215 // any other app running on the user's device.
1216 let (public_key, private_key) =
1217 rpc::auth::keypair().expect("failed to generate keypair for auth");
1218 let public_key_string = String::try_from(public_key)
1219 .expect("failed to serialize public key for auth");
1220
1221 if let Some((login, token)) =
1222 IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1223 {
1224 eprintln!("authenticate as admin {login}, {token}");
1225
1226 return this
1227 .authenticate_as_admin(http, login.clone(), token.clone())
1228 .await;
1229 }
1230
1231 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1232 let server =
1233 tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1234 let port = server.server_addr().port();
1235
1236 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1237 // that the user is signing in from a Zed app running on the same device.
1238 let mut url = http.build_url(&format!(
1239 "/native_app_signin?native_app_port={}&native_app_public_key={}",
1240 port, public_key_string
1241 ));
1242
1243 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1244 log::info!("impersonating user @{}", impersonate_login);
1245 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1246 }
1247
1248 open_url_tx.send(url).log_err();
1249
1250 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1251 // access token from the query params.
1252 //
1253 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1254 // custom URL scheme instead of this local HTTP server.
1255 let (user_id, access_token) = background
1256 .spawn(async move {
1257 for _ in 0..100 {
1258 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1259 let path = req.url();
1260 let mut user_id = None;
1261 let mut access_token = None;
1262 let url = Url::parse(&format!("http://example.com{}", path))
1263 .context("failed to parse login notification url")?;
1264 for (key, value) in url.query_pairs() {
1265 if key == "access_token" {
1266 access_token = Some(value.to_string());
1267 } else if key == "user_id" {
1268 user_id = Some(value.to_string());
1269 }
1270 }
1271
1272 let post_auth_url =
1273 http.build_url("/native_app_signin_succeeded");
1274 req.respond(
1275 tiny_http::Response::empty(302).with_header(
1276 tiny_http::Header::from_bytes(
1277 &b"Location"[..],
1278 post_auth_url.as_bytes(),
1279 )
1280 .unwrap(),
1281 ),
1282 )
1283 .context("failed to respond to login http request")?;
1284 return Ok((
1285 user_id.context("missing user_id parameter")?,
1286 access_token.context("missing access_token parameter")?,
1287 ));
1288 }
1289 }
1290
1291 anyhow::bail!("didn't receive login redirect");
1292 })
1293 .await?;
1294
1295 let access_token = private_key
1296 .decrypt_string(&access_token)
1297 .context("failed to decrypt access token")?;
1298
1299 Ok(Credentials {
1300 user_id: user_id.parse()?,
1301 access_token,
1302 })
1303 })
1304 .await?;
1305
1306 cx.update(|cx| cx.activate(true))?;
1307 Ok(credentials)
1308 })
1309 }
1310
1311 async fn authenticate_as_admin(
1312 self: &Arc<Self>,
1313 http: Arc<HttpClientWithUrl>,
1314 login: String,
1315 mut api_token: String,
1316 ) -> Result<Credentials> {
1317 #[derive(Deserialize)]
1318 struct AuthenticatedUserResponse {
1319 user: User,
1320 }
1321
1322 #[derive(Deserialize)]
1323 struct User {
1324 id: u64,
1325 }
1326
1327 let github_user = {
1328 #[derive(Deserialize)]
1329 struct GithubUser {
1330 id: i32,
1331 login: String,
1332 created_at: DateTime<Utc>,
1333 }
1334
1335 let request = {
1336 let mut request_builder =
1337 Request::get(&format!("https://api.github.com/users/{login}"));
1338 if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1339 request_builder =
1340 request_builder.header("Authorization", format!("Bearer {}", github_token));
1341 }
1342
1343 request_builder.body(AsyncBody::empty())?
1344 };
1345
1346 let mut response = http
1347 .send(request)
1348 .await
1349 .context("error fetching GitHub user")?;
1350
1351 let mut body = Vec::new();
1352 response
1353 .body_mut()
1354 .read_to_end(&mut body)
1355 .await
1356 .context("error reading GitHub user")?;
1357
1358 if !response.status().is_success() {
1359 let text = String::from_utf8_lossy(body.as_slice());
1360 bail!(
1361 "status error {}, response: {text:?}",
1362 response.status().as_u16()
1363 );
1364 }
1365
1366 serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1367 log::error!("Error deserializing: {:?}", err);
1368 log::error!(
1369 "GitHub API response text: {:?}",
1370 String::from_utf8_lossy(body.as_slice())
1371 );
1372 anyhow!("error deserializing GitHub user")
1373 })?
1374 };
1375
1376 let query_params = [
1377 ("github_login", &github_user.login),
1378 ("github_user_id", &github_user.id.to_string()),
1379 (
1380 "github_user_created_at",
1381 &github_user.created_at.to_rfc3339(),
1382 ),
1383 ];
1384
1385 // Use the collab server's admin API to retrieve the ID
1386 // of the impersonated user.
1387 let mut url = self.rpc_url(http.clone(), None).await?;
1388 url.set_path("/user");
1389 url.set_query(Some(
1390 &query_params
1391 .iter()
1392 .map(|(key, value)| {
1393 format!(
1394 "{}={}",
1395 key,
1396 url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1397 )
1398 })
1399 .collect::<Vec<String>>()
1400 .join("&"),
1401 ));
1402 let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1403 .header("Authorization", format!("token {api_token}"))
1404 .body("".into())?;
1405
1406 let mut response = http.send(request).await?;
1407 let mut body = String::new();
1408 response.body_mut().read_to_string(&mut body).await?;
1409 anyhow::ensure!(
1410 response.status().is_success(),
1411 "admin user request failed {} - {}",
1412 response.status().as_u16(),
1413 body,
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 anyhow::bail!("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.into_response().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}