1use crate::util::ResultExt;
2use anyhow::{anyhow, Context, Result};
3use async_recursion::async_recursion;
4use async_tungstenite::tungstenite::{
5 error::Error as WebsocketError,
6 http::{Request, StatusCode},
7};
8use gpui::{AsyncAppContext, Entity, ModelContext, Task};
9use lazy_static::lazy_static;
10use parking_lot::RwLock;
11use postage::{prelude::Stream, watch};
12use rand::prelude::*;
13use std::{
14 any::TypeId,
15 collections::HashMap,
16 convert::TryFrom,
17 future::Future,
18 sync::{Arc, Weak},
19 time::{Duration, Instant},
20};
21use surf::Url;
22use thiserror::Error;
23pub use zrpc::{proto, ConnectionId, PeerId, TypedEnvelope};
24use zrpc::{
25 proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, RequestMessage},
26 Connection, Peer, Receipt,
27};
28
29lazy_static! {
30 static ref ZED_SERVER_URL: String =
31 std::env::var("ZED_SERVER_URL").unwrap_or("https://zed.dev:443".to_string());
32}
33
34pub struct Client {
35 peer: Arc<Peer>,
36 state: RwLock<ClientState>,
37 authenticate:
38 Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
39 establish_connection: Option<
40 Box<
41 dyn 'static
42 + Send
43 + Sync
44 + Fn(
45 &Credentials,
46 &AsyncAppContext,
47 ) -> Task<Result<Connection, EstablishConnectionError>>,
48 >,
49 >,
50}
51
52#[derive(Error, Debug)]
53pub enum EstablishConnectionError {
54 #[error("unauthorized")]
55 Unauthorized,
56 #[error("{0}")]
57 Other(#[from] anyhow::Error),
58 #[error("{0}")]
59 Io(#[from] std::io::Error),
60 #[error("{0}")]
61 Http(#[from] async_tungstenite::tungstenite::http::Error),
62}
63
64impl From<WebsocketError> for EstablishConnectionError {
65 fn from(error: WebsocketError) -> Self {
66 if let WebsocketError::Http(response) = &error {
67 if response.status() == StatusCode::UNAUTHORIZED {
68 return EstablishConnectionError::Unauthorized;
69 }
70 }
71 EstablishConnectionError::Other(error.into())
72 }
73}
74
75impl EstablishConnectionError {
76 pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
77 Self::Other(error.into())
78 }
79}
80
81#[derive(Copy, Clone, Debug)]
82pub enum Status {
83 SignedOut,
84 Authenticating,
85 Connecting,
86 ConnectionError,
87 Connected { connection_id: ConnectionId },
88 ConnectionLost,
89 Reauthenticating,
90 Reconnecting,
91 ReconnectionError { next_reconnection: Instant },
92}
93
94struct ClientState {
95 credentials: Option<Credentials>,
96 status: (watch::Sender<Status>, watch::Receiver<Status>),
97 entity_id_extractors: HashMap<TypeId, Box<dyn Send + Sync + Fn(&dyn AnyTypedEnvelope) -> u64>>,
98 model_handlers: HashMap<
99 (TypeId, u64),
100 Box<dyn Send + Sync + FnMut(Box<dyn AnyTypedEnvelope>, &mut AsyncAppContext)>,
101 >,
102 _maintain_connection: Option<Task<()>>,
103 heartbeat_interval: Duration,
104}
105
106#[derive(Clone)]
107pub struct Credentials {
108 pub user_id: u64,
109 pub access_token: String,
110}
111
112impl Default for ClientState {
113 fn default() -> Self {
114 Self {
115 credentials: None,
116 status: watch::channel_with(Status::SignedOut),
117 entity_id_extractors: Default::default(),
118 model_handlers: Default::default(),
119 _maintain_connection: None,
120 heartbeat_interval: Duration::from_secs(5),
121 }
122 }
123}
124
125pub struct Subscription {
126 client: Weak<Client>,
127 id: (TypeId, u64),
128}
129
130impl Drop for Subscription {
131 fn drop(&mut self) {
132 if let Some(client) = self.client.upgrade() {
133 drop(
134 client
135 .state
136 .write()
137 .model_handlers
138 .remove(&self.id)
139 .unwrap(),
140 );
141 }
142 }
143}
144
145impl Client {
146 pub fn new() -> Arc<Self> {
147 Arc::new(Self {
148 peer: Peer::new(),
149 state: Default::default(),
150 authenticate: None,
151 establish_connection: None,
152 })
153 }
154
155 #[cfg(any(test, feature = "test-support"))]
156 pub fn override_authenticate<F>(&mut self, authenticate: F) -> &mut Self
157 where
158 F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
159 {
160 self.authenticate = Some(Box::new(authenticate));
161 self
162 }
163
164 #[cfg(any(test, feature = "test-support"))]
165 pub fn override_establish_connection<F>(&mut self, connect: F) -> &mut Self
166 where
167 F: 'static
168 + Send
169 + Sync
170 + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
171 {
172 self.establish_connection = Some(Box::new(connect));
173 self
174 }
175
176 pub fn user_id(&self) -> Option<u64> {
177 self.state
178 .read()
179 .credentials
180 .as_ref()
181 .map(|credentials| credentials.user_id)
182 }
183
184 pub fn status(&self) -> watch::Receiver<Status> {
185 self.state.read().status.1.clone()
186 }
187
188 fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
189 let mut state = self.state.write();
190 *state.status.0.borrow_mut() = status;
191
192 match status {
193 Status::Connected { .. } => {
194 let heartbeat_interval = state.heartbeat_interval;
195 let this = self.clone();
196 let foreground = cx.foreground();
197 state._maintain_connection = Some(cx.foreground().spawn(async move {
198 loop {
199 foreground.timer(heartbeat_interval).await;
200 let _ = this.request(proto::Ping {}).await;
201 }
202 }));
203 }
204 Status::ConnectionLost => {
205 let this = self.clone();
206 let foreground = cx.foreground();
207 let heartbeat_interval = state.heartbeat_interval;
208 state._maintain_connection = Some(cx.spawn(|cx| async move {
209 let mut rng = StdRng::from_entropy();
210 let mut delay = Duration::from_millis(100);
211 while let Err(error) = this.authenticate_and_connect(&cx).await {
212 log::error!("failed to connect {}", error);
213 this.set_status(
214 Status::ReconnectionError {
215 next_reconnection: Instant::now() + delay,
216 },
217 &cx,
218 );
219 foreground.timer(delay).await;
220 delay = delay
221 .mul_f32(rng.gen_range(1.0..=2.0))
222 .min(heartbeat_interval);
223 }
224 }));
225 }
226 Status::SignedOut => {
227 state._maintain_connection.take();
228 }
229 _ => {}
230 }
231 }
232
233 pub fn subscribe<T, M, F>(self: &Arc<Self>, cx: ModelContext<M>, mut handler: F) -> Subscription
234 where
235 T: EnvelopedMessage,
236 M: Entity,
237 F: 'static
238 + Send
239 + Sync
240 + FnMut(&mut M, TypedEnvelope<T>, Arc<Self>, &mut ModelContext<M>) -> Result<()>,
241 {
242 let subscription_id = (TypeId::of::<T>(), Default::default());
243 let client = self.clone();
244 let mut state = self.state.write();
245 let model = cx.handle().downgrade();
246 let prev_extractor = state
247 .entity_id_extractors
248 .insert(subscription_id.0, Box::new(|_| Default::default()));
249 if prev_extractor.is_some() {
250 panic!("registered a handler for the same entity twice")
251 }
252
253 state.model_handlers.insert(
254 subscription_id,
255 Box::new(move |envelope, cx| {
256 if let Some(model) = model.upgrade(cx) {
257 let envelope = envelope.into_any().downcast::<TypedEnvelope<T>>().unwrap();
258 model.update(cx, |model, cx| {
259 if let Err(error) = handler(model, *envelope, client.clone(), cx) {
260 log::error!("error handling message: {}", error)
261 }
262 });
263 }
264 }),
265 );
266
267 Subscription {
268 client: Arc::downgrade(self),
269 id: subscription_id,
270 }
271 }
272
273 pub fn subscribe_to_entity<T, M, F>(
274 self: &Arc<Self>,
275 remote_id: u64,
276 cx: &mut ModelContext<M>,
277 mut handler: F,
278 ) -> Subscription
279 where
280 T: EntityMessage,
281 M: Entity,
282 F: 'static
283 + Send
284 + Sync
285 + FnMut(&mut M, TypedEnvelope<T>, Arc<Self>, &mut ModelContext<M>) -> Result<()>,
286 {
287 let subscription_id = (TypeId::of::<T>(), remote_id);
288 let client = self.clone();
289 let mut state = self.state.write();
290 let model = cx.handle().downgrade();
291 state
292 .entity_id_extractors
293 .entry(subscription_id.0)
294 .or_insert_with(|| {
295 Box::new(|envelope| {
296 let envelope = envelope
297 .as_any()
298 .downcast_ref::<TypedEnvelope<T>>()
299 .unwrap();
300 envelope.payload.remote_entity_id()
301 })
302 });
303 let prev_handler = state.model_handlers.insert(
304 subscription_id,
305 Box::new(move |envelope, cx| {
306 if let Some(model) = model.upgrade(cx) {
307 let envelope = envelope.into_any().downcast::<TypedEnvelope<T>>().unwrap();
308 model.update(cx, |model, cx| {
309 if let Err(error) = handler(model, *envelope, client.clone(), cx) {
310 log::error!("error handling message: {}", error)
311 }
312 });
313 }
314 }),
315 );
316 if prev_handler.is_some() {
317 panic!("registered a handler for the same entity twice")
318 }
319
320 Subscription {
321 client: Arc::downgrade(self),
322 id: subscription_id,
323 }
324 }
325
326 #[async_recursion(?Send)]
327 pub async fn authenticate_and_connect(
328 self: &Arc<Self>,
329 cx: &AsyncAppContext,
330 ) -> anyhow::Result<()> {
331 let was_disconnected = match *self.status().borrow() {
332 Status::SignedOut => true,
333 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
334 false
335 }
336 Status::Connected { .. }
337 | Status::Connecting { .. }
338 | Status::Reconnecting { .. }
339 | Status::Authenticating
340 | Status::Reauthenticating => return Ok(()),
341 };
342
343 if was_disconnected {
344 self.set_status(Status::Authenticating, cx);
345 } else {
346 self.set_status(Status::Reauthenticating, cx)
347 }
348
349 let mut read_from_keychain = false;
350 let credentials = self.state.read().credentials.clone();
351 let credentials = if let Some(credentials) = credentials {
352 credentials
353 } else if let Some(credentials) = read_credentials_from_keychain(cx) {
354 read_from_keychain = true;
355 credentials
356 } else {
357 let credentials = match self.authenticate(&cx).await {
358 Ok(credentials) => credentials,
359 Err(err) => {
360 self.set_status(Status::ConnectionError, cx);
361 return Err(err);
362 }
363 };
364 credentials
365 };
366
367 if was_disconnected {
368 self.set_status(Status::Connecting, cx);
369 } else {
370 self.set_status(Status::Reconnecting, cx);
371 }
372
373 match self.establish_connection(&credentials, cx).await {
374 Ok(conn) => {
375 log::info!("connected to rpc address {}", *ZED_SERVER_URL);
376 self.state.write().credentials = Some(credentials.clone());
377 if !read_from_keychain {
378 write_credentials_to_keychain(&credentials, cx).log_err();
379 }
380 self.set_connection(conn, cx).await;
381 Ok(())
382 }
383 Err(err) => {
384 if matches!(err, EstablishConnectionError::Unauthorized) {
385 self.state.write().credentials.take();
386 cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
387 if read_from_keychain {
388 self.set_status(Status::SignedOut, cx);
389 self.authenticate_and_connect(cx).await
390 } else {
391 self.set_status(Status::ConnectionError, cx);
392 Err(err)?
393 }
394 } else {
395 self.set_status(Status::ConnectionError, cx);
396 Err(err)?
397 }
398 }
399 }
400 }
401
402 async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
403 let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn).await;
404 cx.foreground()
405 .spawn({
406 let mut cx = cx.clone();
407 let this = self.clone();
408 async move {
409 while let Some(message) = incoming.recv().await {
410 let mut state = this.state.write();
411 if let Some(extract_entity_id) =
412 state.entity_id_extractors.get(&message.payload_type_id())
413 {
414 let entity_id = (extract_entity_id)(message.as_ref());
415 if let Some(handler) = state
416 .model_handlers
417 .get_mut(&(message.payload_type_id(), entity_id))
418 {
419 let start_time = Instant::now();
420 log::info!("RPC client message {}", message.payload_type_name());
421 (handler)(message, &mut cx);
422 log::info!(
423 "RPC message handled. duration:{:?}",
424 start_time.elapsed()
425 );
426 } else {
427 log::info!("unhandled message {}", message.payload_type_name());
428 }
429 } else {
430 log::info!("unhandled message {}", message.payload_type_name());
431 }
432 }
433 }
434 })
435 .detach();
436
437 self.set_status(Status::Connected { connection_id }, cx);
438
439 let handle_io = cx.background().spawn(handle_io);
440 let this = self.clone();
441 let cx = cx.clone();
442 cx.foreground()
443 .spawn(async move {
444 match handle_io.await {
445 Ok(()) => this.set_status(Status::SignedOut, &cx),
446 Err(err) => {
447 log::error!("connection error: {:?}", err);
448 this.set_status(Status::ConnectionLost, &cx);
449 }
450 }
451 })
452 .detach();
453 }
454
455 fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
456 if let Some(callback) = self.authenticate.as_ref() {
457 callback(cx)
458 } else {
459 self.authenticate_with_browser(cx)
460 }
461 }
462
463 fn establish_connection(
464 self: &Arc<Self>,
465 credentials: &Credentials,
466 cx: &AsyncAppContext,
467 ) -> Task<Result<Connection, EstablishConnectionError>> {
468 if let Some(callback) = self.establish_connection.as_ref() {
469 callback(credentials, cx)
470 } else {
471 self.establish_websocket_connection(credentials, cx)
472 }
473 }
474
475 fn establish_websocket_connection(
476 self: &Arc<Self>,
477 credentials: &Credentials,
478 cx: &AsyncAppContext,
479 ) -> Task<Result<Connection, EstablishConnectionError>> {
480 let request = Request::builder().header(
481 "Authorization",
482 format!("{} {}", credentials.user_id, credentials.access_token),
483 );
484 cx.background().spawn(async move {
485 if let Some(host) = ZED_SERVER_URL.strip_prefix("https://") {
486 let stream = smol::net::TcpStream::connect(host).await?;
487 let request = request.uri(format!("wss://{}/rpc", host)).body(())?;
488 let (stream, _) =
489 async_tungstenite::async_tls::client_async_tls(request, stream).await?;
490 Ok(Connection::new(stream))
491 } else if let Some(host) = ZED_SERVER_URL.strip_prefix("http://") {
492 let stream = smol::net::TcpStream::connect(host).await?;
493 let request = request.uri(format!("ws://{}/rpc", host)).body(())?;
494 let (stream, _) = async_tungstenite::client_async(request, stream).await?;
495 Ok(Connection::new(stream))
496 } else {
497 Err(anyhow!("invalid server url: {}", *ZED_SERVER_URL))?
498 }
499 })
500 }
501
502 pub fn authenticate_with_browser(
503 self: &Arc<Self>,
504 cx: &AsyncAppContext,
505 ) -> Task<Result<Credentials>> {
506 let platform = cx.platform();
507 let executor = cx.background();
508 executor.clone().spawn(async move {
509 // Generate a pair of asymmetric encryption keys. The public key will be used by the
510 // zed server to encrypt the user's access token, so that it can'be intercepted by
511 // any other app running on the user's device.
512 let (public_key, private_key) =
513 zrpc::auth::keypair().expect("failed to generate keypair for auth");
514 let public_key_string =
515 String::try_from(public_key).expect("failed to serialize public key for auth");
516
517 // Start an HTTP server to receive the redirect from Zed's sign-in page.
518 let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
519 let port = server.server_addr().port();
520
521 // Open the Zed sign-in page in the user's browser, with query parameters that indicate
522 // that the user is signing in from a Zed app running on the same device.
523 platform.open_url(&format!(
524 "{}/sign_in?native_app_port={}&native_app_public_key={}",
525 *ZED_SERVER_URL, port, public_key_string
526 ));
527
528 // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
529 // access token from the query params.
530 //
531 // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
532 // custom URL scheme instead of this local HTTP server.
533 let (user_id, access_token) = executor
534 .spawn(async move {
535 if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
536 let path = req.url();
537 let mut user_id = None;
538 let mut access_token = None;
539 let url = Url::parse(&format!("http://example.com{}", path))
540 .context("failed to parse login notification url")?;
541 for (key, value) in url.query_pairs() {
542 if key == "access_token" {
543 access_token = Some(value.to_string());
544 } else if key == "user_id" {
545 user_id = Some(value.to_string());
546 }
547 }
548 req.respond(
549 tiny_http::Response::from_string(LOGIN_RESPONSE).with_header(
550 tiny_http::Header::from_bytes("Content-Type", "text/html").unwrap(),
551 ),
552 )
553 .context("failed to respond to login http request")?;
554 Ok((
555 user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
556 access_token
557 .ok_or_else(|| anyhow!("missing access_token parameter"))?,
558 ))
559 } else {
560 Err(anyhow!("didn't receive login redirect"))
561 }
562 })
563 .await?;
564
565 let access_token = private_key
566 .decrypt_string(&access_token)
567 .context("failed to decrypt access token")?;
568 platform.activate(true);
569
570 Ok(Credentials {
571 user_id: user_id.parse()?,
572 access_token,
573 })
574 })
575 }
576
577 pub async fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
578 let conn_id = self.connection_id()?;
579 self.peer.disconnect(conn_id).await;
580 self.set_status(Status::SignedOut, cx);
581 Ok(())
582 }
583
584 fn connection_id(&self) -> Result<ConnectionId> {
585 if let Status::Connected { connection_id, .. } = *self.status().borrow() {
586 Ok(connection_id)
587 } else {
588 Err(anyhow!("not connected"))
589 }
590 }
591
592 pub async fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
593 self.peer.send(self.connection_id()?, message).await
594 }
595
596 pub async fn request<T: RequestMessage>(&self, request: T) -> Result<T::Response> {
597 self.peer.request(self.connection_id()?, request).await
598 }
599
600 pub fn respond<T: RequestMessage>(
601 &self,
602 receipt: Receipt<T>,
603 response: T::Response,
604 ) -> impl Future<Output = Result<()>> {
605 self.peer.respond(receipt, response)
606 }
607}
608
609fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
610 let (user_id, access_token) = cx
611 .platform()
612 .read_credentials(&ZED_SERVER_URL)
613 .log_err()
614 .flatten()?;
615 Some(Credentials {
616 user_id: user_id.parse().ok()?,
617 access_token: String::from_utf8(access_token).ok()?,
618 })
619}
620
621fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
622 cx.platform().write_credentials(
623 &ZED_SERVER_URL,
624 &credentials.user_id.to_string(),
625 credentials.access_token.as_bytes(),
626 )
627}
628
629const WORKTREE_URL_PREFIX: &'static str = "zed://worktrees/";
630
631pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
632 format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
633}
634
635pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
636 let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
637 let mut parts = path.split('/');
638 let id = parts.next()?.parse::<u64>().ok()?;
639 let access_token = parts.next()?;
640 if access_token.is_empty() {
641 return None;
642 }
643 Some((id, access_token.to_string()))
644}
645
646const LOGIN_RESPONSE: &'static str = "
647<!DOCTYPE html>
648<html>
649<script>window.close();</script>
650</html>
651";
652
653#[cfg(test)]
654mod tests {
655 use super::*;
656 use crate::test::FakeServer;
657 use gpui::TestAppContext;
658
659 #[gpui::test(iterations = 10)]
660 async fn test_heartbeat(cx: TestAppContext) {
661 cx.foreground().forbid_parking();
662
663 let user_id = 5;
664 let mut client = Client::new();
665 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
666
667 cx.foreground().advance_clock(Duration::from_secs(10));
668 let ping = server.receive::<proto::Ping>().await.unwrap();
669 server.respond(ping.receipt(), proto::Ack {}).await;
670
671 cx.foreground().advance_clock(Duration::from_secs(10));
672 let ping = server.receive::<proto::Ping>().await.unwrap();
673 server.respond(ping.receipt(), proto::Ack {}).await;
674
675 client.disconnect(&cx.to_async()).await.unwrap();
676 assert!(server.receive::<proto::Ping>().await.is_err());
677 }
678
679 #[gpui::test(iterations = 10)]
680 async fn test_reconnection(cx: TestAppContext) {
681 cx.foreground().forbid_parking();
682
683 let user_id = 5;
684 let mut client = Client::new();
685 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
686 let mut status = client.status();
687 assert!(matches!(
688 status.recv().await,
689 Some(Status::Connected { .. })
690 ));
691 assert_eq!(server.auth_count(), 1);
692
693 server.forbid_connections();
694 server.disconnect().await;
695 while !matches!(status.recv().await, Some(Status::ReconnectionError { .. })) {}
696
697 server.allow_connections();
698 cx.foreground().advance_clock(Duration::from_secs(10));
699 while !matches!(status.recv().await, Some(Status::Connected { .. })) {}
700 assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
701
702 server.forbid_connections();
703 server.disconnect().await;
704 while !matches!(status.recv().await, Some(Status::ReconnectionError { .. })) {}
705
706 // Clear cached credentials after authentication fails
707 server.roll_access_token();
708 server.allow_connections();
709 cx.foreground().advance_clock(Duration::from_secs(10));
710 assert_eq!(server.auth_count(), 1);
711 cx.foreground().advance_clock(Duration::from_secs(10));
712 while !matches!(status.recv().await, Some(Status::Connected { .. })) {}
713 assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
714 }
715
716 #[test]
717 fn test_encode_and_decode_worktree_url() {
718 let url = encode_worktree_url(5, "deadbeef");
719 assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
720 assert_eq!(
721 decode_worktree_url(&format!("\n {}\t", url)),
722 Some((5, "deadbeef".to_string()))
723 );
724 assert_eq!(decode_worktree_url("not://the-right-format"), None);
725 }
726}