user.rs

  1use super::{proto, Client, Status, TypedEnvelope};
  2use anyhow::{anyhow, Context, Result};
  3use collections::{hash_map::Entry, HashMap, HashSet};
  4use feature_flags::FeatureFlagAppExt;
  5use futures::{channel::mpsc, future, AsyncReadExt, Future, StreamExt};
  6use gpui::{AsyncAppContext, EventEmitter, ImageData, Model, ModelContext, Task};
  7use postage::{sink::Sink, watch};
  8use rpc::proto::{RequestMessage, UsersResponse};
  9use std::sync::{Arc, Weak};
 10use text::ReplicaId;
 11use util::http::HttpClient;
 12use util::TryFutureExt as _;
 13
 14pub type UserId = u64;
 15
 16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 17pub struct ParticipantIndex(pub u32);
 18
 19#[derive(Default, Debug)]
 20pub struct User {
 21    pub id: UserId,
 22    pub github_login: String,
 23    pub avatar: Option<Arc<ImageData>>,
 24}
 25
 26#[derive(Clone, Debug, PartialEq, Eq)]
 27pub struct Collaborator {
 28    pub peer_id: proto::PeerId,
 29    pub replica_id: ReplicaId,
 30    pub user_id: UserId,
 31}
 32
 33impl PartialOrd for User {
 34    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
 35        Some(self.cmp(other))
 36    }
 37}
 38
 39impl Ord for User {
 40    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
 41        self.github_login.cmp(&other.github_login)
 42    }
 43}
 44
 45impl PartialEq for User {
 46    fn eq(&self, other: &Self) -> bool {
 47        self.id == other.id && self.github_login == other.github_login
 48    }
 49}
 50
 51impl Eq for User {}
 52
 53#[derive(Debug, PartialEq)]
 54pub struct Contact {
 55    pub user: Arc<User>,
 56    pub online: bool,
 57    pub busy: bool,
 58}
 59
 60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 61pub enum ContactRequestStatus {
 62    None,
 63    RequestSent,
 64    RequestReceived,
 65    RequestAccepted,
 66}
 67
 68pub struct UserStore {
 69    users: HashMap<u64, Arc<User>>,
 70    participant_indices: HashMap<u64, ParticipantIndex>,
 71    update_contacts_tx: mpsc::UnboundedSender<UpdateContacts>,
 72    current_user: watch::Receiver<Option<Arc<User>>>,
 73    contacts: Vec<Arc<Contact>>,
 74    incoming_contact_requests: Vec<Arc<User>>,
 75    outgoing_contact_requests: Vec<Arc<User>>,
 76    pending_contact_requests: HashMap<u64, usize>,
 77    invite_info: Option<InviteInfo>,
 78    client: Weak<Client>,
 79    http: Arc<dyn HttpClient>,
 80    _maintain_contacts: Task<()>,
 81    _maintain_current_user: Task<Result<()>>,
 82}
 83
 84#[derive(Clone)]
 85pub struct InviteInfo {
 86    pub count: u32,
 87    pub url: Arc<str>,
 88}
 89
 90pub enum Event {
 91    Contact {
 92        user: Arc<User>,
 93        kind: ContactEventKind,
 94    },
 95    ShowContacts,
 96    ParticipantIndicesChanged,
 97}
 98
 99#[derive(Clone, Copy)]
