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