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