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