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 let mut message_id = 0_usize;
534 while let Some(message) = incoming.next().await {
535 let mut state = this.state.write();
536 message_id += 1;
537 let type_name = message.payload_type_name();
538 let payload_type_id = message.payload_type_id();
539 let sender_id = message.original_sender_id().map(|id| id.0);
540
541 let model = state
542 .models_by_message_type
543 .get(&payload_type_id)
544 .cloned()
545 .or_else(|| {
546 let model_type_id =
547 *state.model_types_by_message_type.get(&payload_type_id)?;
548 let entity_id = state
549 .entity_id_extractors
550 .get(&message.payload_type_id())
551 .map(|extract_entity_id| {
552 (extract_entity_id)(message.as_ref())
553 })?;
554 let model = state
555 .models_by_entity_type_and_remote_id
556 .get(&(model_type_id, entity_id))?;
557 if let Some(model) = model.upgrade(&cx) {
558 Some(model)
559 } else {
560 state
561 .models_by_entity_type_and_remote_id
562 .remove(&(model_type_id, entity_id));
563 None
564 }
565 });
566
567 let model = if let Some(model) = model {
568 model
569 } else {
570 log::info!("unhandled message {}", type_name);
571 continue;
572 };
573
574 if let Some(handler) = state.message_handlers.get(&payload_type_id).cloned()
575 {
576 drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
577 let future = handler(model, message, cx.clone());
578
579 let client_id = this.id;
580 log::debug!(
581 "rpc message received. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
582 client_id,
583 message_id,
584 sender_id,
585 type_name
586 );
587 cx.foreground()
588 .spawn(async move {
589 match future.await {
590 Ok(()) => {
591 log::debug!(
592 "rpc message handled. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
593 client_id,
594 message_id,
595 sender_id,
596 type_name
597 );
598 }
599 Err(error) => {
600 log::error!(
601 "error handling message. client_id:{}, message_id:{}, sender_id:{:?}, type:{}, error:{:?}",
602 client_id,
603 message_id,
604 sender_id,
605 type_name,
606 error
607 );
608 }
609 }
610 })
611 .detach();
612 } else {
613 log::info!("unhandled message {}", type_name);
614 }
615 }
616 }
617 })
618 .detach();
619
620 self.set_status(Status::Connected { connection_id }, cx);
621
622 let handle_io = cx.background().spawn(handle_io);
623 let this = self.clone();
624 let cx = cx.clone();
625 cx.foreground()
626 .spawn(async move {
627 match handle_io.await {
628 Ok(()) => this.set_status(Status::SignedOut, &cx),
629 Err(err) => {
630 log::error!("connection error: {:?}", err);
631 this.set_status(Status::ConnectionLost, &cx);
632 }
633 }
634 })
635 .detach();
636 }
637
638 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
639 if let Some(callback) = self.authenticate.as_ref() {
640 callback(cx)
641 } else {
642 self.authenticate_with_browser(cx)
643 }
644 }
645
646 fn establish_connection(
647 self: &Arc<Self>,
648 credentials: &Credentials,
649 cx: &AsyncAppContext,
650 ) -> Task<Result<Connection, EstablishConnectionError>> {
651 if let Some(callback) = self.establish_connection.as_ref() {
652 callback(credentials, cx)
653 } else {
654 self.establish_websocket_connection(credentials, cx)
655 }
656 }
657
658 fn establish_websocket_connection(
659 self: &Arc<Self>,
660 credentials: &Credentials,
661 cx: &AsyncAppContext,
662 ) -> Task<Result<Connection, EstablishConnectionError>> {
663 let request = Request::builder()
664 .header(
665 "Authorization",
666 format!("{} {}", credentials.user_id, credentials.access_token),
667 )
668 .header("X-Zed-Protocol-Version", rpc::PROTOCOL_VERSION);
669
670 let http = self.http.clone();
671 cx.background().spawn(async move {
672 let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
673 let rpc_request = surf::Request::new(
674 Method::Get,
675 surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
676 );
677 let rpc_response = http.send(rpc_request).await?;
678
679 if rpc_response.status().is_redirection() {
680 rpc_url = rpc_response
681 .header("Location")
682 .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
683 .as_str()
684 .to_string();
685 }
686 // Until we switch the zed.dev domain to point to the new Next.js app, there
687 // will be no redirect required, and the app will connect directly to
688 // wss://zed.dev/rpc.
689 else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
690 Err(anyhow!(
691 "unexpected /rpc response status {}",
692 rpc_response.status()
693 ))?
694 }
695
696 let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
697 let rpc_host = rpc_url
698 .host_str()
699 .zip(rpc_url.port_or_known_default())
700 .ok_or_else(|| anyhow!("missing host in rpc url"))?;
701 let stream = smol::net::TcpStream::connect(rpc_host).await?;
702
703 log::info!("connected to rpc endpoint {}", rpc_url);
704
705 match rpc_url.scheme() {
706 "https" => {
707 rpc_url.set_scheme("wss").unwrap();
708 let request = request.uri(rpc_url.as_str()).body(())?;
709 let (stream, _) =
710 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
711 Ok(Connection::new(stream))
712 }
713 "http" => {
714 rpc_url.set_scheme("ws").unwrap();
715 let request = request.uri(rpc_url.as_str()).body(())?;
716 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
717 Ok(Connection::new(stream))
718 }
719 _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
720 }
721 })
722 }
723
724 pub fn authenticate_with_browser(
725 self: &Arc<Self>,
726 cx: &AsyncAppContext,
727 ) -> Task<Result<Credentials>> {
728 let platform = cx.platform();
729 let executor = cx.background();
730 executor.clone().spawn(async move {
731 // Generate a pair of asymmetric encryption keys. The public key will be used by the
732 // zed server to encrypt the user's access token, so that it can'be intercepted by
733 // any other app running on the user's device.
734 let (public_key, private_key) =
735 rpc::auth::keypair().expect("failed to generate keypair for auth");
736 let public_key_string =
737 String::try_from(public_key).expect("failed to serialize public key for auth");
738
739 // Start an HTTP server to receive the redirect from Zed's sign-in page.
740 let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
741 let port = server.server_addr().port();
742
743 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
744 // that the user is signing in from a Zed app running on the same device.
745 let mut url = format!(
746 "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
747 *ZED_SERVER_URL, port, public_key_string
748 );
749
750 if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
751 log::info!("impersonating user @{}", impersonate_login);
752 write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
753 }
754
755 platform.open_url(&url);
756
757 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
758 // access token from the query params.
759 //
760 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
761 // custom URL scheme instead of this local HTTP server.
762 let (user_id, access_token) = executor
763 .spawn(async move {
764 if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
765 let path = req.url();
766 let mut user_id = None;
767 let mut access_token = None;
768 let url = Url::parse(&format!("http://example.com{}", path))
769 .context("failed to parse login notification url")?;
770 for (key, value) in url.query_pairs() {
771 if key == "access_token" {
772 access_token = Some(value.to_string());
773 } else if key == "user_id" {
774 user_id = Some(value.to_string());
775 }
776 }
777
778 let post_auth_url =
779 format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
780 req.respond(
781 tiny_http::Response::empty(302).with_header(
782 tiny_http::Header::from_bytes(
783 &b"Location"[..],
784 post_auth_url.as_bytes(),
785 )
786 .unwrap(),
787 ),
788 )
789 .context("failed to respond to login http request")?;
790 Ok((
791 user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
792 access_token
793 .ok_or_else(|| anyhow!("missing access_token parameter"))?,
794 ))
795 } else {
796 Err(anyhow!("didn't receive login redirect"))
797 }
798 })
799 .await?;
800
801 let access_token = private_key
802 .decrypt_string(&access_token)
803 .context("failed to decrypt access token")?;
804 platform.activate(true);
805
806 Ok(Credentials {
807 user_id: user_id.parse()?,
808 access_token,
809 })
810 })
811 }
812
813 pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
814 let conn_id = self.connection_id()?;
815 self.peer.disconnect(conn_id);
816 self.set_status(Status::SignedOut, cx);
817 Ok(())
818 }
819
820 fn connection_id(&self) -> Result<ConnectionId> {
821 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
822 Ok(connection_id)
823 } else {
824 Err(anyhow!("not connected"))
825 }
826 }
827
828 pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
829 log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
830 self.peer.send(self.connection_id()?, message)
831 }
832
833 pub fn request<T: RequestMessage>(
834 &self,
835 request: T,
836 ) -> impl Future<Output = Result<T::Response>> {
837 let client_id = self.id;
838 log::debug!(
839 "rpc request start. client_id: {}. name:{}",
840 client_id,
841 T::NAME
842 );
843 let response = self
844 .connection_id()
845 .map(|conn_id| self.peer.request(conn_id, request));
846 async move {
847 let response = response?.await;
848 log::debug!(
849 "rpc request finish. client_id: {}. name:{}",
850 client_id,
851 T::NAME
852 );
853 response
854 }
855 }
856
857 fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
858 log::debug!("rpc respond. client_id: {}. name:{}", self.id, T::NAME);
859 self.peer.respond(receipt, response)
860 }
861
862 fn respond_with_error<T: RequestMessage>(
863 &self,
864 receipt: Receipt<T>,
865 error: proto::Error,
866 ) -> Result<()> {
867 log::debug!("rpc respond. client_id: {}. name:{}", self.id, T::NAME);
868 self.peer.respond_with_error(receipt, error)
869 }
870}
871
872fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
873 if IMPERSONATE_LOGIN.is_some() {
874 return None;
875 }
876
877 let (user_id, access_token) = cx
878 .platform()
879 .read_credentials(&ZED_SERVER_URL)
880 .log_err()
881 .flatten()?;
882 Some(Credentials {
883 user_id: user_id.parse().ok()?,
884 access_token: String::from_utf8(access_token).ok()?,
885 })
886}
887
888fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
889 cx.platform().write_credentials(
890 &ZED_SERVER_URL,
891 &credentials.user_id.to_string(),
892 credentials.access_token.as_bytes(),
893 )
894}
895
896const WORKTREE_URL_PREFIX: &'static str = "zed://worktrees/";
897
898pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
899 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
900}
901
902pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
903 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
904 let mut parts = path.split('/');
905 let id = parts.next()?.parse::<u64>().ok()?;
906 let access_token = parts.next()?;
907 if access_token.is_empty() {
908 return None;
909 }
910 Some((id, access_token.to_string()))
911}
912
913#[cfg(test)]
914mod tests {
915 use super::*;
916 use crate::test::{FakeHttpClient, FakeServer};
917 use gpui::TestAppContext;
918
919 #[gpui::test(iterations = 10)]
920 async fn test_heartbeat(cx: TestAppContext) {
921 cx.foreground().forbid_parking();
922
923 let user_id = 5;
924 let mut client = Client::new(FakeHttpClient::with_404_response());
925 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
926
927 cx.foreground().advance_clock(Duration::from_secs(10));
928 let ping = server.receive::<proto::Ping>().await.unwrap();
929 server.respond(ping.receipt(), proto::Ack {}).await;
930
931 cx.foreground().advance_clock(Duration::from_secs(10));
932 let ping = server.receive::<proto::Ping>().await.unwrap();
933 server.respond(ping.receipt(), proto::Ack {}).await;
934
935 client.disconnect(&cx.to_async()).unwrap();
936 assert!(server.receive::<proto::Ping>().await.is_err());
937 }
938
939 #[gpui::test(iterations = 10)]
940 async fn test_reconnection(cx: TestAppContext) {
941 cx.foreground().forbid_parking();
942
943 let user_id = 5;
944 let mut client = Client::new(FakeHttpClient::with_404_response());
945 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
946 let mut status = client.status();
947 assert!(matches!(
948 status.next().await,
949 Some(Status::Connected { .. })
950 ));
951 assert_eq!(server.auth_count(), 1);
952
953 server.forbid_connections();
954 server.disconnect();
955 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
956
957 server.allow_connections();
958 cx.foreground().advance_clock(Duration::from_secs(10));
959 while !matches!(status.next().await, Some(Status::Connected { .. })) {}
960 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
961
962 server.forbid_connections();
963 server.disconnect();
964 while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
965
966 // Clear cached credentials after authentication fails
967 server.roll_access_token();
968 server.allow_connections();
969 cx.foreground().advance_clock(Duration::from_secs(10));
970 assert_eq!(server.auth_count(), 1);
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(mut cx: 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 =
1021 model1.update(&mut cx, |_, cx| client.add_model_for_remote_entity(1, cx));
1022 let _subscription2 =
1023 model2.update(&mut cx, |_, cx| client.add_model_for_remote_entity(2, cx));
1024 // Ensure dropping a subscription for the same entity type still allows receiving of
1025 // messages for other entity IDs of the same type.
1026 let subscription3 =
1027 model3.update(&mut cx, |_, cx| client.add_model_for_remote_entity(3, cx));
1028 drop(subscription3);
1029
1030 server.send(proto::UnshareProject { project_id: 1 });
1031 server.send(proto::UnshareProject { project_id: 2 });
1032 done_rx1.next().await.unwrap();
1033 done_rx2.next().await.unwrap();
1034 }
1035
1036 #[gpui::test]
1037 async fn test_subscribing_after_dropping_subscription(mut cx: TestAppContext) {
1038 cx.foreground().forbid_parking();
1039
1040 let user_id = 5;
1041 let mut client = Client::new(FakeHttpClient::with_404_response());
1042 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1043
1044 let model = cx.add_model(|_| Model::default());
1045 let (done_tx1, _done_rx1) = smol::channel::unbounded();
1046 let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1047 let subscription1 = client.add_message_handler(
1048 model.clone(),
1049 move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1050 done_tx1.try_send(()).unwrap();
1051 async { Ok(()) }
1052 },
1053 );
1054 drop(subscription1);
1055 let _subscription2 =
1056 client.add_message_handler(model, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1057 done_tx2.try_send(()).unwrap();
1058 async { Ok(()) }
1059 });
1060 server.send(proto::Ping {});
1061 done_rx2.next().await.unwrap();
1062 }
1063
1064 #[gpui::test]
1065 async fn test_dropping_subscription_in_handler(mut cx: TestAppContext) {
1066 cx.foreground().forbid_parking();
1067
1068 let user_id = 5;
1069 let mut client = Client::new(FakeHttpClient::with_404_response());
1070 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1071
1072 let model = cx.add_model(|_| Model::default());
1073 let (done_tx, mut done_rx) = smol::channel::unbounded();
1074 let subscription = client.add_message_handler(
1075 model.clone(),
1076 move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1077 model.update(&mut cx, |model, _| model.subscription.take());
1078 done_tx.try_send(()).unwrap();
1079 async { Ok(()) }
1080 },
1081 );
1082 model.update(&mut cx, |model, _| {
1083 model.subscription = Some(subscription);
1084 });
1085 server.send(proto::Ping {});
1086 done_rx.next().await.unwrap();
1087 }
1088
1089 #[derive(Default)]
1090 struct Model {
1091 id: usize,
1092 subscription: Option<Subscription>,
1093 }
1094
1095 impl Entity for Model {
1096 type Event = ();
1097 }
1098}