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