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