client.rs

  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, u64),
128        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, u64),
156}
157
158impl Drop for Subscription {
159    fn drop(&mut self) {
160        if let Some(client) = self.client.upgrade() {
161            drop(
162                client
163                    .state
164                    .write()
165                    .model_handlers
166                    .remove(&self.id)
167                    .unwrap(),
168            );
169        }
170    }
171}
172
173impl Client {
174    pub fn new(http: Arc<dyn HttpClient>) -> Arc<Self> {
175        Arc::new(Self {
176            peer: Peer::new(),
177            http,
178            state: Default::default(),
179            authenticate: None,
180            establish_connection: None,
181        })
182    }
183
184    #[cfg(any(test, feature = "test-support"))]
185    pub fn override_authenticate<F>(&mut self, authenticate: F) -> &mut Self
186    where
187        F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
188    {
189        self.authenticate = Some(Box::new(authenticate));
190        self
191    }
192
193    #[cfg(any(test, feature = "test-support"))]
194    pub fn override_establish_connection<F>(&mut self, connect: F) -> &mut Self
195    where
196        F: 'static
197            + Send
198            + Sync
199            + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
200    {
201        self.establish_connection = Some(Box::new(connect));
202        self
203    }
204
205    pub fn user_id(&self) -> Option<u64> {
206        self.state
207            .read()
208            .credentials
209            .as_ref()
210            .map(|credentials| credentials.user_id)
211    }
212
213    pub fn status(&self) -> watch::Receiver<Status> {
214        self.state.read().status.1.clone()
215    }
216
217    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
218        let mut state = self.state.write();
219        *state.status.0.borrow_mut() = status;
220
221        match status {
222            Status::Connected { .. } => {
223                let heartbeat_interval = state.heartbeat_interval;
224                let this = self.clone();
225                let foreground = cx.foreground();
226                state._maintain_connection = Some(cx.foreground().spawn(async move {
227                    loop {
228                        foreground.timer(heartbeat_interval).await;
229                        let _ = this.request(proto::Ping {}).await;
230                    }
231                }));
232            }
233            Status::ConnectionLost => {
234                let this = self.clone();
235                let foreground = cx.foreground();
236                let heartbeat_interval = state.heartbeat_interval;
237                state._maintain_connection = Some(cx.spawn(|cx| async move {
238                    let mut rng = StdRng::from_entropy();
239                    let mut delay = Duration::from_millis(100);
240                    while let Err(error) = this.authenticate_and_connect(&cx).await {
241                        log::error!("failed to connect {}", error);
242                        this.set_status(
243                            Status::ReconnectionError {
244                                next_reconnection: Instant::now() + delay,
245                            },
246                            &cx,
247                        );
248                        foreground.timer(delay).await;
249                        delay = delay
250                            .mul_f32(rng.gen_range(1.0..=2.0))
251                            .min(heartbeat_interval);
252                    }
253                }));
254            }
255            Status::SignedOut | Status::UpgradeRequired => {
256                state._maintain_connection.take();
257            }
258            _ => {}
259        }
260    }
261
262    pub fn subscribe<T, M, F>(
263        self: &Arc<Self>,
264        cx: &mut ModelContext<M>,
265        mut handler: F,
266    ) -> Subscription
267    where
268        T: EnvelopedMessage,
269        M: Entity,
270        F: 'static
271            + Send
272            + Sync
273            + FnMut(&mut M, TypedEnvelope<T>, Arc<Self>, &mut ModelContext<M>) -> Result<()>,
274    {
275        let subscription_id = (TypeId::of::<T>(), Default::default());
276        let client = self.clone();
277        let mut state = self.state.write();
278        let model = cx.weak_handle();
279        let prev_extractor = state
280            .entity_id_extractors
281            .insert(subscription_id.0, Box::new(|_| Default::default()));
282        if prev_extractor.is_some() {
283            panic!("registered a handler for the same entity twice")
284        }
285
286        state.model_handlers.insert(
287            subscription_id,
288            Box::new(move |envelope, cx| {
289                if let Some(model) = model.upgrade(cx) {
290                    let envelope = envelope.into_any().downcast::<TypedEnvelope<T>>().unwrap();
291                    model.update(cx, |model, cx| {
292                        if let Err(error) = handler(model, *envelope, client.clone(), cx) {
293                            log::error!("error handling message: {}", error)
294                        }
295                    });
296                }
297            }),
298        );
299
300        Subscription {
301            client: Arc::downgrade(self),
302            id: subscription_id,
303        }
304    }
305
306    pub fn subscribe_to_entity<T, M, F>(
307        self: &Arc<Self>,
308        remote_id: u64,
309        cx: &mut ModelContext<M>,
310        mut handler: F,
311    ) -> Subscription
312    where
313        T: EntityMessage,
314        M: Entity,
315        F: 'static
316            + Send
317            + Sync
318            + FnMut(&mut M, TypedEnvelope<T>, Arc<Self>, &mut ModelContext<M>) -> Result<()>,
319    {
320        let subscription_id = (TypeId::of::<T>(), remote_id);
321        let client = self.clone();
322        let mut state = self.state.write();
323        let model = cx.weak_handle();
324        state
325            .entity_id_extractors
326            .entry(subscription_id.0)
327            .or_insert_with(|| {
328                Box::new(|envelope| {
329                    let envelope = envelope
330                        .as_any()
331                        .downcast_ref::<TypedEnvelope<T>>()
332                        .unwrap();
333                    envelope.payload.remote_entity_id()
334                })
335            });
336        let prev_handler = state.model_handlers.insert(
337            subscription_id,
338            Box::new(move |envelope, cx| {
339                if let Some(model) = model.upgrade(cx) {
340                    let envelope = envelope.into_any().downcast::<TypedEnvelope<T>>().unwrap();
341                    model.update(cx, |model, cx| {
342                        if let Err(error) = handler(model, *envelope, client.clone(), cx) {
343                            log::error!("error handling message: {}", error)
344                        }
345                    });
346                }
347            }),
348        );
349        if prev_handler.is_some() {
350            panic!("registered a handler for the same entity twice")
351        }
352
353        Subscription {
354            client: Arc::downgrade(self),
355            id: subscription_id,
356        }
357    }
358
359    #[async_recursion(?Send)]
360    pub async fn authenticate_and_connect(
361        self: &Arc<Self>,
362        cx: &AsyncAppContext,
363    ) -> anyhow::Result<()> {
364        let was_disconnected = match *self.status().borrow() {
365            Status::SignedOut => true,
366            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
367                false
368            }
369            Status::Connected { .. }
370            | Status::Connecting { .. }
371            | Status::Reconnecting { .. }
372            | Status::Authenticating
373            | Status::Reauthenticating => return Ok(()),
374            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
375        };
376
377        if was_disconnected {
378            self.set_status(Status::Authenticating, cx);
379        } else {
380            self.set_status(Status::Reauthenticating, cx)
381        }
382
383        let mut used_keychain = false;
384        let credentials = self.state.read().credentials.clone();
385        let credentials = if let Some(credentials) = credentials {
386            credentials
387        } else if let Some(credentials) = read_credentials_from_keychain(cx) {
388            used_keychain = true;
389            credentials
390        } else {
391            let credentials = match self.authenticate(&cx).await {
392                Ok(credentials) => credentials,
393                Err(err) => {
394                    self.set_status(Status::ConnectionError, cx);
395                    return Err(err);
396                }
397            };
398            credentials
399        };
400
401        if was_disconnected {
402            self.set_status(Status::Connecting, cx);
403        } else {
404            self.set_status(Status::Reconnecting, cx);
405        }
406
407        match self.establish_connection(&credentials, cx).await {
408            Ok(conn) => {
409                self.state.write().credentials = Some(credentials.clone());
410                if !used_keychain && IMPERSONATE_LOGIN.is_none() {
411                    write_credentials_to_keychain(&credentials, cx).log_err();
412                }
413                self.set_connection(conn, cx).await;
414                Ok(())
415            }
416            Err(EstablishConnectionError::Unauthorized) => {
417                self.state.write().credentials.take();
418                if used_keychain {
419                    cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
420                    self.set_status(Status::SignedOut, cx);
421                    self.authenticate_and_connect(cx).await
422                } else {
423                    self.set_status(Status::ConnectionError, cx);
424                    Err(EstablishConnectionError::Unauthorized)?
425                }
426            }
427            Err(EstablishConnectionError::UpgradeRequired) => {
428                self.set_status(Status::UpgradeRequired, cx);
429                Err(EstablishConnectionError::UpgradeRequired)?
430            }
431            Err(error) => {
432                self.set_status(Status::ConnectionError, cx);
433                Err(error)?
434            }
435        }
436    }
437
438    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
439        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn).await;
440        cx.foreground()
441            .spawn({
442                let mut cx = cx.clone();
443                let this = self.clone();
444                async move {
445                    while let Some(message) = incoming.recv().await {
446                        let mut state = this.state.write();
447                        if let Some(extract_entity_id) =
448                            state.entity_id_extractors.get(&message.payload_type_id())
449                        {
450                            let payload_type_id = message.payload_type_id();
451                            let entity_id = (extract_entity_id)(message.as_ref());
452                            let handler_key = (payload_type_id, entity_id);
453                            if let Some(mut handler) = state.model_handlers.remove(&handler_key) {
454                                drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
455                                let start_time = Instant::now();
456                                log::info!("RPC client message {}", message.payload_type_name());
457                                (handler)(message, &mut cx);
458                                log::info!(
459                                    "RPC message handled. duration:{:?}",
460                                    start_time.elapsed()
461                                );
462                                this.state
463                                    .write()
464                                    .model_handlers
465                                    .insert(handler_key, handler);
466                            } else {
467                                log::info!("unhandled message {}", message.payload_type_name());
468                            }
469                        } else {
470                            log::info!("unhandled message {}", message.payload_type_name());
471                        }
472                    }
473                }
474            })
475            .detach();
476
477        self.set_status(Status::Connected { connection_id }, cx);
478
479        let handle_io = cx.background().spawn(handle_io);
480        let this = self.clone();
481        let cx = cx.clone();
482        cx.foreground()
483            .spawn(async move {
484                match handle_io.await {
485                    Ok(()) => this.set_status(Status::SignedOut, &cx),
486                    Err(err) => {
487                        log::error!("connection error: {:?}", err);
488                        this.set_status(Status::ConnectionLost, &cx);
489                    }
490                }
491            })
492            .detach();
493    }
494
495    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
496        if let Some(callback) = self.authenticate.as_ref() {
497            callback(cx)
498        } else {
499            self.authenticate_with_browser(cx)
500        }
501    }
502
503    fn establish_connection(
504        self: &Arc<Self>,
505        credentials: &Credentials,
506        cx: &AsyncAppContext,
507    ) -> Task<Result<Connection, EstablishConnectionError>> {
508        if let Some(callback) = self.establish_connection.as_ref() {
509            callback(credentials, cx)
510        } else {
511            self.establish_websocket_connection(credentials, cx)
512        }
513    }
514
515    fn establish_websocket_connection(
516        self: &Arc<Self>,
517        credentials: &Credentials,
518        cx: &AsyncAppContext,
519    ) -> Task<Result<Connection, EstablishConnectionError>> {
520        let request = Request::builder()
521            .header(
522                "Authorization",
523                format!("{} {}", credentials.user_id, credentials.access_token),
524            )
525            .header("X-Zed-Protocol-Version", rpc::PROTOCOL_VERSION);
526
527        let http = self.http.clone();
528        cx.background().spawn(async move {
529            let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
530            let rpc_request = surf::Request::new(
531                Method::Get,
532                surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
533            );
534            let rpc_response = http.send(rpc_request).await?;
535
536            if rpc_response.status().is_redirection() {
537                rpc_url = rpc_response
538                    .header("Location")
539                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
540                    .as_str()
541                    .to_string();
542            }
543            // Until we switch the zed.dev domain to point to the new Next.js app, there
544            // will be no redirect required, and the app will connect directly to
545            // wss://zed.dev/rpc.
546            else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
547                Err(anyhow!(
548                    "unexpected /rpc response status {}",
549                    rpc_response.status()
550                ))?
551            }
552
553            let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
554            let rpc_host = rpc_url
555                .host_str()
556                .zip(rpc_url.port_or_known_default())
557                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
558            let stream = smol::net::TcpStream::connect(rpc_host).await?;
559
560            log::info!("connected to rpc endpoint {}", rpc_url);
561
562            match rpc_url.scheme() {
563                "https" => {
564                    rpc_url.set_scheme("wss").unwrap();
565                    let request = request.uri(rpc_url.as_str()).body(())?;
566                    let (stream, _) =
567                        async_tungstenite::async_tls::client_async_tls(request, stream).await?;
568                    Ok(Connection::new(stream))
569                }
570                "http" => {
571                    rpc_url.set_scheme("ws").unwrap();
572                    let request = request.uri(rpc_url.as_str()).body(())?;
573                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
574                    Ok(Connection::new(stream))
575                }
576                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
577            }
578        })
579    }
580
581    pub fn authenticate_with_browser(
582        self: &Arc<Self>,
583        cx: &AsyncAppContext,
584    ) -> Task<Result<Credentials>> {
585        let platform = cx.platform();
586        let executor = cx.background();
587        executor.clone().spawn(async move {
588            // Generate a pair of asymmetric encryption keys. The public key will be used by the
589            // zed server to encrypt the user's access token, so that it can'be intercepted by
590            // any other app running on the user's device.
591            let (public_key, private_key) =
592                rpc::auth::keypair().expect("failed to generate keypair for auth");
593            let public_key_string =
594                String::try_from(public_key).expect("failed to serialize public key for auth");
595
596            // Start an HTTP server to receive the redirect from Zed's sign-in page.
597            let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
598            let port = server.server_addr().port();
599
600            // Open the Zed sign-in page in the user's browser, with query parameters that indicate
601            // that the user is signing in from a Zed app running on the same device.
602            let mut url = format!(
603                "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
604                *ZED_SERVER_URL, port, public_key_string
605            );
606
607            if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
608                log::info!("impersonating user @{}", impersonate_login);
609                write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
610            }
611
612            platform.open_url(&url);
613
614            // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
615            // access token from the query params.
616            //
617            // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
618            // custom URL scheme instead of this local HTTP server.
619            let (user_id, access_token) = executor
620                .spawn(async move {
621                    if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
622                        let path = req.url();
623                        let mut user_id = None;
624                        let mut access_token = None;
625                        let url = Url::parse(&format!("http://example.com{}", path))
626                            .context("failed to parse login notification url")?;
627                        for (key, value) in url.query_pairs() {
628                            if key == "access_token" {
629                                access_token = Some(value.to_string());
630                            } else if key == "user_id" {
631                                user_id = Some(value.to_string());
632                            }
633                        }
634
635                        let post_auth_url =
636                            format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
637                        req.respond(
638                            tiny_http::Response::empty(302).with_header(
639                                tiny_http::Header::from_bytes(
640                                    &b"Location"[..],
641                                    post_auth_url.as_bytes(),
642                                )
643                                .unwrap(),
644                            ),
645                        )
646                        .context("failed to respond to login http request")?;
647                        Ok((
648                            user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
649                            access_token
650                                .ok_or_else(|| anyhow!("missing access_token parameter"))?,
651                        ))
652                    } else {
653                        Err(anyhow!("didn't receive login redirect"))
654                    }
655                })
656                .await?;
657
658            let access_token = private_key
659                .decrypt_string(&access_token)
660                .context("failed to decrypt access token")?;
661            platform.activate(true);
662
663            Ok(Credentials {
664                user_id: user_id.parse()?,
665                access_token,
666            })
667        })
668    }
669
670    pub async fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
671        let conn_id = self.connection_id()?;
672        self.peer.disconnect(conn_id).await;
673        self.set_status(Status::SignedOut, cx);
674        Ok(())
675    }
676
677    fn connection_id(&self) -> Result<ConnectionId> {
678        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
679            Ok(connection_id)
680        } else {
681            Err(anyhow!("not connected"))
682        }
683    }
684
685    pub async fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
686        self.peer.send(self.connection_id()?, message).await
687    }
688
689    pub async fn request<T: RequestMessage>(&self, request: T) -> Result<T::Response> {
690        self.peer.request(self.connection_id()?, request).await
691    }
692
693    pub fn respond<T: RequestMessage>(
694        &self,
695        receipt: Receipt<T>,
696        response: T::Response,
697    ) -> impl Future<Output = Result<()>> {
698        self.peer.respond(receipt, response)
699    }
700}
701
702fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
703    if IMPERSONATE_LOGIN.is_some() {
704        return None;
705    }
706
707    let (user_id, access_token) = cx
708        .platform()
709        .read_credentials(&ZED_SERVER_URL)
710        .log_err()
711        .flatten()?;
712    Some(Credentials {
713        user_id: user_id.parse().ok()?,
714        access_token: String::from_utf8(access_token).ok()?,
715    })
716}
717
718fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
719    cx.platform().write_credentials(
720        &ZED_SERVER_URL,
721        &credentials.user_id.to_string(),
722        credentials.access_token.as_bytes(),
723    )
724}
725
726const WORKTREE_URL_PREFIX: &'static str = "zed://worktrees/";
727
728pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
729    format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
730}
731
732pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
733    let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
734    let mut parts = path.split('/');
735    let id = parts.next()?.parse::<u64>().ok()?;
736    let access_token = parts.next()?;
737    if access_token.is_empty() {
738        return None;
739    }
740    Some((id, access_token.to_string()))
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746    use crate::test::{FakeHttpClient, FakeServer};
747    use gpui::TestAppContext;
748
749    #[gpui::test(iterations = 10)]
750    async fn test_heartbeat(cx: TestAppContext) {
751        cx.foreground().forbid_parking();
752
753        let user_id = 5;
754        let mut client = Client::new(FakeHttpClient::with_404_response());
755        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
756
757        cx.foreground().advance_clock(Duration::from_secs(10));
758        let ping = server.receive::<proto::Ping>().await.unwrap();
759        server.respond(ping.receipt(), proto::Ack {}).await;
760
761        cx.foreground().advance_clock(Duration::from_secs(10));
762        let ping = server.receive::<proto::Ping>().await.unwrap();
763        server.respond(ping.receipt(), proto::Ack {}).await;
764
765        client.disconnect(&cx.to_async()).await.unwrap();
766        assert!(server.receive::<proto::Ping>().await.is_err());
767    }
768
769    #[gpui::test(iterations = 10)]
770    async fn test_reconnection(cx: TestAppContext) {
771        cx.foreground().forbid_parking();
772
773        let user_id = 5;
774        let mut client = Client::new(FakeHttpClient::with_404_response());
775        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
776        let mut status = client.status();
777        assert!(matches!(
778            status.recv().await,
779            Some(Status::Connected { .. })
780        ));
781        assert_eq!(server.auth_count(), 1);
782
783        server.forbid_connections();
784        server.disconnect().await;
785        while !matches!(status.recv().await, Some(Status::ReconnectionError { .. })) {}
786
787        server.allow_connections();
788        cx.foreground().advance_clock(Duration::from_secs(10));
789        while !matches!(status.recv().await, Some(Status::Connected { .. })) {}
790        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
791
792        server.forbid_connections();
793        server.disconnect().await;
794        while !matches!(status.recv().await, Some(Status::ReconnectionError { .. })) {}
795
796        // Clear cached credentials after authentication fails
797        server.roll_access_token();
798        server.allow_connections();
799        cx.foreground().advance_clock(Duration::from_secs(10));
800        assert_eq!(server.auth_count(), 1);
801        cx.foreground().advance_clock(Duration::from_secs(10));
802        while !matches!(status.recv().await, Some(Status::Connected { .. })) {}
803        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
804    }
805
806    #[test]
807    fn test_encode_and_decode_worktree_url() {
808        let url = encode_worktree_url(5, "deadbeef");
809        assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
810        assert_eq!(
811            decode_worktree_url(&format!("\n {}\t", url)),
812            Some((5, "deadbeef".to_string()))
813        );
814        assert_eq!(decode_worktree_url("not://the-right-format"), None);
815    }
816}