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