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