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, Option<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, Option<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.model_handlers.remove(&self.id).unwrap();
163        }
164    }
165}
166
167impl Client {
168    pub fn new(http: Arc<dyn HttpClient>) -> Arc<Self> {
169        Arc::new(Self {
170            peer: Peer::new(),
171            http,
172            state: Default::default(),
173            authenticate: None,
174            establish_connection: None,
175        })
176    }
177
178    #[cfg(any(test, feature = "test-support"))]
179    pub fn override_authenticate<F>(&mut self, authenticate: F) -> &mut Self
180    where
181        F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
182    {
183        self.authenticate = Some(Box::new(authenticate));
184        self
185    }
186
187    #[cfg(any(test, feature = "test-support"))]
188    pub fn override_establish_connection<F>(&mut self, connect: F) -> &mut Self
189    where
190        F: 'static
191            + Send
192            + Sync
193            + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
194    {
195        self.establish_connection = Some(Box::new(connect));
196        self
197    }
198
199    pub fn user_id(&self) -> Option<u64> {
200        self.state
201            .read()
202            .credentials
203            .as_ref()
204            .map(|credentials| credentials.user_id)
205    }
206
207    pub fn status(&self) -> watch::Receiver<Status> {
208        self.state.read().status.1.clone()
209    }
210
211    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
212        let mut state = self.state.write();
213        *state.status.0.borrow_mut() = status;
214
215        match status {
216            Status::Connected { .. } => {
217                let heartbeat_interval = state.heartbeat_interval;
218                let this = self.clone();
219                let foreground = cx.foreground();
220                state._maintain_connection = Some(cx.foreground().spawn(async move {
221                    loop {
222                        foreground.timer(heartbeat_interval).await;
223                        let _ = this.request(proto::Ping {}).await;
224                    }
225                }));
226            }
227            Status::ConnectionLost => {
228                let this = self.clone();
229                let foreground = cx.foreground();
230                let heartbeat_interval = state.heartbeat_interval;
231                state._maintain_connection = Some(cx.spawn(|cx| async move {
232                    let mut rng = StdRng::from_entropy();
233                    let mut delay = Duration::from_millis(100);
234                    while let Err(error) = this.authenticate_and_connect(&cx).await {
235                        log::error!("failed to connect {}", error);
236                        this.set_status(
237                            Status::ReconnectionError {
238                                next_reconnection: Instant::now() + delay,
239                            },
240                            &cx,
241                        );
242                        foreground.timer(delay).await;
243                        delay = delay
244                            .mul_f32(rng.gen_range(1.0..=2.0))
245                            .min(heartbeat_interval);
246                    }
247                }));
248            }
249            Status::SignedOut | Status::UpgradeRequired => {
250                state._maintain_connection.take();
251            }
252            _ => {}
253        }
254    }
255
256    pub fn subscribe<T, M, F>(
257        self: &Arc<Self>,
258        cx: &mut ModelContext<M>,
259        mut handler: F,
260    ) -> Subscription
261    where
262        T: EnvelopedMessage,
263        M: Entity,
264        F: 'static
265            + Send
266            + Sync
267            + FnMut(&mut M, TypedEnvelope<T>, Arc<Self>, &mut ModelContext<M>) -> Result<()>,
268    {
269        let subscription_id = (TypeId::of::<T>(), None);
270        let client = self.clone();
271        let mut state = self.state.write();
272        let model = cx.weak_handle();
273        let prev_handler = state.model_handlers.insert(
274            subscription_id,
275            Some(Box::new(move |envelope, cx| {
276                if let Some(model) = model.upgrade(cx) {
277                    let envelope = envelope.into_any().downcast::<TypedEnvelope<T>>().unwrap();
278                    model.update(cx, |model, cx| {
279                        if let Err(error) = handler(model, *envelope, client.clone(), cx) {
280                            log::error!("error handling message: {}", error)
281                        }
282                    });
283                }
284            })),
285        );
286        if prev_handler.is_some() {
287            panic!("registered handler for the same message twice");
288        }
289
290        Subscription {
291            client: Arc::downgrade(self),
292            id: subscription_id,
293        }
294    }
295
296    pub fn subscribe_to_entity<T, M, F>(
297        self: &Arc<Self>,
298        remote_id: u64,
299        cx: &mut ModelContext<M>,
300        mut handler: F,
301    ) -> Subscription
302    where
303        T: EntityMessage,
304        M: Entity,
305        F: 'static
306            + Send
307            + Sync
308            + FnMut(&mut M, TypedEnvelope<T>, Arc<Self>, &mut ModelContext<M>) -> Result<()>,
309    {
310        let subscription_id = (TypeId::of::<T>(), Some(remote_id));
311        let client = self.clone();
312        let mut state = self.state.write();
313        let model = cx.weak_handle();
314        state
315            .entity_id_extractors
316            .entry(subscription_id.0)
317            .or_insert_with(|| {
318                Box::new(|envelope| {
319                    let envelope = envelope
320                        .as_any()
321                        .downcast_ref::<TypedEnvelope<T>>()
322                        .unwrap();
323                    envelope.payload.remote_entity_id()
324                })
325            });
326        let prev_handler = state.model_handlers.insert(
327            subscription_id,
328            Some(Box::new(move |envelope, cx| {
329                if let Some(model) = model.upgrade(cx) {
330                    let envelope = envelope.into_any().downcast::<TypedEnvelope<T>>().unwrap();
331                    model.update(cx, |model, cx| {
332                        if let Err(error) = handler(model, *envelope, client.clone(), cx) {
333                            log::error!("error handling message: {}", error)
334                        }
335                    });
336                }
337            })),
338        );
339        if prev_handler.is_some() {
340            panic!("registered a handler for the same entity twice")
341        }
342
343        Subscription {
344            client: Arc::downgrade(self),
345            id: subscription_id,
346        }
347    }
348
349    pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
350        read_credentials_from_keychain(cx).is_some()
351    }
352
353    #[async_recursion(?Send)]
354    pub async fn authenticate_and_connect(
355        self: &Arc<Self>,
356        cx: &AsyncAppContext,
357    ) -> anyhow::Result<()> {
358        let was_disconnected = match *self.status().borrow() {
359            Status::SignedOut => true,
360            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
361                false
362            }
363            Status::Connected { .. }
364            | Status::Connecting { .. }
365            | Status::Reconnecting { .. }
366            | Status::Authenticating
367            | Status::Reauthenticating => return Ok(()),
368            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
369        };
370
371        if was_disconnected {
372            self.set_status(Status::Authenticating, cx);
373        } else {
374            self.set_status(Status::Reauthenticating, cx)
375        }
376
377        let mut used_keychain = false;
378        let credentials = self.state.read().credentials.clone();
379        let credentials = if let Some(credentials) = credentials {
380            credentials
381        } else if let Some(credentials) = read_credentials_from_keychain(cx) {
382            used_keychain = true;
383            credentials
384        } else {
385            let credentials = match self.authenticate(&cx).await {
386                Ok(credentials) => credentials,
387                Err(err) => {
388                    self.set_status(Status::ConnectionError, cx);
389                    return Err(err);
390                }
391            };
392            credentials
393        };
394
395        if was_disconnected {
396            self.set_status(Status::Connecting, cx);
397        } else {
398            self.set_status(Status::Reconnecting, cx);
399        }
400
401        match self.establish_connection(&credentials, cx).await {
402            Ok(conn) => {
403                self.state.write().credentials = Some(credentials.clone());
404                if !used_keychain && IMPERSONATE_LOGIN.is_none() {
405                    write_credentials_to_keychain(&credentials, cx).log_err();
406                }
407                self.set_connection(conn, cx).await;
408                Ok(())
409            }
410            Err(EstablishConnectionError::Unauthorized) => {
411                self.state.write().credentials.take();
412                if used_keychain {
413                    cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
414                    self.set_status(Status::SignedOut, cx);
415                    self.authenticate_and_connect(cx).await
416                } else {
417                    self.set_status(Status::ConnectionError, cx);
418                    Err(EstablishConnectionError::Unauthorized)?
419                }
420            }
421            Err(EstablishConnectionError::UpgradeRequired) => {
422                self.set_status(Status::UpgradeRequired, cx);
423                Err(EstablishConnectionError::UpgradeRequired)?
424            }
425            Err(error) => {
426                self.set_status(Status::ConnectionError, cx);
427                Err(error)?
428            }
429        }
430    }
431
432    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
433        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn).await;
434        cx.foreground()
435            .spawn({
436                let mut cx = cx.clone();
437                let this = self.clone();
438                async move {
439                    while let Some(message) = incoming.recv().await {
440                        let mut state = this.state.write();
441                        let payload_type_id = message.payload_type_id();
442                        let entity_id = if let Some(extract_entity_id) =
443                            state.entity_id_extractors.get(&message.payload_type_id())
444                        {
445                            Some((extract_entity_id)(message.as_ref()))
446                        } else {
447                            None
448                        };
449
450                        let handler_key = (payload_type_id, entity_id);
451                        if let Some(handler) = state.model_handlers.get_mut(&handler_key) {
452                            let mut handler = handler.take().unwrap();
453                            drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
454                            let start_time = Instant::now();
455                            log::info!("RPC client message {}", message.payload_type_name());
456                            (handler)(message, &mut cx);
457                            log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
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                    }
467                }
468            })
469            .detach();
470
471        self.set_status(Status::Connected { connection_id }, cx);
472
473        let handle_io = cx.background().spawn(handle_io);
474        let this = self.clone();
475        let cx = cx.clone();
476        cx.foreground()
477            .spawn(async move {
478                match handle_io.await {
479                    Ok(()) => this.set_status(Status::SignedOut, &cx),
480                    Err(err) => {
481                        log::error!("connection error: {:?}", err);
482                        this.set_status(Status::ConnectionLost, &cx);
483                    }
484                }
485            })
486            .detach();
487    }
488
489    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
490        if let Some(callback) = self.authenticate.as_ref() {
491            callback(cx)
492        } else {
493            self.authenticate_with_browser(cx)
494        }
495    }
496
497    fn establish_connection(
498        self: &Arc<Self>,
499        credentials: &Credentials,
500        cx: &AsyncAppContext,
501    ) -> Task<Result<Connection, EstablishConnectionError>> {
502        if let Some(callback) = self.establish_connection.as_ref() {
503            callback(credentials, cx)
504        } else {
505            self.establish_websocket_connection(credentials, cx)
506        }
507    }
508
509    fn establish_websocket_connection(
510        self: &Arc<Self>,
511        credentials: &Credentials,
512        cx: &AsyncAppContext,
513    ) -> Task<Result<Connection, EstablishConnectionError>> {
514        let request = Request::builder()
515            .header(
516                "Authorization",
517                format!("{} {}", credentials.user_id, credentials.access_token),
518            )
519            .header("X-Zed-Protocol-Version", rpc::PROTOCOL_VERSION);
520
521        let http = self.http.clone();
522        cx.background().spawn(async move {
523            let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
524            let rpc_request = surf::Request::new(
525                Method::Get,
526                surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
527            );
528            let rpc_response = http.send(rpc_request).await?;
529
530            if rpc_response.status().is_redirection() {
531                rpc_url = rpc_response
532                    .header("Location")
533                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
534                    .as_str()
535                    .to_string();
536            }
537            // Until we switch the zed.dev domain to point to the new Next.js app, there
538            // will be no redirect required, and the app will connect directly to
539            // wss://zed.dev/rpc.
540            else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
541                Err(anyhow!(
542                    "unexpected /rpc response status {}",
543                    rpc_response.status()
544                ))?
545            }
546
547            let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
548            let rpc_host = rpc_url
549                .host_str()
550                .zip(rpc_url.port_or_known_default())
551                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
552            let stream = smol::net::TcpStream::connect(rpc_host).await?;
553
554            log::info!("connected to rpc endpoint {}", rpc_url);
555
556            match rpc_url.scheme() {
557                "https" => {
558                    rpc_url.set_scheme("wss").unwrap();
559                    let request = request.uri(rpc_url.as_str()).body(())?;
560                    let (stream, _) =
561                        async_tungstenite::async_tls::client_async_tls(request, stream).await?;
562                    Ok(Connection::new(stream))
563                }
564                "http" => {
565                    rpc_url.set_scheme("ws").unwrap();
566                    let request = request.uri(rpc_url.as_str()).body(())?;
567                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
568                    Ok(Connection::new(stream))
569                }
570                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
571            }
572        })
573    }
574
575    pub fn authenticate_with_browser(
576        self: &Arc<Self>,
577        cx: &AsyncAppContext,
578    ) -> Task<Result<Credentials>> {
579        let platform = cx.platform();
580        let executor = cx.background();
581        executor.clone().spawn(async move {
582            // Generate a pair of asymmetric encryption keys. The public key will be used by the
583            // zed server to encrypt the user's access token, so that it can'be intercepted by
584            // any other app running on the user's device.
585            let (public_key, private_key) =
586                rpc::auth::keypair().expect("failed to generate keypair for auth");
587            let public_key_string =
588                String::try_from(public_key).expect("failed to serialize public key for auth");
589
590            // Start an HTTP server to receive the redirect from Zed's sign-in page.
591            let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
592            let port = server.server_addr().port();
593
594            // Open the Zed sign-in page in the user's browser, with query parameters that indicate
595            // that the user is signing in from a Zed app running on the same device.
596            let mut url = format!(
597                "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
598                *ZED_SERVER_URL, port, public_key_string
599            );
600
601            if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
602                log::info!("impersonating user @{}", impersonate_login);
603                write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
604            }
605
606            platform.open_url(&url);
607
608            // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
609            // access token from the query params.
610            //
611            // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
612            // custom URL scheme instead of this local HTTP server.
613            let (user_id, access_token) = executor
614                .spawn(async move {
615                    if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
616                        let path = req.url();
617                        let mut user_id = None;
618                        let mut access_token = None;
619                        let url = Url::parse(&format!("http://example.com{}", path))
620                            .context("failed to parse login notification url")?;
621                        for (key, value) in url.query_pairs() {
622                            if key == "access_token" {
623                                access_token = Some(value.to_string());
624                            } else if key == "user_id" {
625                                user_id = Some(value.to_string());
626                            }
627                        }
628
629                        let post_auth_url =
630                            format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
631                        req.respond(
632                            tiny_http::Response::empty(302).with_header(
633                                tiny_http::Header::from_bytes(
634                                    &b"Location"[..],
635                                    post_auth_url.as_bytes(),
636                                )
637                                .unwrap(),
638                            ),
639                        )
640                        .context("failed to respond to login http request")?;
641                        Ok((
642                            user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
643                            access_token
644                                .ok_or_else(|| anyhow!("missing access_token parameter"))?,
645                        ))
646                    } else {
647                        Err(anyhow!("didn't receive login redirect"))
648                    }
649                })
650                .await?;
651
652            let access_token = private_key
653                .decrypt_string(&access_token)
654                .context("failed to decrypt access token")?;
655            platform.activate(true);
656
657            Ok(Credentials {
658                user_id: user_id.parse()?,
659                access_token,
660            })
661        })
662    }
663
664    pub async fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
665        let conn_id = self.connection_id()?;
666        self.peer.disconnect(conn_id).await;
667        self.set_status(Status::SignedOut, cx);
668        Ok(())
669    }
670
671    fn connection_id(&self) -> Result<ConnectionId> {
672        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
673            Ok(connection_id)
674        } else {
675            Err(anyhow!("not connected"))
676        }
677    }
678
679    pub async fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
680        self.peer.send(self.connection_id()?, message).await
681    }
682
683    pub async fn request<T: RequestMessage>(&self, request: T) -> Result<T::Response> {
684        self.peer.request(self.connection_id()?, request).await
685    }
686
687    pub fn respond<T: RequestMessage>(
688        &self,
689        receipt: Receipt<T>,
690        response: T::Response,
691    ) -> impl Future<Output = Result<()>> {
692        self.peer.respond(receipt, response)
693    }
694
695    pub fn respond_with_error<T: RequestMessage>(
696        &self,
697        receipt: Receipt<T>,
698        error: proto::Error,
699    ) -> impl Future<Output = Result<()>> {
700        self.peer.respond_with_error(receipt, error)
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_subscribing_to_entity(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 (mut done_tx1, mut done_rx1) = postage::oneshot::channel();
829        let (mut done_tx2, mut done_rx2) = postage::oneshot::channel();
830        let _subscription1 = model.update(&mut cx, |_, cx| {
831            client.subscribe_to_entity(
832                1,
833                cx,
834                move |_, _: TypedEnvelope<proto::UnshareProject>, _, _| {
835                    postage::sink::Sink::try_send(&mut done_tx1, ()).unwrap();
836                    Ok(())
837                },
838            )
839        });
840        let _subscription2 = model.update(&mut cx, |_, cx| {
841            client.subscribe_to_entity(
842                2,
843                cx,
844                move |_, _: TypedEnvelope<proto::UnshareProject>, _, _| {
845                    postage::sink::Sink::try_send(&mut done_tx2, ()).unwrap();
846                    Ok(())
847                },
848            )
849        });
850
851        // Ensure dropping a subscription for the same entity type still allows receiving of
852        // messages for other entity IDs of the same type.
853        let subscription3 = model.update(&mut cx, |_, cx| {
854            client.subscribe_to_entity(
855                3,
856                cx,
857                move |_, _: TypedEnvelope<proto::UnshareProject>, _, _| Ok(()),
858            )
859        });
860        drop(subscription3);
861
862        server.send(proto::UnshareProject { project_id: 1 }).await;
863        server.send(proto::UnshareProject { project_id: 2 }).await;
864        done_rx1.recv().await.unwrap();
865        done_rx2.recv().await.unwrap();
866    }
867
868    #[gpui::test]
869    async fn test_subscribing_after_dropping_subscription(mut cx: TestAppContext) {
870        cx.foreground().forbid_parking();
871
872        let user_id = 5;
873        let mut client = Client::new(FakeHttpClient::with_404_response());
874        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
875
876        let model = cx.add_model(|_| Model { subscription: None });
877        let (mut done_tx1, _done_rx1) = postage::oneshot::channel();
878        let (mut done_tx2, mut done_rx2) = postage::oneshot::channel();
879        let subscription1 = model.update(&mut cx, |_, cx| {
880            client.subscribe(cx, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
881                postage::sink::Sink::try_send(&mut done_tx1, ()).unwrap();
882                Ok(())
883            })
884        });
885        drop(subscription1);
886        let _subscription2 = model.update(&mut cx, |_, cx| {
887            client.subscribe(cx, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
888                postage::sink::Sink::try_send(&mut done_tx2, ()).unwrap();
889                Ok(())
890            })
891        });
892        server.send(proto::Ping {}).await;
893        done_rx2.recv().await.unwrap();
894    }
895
896    #[gpui::test]
897    async fn test_dropping_subscription_in_handler(mut cx: TestAppContext) {
898        cx.foreground().forbid_parking();
899
900        let user_id = 5;
901        let mut client = Client::new(FakeHttpClient::with_404_response());
902        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
903
904        let model = cx.add_model(|_| Model { subscription: None });
905        let (mut done_tx, mut done_rx) = postage::oneshot::channel();
906        model.update(&mut cx, |model, cx| {
907            model.subscription = Some(client.subscribe(
908                cx,
909                move |model, _: TypedEnvelope<proto::Ping>, _, _| {
910                    model.subscription.take();
911                    postage::sink::Sink::try_send(&mut done_tx, ()).unwrap();
912                    Ok(())
913                },
914            ));
915        });
916        server.send(proto::Ping {}).await;
917        done_rx.recv().await.unwrap();
918    }
919
920    struct Model {
921        subscription: Option<Subscription>,
922    }
923
924    impl Entity for Model {
925        type Event = ();
926    }
927}