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