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