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