1#[cfg(any(test, feature = "test-support"))]
2pub mod test;
3
4pub mod telemetry;
5pub mod user;
6
7use anyhow::{anyhow, Context as _, Result};
8use async_recursion::async_recursion;
9use async_tungstenite::tungstenite::{
10 error::Error as WebsocketError,
11 http::{Request, StatusCode},
12};
13use futures::{
14 channel::oneshot, future::LocalBoxFuture, AsyncReadExt, FutureExt, SinkExt, StreamExt,
15 TryFutureExt as _, TryStreamExt,
16};
17use gpui::{
18 actions, AnyModel, AnyWeakModel, AppContext, AsyncAppContext, Model, SemanticVersion, Task,
19 WeakModel,
20};
21use lazy_static::lazy_static;
22use parking_lot::RwLock;
23use postage::watch;
24use rand::prelude::*;
25use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, PeerId, RequestMessage};
26use schemars::JsonSchema;
27use serde::{Deserialize, Serialize};
28use serde_json;
29use settings::Settings;
30use std::{
31 any::TypeId,
32 collections::HashMap,
33 convert::TryFrom,
34 fmt::Write as _,
35 future::Future,
36 marker::PhantomData,
37 path::PathBuf,
38 sync::{atomic::AtomicU64, Arc, Weak},
39 time::{Duration, Instant},
40};
41use telemetry::Telemetry;
42use thiserror::Error;
43use url::Url;
44use util::channel::ReleaseChannel;
45use util::http::HttpClient;
46use util::{ResultExt, TryFutureExt};
47
48pub use rpc::*;
49pub use telemetry::Event;
50pub use user::*;
51
52lazy_static! {
53 pub static ref ZED_SERVER_URL: String =
54 std::env::var("ZED_SERVER_URL").unwrap_or_else(|_| "https://zed.dev".to_string());
55 pub static ref ZED_RPC_URL: Option<String> = std::env::var("ZED_RPC_URL").ok();
56 pub static ref IMPERSONATE_LOGIN: Option<String> = std::env::var("ZED_IMPERSONATE")
57 .ok()
58 .and_then(|s| if s.is_empty() { None } else { Some(s) });
59 pub static ref ADMIN_API_TOKEN: Option<String> = std::env::var("ZED_ADMIN_API_TOKEN")
60 .ok()
61 .and_then(|s| if s.is_empty() { None } else { Some(s) });
62 pub static ref ZED_APP_VERSION: Option<SemanticVersion> = std::env::var("ZED_APP_VERSION")
63 .ok()
64 .and_then(|v| v.parse().ok());
65 pub static ref ZED_APP_PATH: Option<PathBuf> =
66 std::env::var("ZED_APP_PATH").ok().map(PathBuf::from);
67 pub static ref ZED_ALWAYS_ACTIVE: bool =
68 std::env::var("ZED_ALWAYS_ACTIVE").map_or(false, |e| e.len() > 0);
69}
70
71pub const ZED_SECRET_CLIENT_TOKEN: &str = "618033988749894";
72pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(100);
73pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
74
75actions!(client, [SignIn, SignOut, Reconnect]);
76
77pub fn init_settings(cx: &mut AppContext) {
78 TelemetrySettings::register(cx);
79}
80
81pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
82 init_settings(cx);
83
84 let client = Arc::downgrade(client);
85 cx.on_action({
86 let client = client.clone();
87 move |_: &SignIn, cx| {
88 if let Some(client) = client.upgrade() {
89 cx.spawn(
90 |cx| async move { client.authenticate_and_connect(true, &cx).log_err().await },
91 )
92 .detach();
93 }
94 }
95 });
96
97 cx.on_action({
98 let client = client.clone();
99 move |_: &SignOut, cx| {
100 if let Some(client) = client.upgrade() {
101 cx.spawn(|cx| async move {
102 client.disconnect(&cx);
103 })
104 .detach();
105 }
106 }
107 });
108
109 cx.on_action({
110 let client = client.clone();
111 move |_: &Reconnect, cx| {
112 if let Some(client) = client.upgrade() {
113 cx.spawn(|cx| async move {
114 client.reconnect(&cx);
115 })
116 .detach();
117 }
118 }
119 });
120}
121
122pub struct Client {
123 id: AtomicU64,
124 peer: Arc<Peer>,
125 http: Arc<dyn HttpClient>,
126 telemetry: Arc<Telemetry>,
127 state: RwLock<ClientState>,
128
129 #[allow(clippy::type_complexity)]
130 #[cfg(any(test, feature = "test-support"))]
131 authenticate: RwLock<
132 Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
133 >,
134
135 #[allow(clippy::type_complexity)]
136 #[cfg(any(test, feature = "test-support"))]
137 establish_connection: RwLock<
138 Option<
139 Box<
140 dyn 'static
141 + Send
142 + Sync
143 + Fn(
144 &Credentials,
145 &AsyncAppContext,
146 ) -> Task<Result<Connection, EstablishConnectionError>>,
147 >,
148 >,
149 >,
150}
151
152#[derive(Error, Debug)]
153pub enum EstablishConnectionError {
154 #[error("upgrade required")]
155 UpgradeRequired,
156 #[error("unauthorized")]
157 Unauthorized,
158 #[error("{0}")]
159 Other(#[from] anyhow::Error),
160 #[error("{0}")]
161 Http(#[from] util::http::Error),
162 #[error("{0}")]
163 Io(#[from] std::io::Error),
164 #[error("{0}")]
165 Websocket(#[from] async_tungstenite::tungstenite::http::Error),
166}
167
168impl From<WebsocketError> for EstablishConnectionError {
169 fn from(error: WebsocketError) -> Self {
170 if let WebsocketError::Http(response) = &error {
171 match response.status() {
172 StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
173 StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
174 _ => {}
175 }
176 }
177 EstablishConnectionError::Other(error.into())
178 }
179}
180
181impl EstablishConnectionError {
182 pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
183 Self::Other(error.into())
184 }
185}
186
187#[derive(Copy, Clone, Debug, PartialEq)]
188pub enum Status {
189 SignedOut,
190 UpgradeRequired,
191 Authenticating,
192 Connecting,
193 ConnectionError,
194 Connected {
195 peer_id: PeerId,
196 connection_id: ConnectionId,
197 },
198 ConnectionLost,
199 Reauthenticating,
200 Reconnecting,
201 ReconnectionError {
202 next_reconnection: Instant,
203 },
204}
205
206impl Status {
207 pub fn is_connected(&self) -> bool {
208 matches!(self, Self::Connected { .. })
209 }
210
211 pub fn is_signed_out(&self) -> bool {
212 matches!(self, Self::SignedOut | Self::UpgradeRequired)
213 }
214}
215
216struct ClientState {
217 credentials: Option<Credentials>,
218 status: (watch::Sender<Status>, watch::Receiver<Status>),
219 entity_id_extractors: HashMap<TypeId, fn(&dyn AnyTypedEnvelope) -> u64>,
220 _reconnect_task: Option<Task<()>>,
221 reconnect_interval: Duration,
222 entities_by_type_and_remote_id: HashMap<(TypeId, u64), WeakSubscriber>,
223 models_by_message_type: HashMap<TypeId, AnyWeakModel>,
224 entity_types_by_message_type: HashMap<TypeId, TypeId>,
225 #[allow(clippy::type_complexity)]
226 message_handlers: HashMap<
227 TypeId,
228 Arc<
229 dyn Send
230 + Sync
231 + Fn(
232 AnyModel,
233 Box<dyn AnyTypedEnvelope>,
234 &Arc<Client>,
235 AsyncAppContext,
236 ) -> LocalBoxFuture<'static, Result<()>>,
237 >,
238 >,
239}
240
241enum WeakSubscriber {
242 Entity { handle: AnyWeakModel },
243 Pending(Vec<Box<dyn AnyTypedEnvelope>>),
244}
245
246#[derive(Clone, Debug)]
247pub struct Credentials {
248 pub user_id: u64,
249 pub access_token: String,
250}
251
252impl Default for ClientState {
253 fn default() -> Self {
254 Self {
255 credentials: None,
256 status: watch::channel_with(Status::SignedOut),
257 entity_id_extractors: Default::default(),
258 _reconnect_task: None,
259 reconnect_interval: Duration::from_secs(5),
260 models_by_message_type: Default::default(),
261 entities_by_type_and_remote_id: Default::default(),
262 entity_types_by_message_type: Default::default(),
263 message_handlers: Default::default(),
264 }
265 }
266}
267
268pub enum Subscription {
269 Entity {
270 client: Weak<Client>,
271 id: (TypeId, u64),
272 },
273 Message {
274 client: Weak<Client>,
275 id: TypeId,
276 },
277}
278
279impl Drop for Subscription {
280 fn drop(&mut self) {
281 match self {
282 Subscription::Entity { client, id } => {
283 if let Some(client) = client.upgrade() {
284 let mut state = client.state.write();
285 let _ = state.entities_by_type_and_remote_id.remove(id);
286 }
287 }
288 Subscription::Message { client, id } => {
289 if let Some(client) = client.upgrade() {
290 let mut state = client.state.write();
291 let _ = state.entity_types_by_message_type.remove(id);
292 let _ = state.message_handlers.remove(id);
293 }
294 }
295 }
296 }
297}
298
299pub struct PendingEntitySubscription<T: 'static> {
300 client: Arc<Client>,
301 remote_id: u64,
302 _entity_type: PhantomData<T>,
303 consumed: bool,
304}
305
306impl<T: 'static> PendingEntitySubscription<T> {
307 pub fn set_model(mut self, model: &Model<T>, cx: &mut AsyncAppContext) -> Subscription {
308 self.consumed = true;
309 let mut state = self.client.state.write();
310 let id = (TypeId::of::<T>(), self.remote_id);
311 let Some(WeakSubscriber::Pending(messages)) =
312 state.entities_by_type_and_remote_id.remove(&id)
313 else {
314 unreachable!()
315 };
316
317 state.entities_by_type_and_remote_id.insert(
318 id,
319 WeakSubscriber::Entity {
320 handle: model.downgrade().into(),
321 },
322 );
323 drop(state);
324 for message in messages {
325 self.client.handle_message(message, cx);
326 }
327 Subscription::Entity {
328 client: Arc::downgrade(&self.client),
329 id,
330 }
331 }
332}
333
334impl<T: 'static> Drop for PendingEntitySubscription<T> {
335 fn drop(&mut self) {
336 if !self.consumed {
337 let mut state = self.client.state.write();
338 if let Some(WeakSubscriber::Pending(messages)) = state
339 .entities_by_type_and_remote_id
340 .remove(&(TypeId::of::<T>(), self.remote_id))
341 {
342 for message in messages {
343 log::info!("unhandled message {}", message.payload_type_name());
344 }
345 }
346 }
347 }
348}
349
350#[derive(Copy, Clone)]
351pub struct TelemetrySettings {
352 pub diagnostics: bool,
353 pub metrics: bool,
354}
355
356/// Control what info is collected by Zed.
357#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
358pub struct TelemetrySettingsContent {
359 /// Send debug info like crash reports.
360 ///
361 /// Default: true
362 pub diagnostics: Option<bool>,
363 /// Send anonymized usage data like what languages you're using Zed with.
364 ///
365 /// Default: true
366 pub metrics: Option<bool>,
367}
368
369impl settings::Settings for TelemetrySettings {
370 const KEY: Option<&'static str> = Some("telemetry");
371
372 type FileContent = TelemetrySettingsContent;
373
374 fn load(
375 default_value: &Self::FileContent,
376 user_values: &[&Self::FileContent],
377 _: &mut AppContext,
378 ) -> Result<Self> {
379 Ok(Self {
380 diagnostics: user_values.first().and_then(|v| v.diagnostics).unwrap_or(
381 default_value
382 .diagnostics
383 .ok_or_else(Self::missing_default)?,
384 ),
385 metrics: user_values
386 .first()
387 .and_then(|v| v.metrics)
388 .unwrap_or(default_value.metrics.ok_or_else(Self::missing_default)?),
389 })
390 }
391}
392
393impl Client {
394 pub fn new(http: Arc<dyn HttpClient>, cx: &mut AppContext) -> Arc<Self> {
395 Arc::new(Self {
396 id: AtomicU64::new(0),
397 peer: Peer::new(0),
398 telemetry: Telemetry::new(http.clone(), cx),
399 http,
400 state: Default::default(),
401
402 #[cfg(any(test, feature = "test-support"))]
403 authenticate: Default::default(),
404 #[cfg(any(test, feature = "test-support"))]
405 establish_connection: Default::default(),
406 })
407 }
408
409 pub fn id(&self) -> u64 {
410 self.id.load(std::sync::atomic::Ordering::SeqCst)
411 }
412
413 pub fn http_client(&self) -> Arc<dyn HttpClient> {
414 self.http.clone()
415 }
416
417 pub fn set_id(&self, id: u64) -> &Self {
418 self.id.store(id, std::sync::atomic::Ordering::SeqCst);
419 self
420 }
421
422 #[cfg(any(test, feature = "test-support"))]
423 pub fn teardown(&self) {
424 let mut state = self.state.write();
425 state._reconnect_task.take();
426 state.message_handlers.clear();
427 state.models_by_message_type.clear();
428 state.entities_by_type_and_remote_id.clear();
429 state.entity_id_extractors.clear();
430 self.peer.teardown();
431 }
432
433 #[cfg(any(test, feature = "test-support"))]
434 pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
435 where
436 F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
437 {
438 *self.authenticate.write() = Some(Box::new(authenticate));
439 self
440 }
441
442 #[cfg(any(test, feature = "test-support"))]
443 pub fn override_establish_connection<F>(&self, connect: F) -> &Self
444 where
445 F: 'static
446 + Send
447 + Sync
448 + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
449 {
450 *self.establish_connection.write() = Some(Box::new(connect));
451 self
452 }
453
454 pub fn user_id(&self) -> Option<u64> {
455 self.state
456 .read()
457 .credentials
458 .as_ref()
459 .map(|credentials| credentials.user_id)
460 }
461
462 pub fn peer_id(&self) -> Option<PeerId> {
463 if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
464 Some(*peer_id)
465 } else {
466 None
467 }
468 }
469
470 pub fn status(&self) -> watch::Receiver<Status> {
471 self.state.read().status.1.clone()
472 }
473
474 fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
475 log::info!("set status on client {}: {:?}", self.id(), status);
476 let mut state = self.state.write();
477 *state.status.0.borrow_mut() = status;
478
479 match status {
480 Status::Connected { .. } => {
481 state._reconnect_task = None;
482 }
483 Status::ConnectionLost => {
484 let this = self.clone();
485 let reconnect_interval = state.reconnect_interval;
486 state._reconnect_task = Some(cx.spawn(move |cx| async move {
487 #[cfg(any(test, feature = "test-support"))]
488 let mut rng = StdRng::seed_from_u64(0);
489 #[cfg(not(any(test, feature = "test-support")))]
490 let mut rng = StdRng::from_entropy();
491
492 let mut delay = INITIAL_RECONNECTION_DELAY;
493 while let Err(error) = this.authenticate_and_connect(true, &cx).await {
494 log::error!("failed to connect {}", error);
495 if matches!(*this.status().borrow(), Status::ConnectionError) {
496 this.set_status(
497 Status::ReconnectionError {
498 next_reconnection: Instant::now() + delay,
499 },
500 &cx,
501 );
502 cx.background_executor().timer(delay).await;
503 delay = delay
504 .mul_f32(rng.gen_range(1.0..=2.0))
505 .min(reconnect_interval);
506 } else {
507 break;
508 }
509 }
510 }));
511 }
512 Status::SignedOut | Status::UpgradeRequired => {
513 self.telemetry.set_authenticated_user_info(None, false);
514 state._reconnect_task.take();
515 }
516 _ => {}
517 }
518 }
519
520 pub fn subscribe_to_entity<T>(
521 self: &Arc<Self>,
522 remote_id: u64,
523 ) -> Result<PendingEntitySubscription<T>>
524 where
525 T: 'static,
526 {
527 let id = (TypeId::of::<T>(), remote_id);
528
529 let mut state = self.state.write();
530 if state.entities_by_type_and_remote_id.contains_key(&id) {
531 return Err(anyhow!("already subscribed to entity"));
532 } else {
533 state
534 .entities_by_type_and_remote_id
535 .insert(id, WeakSubscriber::Pending(Default::default()));
536 Ok(PendingEntitySubscription {
537 client: self.clone(),
538 remote_id,
539 consumed: false,
540 _entity_type: PhantomData,
541 })
542 }
543 }
544
545 #[track_caller]
546 pub fn add_message_handler<M, E, H, F>(
547 self: &Arc<Self>,
548 entity: WeakModel<E>,
549 handler: H,
550 ) -> Subscription
551 where
552 M: EnvelopedMessage,
553 E: 'static,
554 H: 'static
555 + Sync
556 + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
557 + Send
558 + Sync,
559 F: 'static + Future<Output = Result<()>>,
560 {
561 let message_type_id = TypeId::of::<M>();
562 let mut state = self.state.write();
563 state
564 .models_by_message_type
565 .insert(message_type_id, entity.into());
566
567 let prev_handler = state.message_handlers.insert(
568 message_type_id,
569 Arc::new(move |subscriber, envelope, client, cx| {
570 let subscriber = subscriber.downcast::<E>().unwrap();
571 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
572 handler(subscriber, *envelope, client.clone(), cx).boxed_local()
573 }),
574 );
575 if prev_handler.is_some() {
576 let location = std::panic::Location::caller();
577 panic!(
578 "{}:{} registered handler for the same message {} twice",
579 location.file(),
580 location.line(),
581 std::any::type_name::<M>()
582 );
583 }
584
585 Subscription::Message {
586 client: Arc::downgrade(self),
587 id: message_type_id,
588 }
589 }
590
591 pub fn add_request_handler<M, E, H, F>(
592 self: &Arc<Self>,
593 model: WeakModel<E>,
594 handler: H,
595 ) -> Subscription
596 where
597 M: RequestMessage,
598 E: 'static,
599 H: 'static
600 + Sync
601 + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
602 + Send
603 + Sync,
604 F: 'static + Future<Output = Result<M::Response>>,
605 {
606 self.add_message_handler(model, move |handle, envelope, this, cx| {
607 Self::respond_to_request(
608 envelope.receipt(),
609 handler(handle, envelope, this.clone(), cx),
610 this,
611 )
612 })
613 }
614
615 pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
616 where
617 M: EntityMessage,
618 E: 'static,
619 H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
620 F: 'static + Future<Output = Result<()>>,
621 {
622 self.add_entity_message_handler::<M, E, _, _>(move |subscriber, message, client, cx| {
623 handler(subscriber.downcast::<E>().unwrap(), message, client, cx)
624 })
625 }
626
627 fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
628 where
629 M: EntityMessage,
630 E: 'static,
631 H: 'static + Fn(AnyModel, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
632 F: 'static + Future<Output = Result<()>>,
633 {
634 let model_type_id = TypeId::of::<E>();
635 let message_type_id = TypeId::of::<M>();
636
637 let mut state = self.state.write();
638 state
639 .entity_types_by_message_type
640 .insert(message_type_id, model_type_id);
641 state
642 .entity_id_extractors
643 .entry(message_type_id)
644 .or_insert_with(|| {
645 |envelope| {
646 envelope
647 .as_any()
648 .downcast_ref::<TypedEnvelope<M>>()
649 .unwrap()
650 .payload
651 .remote_entity_id()
652 }
653 });
654 let prev_handler = state.message_handlers.insert(
655 message_type_id,
656 Arc::new(move |handle, envelope, client, cx| {
657 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
658 handler(handle, *envelope, client.clone(), cx).boxed_local()
659 }),
660 );
661 if prev_handler.is_some() {
662 panic!("registered handler for the same message twice");
663 }
664 }
665
666 pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
667 where
668 M: EntityMessage + RequestMessage,
669 E: 'static,
670 H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
671 F: 'static + Future<Output = Result<M::Response>>,
672 {
673 self.add_model_message_handler(move |entity, envelope, client, cx| {
674 Self::respond_to_request::<M, _>(
675 envelope.receipt(),
676 handler(entity, envelope, client.clone(), cx),
677 client,
678 )
679 })
680 }
681
682 async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
683 receipt: Receipt<T>,
684 response: F,
685 client: Arc<Self>,
686 ) -> Result<()> {
687 match response.await {
688 Ok(response) => {
689 client.respond(receipt, response)?;
690 Ok(())
691 }
692 Err(error) => {
693 client.respond_with_error(
694 receipt,
695 proto::Error {
696 message: format!("{:?}", error),
697 },
698 )?;
699 Err(error)
700 }
701 }
702 }
703
704 pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
705 read_credentials_from_keychain(cx).is_some()
706 }
707
708 #[async_recursion(?Send)]
709 pub async fn authenticate_and_connect(
710 self: &Arc<Self>,
711 try_keychain: bool,
712 cx: &AsyncAppContext,
713 ) -> anyhow::Result<()> {
714 let was_disconnected = match *self.status().borrow() {
715 Status::SignedOut => true,
716 Status::ConnectionError
717 | Status::ConnectionLost
718 | Status::Authenticating { .. }
719 | Status::Reauthenticating { .. }
720 | Status::ReconnectionError { .. } => false,
721 Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
722 return Ok(())
723 }
724 Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
725 };
726
727 if was_disconnected {
728 self.set_status(Status::Authenticating, cx);
729 } else {
730 self.set_status(Status::Reauthenticating, cx)
731 }
732
733 let mut read_from_keychain = false;
734 let mut credentials = self.state.read().credentials.clone();
735 if credentials.is_none() && try_keychain {
736 credentials = read_credentials_from_keychain(cx);
737 read_from_keychain = credentials.is_some();
738 }
739 if credentials.is_none() {
740 let mut status_rx = self.status();
741 let _ = status_rx.next().await;
742 futures::select_biased! {
743 authenticate = self.authenticate(cx).fuse() => {
744 match authenticate {
745 Ok(creds) => credentials = Some(creds),
746 Err(err) => {
747 self.set_status(Status::ConnectionError, cx);
748 return Err(err);
749 }
750 }
751 }
752 _ = status_rx.next().fuse() => {
753 return Err(anyhow!("authentication canceled"));
754 }
755 }
756 }
757 let credentials = credentials.unwrap();
758 self.set_id(credentials.user_id);
759
760 if was_disconnected {
761 self.set_status(Status::Connecting, cx);
762 } else {
763 self.set_status(Status::Reconnecting, cx);
764 }
765
766 let mut timeout =
767 futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
768 futures::select_biased! {
769 connection = self.establish_connection(&credentials, cx).fuse() => {
770 match connection {
771 Ok(conn) => {
772 self.state.write().credentials = Some(credentials.clone());
773 if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
774 write_credentials_to_keychain(credentials, cx).log_err();
775 }
776
777 futures::select_biased! {
778 result = self.set_connection(conn, cx).fuse() => result,
779 _ = timeout => {
780 self.set_status(Status::ConnectionError, cx);
781 Err(anyhow!("timed out waiting on hello message from server"))
782 }
783 }
784 }
785 Err(EstablishConnectionError::Unauthorized) => {
786 self.state.write().credentials.take();
787 if read_from_keychain {
788 delete_credentials_from_keychain(cx).log_err();
789 self.set_status(Status::SignedOut, cx);
790 self.authenticate_and_connect(false, cx).await
791 } else {
792 self.set_status(Status::ConnectionError, cx);
793 Err(EstablishConnectionError::Unauthorized)?
794 }
795 }
796 Err(EstablishConnectionError::UpgradeRequired) => {
797 self.set_status(Status::UpgradeRequired, cx);
798 Err(EstablishConnectionError::UpgradeRequired)?
799 }
800 Err(error) => {
801 self.set_status(Status::ConnectionError, cx);
802 Err(error)?
803 }
804 }
805 }
806 _ = &mut timeout => {
807 self.set_status(Status::ConnectionError, cx);
808 Err(anyhow!("timed out trying to establish connection"))
809 }
810 }
811 }
812
813 async fn set_connection(
814 self: &Arc<Self>,
815 conn: Connection,
816 cx: &AsyncAppContext,
817 ) -> Result<()> {
818 let executor = cx.background_executor();
819 log::info!("add connection to peer");
820 let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
821 let executor = executor.clone();
822 move |duration| executor.timer(duration)
823 });
824 let handle_io = executor.spawn(handle_io);
825
826 let peer_id = async {
827 log::info!("waiting for server hello");
828 let message = incoming
829 .next()
830 .await
831 .ok_or_else(|| anyhow!("no hello message received"))?;
832 log::info!("got server hello");
833 let hello_message_type_name = message.payload_type_name().to_string();
834 let hello = message
835 .into_any()
836 .downcast::<TypedEnvelope<proto::Hello>>()
837 .map_err(|_| {
838 anyhow!(
839 "invalid hello message received: {:?}",
840 hello_message_type_name
841 )
842 })?;
843 let peer_id = hello
844 .payload
845 .peer_id
846 .ok_or_else(|| anyhow!("invalid peer id"))?;
847 Ok(peer_id)
848 };
849
850 let peer_id = match peer_id.await {
851 Ok(peer_id) => peer_id,
852 Err(error) => {
853 self.peer.disconnect(connection_id);
854 return Err(error);
855 }
856 };
857
858 log::info!(
859 "set status to connected (connection id: {:?}, peer id: {:?})",
860 connection_id,
861 peer_id
862 );
863 self.set_status(
864 Status::Connected {
865 peer_id,
866 connection_id,
867 },
868 cx,
869 );
870
871 cx.spawn({
872 let this = self.clone();
873 |cx| {
874 async move {
875 while let Some(message) = incoming.next().await {
876 this.handle_message(message, &cx);
877 // Don't starve the main thread when receiving lots of messages at once.
878 smol::future::yield_now().await;
879 }
880 }
881 }
882 })
883 .detach();
884
885 cx.spawn({
886 let this = self.clone();
887 move |cx| async move {
888 match handle_io.await {
889 Ok(()) => {
890 if this.status().borrow().clone()
891 == (Status::Connected {
892 connection_id,
893 peer_id,
894 })
895 {
896 this.set_status(Status::SignedOut, &cx);
897 }
898 }
899 Err(err) => {
900 log::error!("connection error: {:?}", err);
901 this.set_status(Status::ConnectionLost, &cx);
902 }
903 }
904 }
905 })
906 .detach();
907
908 Ok(())
909 }
910
911 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
912 #[cfg(any(test, feature = "test-support"))]
913 if let Some(callback) = self.authenticate.read().as_ref() {
914 return callback(cx);
915 }
916
917 self.authenticate_with_browser(cx)
918 }
919
920 fn establish_connection(
921 self: &Arc<Self>,
922 credentials: &Credentials,
923 cx: &AsyncAppContext,
924 ) -> Task<Result<Connection, EstablishConnectionError>> {
925 #[cfg(any(test, feature = "test-support"))]
926 if let Some(callback) = self.establish_connection.read().as_ref() {
927 return callback(credentials, cx);
928 }
929
930 self.establish_websocket_connection(credentials, cx)
931 }
932
933 async fn get_rpc_url(
934 http: Arc<dyn HttpClient>,
935 release_channel: Option<ReleaseChannel>,
936 ) -> Result<Url> {
937 if let Some(url) = &*ZED_RPC_URL {
938 return Url::parse(url).context("invalid rpc url");
939 }
940
941 let mut url = format!("{}/rpc", *ZED_SERVER_URL);
942 if let Some(preview_param) =
943 release_channel.and_then(|channel| channel.release_query_param())
944 {
945 url += "?";
946 url += preview_param;
947 }
948 let response = http.get(&url, Default::default(), false).await?;
949 let collab_url = if response.status().is_redirection() {
950 response
951 .headers()
952 .get("Location")
953 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
954 .to_str()
955 .map_err(EstablishConnectionError::other)?
956 .to_string()
957 } else {
958 Err(anyhow!(
959 "unexpected /rpc response status {}",
960 response.status()
961 ))?
962 };
963
964 Url::parse(&collab_url).context("invalid rpc url")
965 }
966
967 fn establish_websocket_connection(
968 self: &Arc<Self>,
969 credentials: &Credentials,
970 cx: &AsyncAppContext,
971 ) -> Task<Result<Connection, EstablishConnectionError>> {
972 let release_channel = cx.try_read_global(|channel: &ReleaseChannel, _| *channel);
973
974 let request = Request::builder()
975 .header(
976 "Authorization",
977 format!("{} {}", credentials.user_id, credentials.access_token),
978 )
979 .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION);
980
981 let http = self.http.clone();
982 cx.background_executor().spawn(async move {
983 let mut rpc_url = Self::get_rpc_url(http, release_channel).await?;
984 let rpc_host = rpc_url
985 .host_str()
986 .zip(rpc_url.port_or_known_default())
987 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
988 let stream = smol::net::TcpStream::connect(rpc_host).await?;
989
990 log::info!("connected to rpc endpoint {}", rpc_url);
991
992 match rpc_url.scheme() {
993 "https" => {
994 rpc_url.set_scheme("wss").unwrap();
995 let request = request.uri(rpc_url.as_str()).body(())?;
996 let (stream, _) =
997 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
998 Ok(Connection::new(
999 stream
1000 .map_err(|error| anyhow!(error))
1001 .sink_map_err(|error| anyhow!(error)),
1002 ))
1003 }
1004 "http" => {
1005 rpc_url.set_scheme("ws").unwrap();
1006 let request = request.uri(rpc_url.as_str()).body(())?;
1007 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1008 Ok(Connection::new(
1009 stream
1010 .map_err(|error| anyhow!(error))
1011 .sink_map_err(|error| anyhow!(error)),
1012 ))
1013 }
1014 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1015 }
1016 })
1017 }
1018
1019 pub fn authenticate_with_browser(
1020 self: &Arc<Self>,
1021 cx: &AsyncAppContext,
1022 ) -> Task<Result<Credentials>> {
1023 let http = self.http.clone();
1024 cx.spawn(|cx| async move {
1025 let background = cx.background_executor().clone();
1026
1027 let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1028 cx.update(|cx| {
1029 cx.spawn(move |cx| async move {
1030 let url = open_url_rx.await?;
1031 cx.update(|cx| cx.open_url(&url))
1032 })
1033 .detach_and_log_err(cx);
1034 })
1035 .log_err();
1036
1037 let credentials = background
1038 .clone()
1039 .spawn(async move {
1040 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1041 // zed server to encrypt the user's access token, so that it can'be intercepted by
1042 // any other app running on the user's device.
1043 let (public_key, private_key) =
1044 rpc::auth::keypair().expect("failed to generate keypair for auth");
1045 let public_key_string = String::try_from(public_key)
1046 .expect("failed to serialize public key for auth");
1047
1048 if let Some((login, token)) =
1049 IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1050 {
1051 return Self::authenticate_as_admin(http, login.clone(), token.clone())
1052 .await;
1053 }
1054
1055 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1056 let server =
1057 tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1058 let port = server.server_addr().port();
1059
1060 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1061 // that the user is signing in from a Zed app running on the same device.
1062 let mut url = format!(
1063 "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
1064 *ZED_SERVER_URL, port, public_key_string
1065 );
1066
1067 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1068 log::info!("impersonating user @{}", impersonate_login);
1069 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1070 }
1071
1072 open_url_tx.send(url).log_err();
1073
1074 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1075 // access token from the query params.
1076 //
1077 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1078 // custom URL scheme instead of this local HTTP server.
1079 let (user_id, access_token) = background
1080 .spawn(async move {
1081 for _ in 0..100 {
1082 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1083 let path = req.url();
1084 let mut user_id = None;
1085 let mut access_token = None;
1086 let url = Url::parse(&format!("http://example.com{}", path))
1087 .context("failed to parse login notification url")?;
1088 for (key, value) in url.query_pairs() {
1089 if key == "access_token" {
1090 access_token = Some(value.to_string());
1091 } else if key == "user_id" {
1092 user_id = Some(value.to_string());
1093 }
1094 }
1095
1096 let post_auth_url =
1097 format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
1098 req.respond(
1099 tiny_http::Response::empty(302).with_header(
1100 tiny_http::Header::from_bytes(
1101 &b"Location"[..],
1102 post_auth_url.as_bytes(),
1103 )
1104 .unwrap(),
1105 ),
1106 )
1107 .context("failed to respond to login http request")?;
1108 return Ok((
1109 user_id
1110 .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1111 access_token.ok_or_else(|| {
1112 anyhow!("missing access_token parameter")
1113 })?,
1114 ));
1115 }
1116 }
1117
1118 Err(anyhow!("didn't receive login redirect"))
1119 })
1120 .await?;
1121
1122 let access_token = private_key
1123 .decrypt_string(&access_token)
1124 .context("failed to decrypt access token")?;
1125
1126 Ok(Credentials {
1127 user_id: user_id.parse()?,
1128 access_token,
1129 })
1130 })
1131 .await?;
1132
1133 cx.update(|cx| cx.activate(true))?;
1134 Ok(credentials)
1135 })
1136 }
1137
1138 async fn authenticate_as_admin(
1139 http: Arc<dyn HttpClient>,
1140 login: String,
1141 mut api_token: String,
1142 ) -> Result<Credentials> {
1143 #[derive(Deserialize)]
1144 struct AuthenticatedUserResponse {
1145 user: User,
1146 }
1147
1148 #[derive(Deserialize)]
1149 struct User {
1150 id: u64,
1151 }
1152
1153 // Use the collab server's admin API to retrieve the id
1154 // of the impersonated user.
1155 let mut url = Self::get_rpc_url(http.clone(), None).await?;
1156 url.set_path("/user");
1157 url.set_query(Some(&format!("github_login={login}")));
1158 let request = Request::get(url.as_str())
1159 .header("Authorization", format!("token {api_token}"))
1160 .body("".into())?;
1161
1162 let mut response = http.send(request).await?;
1163 let mut body = String::new();
1164 response.body_mut().read_to_string(&mut body).await?;
1165 if !response.status().is_success() {
1166 Err(anyhow!(
1167 "admin user request failed {} - {}",
1168 response.status().as_u16(),
1169 body,
1170 ))?;
1171 }
1172 let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1173
1174 // Use the admin API token to authenticate as the impersonated user.
1175 api_token.insert_str(0, "ADMIN_TOKEN:");
1176 Ok(Credentials {
1177 user_id: response.user.id,
1178 access_token: api_token,
1179 })
1180 }
1181
1182 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1183 self.peer.teardown();
1184 self.set_status(Status::SignedOut, cx);
1185 }
1186
1187 pub fn reconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1188 self.peer.teardown();
1189 self.set_status(Status::ConnectionLost, cx);
1190 }
1191
1192 fn connection_id(&self) -> Result<ConnectionId> {
1193 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1194 Ok(connection_id)
1195 } else {
1196 Err(anyhow!("not connected"))
1197 }
1198 }
1199
1200 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1201 log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1202 self.peer.send(self.connection_id()?, message)
1203 }
1204
1205 pub fn request<T: RequestMessage>(
1206 &self,
1207 request: T,
1208 ) -> impl Future<Output = Result<T::Response>> {
1209 self.request_envelope(request)
1210 .map_ok(|envelope| envelope.payload)
1211 }
1212
1213 pub fn request_envelope<T: RequestMessage>(
1214 &self,
1215 request: T,
1216 ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1217 let client_id = self.id();
1218 log::debug!(
1219 "rpc request start. client_id:{}. name:{}",
1220 client_id,
1221 T::NAME
1222 );
1223 let response = self
1224 .connection_id()
1225 .map(|conn_id| self.peer.request_envelope(conn_id, request));
1226 async move {
1227 let response = response?.await;
1228 log::debug!(
1229 "rpc request finish. client_id:{}. name:{}",
1230 client_id,
1231 T::NAME
1232 );
1233 response
1234 }
1235 }
1236
1237 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1238 log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1239 self.peer.respond(receipt, response)
1240 }
1241
1242 fn respond_with_error<T: RequestMessage>(
1243 &self,
1244 receipt: Receipt<T>,
1245 error: proto::Error,
1246 ) -> Result<()> {
1247 log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1248 self.peer.respond_with_error(receipt, error)
1249 }
1250
1251 fn handle_message(
1252 self: &Arc<Client>,
1253 message: Box<dyn AnyTypedEnvelope>,
1254 cx: &AsyncAppContext,
1255 ) {
1256 let mut state = self.state.write();
1257 let type_name = message.payload_type_name();
1258 let payload_type_id = message.payload_type_id();
1259 let sender_id = message.original_sender_id();
1260
1261 let mut subscriber = None;
1262
1263 if let Some(handle) = state
1264 .models_by_message_type
1265 .get(&payload_type_id)
1266 .and_then(|handle| handle.upgrade())
1267 {
1268 subscriber = Some(handle);
1269 } else if let Some((extract_entity_id, entity_type_id)) =
1270 state.entity_id_extractors.get(&payload_type_id).zip(
1271 state
1272 .entity_types_by_message_type
1273 .get(&payload_type_id)
1274 .copied(),
1275 )
1276 {
1277 let entity_id = (extract_entity_id)(message.as_ref());
1278
1279 match state
1280 .entities_by_type_and_remote_id
1281 .get_mut(&(entity_type_id, entity_id))
1282 {
1283 Some(WeakSubscriber::Pending(pending)) => {
1284 pending.push(message);
1285 return;
1286 }
1287 Some(weak_subscriber @ _) => match weak_subscriber {
1288 WeakSubscriber::Entity { handle } => {
1289 subscriber = handle.upgrade();
1290 }
1291
1292 WeakSubscriber::Pending(_) => {}
1293 },
1294 _ => {}
1295 }
1296 }
1297
1298 let subscriber = if let Some(subscriber) = subscriber {
1299 subscriber
1300 } else {
1301 log::info!("unhandled message {}", type_name);
1302 self.peer.respond_with_unhandled_message(message).log_err();
1303 return;
1304 };
1305
1306 let handler = state.message_handlers.get(&payload_type_id).cloned();
1307 // Dropping the state prevents deadlocks if the handler interacts with rpc::Client.
1308 // It also ensures we don't hold the lock while yielding back to the executor, as
1309 // that might cause the executor thread driving this future to block indefinitely.
1310 drop(state);
1311
1312 if let Some(handler) = handler {
1313 let future = handler(subscriber, message, self, cx.clone());
1314 let client_id = self.id();
1315 log::debug!(
1316 "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1317 client_id,
1318 sender_id,
1319 type_name
1320 );
1321 cx.spawn(move |_| async move {
1322 match future.await {
1323 Ok(()) => {
1324 log::debug!(
1325 "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1326 client_id,
1327 sender_id,
1328 type_name
1329 );
1330 }
1331 Err(error) => {
1332 log::error!(
1333 "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1334 client_id,
1335 sender_id,
1336 type_name,
1337 error
1338 );
1339 }
1340 }
1341 })
1342 .detach();
1343 } else {
1344 log::info!("unhandled message {}", type_name);
1345 self.peer.respond_with_unhandled_message(message).log_err();
1346 }
1347 }
1348
1349 pub fn telemetry(&self) -> &Arc<Telemetry> {
1350 &self.telemetry
1351 }
1352}
1353
1354fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1355 if IMPERSONATE_LOGIN.is_some() {
1356 return None;
1357 }
1358
1359 let (user_id, access_token) = cx
1360 .update(|cx| cx.read_credentials(&ZED_SERVER_URL).log_err().flatten())
1361 .ok()??;
1362
1363 Some(Credentials {
1364 user_id: user_id.parse().ok()?,
1365 access_token: String::from_utf8(access_token).ok()?,
1366 })
1367}
1368
1369fn write_credentials_to_keychain(credentials: Credentials, cx: &AsyncAppContext) -> Result<()> {
1370 cx.update(move |cx| {
1371 cx.write_credentials(
1372 &ZED_SERVER_URL,
1373 &credentials.user_id.to_string(),
1374 credentials.access_token.as_bytes(),
1375 )
1376 })?
1377}
1378
1379fn delete_credentials_from_keychain(cx: &AsyncAppContext) -> Result<()> {
1380 cx.update(move |cx| cx.delete_credentials(&ZED_SERVER_URL))?
1381}
1382
1383const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
1384
1385pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1386 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1387}
1388
1389pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1390 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1391 let mut parts = path.split('/');
1392 let id = parts.next()?.parse::<u64>().ok()?;
1393 let access_token = parts.next()?;
1394 if access_token.is_empty() {
1395 return None;
1396 }
1397 Some((id, access_token.to_string()))
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402 use super::*;
1403 use crate::test::FakeServer;
1404
1405 use gpui::{BackgroundExecutor, Context, TestAppContext};
1406 use parking_lot::Mutex;
1407 use settings::SettingsStore;
1408 use std::future;
1409 use util::http::FakeHttpClient;
1410
1411 #[gpui::test(iterations = 10)]
1412 async fn test_reconnection(cx: &mut TestAppContext) {
1413 init_test(cx);
1414 let user_id = 5;
1415 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1416 let server = FakeServer::for_client(user_id, &client, cx).await;
1417 let mut status = client.status();
1418 assert!(matches!(
1419 status.next().await,
1420 Some(Status::Connected { .. })
1421 ));
1422 assert_eq!(server.auth_count(), 1);
1423
1424 server.forbid_connections();
1425 server.disconnect();
1426 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1427
1428 server.allow_connections();
1429 cx.executor().advance_clock(Duration::from_secs(10));
1430 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1431 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1432
1433 server.forbid_connections();
1434 server.disconnect();
1435 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1436
1437 // Clear cached credentials after authentication fails
1438 server.roll_access_token();
1439 server.allow_connections();
1440 cx.executor().run_until_parked();
1441 cx.executor().advance_clock(Duration::from_secs(10));
1442 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1443 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1444 }
1445
1446 #[gpui::test(iterations = 10)]
1447 async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1448 init_test(cx);
1449 let user_id = 5;
1450 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1451 let mut status = client.status();
1452
1453 // Time out when client tries to connect.
1454 client.override_authenticate(move |cx| {
1455 cx.background_executor().spawn(async move {
1456 Ok(Credentials {
1457 user_id,
1458 access_token: "token".into(),
1459 })
1460 })
1461 });
1462 client.override_establish_connection(|_, cx| {
1463 cx.background_executor().spawn(async move {
1464 future::pending::<()>().await;
1465 unreachable!()
1466 })
1467 });
1468 let auth_and_connect = cx.spawn({
1469 let client = client.clone();
1470 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1471 });
1472 executor.run_until_parked();
1473 assert!(matches!(status.next().await, Some(Status::Connecting)));
1474
1475 executor.advance_clock(CONNECTION_TIMEOUT);
1476 assert!(matches!(
1477 status.next().await,
1478 Some(Status::ConnectionError { .. })
1479 ));
1480 auth_and_connect.await.unwrap_err();
1481
1482 // Allow the connection to be established.
1483 let server = FakeServer::for_client(user_id, &client, cx).await;
1484 assert!(matches!(
1485 status.next().await,
1486 Some(Status::Connected { .. })
1487 ));
1488
1489 // Disconnect client.
1490 server.forbid_connections();
1491 server.disconnect();
1492 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1493
1494 // Time out when re-establishing the connection.
1495 server.allow_connections();
1496 client.override_establish_connection(|_, cx| {
1497 cx.background_executor().spawn(async move {
1498 future::pending::<()>().await;
1499 unreachable!()
1500 })
1501 });
1502 executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1503 assert!(matches!(
1504 status.next().await,
1505 Some(Status::Reconnecting { .. })
1506 ));
1507
1508 executor.advance_clock(CONNECTION_TIMEOUT);
1509 assert!(matches!(
1510 status.next().await,
1511 Some(Status::ReconnectionError { .. })
1512 ));
1513 }
1514
1515 #[gpui::test(iterations = 10)]
1516 async fn test_authenticating_more_than_once(
1517 cx: &mut TestAppContext,
1518 executor: BackgroundExecutor,
1519 ) {
1520 init_test(cx);
1521 let auth_count = Arc::new(Mutex::new(0));
1522 let dropped_auth_count = Arc::new(Mutex::new(0));
1523 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1524 client.override_authenticate({
1525 let auth_count = auth_count.clone();
1526 let dropped_auth_count = dropped_auth_count.clone();
1527 move |cx| {
1528 let auth_count = auth_count.clone();
1529 let dropped_auth_count = dropped_auth_count.clone();
1530 cx.background_executor().spawn(async move {
1531 *auth_count.lock() += 1;
1532 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1533 future::pending::<()>().await;
1534 unreachable!()
1535 })
1536 }
1537 });
1538
1539 let _authenticate = cx.spawn({
1540 let client = client.clone();
1541 move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1542 });
1543 executor.run_until_parked();
1544 assert_eq!(*auth_count.lock(), 1);
1545 assert_eq!(*dropped_auth_count.lock(), 0);
1546
1547 let _authenticate = cx.spawn({
1548 let client = client.clone();
1549 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1550 });
1551 executor.run_until_parked();
1552 assert_eq!(*auth_count.lock(), 2);
1553 assert_eq!(*dropped_auth_count.lock(), 1);
1554 }
1555
1556 #[test]
1557 fn test_encode_and_decode_worktree_url() {
1558 let url = encode_worktree_url(5, "deadbeef");
1559 assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1560 assert_eq!(
1561 decode_worktree_url(&format!("\n {}\t", url)),
1562 Some((5, "deadbeef".to_string()))
1563 );
1564 assert_eq!(decode_worktree_url("not://the-right-format"), None);
1565 }
1566
1567 #[gpui::test]
1568 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1569 init_test(cx);
1570 let user_id = 5;
1571 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1572 let server = FakeServer::for_client(user_id, &client, cx).await;
1573
1574 let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1575 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1576 client.add_model_message_handler(
1577 move |model: Model<TestModel>, _: TypedEnvelope<proto::JoinProject>, _, mut cx| {
1578 match model.update(&mut cx, |model, _| model.id).unwrap() {
1579 1 => done_tx1.try_send(()).unwrap(),
1580 2 => done_tx2.try_send(()).unwrap(),
1581 _ => unreachable!(),
1582 }
1583 async { Ok(()) }
1584 },
1585 );
1586 let model1 = cx.new_model(|_| TestModel {
1587 id: 1,
1588 subscription: None,
1589 });
1590 let model2 = cx.new_model(|_| TestModel {
1591 id: 2,
1592 subscription: None,
1593 });
1594 let model3 = cx.new_model(|_| TestModel {
1595 id: 3,
1596 subscription: None,
1597 });
1598
1599 let _subscription1 = client
1600 .subscribe_to_entity(1)
1601 .unwrap()
1602 .set_model(&model1, &mut cx.to_async());
1603 let _subscription2 = client
1604 .subscribe_to_entity(2)
1605 .unwrap()
1606 .set_model(&model2, &mut cx.to_async());
1607 // Ensure dropping a subscription for the same entity type still allows receiving of
1608 // messages for other entity IDs of the same type.
1609 let subscription3 = client
1610 .subscribe_to_entity(3)
1611 .unwrap()
1612 .set_model(&model3, &mut cx.to_async());
1613 drop(subscription3);
1614
1615 server.send(proto::JoinProject { project_id: 1 });
1616 server.send(proto::JoinProject { project_id: 2 });
1617 done_rx1.next().await.unwrap();
1618 done_rx2.next().await.unwrap();
1619 }
1620
1621 #[gpui::test]
1622 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1623 init_test(cx);
1624 let user_id = 5;
1625 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1626 let server = FakeServer::for_client(user_id, &client, cx).await;
1627
1628 let model = cx.new_model(|_| TestModel::default());
1629 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1630 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1631 let subscription1 = client.add_message_handler(
1632 model.downgrade(),
1633 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1634 done_tx1.try_send(()).unwrap();
1635 async { Ok(()) }
1636 },
1637 );
1638 drop(subscription1);
1639 let _subscription2 = client.add_message_handler(
1640 model.downgrade(),
1641 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1642 done_tx2.try_send(()).unwrap();
1643 async { Ok(()) }
1644 },
1645 );
1646 server.send(proto::Ping {});
1647 done_rx2.next().await.unwrap();
1648 }
1649
1650 #[gpui::test]
1651 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1652 init_test(cx);
1653 let user_id = 5;
1654 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1655 let server = FakeServer::for_client(user_id, &client, cx).await;
1656
1657 let model = cx.new_model(|_| TestModel::default());
1658 let (done_tx, mut done_rx) = smol::channel::unbounded();
1659 let subscription = client.add_message_handler(
1660 model.clone().downgrade(),
1661 move |model: Model<TestModel>, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1662 model
1663 .update(&mut cx, |model, _| model.subscription.take())
1664 .unwrap();
1665 done_tx.try_send(()).unwrap();
1666 async { Ok(()) }
1667 },
1668 );
1669 model.update(cx, |model, _| {
1670 model.subscription = Some(subscription);
1671 });
1672 server.send(proto::Ping {});
1673 done_rx.next().await.unwrap();
1674 }
1675
1676 #[derive(Default)]
1677 struct TestModel {
1678 id: usize,
1679 subscription: Option<Subscription>,
1680 }
1681
1682 fn init_test(cx: &mut TestAppContext) {
1683 cx.update(|cx| {
1684 let settings_store = SettingsStore::test(cx);
1685 cx.set_global(settings_store);
1686 });
1687 }
1688}