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