1#[cfg(any(test, feature = "test-support"))]
2pub mod test;
3
4pub mod telemetry;
5pub mod user;
6
7use anyhow::{anyhow, Context as _, Result};
8use async_recursion::async_recursion;
9use async_tungstenite::tungstenite::{
10 error::Error as WebsocketError,
11 http::{Request, StatusCode},
12};
13use futures::{
14 channel::oneshot, future::LocalBoxFuture, AsyncReadExt, FutureExt, SinkExt, StreamExt,
15 TryFutureExt as _, TryStreamExt,
16};
17use gpui::{
18 actions, 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!(client, [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: &mut 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 self.telemetry.set_authenticated_user_info(None, false);
505 state._reconnect_task.take();
506 }
507 _ => {}
508 }
509 }
510
511 pub fn subscribe_to_entity<T>(
512 self: &Arc<Self>,
513 remote_id: u64,
514 ) -> Result<PendingEntitySubscription<T>>
515 where
516 T: 'static,
517 {
518 let id = (TypeId::of::<T>(), remote_id);
519
520 let mut state = self.state.write();
521 if state.entities_by_type_and_remote_id.contains_key(&id) {
522 return Err(anyhow!("already subscribed to entity"));
523 } else {
524 state
525 .entities_by_type_and_remote_id
526 .insert(id, WeakSubscriber::Pending(Default::default()));
527 Ok(PendingEntitySubscription {
528 client: self.clone(),
529 remote_id,
530 consumed: false,
531 _entity_type: PhantomData,
532 })
533 }
534 }
535
536 #[track_caller]
537 pub fn add_message_handler<M, E, H, F>(
538 self: &Arc<Self>,
539 entity: WeakModel<E>,
540 handler: H,
541 ) -> Subscription
542 where
543 M: EnvelopedMessage,
544 E: 'static,
545 H: 'static
546 + Sync
547 + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
548 + Send
549 + Sync,
550 F: 'static + Future<Output = Result<()>>,
551 {
552 let message_type_id = TypeId::of::<M>();
553 let mut state = self.state.write();
554 state
555 .models_by_message_type
556 .insert(message_type_id, entity.into());
557
558 let prev_handler = state.message_handlers.insert(
559 message_type_id,
560 Arc::new(move |subscriber, envelope, client, cx| {
561 let subscriber = subscriber.downcast::<E>().unwrap();
562 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
563 handler(subscriber, *envelope, client.clone(), cx).boxed_local()
564 }),
565 );
566 if prev_handler.is_some() {
567 let location = std::panic::Location::caller();
568 panic!(
569 "{}:{} registered handler for the same message {} twice",
570 location.file(),
571 location.line(),
572 std::any::type_name::<M>()
573 );
574 }
575
576 Subscription::Message {
577 client: Arc::downgrade(self),
578 id: message_type_id,
579 }
580 }
581
582 pub fn add_request_handler<M, E, H, F>(
583 self: &Arc<Self>,
584 model: WeakModel<E>,
585 handler: H,
586 ) -> Subscription
587 where
588 M: RequestMessage,
589 E: 'static,
590 H: 'static
591 + Sync
592 + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
593 + Send
594 + Sync,
595 F: 'static + Future<Output = Result<M::Response>>,
596 {
597 self.add_message_handler(model, move |handle, envelope, this, cx| {
598 Self::respond_to_request(
599 envelope.receipt(),
600 handler(handle, envelope, this.clone(), cx),
601 this,
602 )
603 })
604 }
605
606 pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
607 where
608 M: EntityMessage,
609 E: 'static,
610 H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
611 F: 'static + Future<Output = Result<()>>,
612 {
613 self.add_entity_message_handler::<M, E, _, _>(move |subscriber, message, client, cx| {
614 handler(subscriber.downcast::<E>().unwrap(), message, client, cx)
615 })
616 }
617
618 fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
619 where
620 M: EntityMessage,
621 E: 'static,
622 H: 'static + Fn(AnyModel, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
623 F: 'static + Future<Output = Result<()>>,
624 {
625 let model_type_id = TypeId::of::<E>();
626 let message_type_id = TypeId::of::<M>();
627
628 let mut state = self.state.write();
629 state
630 .entity_types_by_message_type
631 .insert(message_type_id, model_type_id);
632 state
633 .entity_id_extractors
634 .entry(message_type_id)
635 .or_insert_with(|| {
636 |envelope| {
637 envelope
638 .as_any()
639 .downcast_ref::<TypedEnvelope<M>>()
640 .unwrap()
641 .payload
642 .remote_entity_id()
643 }
644 });
645 let prev_handler = state.message_handlers.insert(
646 message_type_id,
647 Arc::new(move |handle, envelope, client, cx| {
648 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
649 handler(handle, *envelope, client.clone(), cx).boxed_local()
650 }),
651 );
652 if prev_handler.is_some() {
653 panic!("registered handler for the same message twice");
654 }
655 }
656
657 pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
658 where
659 M: EntityMessage + RequestMessage,
660 E: 'static,
661 H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
662 F: 'static + Future<Output = Result<M::Response>>,
663 {
664 self.add_model_message_handler(move |entity, envelope, client, cx| {
665 Self::respond_to_request::<M, _>(
666 envelope.receipt(),
667 handler(entity, envelope, client.clone(), cx),
668 client,
669 )
670 })
671 }
672
673 async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
674 receipt: Receipt<T>,
675 response: F,
676 client: Arc<Self>,
677 ) -> Result<()> {
678 match response.await {
679 Ok(response) => {
680 client.respond(receipt, response)?;
681 Ok(())
682 }
683 Err(error) => {
684 client.respond_with_error(
685 receipt,
686 proto::Error {
687 message: format!("{:?}", error),
688 },
689 )?;
690 Err(error)
691 }
692 }
693 }
694
695 pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
696 read_credentials_from_keychain(cx).is_some()
697 }
698
699 #[async_recursion(?Send)]
700 pub async fn authenticate_and_connect(
701 self: &Arc<Self>,
702 try_keychain: bool,
703 cx: &AsyncAppContext,
704 ) -> anyhow::Result<()> {
705 let was_disconnected = match *self.status().borrow() {
706 Status::SignedOut => true,
707 Status::ConnectionError
708 | Status::ConnectionLost
709 | Status::Authenticating { .. }
710 | Status::Reauthenticating { .. }
711 | Status::ReconnectionError { .. } => false,
712 Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
713 return Ok(())
714 }
715 Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
716 };
717
718 if was_disconnected {
719 self.set_status(Status::Authenticating, cx);
720 } else {
721 self.set_status(Status::Reauthenticating, cx)
722 }
723
724 let mut read_from_keychain = false;
725 let mut credentials = self.state.read().credentials.clone();
726 if credentials.is_none() && try_keychain {
727 credentials = read_credentials_from_keychain(cx);
728 read_from_keychain = credentials.is_some();
729 }
730 if credentials.is_none() {
731 let mut status_rx = self.status();
732 let _ = status_rx.next().await;
733 futures::select_biased! {
734 authenticate = self.authenticate(cx).fuse() => {
735 match authenticate {
736 Ok(creds) => credentials = Some(creds),
737 Err(err) => {
738 self.set_status(Status::ConnectionError, cx);
739 return Err(err);
740 }
741 }
742 }
743 _ = status_rx.next().fuse() => {
744 return Err(anyhow!("authentication canceled"));
745 }
746 }
747 }
748 let credentials = credentials.unwrap();
749 self.set_id(credentials.user_id);
750
751 if was_disconnected {
752 self.set_status(Status::Connecting, cx);
753 } else {
754 self.set_status(Status::Reconnecting, cx);
755 }
756
757 let mut timeout =
758 futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
759 futures::select_biased! {
760 connection = self.establish_connection(&credentials, cx).fuse() => {
761 match connection {
762 Ok(conn) => {
763 self.state.write().credentials = Some(credentials.clone());
764 if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
765 write_credentials_to_keychain(credentials, cx).log_err();
766 }
767
768 futures::select_biased! {
769 result = self.set_connection(conn, cx).fuse() => result,
770 _ = timeout => {
771 self.set_status(Status::ConnectionError, cx);
772 Err(anyhow!("timed out waiting on hello message from server"))
773 }
774 }
775 }
776 Err(EstablishConnectionError::Unauthorized) => {
777 self.state.write().credentials.take();
778 if read_from_keychain {
779 delete_credentials_from_keychain(cx).log_err();
780 self.set_status(Status::SignedOut, cx);
781 self.authenticate_and_connect(false, cx).await
782 } else {
783 self.set_status(Status::ConnectionError, cx);
784 Err(EstablishConnectionError::Unauthorized)?
785 }
786 }
787 Err(EstablishConnectionError::UpgradeRequired) => {
788 self.set_status(Status::UpgradeRequired, cx);
789 Err(EstablishConnectionError::UpgradeRequired)?
790 }
791 Err(error) => {
792 self.set_status(Status::ConnectionError, cx);
793 Err(error)?
794 }
795 }
796 }
797 _ = &mut timeout => {
798 self.set_status(Status::ConnectionError, cx);
799 Err(anyhow!("timed out trying to establish connection"))
800 }
801 }
802 }
803
804 async fn set_connection(
805 self: &Arc<Self>,
806 conn: Connection,
807 cx: &AsyncAppContext,
808 ) -> Result<()> {
809 let executor = cx.background_executor();
810 log::info!("add connection to peer");
811 let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
812 let executor = executor.clone();
813 move |duration| executor.timer(duration)
814 });
815 let handle_io = executor.spawn(handle_io);
816
817 let peer_id = async {
818 log::info!("waiting for server hello");
819 let message = incoming
820 .next()
821 .await
822 .ok_or_else(|| anyhow!("no hello message received"))?;
823 log::info!("got server hello");
824 let hello_message_type_name = message.payload_type_name().to_string();
825 let hello = message
826 .into_any()
827 .downcast::<TypedEnvelope<proto::Hello>>()
828 .map_err(|_| {
829 anyhow!(
830 "invalid hello message received: {:?}",
831 hello_message_type_name
832 )
833 })?;
834 let peer_id = hello
835 .payload
836 .peer_id
837 .ok_or_else(|| anyhow!("invalid peer id"))?;
838 Ok(peer_id)
839 };
840
841 let peer_id = match peer_id.await {
842 Ok(peer_id) => peer_id,
843 Err(error) => {
844 self.peer.disconnect(connection_id);
845 return Err(error);
846 }
847 };
848
849 log::info!(
850 "set status to connected (connection id: {:?}, peer id: {:?})",
851 connection_id,
852 peer_id
853 );
854 self.set_status(
855 Status::Connected {
856 peer_id,
857 connection_id,
858 },
859 cx,
860 );
861
862 cx.spawn({
863 let this = self.clone();
864 |cx| {
865 async move {
866 while let Some(message) = incoming.next().await {
867 this.handle_message(message, &cx);
868 // Don't starve the main thread when receiving lots of messages at once.
869 smol::future::yield_now().await;
870 }
871 }
872 }
873 })
874 .detach();
875
876 cx.spawn({
877 let this = self.clone();
878 move |cx| async move {
879 match handle_io.await {
880 Ok(()) => {
881 if this.status().borrow().clone()
882 == (Status::Connected {
883 connection_id,
884 peer_id,
885 })
886 {
887 this.set_status(Status::SignedOut, &cx);
888 }
889 }
890 Err(err) => {
891 log::error!("connection error: {:?}", err);
892 this.set_status(Status::ConnectionLost, &cx);
893 }
894 }
895 }
896 })
897 .detach();
898
899 Ok(())
900 }
901
902 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
903 #[cfg(any(test, feature = "test-support"))]
904 if let Some(callback) = self.authenticate.read().as_ref() {
905 return callback(cx);
906 }
907
908 self.authenticate_with_browser(cx)
909 }
910
911 fn establish_connection(
912 self: &Arc<Self>,
913 credentials: &Credentials,
914 cx: &AsyncAppContext,
915 ) -> Task<Result<Connection, EstablishConnectionError>> {
916 #[cfg(any(test, feature = "test-support"))]
917 if let Some(callback) = self.establish_connection.read().as_ref() {
918 return callback(credentials, cx);
919 }
920
921 self.establish_websocket_connection(credentials, cx)
922 }
923
924 async fn get_rpc_url(
925 http: Arc<dyn HttpClient>,
926 release_channel: Option<ReleaseChannel>,
927 ) -> Result<Url> {
928 let mut url = format!("{}/rpc", *ZED_SERVER_URL);
929 if let Some(preview_param) =
930 release_channel.and_then(|channel| channel.release_query_param())
931 {
932 url += "?";
933 url += preview_param;
934 }
935 let response = http.get(&url, Default::default(), false).await?;
936
937 // Normally, ZED_SERVER_URL is set to the URL of zed.dev website.
938 // The website's /rpc endpoint redirects to a collab server's /rpc endpoint,
939 // which requires authorization via an HTTP header.
940 //
941 // For testing purposes, ZED_SERVER_URL can also set to the direct URL of
942 // of a collab server. In that case, a request to the /rpc endpoint will
943 // return an 'unauthorized' response.
944 let collab_url = if response.status().is_redirection() {
945 response
946 .headers()
947 .get("Location")
948 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
949 .to_str()
950 .map_err(EstablishConnectionError::other)?
951 .to_string()
952 } else if response.status() == StatusCode::UNAUTHORIZED {
953 url
954 } else {
955 Err(anyhow!(
956 "unexpected /rpc response status {}",
957 response.status()
958 ))?
959 };
960
961 Url::parse(&collab_url).context("invalid rpc url")
962 }
963
964 fn establish_websocket_connection(
965 self: &Arc<Self>,
966 credentials: &Credentials,
967 cx: &AsyncAppContext,
968 ) -> Task<Result<Connection, EstablishConnectionError>> {
969 let release_channel = cx.try_read_global(|channel: &ReleaseChannel, _| *channel);
970
971 let request = Request::builder()
972 .header(
973 "Authorization",
974 format!("{} {}", credentials.user_id, credentials.access_token),
975 )
976 .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION);
977
978 let http = self.http.clone();
979 cx.background_executor().spawn(async move {
980 let mut rpc_url = Self::get_rpc_url(http, release_channel).await?;
981 let rpc_host = rpc_url
982 .host_str()
983 .zip(rpc_url.port_or_known_default())
984 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
985 let stream = smol::net::TcpStream::connect(rpc_host).await?;
986
987 log::info!("connected to rpc endpoint {}", rpc_url);
988
989 match rpc_url.scheme() {
990 "https" => {
991 rpc_url.set_scheme("wss").unwrap();
992 let request = request.uri(rpc_url.as_str()).body(())?;
993 let (stream, _) =
994 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
995 Ok(Connection::new(
996 stream
997 .map_err(|error| anyhow!(error))
998 .sink_map_err(|error| anyhow!(error)),
999 ))
1000 }
1001 "http" => {
1002 rpc_url.set_scheme("ws").unwrap();
1003 let request = request.uri(rpc_url.as_str()).body(())?;
1004 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1005 Ok(Connection::new(
1006 stream
1007 .map_err(|error| anyhow!(error))
1008 .sink_map_err(|error| anyhow!(error)),
1009 ))
1010 }
1011 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1012 }
1013 })
1014 }
1015
1016 pub fn authenticate_with_browser(
1017 self: &Arc<Self>,
1018 cx: &AsyncAppContext,
1019 ) -> Task<Result<Credentials>> {
1020 let http = self.http.clone();
1021 cx.spawn(|cx| async move {
1022 let background = cx.background_executor().clone();
1023
1024 let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1025 cx.update(|cx| {
1026 cx.spawn(move |cx| async move {
1027 let url = open_url_rx.await?;
1028 cx.update(|cx| cx.open_url(&url))
1029 })
1030 .detach_and_log_err(cx);
1031 })
1032 .log_err();
1033
1034 let credentials = background
1035 .clone()
1036 .spawn(async move {
1037 // Generate a pair of asymmetric encryption keys. The public key will be used by the
1038 // zed server to encrypt the user's access token, so that it can'be intercepted by
1039 // any other app running on the user's device.
1040 let (public_key, private_key) =
1041 rpc::auth::keypair().expect("failed to generate keypair for auth");
1042 let public_key_string = String::try_from(public_key)
1043 .expect("failed to serialize public key for auth");
1044
1045 if let Some((login, token)) =
1046 IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1047 {
1048 return Self::authenticate_as_admin(http, login.clone(), token.clone())
1049 .await;
1050 }
1051
1052 // Start an HTTP server to receive the redirect from Zed's sign-in page.
1053 let server =
1054 tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1055 let port = server.server_addr().port();
1056
1057 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1058 // that the user is signing in from a Zed app running on the same device.
1059 let mut url = format!(
1060 "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
1061 *ZED_SERVER_URL, port, public_key_string
1062 );
1063
1064 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1065 log::info!("impersonating user @{}", impersonate_login);
1066 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1067 }
1068
1069 open_url_tx.send(url).log_err();
1070
1071 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1072 // access token from the query params.
1073 //
1074 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1075 // custom URL scheme instead of this local HTTP server.
1076 let (user_id, access_token) = background
1077 .spawn(async move {
1078 for _ in 0..100 {
1079 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1080 let path = req.url();
1081 let mut user_id = None;
1082 let mut access_token = None;
1083 let url = Url::parse(&format!("http://example.com{}", path))
1084 .context("failed to parse login notification url")?;
1085 for (key, value) in url.query_pairs() {
1086 if key == "access_token" {
1087 access_token = Some(value.to_string());
1088 } else if key == "user_id" {
1089 user_id = Some(value.to_string());
1090 }
1091 }
1092
1093 let post_auth_url =
1094 format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
1095 req.respond(
1096 tiny_http::Response::empty(302).with_header(
1097 tiny_http::Header::from_bytes(
1098 &b"Location"[..],
1099 post_auth_url.as_bytes(),
1100 )
1101 .unwrap(),
1102 ),
1103 )
1104 .context("failed to respond to login http request")?;
1105 return Ok((
1106 user_id
1107 .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1108 access_token.ok_or_else(|| {
1109 anyhow!("missing access_token parameter")
1110 })?,
1111 ));
1112 }
1113 }
1114
1115 Err(anyhow!("didn't receive login redirect"))
1116 })
1117 .await?;
1118
1119 let access_token = private_key
1120 .decrypt_string(&access_token)
1121 .context("failed to decrypt access token")?;
1122
1123 Ok(Credentials {
1124 user_id: user_id.parse()?,
1125 access_token,
1126 })
1127 })
1128 .await?;
1129
1130 cx.update(|cx| cx.activate(true))?;
1131 Ok(credentials)
1132 })
1133 }
1134
1135 async fn authenticate_as_admin(
1136 http: Arc<dyn HttpClient>,
1137 login: String,
1138 mut api_token: String,
1139 ) -> Result<Credentials> {
1140 #[derive(Deserialize)]
1141 struct AuthenticatedUserResponse {
1142 user: User,
1143 }
1144
1145 #[derive(Deserialize)]
1146 struct User {
1147 id: u64,
1148 }
1149
1150 // Use the collab server's admin API to retrieve the id
1151 // of the impersonated user.
1152 let mut url = Self::get_rpc_url(http.clone(), None).await?;
1153 url.set_path("/user");
1154 url.set_query(Some(&format!("github_login={login}")));
1155 let request = Request::get(url.as_str())
1156 .header("Authorization", format!("token {api_token}"))
1157 .body("".into())?;
1158
1159 let mut response = http.send(request).await?;
1160 let mut body = String::new();
1161 response.body_mut().read_to_string(&mut body).await?;
1162 if !response.status().is_success() {
1163 Err(anyhow!(
1164 "admin user request failed {} - {}",
1165 response.status().as_u16(),
1166 body,
1167 ))?;
1168 }
1169 let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1170
1171 // Use the admin API token to authenticate as the impersonated user.
1172 api_token.insert_str(0, "ADMIN_TOKEN:");
1173 Ok(Credentials {
1174 user_id: response.user.id,
1175 access_token: api_token,
1176 })
1177 }
1178
1179 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1180 self.peer.teardown();
1181 self.set_status(Status::SignedOut, cx);
1182 }
1183
1184 pub fn reconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1185 self.peer.teardown();
1186 self.set_status(Status::ConnectionLost, cx);
1187 }
1188
1189 fn connection_id(&self) -> Result<ConnectionId> {
1190 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1191 Ok(connection_id)
1192 } else {
1193 Err(anyhow!("not connected"))
1194 }
1195 }
1196
1197 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1198 log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1199 self.peer.send(self.connection_id()?, message)
1200 }
1201
1202 pub fn request<T: RequestMessage>(
1203 &self,
1204 request: T,
1205 ) -> impl Future<Output = Result<T::Response>> {
1206 self.request_envelope(request)
1207 .map_ok(|envelope| envelope.payload)
1208 }
1209
1210 pub fn request_envelope<T: RequestMessage>(
1211 &self,
1212 request: T,
1213 ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1214 let client_id = self.id();
1215 log::debug!(
1216 "rpc request start. client_id:{}. name:{}",
1217 client_id,
1218 T::NAME
1219 );
1220 let response = self
1221 .connection_id()
1222 .map(|conn_id| self.peer.request_envelope(conn_id, request));
1223 async move {
1224 let response = response?.await;
1225 log::debug!(
1226 "rpc request finish. client_id:{}. name:{}",
1227 client_id,
1228 T::NAME
1229 );
1230 response
1231 }
1232 }
1233
1234 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1235 log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1236 self.peer.respond(receipt, response)
1237 }
1238
1239 fn respond_with_error<T: RequestMessage>(
1240 &self,
1241 receipt: Receipt<T>,
1242 error: proto::Error,
1243 ) -> Result<()> {
1244 log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1245 self.peer.respond_with_error(receipt, error)
1246 }
1247
1248 fn handle_message(
1249 self: &Arc<Client>,
1250 message: Box<dyn AnyTypedEnvelope>,
1251 cx: &AsyncAppContext,
1252 ) {
1253 let mut state = self.state.write();
1254 let type_name = message.payload_type_name();
1255 let payload_type_id = message.payload_type_id();
1256 let sender_id = message.original_sender_id();
1257
1258 let mut subscriber = None;
1259
1260 if let Some(handle) = state
1261 .models_by_message_type
1262 .get(&payload_type_id)
1263 .and_then(|handle| handle.upgrade())
1264 {
1265 subscriber = Some(handle);
1266 } else if let Some((extract_entity_id, entity_type_id)) =
1267 state.entity_id_extractors.get(&payload_type_id).zip(
1268 state
1269 .entity_types_by_message_type
1270 .get(&payload_type_id)
1271 .copied(),
1272 )
1273 {
1274 let entity_id = (extract_entity_id)(message.as_ref());
1275
1276 match state
1277 .entities_by_type_and_remote_id
1278 .get_mut(&(entity_type_id, entity_id))
1279 {
1280 Some(WeakSubscriber::Pending(pending)) => {
1281 pending.push(message);
1282 return;
1283 }
1284 Some(weak_subscriber @ _) => match weak_subscriber {
1285 WeakSubscriber::Entity { handle } => {
1286 subscriber = handle.upgrade();
1287 }
1288
1289 WeakSubscriber::Pending(_) => {}
1290 },
1291 _ => {}
1292 }
1293 }
1294
1295 let subscriber = if let Some(subscriber) = subscriber {
1296 subscriber
1297 } else {
1298 log::info!("unhandled message {}", type_name);
1299 self.peer.respond_with_unhandled_message(message).log_err();
1300 return;
1301 };
1302
1303 let handler = state.message_handlers.get(&payload_type_id).cloned();
1304 // Dropping the state prevents deadlocks if the handler interacts with rpc::Client.
1305 // It also ensures we don't hold the lock while yielding back to the executor, as
1306 // that might cause the executor thread driving this future to block indefinitely.
1307 drop(state);
1308
1309 if let Some(handler) = handler {
1310 let future = handler(subscriber, message, &self, cx.clone());
1311 let client_id = self.id();
1312 log::debug!(
1313 "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1314 client_id,
1315 sender_id,
1316 type_name
1317 );
1318 cx.spawn(move |_| async move {
1319 match future.await {
1320 Ok(()) => {
1321 log::debug!(
1322 "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1323 client_id,
1324 sender_id,
1325 type_name
1326 );
1327 }
1328 Err(error) => {
1329 log::error!(
1330 "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1331 client_id,
1332 sender_id,
1333 type_name,
1334 error
1335 );
1336 }
1337 }
1338 })
1339 .detach();
1340 } else {
1341 log::info!("unhandled message {}", type_name);
1342 self.peer.respond_with_unhandled_message(message).log_err();
1343 }
1344 }
1345
1346 pub fn telemetry(&self) -> &Arc<Telemetry> {
1347 &self.telemetry
1348 }
1349}
1350
1351fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1352 if IMPERSONATE_LOGIN.is_some() {
1353 return None;
1354 }
1355
1356 let (user_id, access_token) = cx
1357 .update(|cx| cx.read_credentials(&ZED_SERVER_URL).log_err().flatten())
1358 .ok()??;
1359
1360 Some(Credentials {
1361 user_id: user_id.parse().ok()?,
1362 access_token: String::from_utf8(access_token).ok()?,
1363 })
1364}
1365
1366async fn write_credentials_to_keychain(
1367 credentials: Credentials,
1368 cx: &AsyncAppContext,
1369) -> Result<()> {
1370 cx.update(move |cx| {
1371 cx.write_credentials(
1372 &ZED_SERVER_URL,
1373 &credentials.user_id.to_string(),
1374 credentials.access_token.as_bytes(),
1375 )
1376 })?
1377}
1378
1379async fn delete_credentials_from_keychain(cx: &AsyncAppContext) -> Result<()> {
1380 cx.update(move |cx| cx.delete_credentials(&ZED_SERVER_URL))?
1381}
1382
1383const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
1384
1385pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1386 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1387}
1388
1389pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1390 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1391 let mut parts = path.split('/');
1392 let id = parts.next()?.parse::<u64>().ok()?;
1393 let access_token = parts.next()?;
1394 if access_token.is_empty() {
1395 return None;
1396 }
1397 Some((id, access_token.to_string()))
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402 use super::*;
1403 use crate::test::FakeServer;
1404
1405 use gpui::{BackgroundExecutor, Context, TestAppContext};
1406 use parking_lot::Mutex;
1407 use std::future;
1408 use util::http::FakeHttpClient;
1409
1410 #[gpui::test(iterations = 10)]
1411 async fn test_reconnection(cx: &mut TestAppContext) {
1412 let user_id = 5;
1413 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1414 let server = FakeServer::for_client(user_id, &client, cx).await;
1415 let mut status = client.status();
1416 assert!(matches!(
1417 status.next().await,
1418 Some(Status::Connected { .. })
1419 ));
1420 assert_eq!(server.auth_count(), 1);
1421
1422 server.forbid_connections();
1423 server.disconnect();
1424 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1425
1426 server.allow_connections();
1427 cx.executor().advance_clock(Duration::from_secs(10));
1428 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1429 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1430
1431 server.forbid_connections();
1432 server.disconnect();
1433 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1434
1435 // Clear cached credentials after authentication fails
1436 server.roll_access_token();
1437 server.allow_connections();
1438 cx.executor().run_until_parked();
1439 cx.executor().advance_clock(Duration::from_secs(10));
1440 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1441 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1442 }
1443
1444 #[gpui::test(iterations = 10)]
1445 async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1446 let user_id = 5;
1447 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1448 let mut status = client.status();
1449
1450 // Time out when client tries to connect.
1451 client.override_authenticate(move |cx| {
1452 cx.background_executor().spawn(async move {
1453 Ok(Credentials {
1454 user_id,
1455 access_token: "token".into(),
1456 })
1457 })
1458 });
1459 client.override_establish_connection(|_, cx| {
1460 cx.background_executor().spawn(async move {
1461 future::pending::<()>().await;
1462 unreachable!()
1463 })
1464 });
1465 let auth_and_connect = cx.spawn({
1466 let client = client.clone();
1467 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1468 });
1469 executor.run_until_parked();
1470 assert!(matches!(status.next().await, Some(Status::Connecting)));
1471
1472 executor.advance_clock(CONNECTION_TIMEOUT);
1473 assert!(matches!(
1474 status.next().await,
1475 Some(Status::ConnectionError { .. })
1476 ));
1477 auth_and_connect.await.unwrap_err();
1478
1479 // Allow the connection to be established.
1480 let server = FakeServer::for_client(user_id, &client, cx).await;
1481 assert!(matches!(
1482 status.next().await,
1483 Some(Status::Connected { .. })
1484 ));
1485
1486 // Disconnect client.
1487 server.forbid_connections();
1488 server.disconnect();
1489 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1490
1491 // Time out when re-establishing the connection.
1492 server.allow_connections();
1493 client.override_establish_connection(|_, cx| {
1494 cx.background_executor().spawn(async move {
1495 future::pending::<()>().await;
1496 unreachable!()
1497 })
1498 });
1499 executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1500 assert!(matches!(
1501 status.next().await,
1502 Some(Status::Reconnecting { .. })
1503 ));
1504
1505 executor.advance_clock(CONNECTION_TIMEOUT);
1506 assert!(matches!(
1507 status.next().await,
1508 Some(Status::ReconnectionError { .. })
1509 ));
1510 }
1511
1512 #[gpui::test(iterations = 10)]
1513 async fn test_authenticating_more_than_once(
1514 cx: &mut TestAppContext,
1515 executor: BackgroundExecutor,
1516 ) {
1517 let auth_count = Arc::new(Mutex::new(0));
1518 let dropped_auth_count = Arc::new(Mutex::new(0));
1519 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1520 client.override_authenticate({
1521 let auth_count = auth_count.clone();
1522 let dropped_auth_count = dropped_auth_count.clone();
1523 move |cx| {
1524 let auth_count = auth_count.clone();
1525 let dropped_auth_count = dropped_auth_count.clone();
1526 cx.background_executor().spawn(async move {
1527 *auth_count.lock() += 1;
1528 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1529 future::pending::<()>().await;
1530 unreachable!()
1531 })
1532 }
1533 });
1534
1535 let _authenticate = cx.spawn({
1536 let client = client.clone();
1537 move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1538 });
1539 executor.run_until_parked();
1540 assert_eq!(*auth_count.lock(), 1);
1541 assert_eq!(*dropped_auth_count.lock(), 0);
1542
1543 let _authenticate = cx.spawn({
1544 let client = client.clone();
1545 |cx| async move { client.authenticate_and_connect(false, &cx).await }
1546 });
1547 executor.run_until_parked();
1548 assert_eq!(*auth_count.lock(), 2);
1549 assert_eq!(*dropped_auth_count.lock(), 1);
1550 }
1551
1552 #[test]
1553 fn test_encode_and_decode_worktree_url() {
1554 let url = encode_worktree_url(5, "deadbeef");
1555 assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1556 assert_eq!(
1557 decode_worktree_url(&format!("\n {}\t", url)),
1558 Some((5, "deadbeef".to_string()))
1559 );
1560 assert_eq!(decode_worktree_url("not://the-right-format"), None);
1561 }
1562
1563 #[gpui::test]
1564 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1565 let user_id = 5;
1566 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1567 let server = FakeServer::for_client(user_id, &client, cx).await;
1568
1569 let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1570 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1571 client.add_model_message_handler(
1572 move |model: Model<TestModel>, _: TypedEnvelope<proto::JoinProject>, _, mut cx| {
1573 match model.update(&mut cx, |model, _| model.id).unwrap() {
1574 1 => done_tx1.try_send(()).unwrap(),
1575 2 => done_tx2.try_send(()).unwrap(),
1576 _ => unreachable!(),
1577 }
1578 async { Ok(()) }
1579 },
1580 );
1581 let model1 = cx.new_model(|_| TestModel {
1582 id: 1,
1583 subscription: None,
1584 });
1585 let model2 = cx.new_model(|_| TestModel {
1586 id: 2,
1587 subscription: None,
1588 });
1589 let model3 = cx.new_model(|_| TestModel {
1590 id: 3,
1591 subscription: None,
1592 });
1593
1594 let _subscription1 = client
1595 .subscribe_to_entity(1)
1596 .unwrap()
1597 .set_model(&model1, &mut cx.to_async());
1598 let _subscription2 = client
1599 .subscribe_to_entity(2)
1600 .unwrap()
1601 .set_model(&model2, &mut cx.to_async());
1602 // Ensure dropping a subscription for the same entity type still allows receiving of
1603 // messages for other entity IDs of the same type.
1604 let subscription3 = client
1605 .subscribe_to_entity(3)
1606 .unwrap()
1607 .set_model(&model3, &mut cx.to_async());
1608 drop(subscription3);
1609
1610 server.send(proto::JoinProject { project_id: 1 });
1611 server.send(proto::JoinProject { project_id: 2 });
1612 done_rx1.next().await.unwrap();
1613 done_rx2.next().await.unwrap();
1614 }
1615
1616 #[gpui::test]
1617 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1618 let user_id = 5;
1619 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1620 let server = FakeServer::for_client(user_id, &client, cx).await;
1621
1622 let model = cx.new_model(|_| TestModel::default());
1623 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1624 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1625 let subscription1 = client.add_message_handler(
1626 model.downgrade(),
1627 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1628 done_tx1.try_send(()).unwrap();
1629 async { Ok(()) }
1630 },
1631 );
1632 drop(subscription1);
1633 let _subscription2 = client.add_message_handler(
1634 model.downgrade(),
1635 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1636 done_tx2.try_send(()).unwrap();
1637 async { Ok(()) }
1638 },
1639 );
1640 server.send(proto::Ping {});
1641 done_rx2.next().await.unwrap();
1642 }
1643
1644 #[gpui::test]
1645 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1646 let user_id = 5;
1647 let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1648 let server = FakeServer::for_client(user_id, &client, cx).await;
1649
1650 let model = cx.new_model(|_| TestModel::default());
1651 let (done_tx, mut done_rx) = smol::channel::unbounded();
1652 let subscription = client.add_message_handler(
1653 model.clone().downgrade(),
1654 move |model: Model<TestModel>, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1655 model
1656 .update(&mut cx, |model, _| model.subscription.take())
1657 .unwrap();
1658 done_tx.try_send(()).unwrap();
1659 async { Ok(()) }
1660 },
1661 );
1662 model.update(cx, |model, _| {
1663 model.subscription = Some(subscription);
1664 });
1665 server.send(proto::Ping {});
1666 done_rx.next().await.unwrap();
1667 }
1668
1669 #[derive(Default)]
1670 struct TestModel {
1671 id: usize,
1672 subscription: Option<Subscription>,
1673 }
1674}