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