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