1#[cfg(any(test, feature = "test-support"))]
2pub mod test;
3
4pub mod call;
5pub mod channel;
6pub mod http;
7pub mod user;
8
9use anyhow::{anyhow, Context, Result};
10use async_recursion::async_recursion;
11use async_tungstenite::tungstenite::{
12 error::Error as WebsocketError,
13 http::{Request, StatusCode},
14};
15use futures::{future::LocalBoxFuture, FutureExt, SinkExt, StreamExt, TryStreamExt};
16use gpui::{
17 actions, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AnyWeakViewHandle, AsyncAppContext,
18 Entity, ModelContext, ModelHandle, MutableAppContext, Task, View, ViewContext, ViewHandle,
19};
20use http::HttpClient;
21use lazy_static::lazy_static;
22use parking_lot::RwLock;
23use postage::watch;
24use rand::prelude::*;
25use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, RequestMessage};
26use std::{
27 any::TypeId,
28 collections::HashMap,
29 convert::TryFrom,
30 fmt::Write as _,
31 future::Future,
32 sync::{Arc, Weak},
33 time::{Duration, Instant},
34};
35use thiserror::Error;
36use url::Url;
37use util::{ResultExt, TryFutureExt};
38
39pub use channel::*;
40pub use rpc::*;
41pub use user::*;
42
43lazy_static! {
44 pub static ref ZED_SERVER_URL: String =
45 std::env::var("ZED_SERVER_URL").unwrap_or_else(|_| "https://zed.dev".to_string());
46 pub static ref IMPERSONATE_LOGIN: Option<String> = std::env::var("ZED_IMPERSONATE")
47 .ok()
48 .and_then(|s| if s.is_empty() { None } else { Some(s) });
49}
50
51pub const ZED_SECRET_CLIENT_TOKEN: &str = "618033988749894";
52
53actions!(client, [Authenticate]);
54
55pub fn init(rpc: Arc<Client>, cx: &mut MutableAppContext) {
56 cx.add_global_action(move |_: &Authenticate, cx| {
57 let rpc = rpc.clone();
58 cx.spawn(|cx| async move { rpc.authenticate_and_connect(true, &cx).log_err().await })
59 .detach();
60 });
61}
62
63pub struct Client {
64 id: usize,
65 peer: Arc<Peer>,
66 http: Arc<dyn HttpClient>,
67 state: RwLock<ClientState>,
68
69 #[allow(clippy::type_complexity)]
70 #[cfg(any(test, feature = "test-support"))]
71 authenticate: RwLock<
72 Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
73 >,
74
75 #[allow(clippy::type_complexity)]
76 #[cfg(any(test, feature = "test-support"))]
77 establish_connection: RwLock<
78 Option<
79 Box<
80 dyn 'static
81 + Send
82 + Sync
83 + Fn(
84 &Credentials,
85 &AsyncAppContext,
86 ) -> Task<Result<Connection, EstablishConnectionError>>,
87 >,
88 >,
89 >,
90}
91
92#[derive(Error, Debug)]
93pub enum EstablishConnectionError {
94 #[error("upgrade required")]
95 UpgradeRequired,
96 #[error("unauthorized")]
97 Unauthorized,
98 #[error("{0}")]
99 Other(#[from] anyhow::Error),
100 #[error("{0}")]
101 Http(#[from] http::Error),
102 #[error("{0}")]
103 Io(#[from] std::io::Error),
104 #[error("{0}")]
105 Websocket(#[from] async_tungstenite::tungstenite::http::Error),
106}
107
108impl From<WebsocketError> for EstablishConnectionError {
109 fn from(error: WebsocketError) -> Self {
110 if let WebsocketError::Http(response) = &error {
111 match response.status() {
112 StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
113 StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
114 _ => {}
115 }
116 }
117 EstablishConnectionError::Other(error.into())
118 }
119}
120
121impl EstablishConnectionError {
122 pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
123 Self::Other(error.into())
124 }
125}
126
127#[derive(Copy, Clone, Debug, Eq, PartialEq)]
128pub enum Status {
129 SignedOut,
130 UpgradeRequired,
131 Authenticating,
132 Connecting,
133 ConnectionError,
134 Connected { connection_id: ConnectionId },
135 ConnectionLost,
136 Reauthenticating,
137 Reconnecting,
138 ReconnectionError { next_reconnection: Instant },
139}
140
141impl Status {
142 pub fn is_connected(&self) -> bool {
143 matches!(self, Self::Connected { .. })
144 }
145}
146
147struct ClientState {
148 credentials: Option<Credentials>,
149 status: (watch::Sender<Status>, watch::Receiver<Status>),
150 entity_id_extractors: HashMap<TypeId, fn(&dyn AnyTypedEnvelope) -> u64>,
151 _reconnect_task: Option<Task<()>>,
152 reconnect_interval: Duration,
153 entities_by_type_and_remote_id: HashMap<(TypeId, u64), AnyWeakEntityHandle>,
154 models_by_message_type: HashMap<TypeId, AnyWeakModelHandle>,
155 entity_types_by_message_type: HashMap<TypeId, TypeId>,
156 #[allow(clippy::type_complexity)]
157 message_handlers: HashMap<
158 TypeId,
159 Arc<
160 dyn Send
161 + Sync
162 + Fn(
163 AnyEntityHandle,
164 Box<dyn AnyTypedEnvelope>,
165 &Arc<Client>,
166 AsyncAppContext,
167 ) -> LocalBoxFuture<'static, Result<()>>,
168 >,
169 >,
170}
171
172enum AnyWeakEntityHandle {
173 Model(AnyWeakModelHandle),
174 View(AnyWeakViewHandle),
175}
176
177enum AnyEntityHandle {
178 Model(AnyModelHandle),
179 View(AnyViewHandle),
180}
181
182#[derive(Clone, Debug)]
183pub struct Credentials {
184 pub user_id: u64,
185 pub access_token: String,
186}
187
188impl Default for ClientState {
189 fn default() -> Self {
190 Self {
191 credentials: None,
192 status: watch::channel_with(Status::SignedOut),
193 entity_id_extractors: Default::default(),
194 _reconnect_task: None,
195 reconnect_interval: Duration::from_secs(5),
196 models_by_message_type: Default::default(),
197 entities_by_type_and_remote_id: Default::default(),
198 entity_types_by_message_type: Default::default(),
199 message_handlers: Default::default(),
200 }
201 }
202}
203
204pub enum Subscription {
205 Entity {
206 client: Weak<Client>,
207 id: (TypeId, u64),
208 },
209 Message {
210 client: Weak<Client>,
211 id: TypeId,
212 },
213}
214
215impl Drop for Subscription {
216 fn drop(&mut self) {
217 match self {
218 Subscription::Entity { client, id } => {
219 if let Some(client) = client.upgrade() {
220 let mut state = client.state.write();
221 let _ = state.entities_by_type_and_remote_id.remove(id);
222 }
223 }
224 Subscription::Message { client, id } => {
225 if let Some(client) = client.upgrade() {
226 let mut state = client.state.write();
227 let _ = state.entity_types_by_message_type.remove(id);
228 let _ = state.message_handlers.remove(id);
229 }
230 }
231 }
232 }
233}
234
235impl Client {
236 pub fn new(http: Arc<dyn HttpClient>) -> Arc<Self> {
237 Arc::new(Self {
238 id: 0,
239 peer: Peer::new(),
240 http,
241 state: Default::default(),
242
243 #[cfg(any(test, feature = "test-support"))]
244 authenticate: Default::default(),
245 #[cfg(any(test, feature = "test-support"))]
246 establish_connection: Default::default(),
247 })
248 }
249
250 pub fn id(&self) -> usize {
251 self.id
252 }
253
254 pub fn http_client(&self) -> Arc<dyn HttpClient> {
255 self.http.clone()
256 }
257
258 #[cfg(any(test, feature = "test-support"))]
259 pub fn set_id(&mut self, id: usize) -> &Self {
260 self.id = id;
261 self
262 }
263
264 #[cfg(any(test, feature = "test-support"))]
265 pub fn tear_down(&self) {
266 let mut state = self.state.write();
267 state._reconnect_task.take();
268 state.message_handlers.clear();
269 state.models_by_message_type.clear();
270 state.entities_by_type_and_remote_id.clear();
271 state.entity_id_extractors.clear();
272 self.peer.reset();
273 }
274
275 #[cfg(any(test, feature = "test-support"))]
276 pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
277 where
278 F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
279 {
280 *self.authenticate.write() = Some(Box::new(authenticate));
281 self
282 }
283
284 #[cfg(any(test, feature = "test-support"))]
285 pub fn override_establish_connection<F>(&self, connect: F) -> &Self
286 where
287 F: 'static
288 + Send
289 + Sync
290 + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
291 {
292 *self.establish_connection.write() = Some(Box::new(connect));
293 self
294 }
295
296 pub fn user_id(&self) -> Option<u64> {
297 self.state
298 .read()
299 .credentials
300 .as_ref()
301 .map(|credentials| credentials.user_id)
302 }
303
304 pub fn status(&self) -> watch::Receiver<Status> {
305 self.state.read().status.1.clone()
306 }
307
308 fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
309 log::info!("set status on client {}: {:?}", self.id, status);
310 let mut state = self.state.write();
311 *state.status.0.borrow_mut() = status;
312
313 match status {
314 Status::Connected { .. } => {
315 state._reconnect_task = None;
316 }
317 Status::ConnectionLost => {
318 let this = self.clone();
319 let reconnect_interval = state.reconnect_interval;
320 state._reconnect_task = Some(cx.spawn(|cx| async move {
321 let mut rng = StdRng::from_entropy();
322 let mut delay = Duration::from_millis(100);
323 while let Err(error) = this.authenticate_and_connect(true, &cx).await {
324 log::error!("failed to connect {}", error);
325 if matches!(*this.status().borrow(), Status::ConnectionError) {
326 this.set_status(
327 Status::ReconnectionError {
328 next_reconnection: Instant::now() + delay,
329 },
330 &cx,
331 );
332 cx.background().timer(delay).await;
333 delay = delay
334 .mul_f32(rng.gen_range(1.0..=2.0))
335 .min(reconnect_interval);
336 } else {
337 break;
338 }
339 }
340 }));
341 }
342 Status::SignedOut | Status::UpgradeRequired => {
343 state._reconnect_task.take();
344 }
345 _ => {}
346 }
347 }
348
349 pub fn add_view_for_remote_entity<T: View>(
350 self: &Arc<Self>,
351 remote_id: u64,
352 cx: &mut ViewContext<T>,
353 ) -> Subscription {
354 let id = (TypeId::of::<T>(), remote_id);
355 self.state
356 .write()
357 .entities_by_type_and_remote_id
358 .insert(id, AnyWeakEntityHandle::View(cx.weak_handle().into()));
359 Subscription::Entity {
360 client: Arc::downgrade(self),
361 id,
362 }
363 }
364
365 pub fn add_model_for_remote_entity<T: Entity>(
366 self: &Arc<Self>,
367 remote_id: u64,
368 cx: &mut ModelContext<T>,
369 ) -> Subscription {
370 let id = (TypeId::of::<T>(), remote_id);
371 self.state
372 .write()
373 .entities_by_type_and_remote_id
374 .insert(id, AnyWeakEntityHandle::Model(cx.weak_handle().into()));
375 Subscription::Entity {
376 client: Arc::downgrade(self),
377 id,
378 }
379 }
380
381 pub fn add_message_handler<M, E, H, F>(
382 self: &Arc<Self>,
383 model: ModelHandle<E>,
384 handler: H,
385 ) -> Subscription
386 where
387 M: EnvelopedMessage,
388 E: Entity,
389 H: 'static
390 + Send
391 + Sync
392 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
393 F: 'static + Future<Output = Result<()>>,
394 {
395 let message_type_id = TypeId::of::<M>();
396
397 let mut state = self.state.write();
398 state
399 .models_by_message_type
400 .insert(message_type_id, model.downgrade().into());
401
402 let prev_handler = state.message_handlers.insert(
403 message_type_id,
404 Arc::new(move |handle, envelope, client, cx| {
405 let handle = if let AnyEntityHandle::Model(handle) = handle {
406 handle
407 } else {
408 unreachable!();
409 };
410 let model = handle.downcast::<E>().unwrap();
411 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
412 handler(model, *envelope, client.clone(), cx).boxed_local()
413 }),
414 );
415 if prev_handler.is_some() {
416 panic!("registered handler for the same message twice");
417 }
418
419 Subscription::Message {
420 client: Arc::downgrade(self),
421 id: message_type_id,
422 }
423 }
424
425 pub fn add_request_handler<M, E, H, F>(
426 self: &Arc<Self>,
427 model: ModelHandle<E>,
428 handler: H,
429 ) -> Subscription
430 where
431 M: RequestMessage,
432 E: Entity,
433 H: 'static
434 + Send
435 + Sync
436 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
437 F: 'static + Future<Output = Result<M::Response>>,
438 {
439 self.add_message_handler(model, move |handle, envelope, this, cx| {
440 Self::respond_to_request(
441 envelope.receipt(),
442 handler(handle, envelope, this.clone(), cx),
443 this,
444 )
445 })
446 }
447
448 pub fn add_view_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
449 where
450 M: EntityMessage,
451 E: View,
452 H: 'static
453 + Send
454 + Sync
455 + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
456 F: 'static + Future<Output = Result<()>>,
457 {
458 self.add_entity_message_handler::<M, E, _, _>(move |handle, message, client, cx| {
459 if let AnyEntityHandle::View(handle) = handle {
460 handler(handle.downcast::<E>().unwrap(), message, client, cx)
461 } else {
462 unreachable!();
463 }
464 })
465 }
466
467 pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
468 where
469 M: EntityMessage,
470 E: Entity,
471 H: 'static
472 + Send
473 + Sync
474 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
475 F: 'static + Future<Output = Result<()>>,
476 {
477 self.add_entity_message_handler::<M, E, _, _>(move |handle, message, client, cx| {
478 if let AnyEntityHandle::Model(handle) = handle {
479 handler(handle.downcast::<E>().unwrap(), message, client, cx)
480 } else {
481 unreachable!();
482 }
483 })
484 }
485
486 fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
487 where
488 M: EntityMessage,
489 E: Entity,
490 H: 'static
491 + Send
492 + Sync
493 + Fn(AnyEntityHandle, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
494 F: 'static + Future<Output = Result<()>>,
495 {
496 let model_type_id = TypeId::of::<E>();
497 let message_type_id = TypeId::of::<M>();
498
499 let mut state = self.state.write();
500 state
501 .entity_types_by_message_type
502 .insert(message_type_id, model_type_id);
503 state
504 .entity_id_extractors
505 .entry(message_type_id)
506 .or_insert_with(|| {
507 |envelope| {
508 envelope
509 .as_any()
510 .downcast_ref::<TypedEnvelope<M>>()
511 .unwrap()
512 .payload
513 .remote_entity_id()
514 }
515 });
516 let prev_handler = state.message_handlers.insert(
517 message_type_id,
518 Arc::new(move |handle, envelope, client, cx| {
519 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
520 handler(handle, *envelope, client.clone(), cx).boxed_local()
521 }),
522 );
523 if prev_handler.is_some() {
524 panic!("registered handler for the same message twice");
525 }
526 }
527
528 pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
529 where
530 M: EntityMessage + RequestMessage,
531 E: Entity,
532 H: 'static
533 + Send
534 + Sync
535 + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
536 F: 'static + Future<Output = Result<M::Response>>,
537 {
538 self.add_model_message_handler(move |entity, envelope, client, cx| {
539 Self::respond_to_request::<M, _>(
540 envelope.receipt(),
541 handler(entity, envelope, client.clone(), cx),
542 client,
543 )
544 })
545 }
546
547 pub fn add_view_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
548 where
549 M: EntityMessage + RequestMessage,
550 E: View,
551 H: 'static
552 + Send
553 + Sync
554 + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
555 F: 'static + Future<Output = Result<M::Response>>,
556 {
557 self.add_view_message_handler(move |entity, envelope, client, cx| {
558 Self::respond_to_request::<M, _>(
559 envelope.receipt(),
560 handler(entity, envelope, client.clone(), cx),
561 client,
562 )
563 })
564 }
565
566 async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
567 receipt: Receipt<T>,
568 response: F,
569 client: Arc<Self>,
570 ) -> Result<()> {
571 match response.await {
572 Ok(response) => {
573 client.respond(receipt, response)?;
574 Ok(())
575 }
576 Err(error) => {
577 client.respond_with_error(
578 receipt,
579 proto::Error {
580 message: format!("{:?}", error),
581 },
582 )?;
583 Err(error)
584 }
585 }
586 }
587
588 pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
589 read_credentials_from_keychain(cx).is_some()
590 }
591
592 #[async_recursion(?Send)]
593 pub async fn authenticate_and_connect(
594 self: &Arc<Self>,
595 try_keychain: bool,
596 cx: &AsyncAppContext,
597 ) -> anyhow::Result<()> {
598 let was_disconnected = match *self.status().borrow() {
599 Status::SignedOut => true,
600 Status::ConnectionError
601 | Status::ConnectionLost
602 | Status::Authenticating { .. }
603 | Status::Reauthenticating { .. }
604 | Status::ReconnectionError { .. } => false,
605 Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
606 return Ok(())
607 }
608 Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
609 };
610
611 if was_disconnected {
612 self.set_status(Status::Authenticating, cx);
613 } else {
614 self.set_status(Status::Reauthenticating, cx)
615 }
616
617 let mut read_from_keychain = false;
618 let mut credentials = self.state.read().credentials.clone();
619 if credentials.is_none() && try_keychain {
620 credentials = read_credentials_from_keychain(cx);
621 read_from_keychain = credentials.is_some();
622 }
623 if credentials.is_none() {
624 let mut status_rx = self.status();
625 let _ = status_rx.next().await;
626 futures::select_biased! {
627 authenticate = self.authenticate(cx).fuse() => {
628 match authenticate {
629 Ok(creds) => credentials = Some(creds),
630 Err(err) => {
631 self.set_status(Status::ConnectionError, cx);
632 return Err(err);
633 }
634 }
635 }
636 _ = status_rx.next().fuse() => {
637 return Err(anyhow!("authentication canceled"));
638 }
639 }
640 }
641 let credentials = credentials.unwrap();
642
643 if was_disconnected {
644 self.set_status(Status::Connecting, cx);
645 } else {
646 self.set_status(Status::Reconnecting, cx);
647 }
648
649 match self.establish_connection(&credentials, cx).await {
650 Ok(conn) => {
651 self.state.write().credentials = Some(credentials.clone());
652 if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
653 write_credentials_to_keychain(&credentials, cx).log_err();
654 }
655 self.set_connection(conn, cx).await;
656 Ok(())
657 }
658 Err(EstablishConnectionError::Unauthorized) => {
659 self.state.write().credentials.take();
660 if read_from_keychain {
661 cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
662 self.set_status(Status::SignedOut, cx);
663 self.authenticate_and_connect(false, cx).await
664 } else {
665 self.set_status(Status::ConnectionError, cx);
666 Err(EstablishConnectionError::Unauthorized)?
667 }
668 }
669 Err(EstablishConnectionError::UpgradeRequired) => {
670 self.set_status(Status::UpgradeRequired, cx);
671 Err(EstablishConnectionError::UpgradeRequired)?
672 }
673 Err(error) => {
674 self.set_status(Status::ConnectionError, cx);
675 Err(error)?
676 }
677 }
678 }
679
680 async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
681 let executor = cx.background();
682 log::info!("add connection to peer");
683 let (connection_id, handle_io, mut incoming) = self
684 .peer
685 .add_connection(conn, move |duration| executor.timer(duration))
686 .await;
687 log::info!("set status to connected {}", connection_id);
688 self.set_status(Status::Connected { connection_id }, cx);
689 cx.foreground()
690 .spawn({
691 let cx = cx.clone();
692 let this = self.clone();
693 async move {
694 let mut message_id = 0_usize;
695 while let Some(message) = incoming.next().await {
696 let mut state = this.state.write();
697 message_id += 1;
698 let type_name = message.payload_type_name();
699 let payload_type_id = message.payload_type_id();
700 let sender_id = message.original_sender_id().map(|id| id.0);
701
702 let model = state
703 .models_by_message_type
704 .get(&payload_type_id)
705 .and_then(|model| model.upgrade(&cx))
706 .map(AnyEntityHandle::Model)
707 .or_else(|| {
708 let entity_type_id =
709 *state.entity_types_by_message_type.get(&payload_type_id)?;
710 let entity_id = state
711 .entity_id_extractors
712 .get(&message.payload_type_id())
713 .map(|extract_entity_id| {
714 (extract_entity_id)(message.as_ref())
715 })?;
716
717 let entity = state
718 .entities_by_type_and_remote_id
719 .get(&(entity_type_id, entity_id))?;
720 if let Some(entity) = entity.upgrade(&cx) {
721 Some(entity)
722 } else {
723 state
724 .entities_by_type_and_remote_id
725 .remove(&(entity_type_id, entity_id));
726 None
727 }
728 });
729
730 let model = if let Some(model) = model {
731 model
732 } else {
733 log::info!("unhandled message {}", type_name);
734 continue;
735 };
736
737 if let Some(handler) = state.message_handlers.get(&payload_type_id).cloned()
738 {
739 drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
740 let future = handler(model, message, &this, cx.clone());
741
742 let client_id = this.id;
743 log::debug!(
744 "rpc message received. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
745 client_id,
746 message_id,
747 sender_id,
748 type_name
749 );
750 cx.foreground()
751 .spawn(async move {
752 match future.await {
753 Ok(()) => {
754 log::debug!(
755 "rpc message handled. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
756 client_id,
757 message_id,
758 sender_id,
759 type_name
760 );
761 }
762 Err(error) => {
763 log::error!(
764 "error handling message. client_id:{}, message_id:{}, sender_id:{:?}, type:{}, error:{:?}",
765 client_id,
766 message_id,
767 sender_id,
768 type_name,
769 error
770 );
771 }
772 }
773 })
774 .detach();
775 } else {
776 log::info!("unhandled message {}", type_name);
777 }
778
779 // Don't starve the main thread when receiving lots of messages at once.
780 smol::future::yield_now().await;
781 }
782 }
783 })
784 .detach();
785
786 let handle_io = cx.background().spawn(handle_io);
787 let this = self.clone();
788 let cx = cx.clone();
789 cx.foreground()
790 .spawn(async move {
791 match handle_io.await {
792 Ok(()) => {
793 if *this.status().borrow() == (Status::Connected { connection_id }) {
794 this.set_status(Status::SignedOut, &cx);
795 }
796 }
797 Err(err) => {
798 log::error!("connection error: {:?}", err);
799 this.set_status(Status::ConnectionLost, &cx);
800 }
801 }
802 })
803 .detach();
804 }
805
806 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
807 #[cfg(any(test, feature = "test-support"))]
808 if let Some(callback) = self.authenticate.read().as_ref() {
809 return callback(cx);
810 }
811
812 self.authenticate_with_browser(cx)
813 }
814
815 fn establish_connection(
816 self: &Arc<Self>,
817 credentials: &Credentials,
818 cx: &AsyncAppContext,
819 ) -> Task<Result<Connection, EstablishConnectionError>> {
820 #[cfg(any(test, feature = "test-support"))]
821 if let Some(callback) = self.establish_connection.read().as_ref() {
822 return callback(credentials, cx);
823 }
824
825 self.establish_websocket_connection(credentials, cx)
826 }
827
828 fn establish_websocket_connection(
829 self: &Arc<Self>,
830 credentials: &Credentials,
831 cx: &AsyncAppContext,
832 ) -> Task<Result<Connection, EstablishConnectionError>> {
833 let request = Request::builder()
834 .header(
835 "Authorization",
836 format!("{} {}", credentials.user_id, credentials.access_token),
837 )
838 .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION);
839
840 let http = self.http.clone();
841 cx.background().spawn(async move {
842 let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
843 let rpc_response = http.get(&rpc_url, Default::default(), false).await?;
844 if rpc_response.status().is_redirection() {
845 rpc_url = rpc_response
846 .headers()
847 .get("Location")
848 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
849 .to_str()
850 .map_err(EstablishConnectionError::other)?
851 .to_string();
852 }
853 // Until we switch the zed.dev domain to point to the new Next.js app, there
854 // will be no redirect required, and the app will connect directly to
855 // wss://zed.dev/rpc.
856 else if rpc_response.status() != StatusCode::UPGRADE_REQUIRED {
857 Err(anyhow!(
858 "unexpected /rpc response status {}",
859 rpc_response.status()
860 ))?
861 }
862
863 let mut rpc_url = Url::parse(&rpc_url).context("invalid rpc url")?;
864 let rpc_host = rpc_url
865 .host_str()
866 .zip(rpc_url.port_or_known_default())
867 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
868 let stream = smol::net::TcpStream::connect(rpc_host).await?;
869
870 log::info!("connected to rpc endpoint {}", rpc_url);
871
872 match rpc_url.scheme() {
873 "https" => {
874 rpc_url.set_scheme("wss").unwrap();
875 let request = request.uri(rpc_url.as_str()).body(())?;
876 let (stream, _) =
877 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
878 Ok(Connection::new(
879 stream
880 .map_err(|error| anyhow!(error))
881 .sink_map_err(|error| anyhow!(error)),
882 ))
883 }
884 "http" => {
885 rpc_url.set_scheme("ws").unwrap();
886 let request = request.uri(rpc_url.as_str()).body(())?;
887 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
888 Ok(Connection::new(
889 stream
890 .map_err(|error| anyhow!(error))
891 .sink_map_err(|error| anyhow!(error)),
892 ))
893 }
894 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
895 }
896 })
897 }
898
899 pub fn authenticate_with_browser(
900 self: &Arc<Self>,
901 cx: &AsyncAppContext,
902 ) -> Task<Result<Credentials>> {
903 let platform = cx.platform();
904 let executor = cx.background();
905 executor.clone().spawn(async move {
906 // Generate a pair of asymmetric encryption keys. The public key will be used by the
907 // zed server to encrypt the user's access token, so that it can'be intercepted by
908 // any other app running on the user's device.
909 let (public_key, private_key) =
910 rpc::auth::keypair().expect("failed to generate keypair for auth");
911 let public_key_string =
912 String::try_from(public_key).expect("failed to serialize public key for auth");
913
914 // Start an HTTP server to receive the redirect from Zed's sign-in page.
915 let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
916 let port = server.server_addr().port();
917
918 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
919 // that the user is signing in from a Zed app running on the same device.
920 let mut url = format!(
921 "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
922 *ZED_SERVER_URL, port, public_key_string
923 );
924
925 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
926 log::info!("impersonating user @{}", impersonate_login);
927 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
928 }
929
930 platform.open_url(&url);
931
932 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
933 // access token from the query params.
934 //
935 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
936 // custom URL scheme instead of this local HTTP server.
937 let (user_id, access_token) = executor
938 .spawn(async move {
939 for _ in 0..100 {
940 if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
941 let path = req.url();
942 let mut user_id = None;
943 let mut access_token = None;
944 let url = Url::parse(&format!("http://example.com{}", path))
945 .context("failed to parse login notification url")?;
946 for (key, value) in url.query_pairs() {
947 if key == "access_token" {
948 access_token = Some(value.to_string());
949 } else if key == "user_id" {
950 user_id = Some(value.to_string());
951 }
952 }
953
954 let post_auth_url =
955 format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
956 req.respond(
957 tiny_http::Response::empty(302).with_header(
958 tiny_http::Header::from_bytes(
959 &b"Location"[..],
960 post_auth_url.as_bytes(),
961 )
962 .unwrap(),
963 ),
964 )
965 .context("failed to respond to login http request")?;
966 return Ok((
967 user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
968 access_token
969 .ok_or_else(|| anyhow!("missing access_token parameter"))?,
970 ));
971 }
972 }
973
974 Err(anyhow!("didn't receive login redirect"))
975 })
976 .await?;
977
978 let access_token = private_key
979 .decrypt_string(&access_token)
980 .context("failed to decrypt access token")?;
981 platform.activate(true);
982
983 Ok(Credentials {
984 user_id: user_id.parse()?,
985 access_token,
986 })
987 })
988 }
989
990 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
991 let conn_id = self.connection_id()?;
992 self.peer.disconnect(conn_id);
993 self.set_status(Status::SignedOut, cx);
994 Ok(())
995 }
996
997 fn connection_id(&self) -> Result<ConnectionId> {
998 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
999 Ok(connection_id)
1000 } else {
1001 Err(anyhow!("not connected"))
1002 }
1003 }
1004
1005 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1006 log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
1007 self.peer.send(self.connection_id()?, message)
1008 }
1009
1010 pub fn request<T: RequestMessage>(
1011 &self,
1012 request: T,
1013 ) -> impl Future<Output = Result<T::Response>> {
1014 let client_id = self.id;
1015 log::debug!(
1016 "rpc request start. client_id:{}. name:{}",
1017 client_id,
1018 T::NAME
1019 );
1020 let response = self
1021 .connection_id()
1022 .map(|conn_id| self.peer.request(conn_id, request));
1023 async move {
1024 let response = response?.await;
1025 log::debug!(
1026 "rpc request finish. client_id:{}. name:{}",
1027 client_id,
1028 T::NAME
1029 );
1030 response
1031 }
1032 }
1033
1034 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1035 log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1036 self.peer.respond(receipt, response)
1037 }
1038
1039 fn respond_with_error<T: RequestMessage>(
1040 &self,
1041 receipt: Receipt<T>,
1042 error: proto::Error,
1043 ) -> Result<()> {
1044 log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1045 self.peer.respond_with_error(receipt, error)
1046 }
1047}
1048
1049impl AnyWeakEntityHandle {
1050 fn upgrade(&self, cx: &AsyncAppContext) -> Option<AnyEntityHandle> {
1051 match self {
1052 AnyWeakEntityHandle::Model(handle) => handle.upgrade(cx).map(AnyEntityHandle::Model),
1053 AnyWeakEntityHandle::View(handle) => handle.upgrade(cx).map(AnyEntityHandle::View),
1054 }
1055 }
1056}
1057
1058fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1059 if IMPERSONATE_LOGIN.is_some() {
1060 return None;
1061 }
1062
1063 let (user_id, access_token) = cx
1064 .platform()
1065 .read_credentials(&ZED_SERVER_URL)
1066 .log_err()
1067 .flatten()?;
1068 Some(Credentials {
1069 user_id: user_id.parse().ok()?,
1070 access_token: String::from_utf8(access_token).ok()?,
1071 })
1072}
1073
1074fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
1075 cx.platform().write_credentials(
1076 &ZED_SERVER_URL,
1077 &credentials.user_id.to_string(),
1078 credentials.access_token.as_bytes(),
1079 )
1080}
1081
1082const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
1083
1084pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1085 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1086}
1087
1088pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1089 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1090 let mut parts = path.split('/');
1091 let id = parts.next()?.parse::<u64>().ok()?;
1092 let access_token = parts.next()?;
1093 if access_token.is_empty() {
1094 return None;
1095 }
1096 Some((id, access_token.to_string()))
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101 use super::*;
1102 use crate::test::{FakeHttpClient, FakeServer};
1103 use gpui::{executor::Deterministic, TestAppContext};
1104 use parking_lot::Mutex;
1105 use std::future;
1106
1107 #[gpui::test(iterations = 10)]
1108 async fn test_reconnection(cx: &mut TestAppContext) {
1109 cx.foreground().forbid_parking();
1110
1111 let user_id = 5;
1112 let client = Client::new(FakeHttpClient::with_404_response());
1113 let server = FakeServer::for_client(user_id, &client, cx).await;
1114 let mut status = client.status();
1115 assert!(matches!(
1116 status.next().await,
1117 Some(Status::Connected { .. })
1118 ));
1119 assert_eq!(server.auth_count(), 1);
1120
1121 server.forbid_connections();
1122 server.disconnect();
1123 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1124
1125 server.allow_connections();
1126 cx.foreground().advance_clock(Duration::from_secs(10));
1127 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1128 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1129
1130 server.forbid_connections();
1131 server.disconnect();
1132 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1133
1134 // Clear cached credentials after authentication fails
1135 server.roll_access_token();
1136 server.allow_connections();
1137 cx.foreground().advance_clock(Duration::from_secs(10));
1138 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1139 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1140 }
1141
1142 #[gpui::test(iterations = 10)]
1143 async fn test_authenticating_more_than_once(
1144 cx: &mut TestAppContext,
1145 deterministic: Arc<Deterministic>,
1146 ) {
1147 cx.foreground().forbid_parking();
1148
1149 let auth_count = Arc::new(Mutex::new(0));
1150 let dropped_auth_count = Arc::new(Mutex::new(0));
1151 let client = Client::new(FakeHttpClient::with_404_response());
1152 client.override_authenticate({
1153 let auth_count = auth_count.clone();
1154 let dropped_auth_count = dropped_auth_count.clone();
1155 move |cx| {
1156 let auth_count = auth_count.clone();
1157 let dropped_auth_count = dropped_auth_count.clone();
1158 cx.foreground().spawn(async move {
1159 *auth_count.lock() += 1;
1160 let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1161 future::pending::<()>().await;
1162 unreachable!()
1163 })
1164 }
1165 });
1166
1167 let _authenticate = cx.spawn(|cx| {
1168 let client = client.clone();
1169 async move { client.authenticate_and_connect(false, &cx).await }
1170 });
1171 deterministic.run_until_parked();
1172 assert_eq!(*auth_count.lock(), 1);
1173 assert_eq!(*dropped_auth_count.lock(), 0);
1174
1175 let _authenticate = cx.spawn(|cx| {
1176 let client = client.clone();
1177 async move { client.authenticate_and_connect(false, &cx).await }
1178 });
1179 deterministic.run_until_parked();
1180 assert_eq!(*auth_count.lock(), 2);
1181 assert_eq!(*dropped_auth_count.lock(), 1);
1182 }
1183
1184 #[test]
1185 fn test_encode_and_decode_worktree_url() {
1186 let url = encode_worktree_url(5, "deadbeef");
1187 assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1188 assert_eq!(
1189 decode_worktree_url(&format!("\n {}\t", url)),
1190 Some((5, "deadbeef".to_string()))
1191 );
1192 assert_eq!(decode_worktree_url("not://the-right-format"), None);
1193 }
1194
1195 #[gpui::test]
1196 async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1197 cx.foreground().forbid_parking();
1198
1199 let user_id = 5;
1200 let client = Client::new(FakeHttpClient::with_404_response());
1201 let server = FakeServer::for_client(user_id, &client, cx).await;
1202
1203 let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1204 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1205 client.add_model_message_handler(
1206 move |model: ModelHandle<Model>, _: TypedEnvelope<proto::JoinProject>, _, cx| {
1207 match model.read_with(&cx, |model, _| model.id) {
1208 1 => done_tx1.try_send(()).unwrap(),
1209 2 => done_tx2.try_send(()).unwrap(),
1210 _ => unreachable!(),
1211 }
1212 async { Ok(()) }
1213 },
1214 );
1215 let model1 = cx.add_model(|_| Model {
1216 id: 1,
1217 subscription: None,
1218 });
1219 let model2 = cx.add_model(|_| Model {
1220 id: 2,
1221 subscription: None,
1222 });
1223 let model3 = cx.add_model(|_| Model {
1224 id: 3,
1225 subscription: None,
1226 });
1227
1228 let _subscription1 = model1.update(cx, |_, cx| client.add_model_for_remote_entity(1, cx));
1229 let _subscription2 = model2.update(cx, |_, cx| client.add_model_for_remote_entity(2, cx));
1230 // Ensure dropping a subscription for the same entity type still allows receiving of
1231 // messages for other entity IDs of the same type.
1232 let subscription3 = model3.update(cx, |_, cx| client.add_model_for_remote_entity(3, cx));
1233 drop(subscription3);
1234
1235 server.send(proto::JoinProject { project_id: 1 });
1236 server.send(proto::JoinProject { project_id: 2 });
1237 done_rx1.next().await.unwrap();
1238 done_rx2.next().await.unwrap();
1239 }
1240
1241 #[gpui::test]
1242 async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1243 cx.foreground().forbid_parking();
1244
1245 let user_id = 5;
1246 let client = Client::new(FakeHttpClient::with_404_response());
1247 let server = FakeServer::for_client(user_id, &client, cx).await;
1248
1249 let model = cx.add_model(|_| Model::default());
1250 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1251 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1252 let subscription1 = client.add_message_handler(
1253 model.clone(),
1254 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1255 done_tx1.try_send(()).unwrap();
1256 async { Ok(()) }
1257 },
1258 );
1259 drop(subscription1);
1260 let _subscription2 =
1261 client.add_message_handler(model, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1262 done_tx2.try_send(()).unwrap();
1263 async { Ok(()) }
1264 });
1265 server.send(proto::Ping {});
1266 done_rx2.next().await.unwrap();
1267 }
1268
1269 #[gpui::test]
1270 async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1271 cx.foreground().forbid_parking();
1272
1273 let user_id = 5;
1274 let client = Client::new(FakeHttpClient::with_404_response());
1275 let server = FakeServer::for_client(user_id, &client, cx).await;
1276
1277 let model = cx.add_model(|_| Model::default());
1278 let (done_tx, mut done_rx) = smol::channel::unbounded();
1279 let subscription = client.add_message_handler(
1280 model.clone(),
1281 move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1282 model.update(&mut cx, |model, _| model.subscription.take());
1283 done_tx.try_send(()).unwrap();
1284 async { Ok(()) }
1285 },
1286 );
1287 model.update(cx, |model, _| {
1288 model.subscription = Some(subscription);
1289 });
1290 server.send(proto::Ping {});
1291 done_rx.next().await.unwrap();
1292 }
1293
1294 #[derive(Default)]
1295 struct Model {
1296 id: usize,
1297 subscription: Option<Subscription>,
1298 }
1299
1300 impl Entity for Model {
1301 type Event = ();
1302 }
1303}