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