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