100pub enum ContactEventKind {
101    Requested,
102    Accepted,
103    Cancelled,
104}
105
106impl EventEmitter for UserStore {
107    type Event = Event;
108}
109
110enum UpdateContacts {
111    Update(proto::UpdateContacts),
112    Wait(postage::barrier::Sender),
113    Clear(postage::barrier::Sender),
114}
115
116impl UserStore {
117    pub fn new(
118        client: Arc<Client>,
119        http: Arc<dyn HttpClient>,
120        cx: &mut ModelContext<Self>,
121    ) -> Self {
122        let (mut current_user_tx, current_user_rx) = watch::channel();
123        let (update_contacts_tx, mut update_contacts_rx) = mpsc::unbounded();
124        let rpc_subscriptions = vec![
125            client.add_message_handler(cx.weak_model(), Self::handle_update_contacts),
126            client.add_message_handler(cx.weak_model(), Self::handle_update_invite_info),
127            client.add_message_handler(cx.weak_model(), Self::handle_show_contacts),
128        ];
129        Self {
130            users: Default::default(),
131            current_user: current_user_rx,
132            contacts: Default::default(),
133            incoming_contact_requests: Default::default(),
134            participant_indices: Default::default(),
135            outgoing_contact_requests: Default::default(),
136            invite_info: None,
137            client: Arc::downgrade(&client),
138            update_contacts_tx,
139            http,
140            _maintain_contacts: cx.spawn(|this, mut cx| async move {
141                let _subscriptions = rpc_subscriptions;
142                while let Some(message) = update_contacts_rx.next().await {
143                    if let Ok(task) =
144                        this.update(&mut cx, |this, cx| this.update_contacts(message, cx))
145                    {
146                        task.log_err().await;
147                    } else {
148                        break;
149                    }
150                }
151            }),
152            _maintain_current_user: cx.spawn(|this, mut cx| async move {
153                let mut status = client.status();
154                while let Some(status) = status.next().await {
155                    match status {
156                        Status::Connected { .. } => {
157                            if let Some(user_id) = client.user_id() {
158                                let fetch_user = if let Ok(fetch_user) = this
159                                    .update(&mut cx, |this, cx| {
160                                        this.get_user(user_id, cx).log_err()
161                                    }) {
162                                    fetch_user
163                                } else {
164                                    break;
165                                };
166                                let fetch_metrics_id =
167                                    client.request(proto::GetPrivateUserInfo {}).log_err();
168                                let (user, info) = futures::join!(fetch_user, fetch_metrics_id);
169
170                                cx.update(|cx| {
171                                    if let Some(info) = info {
172                                        cx.update_flags(info.staff, info.flags);
173                                        client.telemetry.set_authenticated_user_info(
174                                            Some(info.metrics_id.clone()),
175                                            info.staff,
176                                            cx,
177                                        )
178                                    }
179                                })?;
180
181                                current_user_tx.send(user).await.ok();
182
183                                this.update(&mut cx, |_, cx| cx.notify())?;
184                            }
185                        }
186                        Status::SignedOut => {
187                            current_user_tx.send(None).await.ok();
188                            this.update(&mut cx, |this, cx| {
189                                cx.notify();
190                                this.clear_contacts()
191                            })?
192                            .await;
193                        }
194                        Status::ConnectionLost => {
195                            this.update(&mut cx, |this, cx| {
196                                cx.notify();
197                                this.clear_contacts()
198                            })?
199                            .await;
200                        }
201                        _ => {}
202                    }
203                }
204                Ok(())
205            }),
206            pending_contact_requests: Default::default(),
207        }
208    }
209
210    #[cfg(feature = "test-support")]
211    pub fn clear_cache(&mut self) {
212        self.users.clear();
213    }
214
215    async fn handle_update_invite_info(
216        this: Model<Self>,
217        message: TypedEnvelope<proto::UpdateInviteInfo>,
218        _: Arc<Client>,
219        mut cx: AsyncAppContext,
220    ) -> Result<()> {
221        this.update(&mut cx, |this, cx| {
222            this.invite_info = Some(InviteInfo {
223                url: Arc::from(message.payload.url),
224                count: message.payload.count,
225            });
226            cx.notify();
227        })?;
228        Ok(())
229    }
230
231    async fn handle_show_contacts(
232        this: Model<Self>,
233        _: TypedEnvelope<proto::ShowContacts>,
234        _: Arc<Client>,
235        mut cx: AsyncAppContext,
236    ) -> Result<()> {
237        this.update(&mut cx, |_, cx| cx.emit(Event::ShowContacts))?;
238        Ok(())
239    }
240
241    pub fn invite_info(&self) -> Option<&InviteInfo> {
242        self.invite_info.as_ref()
243    }
244
245    async fn handle_update_contacts(
246        this: Model<Self>,
247        message: TypedEnvelope<proto::UpdateContacts>,
248        _: Arc<Client>,
249        mut cx: AsyncAppContext,
250    ) -> Result<()> {
251        this.update(&mut cx, |this, _| {
252            this.update_contacts_tx
253                .unbounded_send(UpdateContacts::Update(message.payload))
254                .unwrap();
255        })?;
256        Ok(())
257    }
258
259    fn update_contacts(
260        &mut self,
261        message: UpdateContacts,
262        cx: &mut ModelContext<Self>,
263    ) -> Task<Result<()>> {
264        match message {
265            UpdateContacts::Wait(barrier) => {
266                drop(barrier);
267                Task::ready(Ok(()))
268            }
269            UpdateContacts::Clear(barrier) => {
270                self.contacts.clear();
271                self.incoming_contact_requests.clear();
272                self.outgoing_contact_requests.clear();
273                drop(barrier);
274                Task::ready(Ok(()))
275            }
276            UpdateContacts::Update(message) => {
277                let mut user_ids = HashSet::default();
278                for contact in &message.contacts {
279                    user_ids.insert(contact.user_id);
280                }
281                user_ids.extend(message.incoming_requests.iter().map(|req| req.requester_id));
282                user_ids.extend(message.outgoing_requests.iter());
283
284                let load_users = self.get_users(user_ids.into_iter().collect(), cx);
285                cx.spawn(|this, mut cx| async move {
286                    load_users.await?;
287
288                    // Users are fetched in parallel above and cached in call to get_users
289                    // No need to paralellize here
290                    let mut updated_contacts = Vec::new();
291                    let this = this
292                        .upgrade()
293                        .ok_or_else(|| anyhow!("can't upgrade user store handle"))?;
294                    for contact in message.contacts {
295                        updated_contacts.push(Arc::new(
296                            Contact::from_proto(contact, &this, &mut cx).await?,
297                        ));
298                    }
299
300                    let mut incoming_requests = Vec::new();
301                    for request in message.incoming_requests {
302                        incoming_requests.push({
303                            this.update(&mut cx, |this, cx| {
304                                this.get_user(request.requester_id, cx)
305                            })?
306                            .await?
307                        });
308                    }
309
310                    let mut outgoing_requests = Vec::new();
311                    for requested_user_id in message.outgoing_requests {
312                        outgoing_requests.push(
313                            this.update(&mut cx, |this, cx| this.get_user(requested_user_id, cx))?
314                                .await?,
315                        );
316                    }
317
318                    let removed_contacts =
319                        HashSet::<u64>::from_iter(message.remove_contacts.iter().copied());
320                    let removed_incoming_requests =
321                        HashSet::<u64>::from_iter(message.remove_incoming_requests.iter().copied());
322                    let removed_outgoing_requests =
323                        HashSet::<u64>::from_iter(message.remove_outgoing_requests.iter().copied());
324
325                    this.update(&mut cx, |this, cx| {
326                        // Remove contacts
327                        this.contacts
328                            .retain(|contact| !removed_contacts.contains(&contact.user.id));
329                        // Update existing contacts and insert new ones
330                        for updated_contact in updated_contacts {
331                            match this.contacts.binary_search_by_key(
332                                &&updated_contact.user.github_login,
333                                |contact| &contact.user.github_login,
334                            ) {
335                                Ok(ix) => this.contacts[ix] = updated_contact,
336                                Err(ix) => this.contacts.insert(ix, updated_contact),
337                            }
338                        }
339
340                        // Remove incoming contact requests
341                        this.incoming_contact_requests.retain(|user| {
342                            if removed_incoming_requests.contains(&user.id) {
343                                cx.emit(Event::Contact {
344                                    user: user.clone(),
345                                    kind: ContactEventKind::Cancelled,
346                                });
347                                false
348                            } else {
349                                true
350                            }
351                        });
352                        // Update existing incoming requests and insert new ones
353                        for user in incoming_requests {
354                            match this
355                                .incoming_contact_requests
356                                .binary_search_by_key(&&user.github_login, |contact| {
357                                    &contact.github_login
358                                }) {
359                                Ok(ix) => this.incoming_contact_requests[ix] = user,
360                                Err(ix) => this.incoming_contact_requests.insert(ix, user),
361                            }
362                        }
363
364                        // Remove outgoing contact requests
365                        this.outgoing_contact_requests
366                            .retain(|user| !removed_outgoing_requests.contains(&user.id));
367                        // Update existing incoming requests and insert new ones
368                        for request in outgoing_requests {
369                            match this
370                                .outgoing_contact_requests
371                                .binary_search_by_key(&&request.github_login, |contact| {
372                                    &contact.github_login
373                                }) {
374                                Ok(ix) => this.outgoing_contact_requests[ix] = request,
375                                Err(ix) => this.outgoing_contact_requests.insert(ix, request),
376                            }
377                        }
378
379                        cx.notify();
380                    })?;
381
382                    Ok(())
383                })
384            }
385        }
386    }
387
388    pub fn contacts(&self) -> &[Arc<Contact>] {
389        &self.contacts
390    }
391
392    pub fn has_contact(&self, user: &Arc<User>) -> bool {
393        self.contacts
394            .binary_search_by_key(&&user.github_login, |contact| &contact.user.github_login)
395            .is_ok()
396    }
397
398    pub fn incoming_contact_requests(&self) -> &[Arc<User>] {
399        &self.incoming_contact_requests
400    }
401
402    pub fn outgoing_contact_requests(&self) -> &[Arc<User>] {
403        &self.outgoing_contact_requests
404    }
405
406    pub fn is_contact_request_pending(&self, user: &User) -> bool {
407        self.pending_contact_requests.contains_key(&user.id)
408    }
409
410    pub fn contact_request_status(&self, user: &User) -> ContactRequestStatus {
411        if self
412            .contacts
413            .binary_search_by_key(&&user.github_login, |contact| &contact.user.github_login)
414            .is_ok()
415        {
416            ContactRequestStatus::RequestAccepted
417        } else if self
418            .outgoing_contact_requests
419            .binary_search_by_key(&&user.github_login, |user| &user.github_login)
420            .is_ok()
421        {
422            ContactRequestStatus::RequestSent
423        } else if self
424            .incoming_contact_requests
425            .binary_search_by_key(&&user.github_login, |user| &user.github_login)
426            .is_ok()
427        {
428            ContactRequestStatus::RequestReceived
429        } else {
430            ContactRequestStatus::None
431        }
432    }
433
434    pub fn request_contact(
435        &mut self,
436        responder_id: u64,
437        cx: &mut ModelContext<Self>,
438    ) -> Task<Result<()>> {
439        self.perform_contact_request(responder_id, proto::RequestContact { responder_id }, cx)
440    }
441
442    pub fn remove_contact(
443        &mut self,
444        user_id: u64,
445        cx: &mut ModelContext<Self>,
446    ) -> Task<Result<()>> {
447        self.perform_contact_request(user_id, proto::RemoveContact { user_id }, cx)
448    }
449
450    pub fn respond_to_contact_request(
451        &mut self,
452        requester_id: u64,
453        accept: bool,
454        cx: &mut ModelContext<Self>,
455    ) -> Task<Result<()>> {
456        self.perform_contact_request(
457            requester_id,
458            proto::RespondToContactRequest {
459                requester_id,
460                response: if accept {
461                    proto::ContactRequestResponse::Accept
462                } else {
463                    proto::ContactRequestResponse::Decline
464                } as i32,
465            },
466            cx,
467        )
468    }
469
470    pub fn dismiss_contact_request(
471        &mut self,
472        requester_id: u64,
473        cx: &mut ModelContext<Self>,
474    ) -> Task<Result<()>> {
475        let client = self.client.upgrade();
476        cx.spawn(move |_, _| async move {
477            client
478                .ok_or_else(|| anyhow!("can't upgrade client reference"))?
479                .request(proto::RespondToContactRequest {
480                    requester_id,
481                    response: proto::ContactRequestResponse::Dismiss as i32,
482                })
483                .await?;
484            Ok(())
485        })
486    }
487
488    fn perform_contact_request<T: RequestMessage>(
489        &mut self,
490        user_id: u64,
491        request: T,
492        cx: &mut ModelContext<Self>,
493    ) -> Task<Result<()>> {
494        let client = self.client.upgrade();
495        *self.pending_contact_requests.entry(user_id).or_insert(0) += 1;
496        cx.notify();
497
498        cx.spawn(move |this, mut cx| async move {
499            let response = client
500                .ok_or_else(|| anyhow!("can't upgrade client reference"))?
501                .request(request)
502                .await;
503            this.update(&mut cx, |this, cx| {
504                if let Entry::Occupied(mut request_count) =
505                    this.pending_contact_requests.entry(user_id)
506                {
507                    *request_count.get_mut() -= 1;
508                    if *request_count.get() == 0 {
509                        request_count.remove();
510                    }
511                }
512                cx.notify();
513            })?;
514            response?;
515            Ok(())
516        })
517    }
518
519    pub fn clear_contacts(&mut self) -> impl Future<Output = ()> {
520        let (tx, mut rx) = postage::barrier::channel();
521        self.update_contacts_tx
522            .unbounded_send(UpdateContacts::Clear(tx))
523            .unwrap();
524        async move {
525            rx.next().await;
526        }
527    }
528
529    pub fn contact_updates_done(&mut self) -> impl Future<Output = ()> {
530        let (tx, mut rx) = postage::barrier::channel();
531        self.update_contacts_tx
532            .unbounded_send(UpdateContacts::Wait(tx))
533            .unwrap();
534        async move {
535            rx.next().await;
536        }
537    }
538
539    pub fn get_users(
540        &mut self,
541        user_ids: Vec<u64>,
542        cx: &mut ModelContext<Self>,
543    ) -> Task<Result<Vec<Arc<User>>>> {
544        let mut user_ids_to_fetch = user_ids.clone();
545        user_ids_to_fetch.retain(|id| !self.users.contains_key(id));
546
547        cx.spawn(|this, mut cx| async move {
548            if !user_ids_to_fetch.is_empty() {
549                this.update(&mut cx, |this, cx| {
550                    this.load_users(
551                        proto::GetUsers {
552                            user_ids: user_ids_to_fetch,
553                        },
554                        cx,
555                    )
556                })?
557                .await?;
558            }
559
560            this.update(&mut cx, |this, _| {
561                user_ids
562                    .iter()
563                    .map(|user_id| {
564                        this.users
565                            .get(user_id)
566                            .cloned()
567                            .ok_or_else(|| anyhow!("user {} not found", user_id))
568                    })
569                    .collect()
570            })?
571        })
572    }
573
574    pub fn fuzzy_search_users(
575        &mut self,
576        query: String,
577        cx: &mut ModelContext<Self>,
578    ) -> Task<Result<Vec<Arc<User>>>> {
579        self.load_users(proto::FuzzySearchUsers { query }, cx)
580    }
581
582    pub fn get_cached_user(&self, user_id: u64) -> Option<Arc<User>> {
583        self.users.get(&user_id).cloned()
584    }
585
586    pub fn get_user(
587        &mut self,
588        user_id: u64,
589        cx: &mut ModelContext<Self>,
590    ) -> Task<Result<Arc<User>>> {
591        if let Some(user) = self.users.get(&user_id).cloned() {
592            return Task::ready(Ok(user));
593        }
594
595        let load_users = self.get_users(vec![user_id], cx);
596        cx.spawn(move |this, mut cx| async move {
597            load_users.await?;
598            this.update(&mut cx, |this, _| {
599                this.users
600                    .get(&user_id)
601                    .cloned()
602                    .ok_or_else(|| anyhow!("server responded with no users"))
603            })?
604        })
605    }
606
607    pub fn current_user(&self) -> Option<Arc<User>> {
608        self.current_user.borrow().clone()
609    }
610
611    pub fn watch_current_user(&self) -> watch::Receiver<Option<Arc<User>>> {
612        self.current_user.clone()
613    }
614
615    fn load_users(
616        &mut self,
617        request: impl RequestMessage<Response = UsersResponse>,
618        cx: &mut ModelContext<Self>,
619    ) -> Task<Result<Vec<Arc<User>>>> {
620        let client = self.client.clone();
621        let http = self.http.clone();
622        cx.spawn(|this, mut cx| async move {
623            if let Some(rpc) = client.upgrade() {
624                let response = rpc.request(request).await.context("error loading users")?;
625                let users = future::join_all(
626                    response
627                        .users
628                        .into_iter()
629                        .map(|user| User::new(user, http.as_ref())),
630                )
631                .await;
632
633                this.update(&mut cx, |this, _| {
634                    for user in &users {
635                        this.users.insert(user.id, user.clone());
636                    }
637                })
638                .ok();
639
640                Ok(users)
641            } else {
642                Ok(Vec::new())
643            }
644        })
645    }
646
647    pub fn set_participant_indices(
648        &mut self,
649        participant_indices: HashMap<u64, ParticipantIndex>,
650        cx: &mut ModelContext<Self>,
651    ) {
652        if participant_indices != self.participant_indices {
653            self.participant_indices = participant_indices;
654            cx.emit(Event::ParticipantIndicesChanged);
655        }
656    }
657
658    pub fn participant_indices(&self) -> &HashMap<u64, ParticipantIndex> {
659        &self.participant_indices
660    }
661}
662
663impl User {
664    async fn new(message: proto::User, http: &dyn HttpClient) -> Arc<Self> {
665        Arc::new(User {
666            id: message.id,
667            github_login: message.github_login,
668            avatar: fetch_avatar(http, &message.avatar_url).warn_on_err().await,
669        })
670    }
671}
672
673impl Contact {
674    async fn from_proto(
675        contact: proto::Contact,
676        user_store: &Model<UserStore>,
677        cx: &mut AsyncAppContext,
678    ) -> Result<Self> {
679        let user = user_store
680            .update(cx, |user_store, cx| {
681                user_store.get_user(contact.user_id, cx)
682            })?
683            .await?;
684        Ok(Self {
685            user,
686            online: contact.online,
687            busy: contact.busy,
688        })
689    }
690}
691
692impl Collaborator {
693    pub fn from_proto(message: proto::Collaborator) -> Result<Self> {
694        Ok(Self {
695            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
696            replica_id: message.replica_id as ReplicaId,
697            user_id: message.user_id as UserId,
698        })
699    }
700}
701
702// todo!("we probably don't need this now that we fetch")
703async fn fetch_avatar(http: &dyn HttpClient, url: &str) -> Result<Arc<ImageData>> {
704    let mut response = http
705        .get(url, Default::default(), true)
706        .await
707        .map_err(|e| anyhow!("failed to send user avatar request: {}", e))?;
708
709    if !response.status().is_success() {
710        return Err(anyhow!("avatar request failed {:?}", response.status()));
711    }
712
713    let mut body = Vec::new();
714    response
715        .body_mut()
716        .read_to_end(&mut body)
717        .await
718        .map_err(|e| anyhow!("failed to read user avatar response body: {}", e))?;
719    let format = image::guess_format(&body)?;
720    let image = image::load_from_memory_with_format(&body, format)?.into_bgra8();
721    Ok(Arc::new(ImageData::new(image)))
722}