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