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    pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
360        read_credentials_from_keychain(cx).is_some()
361    }
362
363    #[async_recursion(?Send)]
364    pub async fn authenticate_and_connect(
365        self: &Arc<Self>,
366        cx: &AsyncAppContext,
367    ) -> anyhow::Result<()> {
368        let was_disconnected = match *self.status().borrow() {
369            Status::SignedOut => true,
370            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
371                false
372            }
373            Status::Connected { .. }
374            | Status::Connecting { .. }
375            | Status::Reconnecting { .. }
376            | Status::Authenticating
377            | Status::Reauthenticating => return Ok(()),
378            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
379        };
380
381        if was_disconnected {
382            self.set_status(Status::Authenticating, cx);
383        } else {
384            self.set_status(Status::Reauthenticating, cx)
385        }
386
387        let mut used_keychain = false;
388        let credentials = self.state.read().credentials.clone();
389        let credentials = if let Some(credentials) = credentials {
390            credentials
391        } else if let Some(credentials) = read_credentials_from_keychain(cx) {
392            used_keychain = true;
393            credentials
394        } else {
395            let credentials = match self.authenticate(&cx).await {
396                Ok(credentials) => credentials,
397                Err(err) => {
398                    self.set_status(Status::ConnectionError, cx);
399                    return Err(err);
400                }
401            };
402            credentials
403        };
404
405        if was_disconnected {
406            self.set_status(Status::Connecting, cx);
407        } else {
408            self.set_status(Status::Reconnecting, cx);
409        }
410
411        match self.establish_connection(&credentials, cx).await {
412            Ok(conn) => {
413                self.state.write().credentials = Some(credentials.clone());
414                if !used_keychain && IMPERSONATE_LOGIN.is_none() {
415                    write_credentials_to_keychain(&credentials, cx).log_err();
416                }
417                self.set_connection(conn, cx).await;
418                Ok(())
419            }
420            Err(EstablishConnectionError::Unauthorized) => {
421                self.state.write().credentials.take();
422                if used_keychain {
423                    cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
424                    self.set_status(Status::SignedOut, cx);
425                    self.authenticate_and_connect(cx).await
426                } else {
427                    self.set_status(Status::ConnectionError, cx);
428                    Err(EstablishConnectionError::Unauthorized)?
429                }
430            }
431            Err(EstablishConnectionError::UpgradeRequired) => {
432                self.set_status(Status::UpgradeRequired, cx);
433                Err(EstablishConnectionError::UpgradeRequired)?
434            }
435            Err(error) => {
436                self.set_status(Status::ConnectionError, cx);
437                Err(error)?
438            }
439        }
440    }
441
442    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
443        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn).await;
444        cx.foreground()
445            .spawn({
446                let mut cx = cx.clone();
447                let this = self.clone();
448                async move {
449                    while let Some(message) = incoming.recv().await {
450                        let mut state = this.state.write();
451                        if let Some(extract_entity_id) =
452                            state.entity_id_extractors.get(&message.payload_type_id())
453                        {
454                            let payload_type_id = message.payload_type_id();
455                            let entity_id = (extract_entity_id)(message.as_ref());
456                            let handler_key = (payload_type_id, entity_id);
457                            if let Some(mut handler) = state.model_handlers.remove(&handler_key) {
458                                drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
459                                let start_time = Instant::now();
460                                log::info!("RPC client message {}", message.payload_type_name());
461                                (handler)(message, &mut cx);
462                                log::info!(
463                                    "RPC message handled. duration:{:?}",
464                                    start_time.elapsed()
465                                );
466                                this.state
467                                    .write()
468                                    .model_handlers
469                                    .insert(handler_key, handler);
470                            } else {
471                                log::info!("unhandled message {}", message.payload_type_name());
472                            }
473                        } else {
474                            log::info!("unhandled message {}", message.payload_type_name());
475                        }
476                    }
477                }
478            })
479            .detach();
480
481        self.set_status(Status::Connected { connection_id }, cx);
482
483        let handle_io = cx.background().spawn(handle_io);
484        let this = self.clone();
485        let cx = cx.clone();
486        cx.foreground()
487            .spawn(async move {
488                match handle_io.await {
489                    Ok(()) => this.set_status(Status::SignedOut, &cx),
490                    Err(err) => {
491                        log::error!("connection error: {:?}", err);
492                        this.set_status(Status::ConnectionLost, &cx);
493                    }
494                }
495            })
496            .detach();
497    }
498
499    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
500        if let Some(callback) = self.authenticate.as_ref() {
501            callback(cx)
502        } else {
503            self.authenticate_with_browser(cx)
504        }
505    }
506
507    fn establish_connection(
508        self: &Arc<Self>,
509        credentials: &Credentials,
510        cx: &AsyncAppContext,
511    ) -> Task<Result<Connection, EstablishConnectionError>> {
512        if let Some(callback) = self.establish_connection.as_ref() {
513            callback(credentials, cx)
514        } else {
515            self.establish_websocket_connection(credentials, cx)
516        }
517    }
518
519    fn establish_websocket_connection(
520        self: &Arc<Self>,
521        credentials: &Credentials,
522        cx: &AsyncAppContext,
523    ) -> Task<Result<Connection, EstablishConnectionError>> {
524        let request = Request::builder()
525            .header(
526                "Authorization",
527                format!("{} {}", credentials.user_id, credentials.access_token),
528            )
529            .header("X-Zed-Protocol-Version", rpc::PROTOCOL_VERSION);
530
531        let http = self.http.clone();
532        cx.background().spawn(async move {
533            let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
534            let rpc_request = surf::Request::new(
535                Method::Get,
536                surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
537            );
538            let rpc_response = http.send(rpc_request).await?;
539
540            if rpc_response.status().is_redirection() {
541                rpc_url = rpc_response
542                    .header("Location")
543                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
544                    .as_str()
545                    .to_string();
546            }
547            // Until we switch the zed.dev domain to point to the new Next.js app, there
548            // will be no redirect required, and the app will connect directly to
549            // wss://zed.dev/rpc.
550            else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
551                Err(anyhow!(
552                    "unexpected /rpc response status {}",
553                    rpc_response.status()
554                ))?
555            }
556
557            let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
558            let rpc_host = rpc_url
559                .host_str()
560                .zip(rpc_url.port_or_known_default())
561                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
562            let stream = smol::net::TcpStream::connect(rpc_host).await?;
563
564            log::info!("connected to rpc endpoint {}", rpc_url);
565
566            match rpc_url.scheme() {
567                "https" => {
568                    rpc_url.set_scheme("wss").unwrap();
569                    let request = request.uri(rpc_url.as_str()).body(())?;
570                    let (stream, _) =
571                        async_tungstenite::async_tls::client_async_tls(request, stream).await?;
572                    Ok(Connection::new(stream))
573                }
574                "http" => {
575                    rpc_url.set_scheme("ws").unwrap();
576                    let request = request.uri(rpc_url.as_str()).body(())?;
577                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
578                    Ok(Connection::new(stream))
579                }
580                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
581            }
582        })
583    }
584
585    pub fn authenticate_with_browser(
586        self: &Arc<Self>,
587        cx: &AsyncAppContext,
588    ) -> Task<Result<Credentials>> {
589        let platform = cx.platform();
590        let executor = cx.background();
591        executor.clone().spawn(async move {
592            // Generate a pair of asymmetric encryption keys. The public key will be used by the
593            // zed server to encrypt the user's access token, so that it can'be intercepted by
594            // any other app running on the user's device.
595            let (public_key, private_key) =
596                rpc::auth::keypair().expect("failed to generate keypair for auth");
597            let public_key_string =
598                String::try_from(public_key).expect("failed to serialize public key for auth");
599
600            // Start an HTTP server to receive the redirect from Zed's sign-in page.
601            let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
602            let port = server.server_addr().port();
603
604            // Open the Zed sign-in page in the user's browser, with query parameters that indicate
605            // that the user is signing in from a Zed app running on the same device.
606            let mut url = format!(
607                "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
608                *ZED_SERVER_URL, port, public_key_string
609            );
610
611            if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
612                log::info!("impersonating user @{}", impersonate_login);
613                write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
614            }
615
616            platform.open_url(&url);
617
618            // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
619            // access token from the query params.
620            //
621            // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
622            // custom URL scheme instead of this local HTTP server.
623            let (user_id, access_token) = executor
624                .spawn(async move {
625                    if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
626                        let path = req.url();
627                        let mut user_id = None;
628                        let mut access_token = None;
629                        let url = Url::parse(&format!("http://example.com{}", path))
630                            .context("failed to parse login notification url")?;
631                        for (key, value) in url.query_pairs() {
632                            if key == "access_token" {
633                                access_token = Some(value.to_string());
634                            } else if key == "user_id" {
635                                user_id = Some(value.to_string());
636                            }
637                        }
638
639                        let post_auth_url =
640                            format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
641                        req.respond(
642                            tiny_http::Response::empty(302).with_header(
643                                tiny_http::Header::from_bytes(
644                                    &b"Location"[..],
645                                    post_auth_url.as_bytes(),
646                                )
647                                .unwrap(),
648                            ),
649                        )
650                        .context("failed to respond to login http request")?;
651                        Ok((
652                            user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
653                            access_token
654                                .ok_or_else(|| anyhow!("missing access_token parameter"))?,
655                        ))
656                    } else {
657                        Err(anyhow!("didn't receive login redirect"))
658                    }
659                })
660                .await?;
661
662            let access_token = private_key
663                .decrypt_string(&access_token)
664                .context("failed to decrypt access token")?;
665            platform.activate(true);
666
667            Ok(Credentials {
668                user_id: user_id.parse()?,
669                access_token,
670            })
671        })
672    }
673
674    pub async fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
675        let conn_id = self.connection_id()?;
676        self.peer.disconnect(conn_id).await;
677        self.set_status(Status::SignedOut, cx);
678        Ok(())
679    }
680
681    fn connection_id(&self) -> Result<ConnectionId> {
682        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
683            Ok(connection_id)
684        } else {
685            Err(anyhow!("not connected"))
686        }
687    }
688
689    pub async fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
690        self.peer.send(self.connection_id()?, message).await
691    }
692
693    pub async fn request<T: RequestMessage>(&self, request: T) -> Result<T::Response> {
694        self.peer.request(self.connection_id()?, request).await
695    }
696
697    pub fn respond<T: RequestMessage>(
698        &self,
699        receipt: Receipt<T>,
700        response: T::Response,
701    ) -> impl Future<Output = Result<()>> {
702        self.peer.respond(receipt, response)
703    }
704}
705
706fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
707    if IMPERSONATE_LOGIN.is_some() {
708        return None;
709    }
710
711    let (user_id, access_token) = cx
712        .platform()
713        .read_credentials(&ZED_SERVER_URL)
714        .log_err()
715        .flatten()?;
716    Some(Credentials {
717        user_id: user_id.parse().ok()?,
718        access_token: String::from_utf8(access_token).ok()?,
719    })
720}
721
722fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
723    cx.platform().write_credentials(
724        &ZED_SERVER_URL,
725        &credentials.user_id.to_string(),
726        credentials.access_token.as_bytes(),
727    )
728}
729
730const WORKTREE_URL_PREFIX: &'static str = "zed://worktrees/";
731
732pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
733    format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
734}
735
736pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
737    let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
738    let mut parts = path.split('/');
739    let id = parts.next()?.parse::<u64>().ok()?;
740    let access_token = parts.next()?;
741    if access_token.is_empty() {
742        return None;
743    }
744    Some((id, access_token.to_string()))
745}
746
747#[cfg(test)]
748mod tests {
749    use super::*;
750    use crate::test::{FakeHttpClient, FakeServer};
751    use gpui::TestAppContext;
752
753    #[gpui::test(iterations = 10)]
754    async fn test_heartbeat(cx: TestAppContext) {
755        cx.foreground().forbid_parking();
756
757        let user_id = 5;
758        let mut client = Client::new(FakeHttpClient::with_404_response());
759        let server = FakeServer::for_client(user_id, &mut client, &cx).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        cx.foreground().advance_clock(Duration::from_secs(10));
766        let ping = server.receive::<proto::Ping>().await.unwrap();
767        server.respond(ping.receipt(), proto::Ack {}).await;
768
769        client.disconnect(&cx.to_async()).await.unwrap();
770        assert!(server.receive::<proto::Ping>().await.is_err());
771    }
772
773    #[gpui::test(iterations = 10)]
774    async fn test_reconnection(cx: TestAppContext) {
775        cx.foreground().forbid_parking();
776
777        let user_id = 5;
778        let mut client = Client::new(FakeHttpClient::with_404_response());
779        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
780        let mut status = client.status();
781        assert!(matches!(
782            status.recv().await,
783            Some(Status::Connected { .. })
784        ));
785        assert_eq!(server.auth_count(), 1);
786
787        server.forbid_connections();
788        server.disconnect().await;
789        while !matches!(status.recv().await, Some(Status::ReconnectionError { .. })) {}
790
791        server.allow_connections();
792        cx.foreground().advance_clock(Duration::from_secs(10));
793        while !matches!(status.recv().await, Some(Status::Connected { .. })) {}
794        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
795
796        server.forbid_connections();
797        server.disconnect().await;
798        while !matches!(status.recv().await, Some(Status::ReconnectionError { .. })) {}
799
800        // Clear cached credentials after authentication fails
801        server.roll_access_token();
802        server.allow_connections();
803        cx.foreground().advance_clock(Duration::from_secs(10));
804        assert_eq!(server.auth_count(), 1);
805        cx.foreground().advance_clock(Duration::from_secs(10));
806        while !matches!(status.recv().await, Some(Status::Connected { .. })) {}
807        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
808    }
809
810    #[test]
811    fn test_encode_and_decode_worktree_url() {
812        let url = encode_worktree_url(5, "deadbeef");
813        assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
814        assert_eq!(
815            decode_worktree_url(&format!("\n {}\t", url)),
816            Some((5, "deadbeef".to_string()))
817        );
818        assert_eq!(decode_worktree_url("not://the-right-format"), None);
819    }
820}