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