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