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