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