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