channel_store.rs

   1mod channel_index;
   2
   3use crate::{ChannelMessage, channel_buffer::ChannelBuffer, channel_chat::ChannelChat};
   4use anyhow::{Context as _, Result, anyhow};
   5use channel_index::ChannelIndex;
   6use client::{ChannelId, Client, ClientSettings, Subscription, User, UserId, UserStore};
   7use collections::{HashMap, HashSet};
   8use futures::{Future, FutureExt, StreamExt, channel::mpsc, future::Shared};
   9use gpui::{
  10    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, SharedString, Task,
  11    WeakEntity,
  12};
  13use language::Capability;
  14use postage::{sink::Sink, watch};
  15use rpc::{
  16    TypedEnvelope,
  17    proto::{self, ChannelRole, ChannelVisibility},
  18};
  19use settings::Settings;
  20use std::{mem, sync::Arc, time::Duration};
  21use util::{ResultExt, maybe};
  22
  23pub const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30);
  24
  25pub fn init(client: &Arc<Client>, user_store: Entity<UserStore>, cx: &mut App) {
  26    let channel_store = cx.new(|cx| ChannelStore::new(client.clone(), user_store.clone(), cx));
  27    cx.set_global(GlobalChannelStore(channel_store));
  28}
  29
  30#[derive(Debug, Clone, Default, PartialEq)]
  31struct NotesVersion {
  32    epoch: u64,
  33    version: clock::Global,
  34}
  35
  36pub struct ChannelStore {
  37    pub channel_index: ChannelIndex,
  38    channel_invitations: Vec<Arc<Channel>>,
  39    channel_participants: HashMap<ChannelId, Vec<Arc<User>>>,
  40    channel_states: HashMap<ChannelId, ChannelState>,
  41    outgoing_invites: HashSet<(ChannelId, UserId)>,
  42    update_channels_tx: mpsc::UnboundedSender<proto::UpdateChannels>,
  43    opened_buffers: HashMap<ChannelId, OpenEntityHandle<ChannelBuffer>>,
  44    opened_chats: HashMap<ChannelId, OpenEntityHandle<ChannelChat>>,
  45    client: Arc<Client>,
  46    did_subscribe: bool,
  47    channels_loaded: (watch::Sender<bool>, watch::Receiver<bool>),
  48    user_store: Entity<UserStore>,
  49    _rpc_subscriptions: [Subscription; 2],
  50    _watch_connection_status: Task<Option<()>>,
  51    disconnect_channel_buffers_task: Option<Task<()>>,
  52    _update_channels: Task<()>,
  53}
  54
  55#[derive(Clone, Debug)]
  56pub struct Channel {
  57    pub id: ChannelId,
  58    pub name: SharedString,
  59    pub visibility: proto::ChannelVisibility,
  60    pub parent_path: Vec<ChannelId>,
  61    pub channel_order: i32,
  62}
  63
  64#[derive(Default, Debug)]
  65pub struct ChannelState {
  66    latest_chat_message: Option<u64>,
  67    latest_notes_version: NotesVersion,
  68    observed_notes_version: NotesVersion,
  69    observed_chat_message: Option<u64>,
  70    role: Option<ChannelRole>,
  71}
  72
  73impl Channel {
  74    pub fn link(&self, cx: &App) -> String {
  75        format!(
  76            "{}/channel/{}-{}",
  77            ClientSettings::get_global(cx).server_url,
  78            Self::slug(&self.name),
  79            self.id
  80        )
  81    }
  82
  83    pub fn notes_link(&self, heading: Option<String>, cx: &App) -> String {
  84        self.link(cx)
  85            + "/notes"
  86            + &heading
  87                .map(|h| format!("#{}", Self::slug(&h)))
  88                .unwrap_or_default()
  89    }
  90
  91    pub fn is_root_channel(&self) -> bool {
  92        self.parent_path.is_empty()
  93    }
  94
  95    pub fn root_id(&self) -> ChannelId {
  96        self.parent_path.first().copied().unwrap_or(self.id)
  97    }
  98
  99    pub fn slug(str: &str) -> String {
 100        let slug: String = str
 101            .chars()
 102            .map(|c| if c.is_alphanumeric() { c } else { '-' })
 103            .collect();
 104
 105        slug.trim_matches(|c| c == '-').to_string()
 106    }
 107}
 108
 109#[derive(Debug)]
 110pub struct ChannelMembership {
 111    pub user: Arc<User>,
 112    pub kind: proto::channel_member::Kind,
 113    pub role: proto::ChannelRole,
 114}
 115impl ChannelMembership {
 116    pub fn sort_key(&self) -> MembershipSortKey<'_> {
 117        MembershipSortKey {
 118            role_order: match self.role {
 119                proto::ChannelRole::Admin => 0,
 120                proto::ChannelRole::Member => 1,
 121                proto::ChannelRole::Banned => 2,
 122                proto::ChannelRole::Talker => 3,
 123                proto::ChannelRole::Guest => 4,
 124            },
 125            kind_order: match self.kind {
 126                proto::channel_member::Kind::Member => 0,
 127                proto::channel_member::Kind::Invitee => 1,
 128            },
 129            username_order: &self.user.github_login,
 130        }
 131    }
 132}
 133
 134#[derive(PartialOrd, Ord, PartialEq, Eq)]
 135pub struct MembershipSortKey<'a> {
 136    role_order: u8,
 137    kind_order: u8,
 138    username_order: &'a str,
 139}
 140
 141pub enum ChannelEvent {
 142    ChannelCreated(ChannelId),
 143    ChannelRenamed(ChannelId),
 144}
 145
 146impl EventEmitter<ChannelEvent> for ChannelStore {}
 147
 148enum OpenEntityHandle<E> {
 149    Open(WeakEntity<E>),
 150    Loading(Shared<Task<Result<Entity<E>, Arc<anyhow::Error>>>>),
 151}
 152
 153struct GlobalChannelStore(Entity<ChannelStore>);
 154
 155impl Global for GlobalChannelStore {}
 156
 157impl ChannelStore {
 158    pub fn global(cx: &App) -> Entity<Self> {
 159        cx.global::<GlobalChannelStore>().0.clone()
 160    }
 161
 162    pub fn new(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut Context<Self>) -> Self {
 163        let rpc_subscriptions = [
 164            client.add_message_handler(cx.weak_entity(), Self::handle_update_channels),
 165            client.add_message_handler(cx.weak_entity(), Self::handle_update_user_channels),
 166        ];
 167
 168        let mut connection_status = client.status();
 169        let (update_channels_tx, mut update_channels_rx) = mpsc::unbounded();
 170        let watch_connection_status = cx.spawn(async move |this, cx| {
 171            while let Some(status) = connection_status.next().await {
 172                let this = this.upgrade()?;
 173                match status {
 174                    client::Status::Connected { .. } => {
 175                        this.update(cx, |this, cx| this.handle_connect(cx))
 176                            .ok()?
 177                            .await
 178                            .log_err()?;
 179                    }
 180                    client::Status::SignedOut | client::Status::UpgradeRequired => {
 181                        this.update(cx, |this, cx| this.handle_disconnect(false, cx))
 182                            .ok();
 183                    }
 184                    _ => {
 185                        this.update(cx, |this, cx| this.handle_disconnect(true, cx))
 186                            .ok();
 187                    }
 188                }
 189            }
 190            Some(())
 191        });
 192
 193        Self {
 194            channel_invitations: Vec::default(),
 195            channel_index: ChannelIndex::default(),
 196            channel_participants: Default::default(),
 197            outgoing_invites: Default::default(),
 198            opened_buffers: Default::default(),
 199            opened_chats: Default::default(),
 200            update_channels_tx,
 201            client,
 202            user_store,
 203            _rpc_subscriptions: rpc_subscriptions,
 204            _watch_connection_status: watch_connection_status,
 205            disconnect_channel_buffers_task: None,
 206            _update_channels: cx.spawn(async move |this, cx| {
 207                maybe!(async move {
 208                    while let Some(update_channels) = update_channels_rx.next().await {
 209                        if let Some(this) = this.upgrade() {
 210                            let update_task = this
 211                                .update(cx, |this, cx| this.update_channels(update_channels, cx))?;
 212                            if let Some(update_task) = update_task {
 213                                update_task.await.log_err();
 214                            }
 215                        }
 216                    }
 217                    anyhow::Ok(())
 218                })
 219                .await
 220                .log_err();
 221            }),
 222            channel_states: Default::default(),
 223            did_subscribe: false,
 224            channels_loaded: watch::channel_with(false),
 225        }
 226    }
 227
 228    pub fn initialize(&mut self) {
 229        if !self.did_subscribe
 230            && self
 231                .client
 232                .send(proto::SubscribeToChannels {})
 233                .log_err()
 234                .is_some()
 235        {
 236            self.did_subscribe = true;
 237        }
 238    }
 239
 240    pub fn wait_for_channels(
 241        &mut self,
 242        timeout: Duration,
 243        cx: &mut Context<Self>,
 244    ) -> Task<Result<()>> {
 245        let mut channels_loaded_rx = self.channels_loaded.1.clone();
 246        if *channels_loaded_rx.borrow() {
 247            return Task::ready(Ok(()));
 248        }
 249
 250        let mut status_receiver = self.client.status();
 251        if status_receiver.borrow().is_connected() {
 252            self.initialize();
 253        }
 254
 255        let mut timer = cx.background_executor().timer(timeout).fuse();
 256        cx.spawn(async move |this, cx| {
 257            loop {
 258                futures::select_biased! {
 259                    channels_loaded = channels_loaded_rx.next().fuse() => {
 260                        if let Some(true) = channels_loaded {
 261                            return Ok(());
 262                        }
 263                    }
 264                    status = status_receiver.next().fuse() => {
 265                        if let Some(status) = status
 266                            && status.is_connected() {
 267                                this.update(cx, |this, _cx| {
 268                                    this.initialize();
 269                                }).ok();
 270                            }
 271                        continue;
 272                    }
 273                    _ = timer => {
 274                        return Err(anyhow!("{:?} elapsed without receiving channels", timeout));
 275                    }
 276                }
 277            }
 278        })
 279    }
 280
 281    pub fn client(&self) -> Arc<Client> {
 282        self.client.clone()
 283    }
 284
 285    /// Returns the number of unique channels in the store
 286    pub fn channel_count(&self) -> usize {
 287        self.channel_index.by_id().len()
 288    }
 289
 290    /// Returns the index of a channel ID in the list of unique channels
 291    pub fn index_of_channel(&self, channel_id: ChannelId) -> Option<usize> {
 292        self.channel_index
 293            .by_id()
 294            .keys()
 295            .position(|id| *id == channel_id)
 296    }
 297
 298    /// Returns an iterator over all unique channels
 299    pub fn channels(&self) -> impl '_ + Iterator<Item = &Arc<Channel>> {
 300        self.channel_index.by_id().values()
 301    }
 302
 303    /// Iterate over all entries in the channel DAG
 304    pub fn ordered_channels(&self) -> impl '_ + Iterator<Item = (usize, &Arc<Channel>)> {
 305        self.channel_index
 306            .ordered_channels()
 307            .iter()
 308            .filter_map(move |id| {
 309                let channel = self.channel_index.by_id().get(id)?;
 310                Some((channel.parent_path.len(), channel))
 311            })
 312    }
 313
 314    pub fn channel_at_index(&self, ix: usize) -> Option<&Arc<Channel>> {
 315        let channel_id = self.channel_index.ordered_channels().get(ix)?;
 316        self.channel_index.by_id().get(channel_id)
 317    }
 318
 319    pub fn channel_at(&self, ix: usize) -> Option<&Arc<Channel>> {
 320        self.channel_index.by_id().values().nth(ix)
 321    }
 322
 323    pub fn has_channel_invitation(&self, channel_id: ChannelId) -> bool {
 324        self.channel_invitations
 325            .iter()
 326            .any(|channel| channel.id == channel_id)
 327    }
 328
 329    pub fn channel_invitations(&self) -> &[Arc<Channel>] {
 330        &self.channel_invitations
 331    }
 332
 333    pub fn channel_for_id(&self, channel_id: ChannelId) -> Option<&Arc<Channel>> {
 334        self.channel_index.by_id().get(&channel_id)
 335    }
 336
 337    pub fn has_open_channel_buffer(&self, channel_id: ChannelId, _cx: &App) -> bool {
 338        if let Some(buffer) = self.opened_buffers.get(&channel_id)
 339            && let OpenEntityHandle::Open(buffer) = buffer {
 340                return buffer.upgrade().is_some();
 341            }
 342        false
 343    }
 344
 345    pub fn open_channel_buffer(
 346        &mut self,
 347        channel_id: ChannelId,
 348        cx: &mut Context<Self>,
 349    ) -> Task<Result<Entity<ChannelBuffer>>> {
 350        let client = self.client.clone();
 351        let user_store = self.user_store.clone();
 352        let channel_store = cx.entity();
 353        self.open_channel_resource(
 354            channel_id,
 355            "notes",
 356            |this| &mut this.opened_buffers,
 357            async move |channel, cx| {
 358                ChannelBuffer::new(channel, client, user_store, channel_store, cx).await
 359            },
 360            cx,
 361        )
 362    }
 363
 364    pub fn fetch_channel_messages(
 365        &self,
 366        message_ids: Vec<u64>,
 367        cx: &mut Context<Self>,
 368    ) -> Task<Result<Vec<ChannelMessage>>> {
 369        let request = if message_ids.is_empty() {
 370            None
 371        } else {
 372            Some(
 373                self.client
 374                    .request(proto::GetChannelMessagesById { message_ids }),
 375            )
 376        };
 377        cx.spawn(async move |this, cx| {
 378            if let Some(request) = request {
 379                let response = request.await?;
 380                let this = this.upgrade().context("channel store dropped")?;
 381                let user_store = this.read_with(cx, |this, _| this.user_store.clone())?;
 382                ChannelMessage::from_proto_vec(response.messages, &user_store, cx).await
 383            } else {
 384                Ok(Vec::new())
 385            }
 386        })
 387    }
 388
 389    pub fn has_channel_buffer_changed(&self, channel_id: ChannelId) -> bool {
 390        self.channel_states
 391            .get(&channel_id)
 392            .is_some_and(|state| state.has_channel_buffer_changed())
 393    }
 394
 395    pub fn has_new_messages(&self, channel_id: ChannelId) -> bool {
 396        self.channel_states
 397            .get(&channel_id)
 398            .is_some_and(|state| state.has_new_messages())
 399    }
 400
 401    pub fn set_acknowledged_message_id(&mut self, channel_id: ChannelId, message_id: Option<u64>) {
 402        if let Some(state) = self.channel_states.get_mut(&channel_id) {
 403            state.latest_chat_message = message_id;
 404        }
 405    }
 406
 407    pub fn last_acknowledge_message_id(&self, channel_id: ChannelId) -> Option<u64> {
 408        self.channel_states.get(&channel_id).and_then(|state| {
 409            if let Some(last_message_id) = state.latest_chat_message
 410                && state
 411                    .last_acknowledged_message_id()
 412                    .is_some_and(|id| id < last_message_id)
 413                {
 414                    return state.last_acknowledged_message_id();
 415                }
 416
 417            None
 418        })
 419    }
 420
 421    pub fn acknowledge_message_id(
 422        &mut self,
 423        channel_id: ChannelId,
 424        message_id: u64,
 425        cx: &mut Context<Self>,
 426    ) {
 427        self.channel_states
 428            .entry(channel_id)
 429            .or_default()
 430            .acknowledge_message_id(message_id);
 431        cx.notify();
 432    }
 433
 434    pub fn update_latest_message_id(
 435        &mut self,
 436        channel_id: ChannelId,
 437        message_id: u64,
 438        cx: &mut Context<Self>,
 439    ) {
 440        self.channel_states
 441            .entry(channel_id)
 442            .or_default()
 443            .update_latest_message_id(message_id);
 444        cx.notify();
 445    }
 446
 447    pub fn acknowledge_notes_version(
 448        &mut self,
 449        channel_id: ChannelId,
 450        epoch: u64,
 451        version: &clock::Global,
 452        cx: &mut Context<Self>,
 453    ) {
 454        self.channel_states
 455            .entry(channel_id)
 456            .or_default()
 457            .acknowledge_notes_version(epoch, version);
 458        cx.notify()
 459    }
 460
 461    pub fn update_latest_notes_version(
 462        &mut self,
 463        channel_id: ChannelId,
 464        epoch: u64,
 465        version: &clock::Global,
 466        cx: &mut Context<Self>,
 467    ) {
 468        self.channel_states
 469            .entry(channel_id)
 470            .or_default()
 471            .update_latest_notes_version(epoch, version);
 472        cx.notify()
 473    }
 474
 475    pub fn open_channel_chat(
 476        &mut self,
 477        channel_id: ChannelId,
 478        cx: &mut Context<Self>,
 479    ) -> Task<Result<Entity<ChannelChat>>> {
 480        let client = self.client.clone();
 481        let user_store = self.user_store.clone();
 482        let this = cx.entity();
 483        self.open_channel_resource(
 484            channel_id,
 485            "chat",
 486            |this| &mut this.opened_chats,
 487            async move |channel, cx| ChannelChat::new(channel, this, user_store, client, cx).await,
 488            cx,
 489        )
 490    }
 491
 492    /// Asynchronously open a given resource associated with a channel.
 493    ///
 494    /// Make sure that the resource is only opened once, even if this method
 495    /// is called multiple times with the same channel id while the first task
 496    /// is still running.
 497    fn open_channel_resource<T, F>(
 498        &mut self,
 499        channel_id: ChannelId,
 500        resource_name: &'static str,
 501        get_map: fn(&mut Self) -> &mut HashMap<ChannelId, OpenEntityHandle<T>>,
 502        load: F,
 503        cx: &mut Context<Self>,
 504    ) -> Task<Result<Entity<T>>>
 505    where
 506        F: AsyncFnOnce(Arc<Channel>, &mut AsyncApp) -> Result<Entity<T>> + 'static,
 507        T: 'static,
 508    {
 509        let task = loop {
 510            match get_map(self).get(&channel_id) {
 511                Some(OpenEntityHandle::Open(entity)) => {
 512                    if let Some(entity) = entity.upgrade() {
 513                        break Task::ready(Ok(entity)).shared();
 514                    } else {
 515                        get_map(self).remove(&channel_id);
 516                        continue;
 517                    }
 518                }
 519                Some(OpenEntityHandle::Loading(task)) => break task.clone(),
 520                None => {}
 521            }
 522
 523            let channels_ready = self.wait_for_channels(Duration::from_secs(10), cx);
 524            let task = cx
 525                .spawn(async move |this, cx| {
 526                    channels_ready.await?;
 527                    let channel = this.read_with(cx, |this, _| {
 528                        this.channel_for_id(channel_id)
 529                            .cloned()
 530                            .ok_or_else(|| Arc::new(anyhow!("no channel for id: {channel_id}")))
 531                    })??;
 532
 533                    load(channel, cx).await.map_err(Arc::new)
 534                })
 535                .shared();
 536
 537            get_map(self).insert(channel_id, OpenEntityHandle::Loading(task.clone()));
 538            let task = cx.spawn({
 539                async move |this, cx| {
 540                    let result = task.await;
 541                    this.update(cx, |this, _| match &result {
 542                        Ok(model) => {
 543                            get_map(this)
 544                                .insert(channel_id, OpenEntityHandle::Open(model.downgrade()));
 545                        }
 546                        Err(_) => {
 547                            get_map(this).remove(&channel_id);
 548                        }
 549                    })?;
 550                    result
 551                }
 552            });
 553            break task.shared();
 554        };
 555        cx.background_spawn(async move {
 556            task.await.map_err(|error| {
 557                anyhow!("{error}").context(format!("failed to open channel {resource_name}"))
 558            })
 559        })
 560    }
 561
 562    pub fn is_channel_admin(&self, channel_id: ChannelId) -> bool {
 563        self.channel_role(channel_id) == proto::ChannelRole::Admin
 564    }
 565
 566    pub fn is_root_channel(&self, channel_id: ChannelId) -> bool {
 567        self.channel_index
 568            .by_id()
 569            .get(&channel_id)
 570            .map_or(false, |channel| channel.is_root_channel())
 571    }
 572
 573    pub fn is_public_channel(&self, channel_id: ChannelId) -> bool {
 574        self.channel_index
 575            .by_id()
 576            .get(&channel_id)
 577            .map_or(false, |channel| {
 578                channel.visibility == ChannelVisibility::Public
 579            })
 580    }
 581
 582    pub fn channel_capability(&self, channel_id: ChannelId) -> Capability {
 583        match self.channel_role(channel_id) {
 584            ChannelRole::Admin | ChannelRole::Member => Capability::ReadWrite,
 585            _ => Capability::ReadOnly,
 586        }
 587    }
 588
 589    pub fn channel_role(&self, channel_id: ChannelId) -> proto::ChannelRole {
 590        maybe!({
 591            let mut channel = self.channel_for_id(channel_id)?;
 592            if !channel.is_root_channel() {
 593                channel = self.channel_for_id(channel.root_id())?;
 594            }
 595            let root_channel_state = self.channel_states.get(&channel.id);
 596            root_channel_state?.role
 597        })
 598        .unwrap_or(proto::ChannelRole::Guest)
 599    }
 600
 601    pub fn channel_participants(&self, channel_id: ChannelId) -> &[Arc<User>] {
 602        self.channel_participants
 603            .get(&channel_id)
 604            .map_or(&[], |v| v.as_slice())
 605    }
 606
 607    pub fn create_channel(
 608        &self,
 609        name: &str,
 610        parent_id: Option<ChannelId>,
 611        cx: &mut Context<Self>,
 612    ) -> Task<Result<ChannelId>> {
 613        let client = self.client.clone();
 614        let name = name.trim_start_matches('#').to_owned();
 615        cx.spawn(async move |this, cx| {
 616            let response = client
 617                .request(proto::CreateChannel {
 618                    name,
 619                    parent_id: parent_id.map(|cid| cid.0),
 620                })
 621                .await?;
 622
 623            let channel = response.channel.context("missing channel in response")?;
 624            let channel_id = ChannelId(channel.id);
 625
 626            this.update(cx, |this, cx| {
 627                let task = this.update_channels(
 628                    proto::UpdateChannels {
 629                        channels: vec![channel],
 630                        ..Default::default()
 631                    },
 632                    cx,
 633                );
 634                assert!(task.is_none());
 635
 636                // This event is emitted because the collab panel wants to clear the pending edit state
 637                // before this frame is rendered. But we can't guarantee that the collab panel's future
 638                // will resolve before this flush_effects finishes. Synchronously emitting this event
 639                // ensures that the collab panel will observe this creation before the frame completes
 640                cx.emit(ChannelEvent::ChannelCreated(channel_id));
 641            })?;
 642
 643            Ok(channel_id)
 644        })
 645    }
 646
 647    pub fn move_channel(
 648        &mut self,
 649        channel_id: ChannelId,
 650        to: ChannelId,
 651        cx: &mut Context<Self>,
 652    ) -> Task<Result<()>> {
 653        let client = self.client.clone();
 654        cx.spawn(async move |_, _| {
 655            let _ = client
 656                .request(proto::MoveChannel {
 657                    channel_id: channel_id.0,
 658                    to: to.0,
 659                })
 660                .await?;
 661            Ok(())
 662        })
 663    }
 664
 665    pub fn reorder_channel(
 666        &mut self,
 667        channel_id: ChannelId,
 668        direction: proto::reorder_channel::Direction,
 669        cx: &mut Context<Self>,
 670    ) -> Task<Result<()>> {
 671        let client = self.client.clone();
 672        cx.spawn(async move |_, _| {
 673            client
 674                .request(proto::ReorderChannel {
 675                    channel_id: channel_id.0,
 676                    direction: direction.into(),
 677                })
 678                .await?;
 679            Ok(())
 680        })
 681    }
 682
 683    pub fn set_channel_visibility(
 684        &mut self,
 685        channel_id: ChannelId,
 686        visibility: ChannelVisibility,
 687        cx: &mut Context<Self>,
 688    ) -> Task<Result<()>> {
 689        let client = self.client.clone();
 690        cx.spawn(async move |_, _| {
 691            let _ = client
 692                .request(proto::SetChannelVisibility {
 693                    channel_id: channel_id.0,
 694                    visibility: visibility.into(),
 695                })
 696                .await?;
 697
 698            Ok(())
 699        })
 700    }
 701
 702    pub fn invite_member(
 703        &mut self,
 704        channel_id: ChannelId,
 705        user_id: UserId,
 706        role: proto::ChannelRole,
 707        cx: &mut Context<Self>,
 708    ) -> Task<Result<()>> {
 709        if !self.outgoing_invites.insert((channel_id, user_id)) {
 710            return Task::ready(Err(anyhow!("invite request already in progress")));
 711        }
 712
 713        cx.notify();
 714        let client = self.client.clone();
 715        cx.spawn(async move |this, cx| {
 716            let result = client
 717                .request(proto::InviteChannelMember {
 718                    channel_id: channel_id.0,
 719                    user_id,
 720                    role: role.into(),
 721                })
 722                .await;
 723
 724            this.update(cx, |this, cx| {
 725                this.outgoing_invites.remove(&(channel_id, user_id));
 726                cx.notify();
 727            })?;
 728
 729            result?;
 730
 731            Ok(())
 732        })
 733    }
 734
 735    pub fn remove_member(
 736        &mut self,
 737        channel_id: ChannelId,
 738        user_id: u64,
 739        cx: &mut Context<Self>,
 740    ) -> Task<Result<()>> {
 741        if !self.outgoing_invites.insert((channel_id, user_id)) {
 742            return Task::ready(Err(anyhow!("invite request already in progress")));
 743        }
 744
 745        cx.notify();
 746        let client = self.client.clone();
 747        cx.spawn(async move |this, cx| {
 748            let result = client
 749                .request(proto::RemoveChannelMember {
 750                    channel_id: channel_id.0,
 751                    user_id,
 752                })
 753                .await;
 754
 755            this.update(cx, |this, cx| {
 756                this.outgoing_invites.remove(&(channel_id, user_id));
 757                cx.notify();
 758            })?;
 759            result?;
 760            Ok(())
 761        })
 762    }
 763
 764    pub fn set_member_role(
 765        &mut self,
 766        channel_id: ChannelId,
 767        user_id: UserId,
 768        role: proto::ChannelRole,
 769        cx: &mut Context<Self>,
 770    ) -> Task<Result<()>> {
 771        if !self.outgoing_invites.insert((channel_id, user_id)) {
 772            return Task::ready(Err(anyhow!("member request already in progress")));
 773        }
 774
 775        cx.notify();
 776        let client = self.client.clone();
 777        cx.spawn(async move |this, cx| {
 778            let result = client
 779                .request(proto::SetChannelMemberRole {
 780                    channel_id: channel_id.0,
 781                    user_id,
 782                    role: role.into(),
 783                })
 784                .await;
 785
 786            this.update(cx, |this, cx| {
 787                this.outgoing_invites.remove(&(channel_id, user_id));
 788                cx.notify();
 789            })?;
 790
 791            result?;
 792            Ok(())
 793        })
 794    }
 795
 796    pub fn rename(
 797        &mut self,
 798        channel_id: ChannelId,
 799        new_name: &str,
 800        cx: &mut Context<Self>,
 801    ) -> Task<Result<()>> {
 802        let client = self.client.clone();
 803        let name = new_name.to_string();
 804        cx.spawn(async move |this, cx| {
 805            let channel = client
 806                .request(proto::RenameChannel {
 807                    channel_id: channel_id.0,
 808                    name,
 809                })
 810                .await?
 811                .channel
 812                .context("missing channel in response")?;
 813            this.update(cx, |this, cx| {
 814                let task = this.update_channels(
 815                    proto::UpdateChannels {
 816                        channels: vec![channel],
 817                        ..Default::default()
 818                    },
 819                    cx,
 820                );
 821                assert!(task.is_none());
 822
 823                // This event is emitted because the collab panel wants to clear the pending edit state
 824                // before this frame is rendered. But we can't guarantee that the collab panel's future
 825                // will resolve before this flush_effects finishes. Synchronously emitting this event
 826                // ensures that the collab panel will observe this creation before the frame complete
 827                cx.emit(ChannelEvent::ChannelRenamed(channel_id))
 828            })?;
 829            Ok(())
 830        })
 831    }
 832
 833    pub fn respond_to_channel_invite(
 834        &mut self,
 835        channel_id: ChannelId,
 836        accept: bool,
 837        cx: &mut Context<Self>,
 838    ) -> Task<Result<()>> {
 839        let client = self.client.clone();
 840        cx.background_spawn(async move {
 841            client
 842                .request(proto::RespondToChannelInvite {
 843                    channel_id: channel_id.0,
 844                    accept,
 845                })
 846                .await?;
 847            Ok(())
 848        })
 849    }
 850    pub fn fuzzy_search_members(
 851        &self,
 852        channel_id: ChannelId,
 853        query: String,
 854        limit: u16,
 855        cx: &mut Context<Self>,
 856    ) -> Task<Result<Vec<ChannelMembership>>> {
 857        let client = self.client.clone();
 858        let user_store = self.user_store.downgrade();
 859        cx.spawn(async move |_, cx| {
 860            let response = client
 861                .request(proto::GetChannelMembers {
 862                    channel_id: channel_id.0,
 863                    query,
 864                    limit: limit as u64,
 865                })
 866                .await?;
 867            user_store.update(cx, |user_store, _| {
 868                user_store.insert(response.users);
 869                response
 870                    .members
 871                    .into_iter()
 872                    .filter_map(|member| {
 873                        Some(ChannelMembership {
 874                            user: user_store.get_cached_user(member.user_id)?,
 875                            role: member.role(),
 876                            kind: member.kind(),
 877                        })
 878                    })
 879                    .collect()
 880            })
 881        })
 882    }
 883
 884    pub fn remove_channel(
 885        &self,
 886        channel_id: ChannelId,
 887    ) -> impl Future<Output = Result<()>> + use<> {
 888        let client = self.client.clone();
 889        async move {
 890            client
 891                .request(proto::DeleteChannel {
 892                    channel_id: channel_id.0,
 893                })
 894                .await?;
 895            Ok(())
 896        }
 897    }
 898
 899    pub fn has_pending_channel_invite_response(&self, _: &Arc<Channel>) -> bool {
 900        false
 901    }
 902
 903    pub fn has_pending_channel_invite(&self, channel_id: ChannelId, user_id: UserId) -> bool {
 904        self.outgoing_invites.contains(&(channel_id, user_id))
 905    }
 906
 907    async fn handle_update_channels(
 908        this: Entity<Self>,
 909        message: TypedEnvelope<proto::UpdateChannels>,
 910        mut cx: AsyncApp,
 911    ) -> Result<()> {
 912        this.read_with(&mut cx, |this, _| {
 913            this.update_channels_tx
 914                .unbounded_send(message.payload)
 915                .unwrap();
 916        })?;
 917        Ok(())
 918    }
 919
 920    async fn handle_update_user_channels(
 921        this: Entity<Self>,
 922        message: TypedEnvelope<proto::UpdateUserChannels>,
 923        mut cx: AsyncApp,
 924    ) -> Result<()> {
 925        this.update(&mut cx, |this, cx| {
 926            for buffer_version in message.payload.observed_channel_buffer_version {
 927                let version = language::proto::deserialize_version(&buffer_version.version);
 928                this.acknowledge_notes_version(
 929                    ChannelId(buffer_version.channel_id),
 930                    buffer_version.epoch,
 931                    &version,
 932                    cx,
 933                );
 934            }
 935            for message_id in message.payload.observed_channel_message_id {
 936                this.acknowledge_message_id(
 937                    ChannelId(message_id.channel_id),
 938                    message_id.message_id,
 939                    cx,
 940                );
 941            }
 942            for membership in message.payload.channel_memberships {
 943                if let Some(role) = ChannelRole::from_i32(membership.role) {
 944                    this.channel_states
 945                        .entry(ChannelId(membership.channel_id))
 946                        .or_default()
 947                        .set_role(role)
 948                }
 949            }
 950        })
 951    }
 952
 953    fn handle_connect(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 954        self.channel_index.clear();
 955        self.channel_invitations.clear();
 956        self.channel_participants.clear();
 957        self.channel_index.clear();
 958        self.outgoing_invites.clear();
 959        self.disconnect_channel_buffers_task.take();
 960
 961        for chat in self.opened_chats.values() {
 962            if let OpenEntityHandle::Open(chat) = chat
 963                && let Some(chat) = chat.upgrade() {
 964                    chat.update(cx, |chat, cx| {
 965                        chat.rejoin(cx);
 966                    });
 967                }
 968        }
 969
 970        let mut buffer_versions = Vec::new();
 971        for buffer in self.opened_buffers.values() {
 972            if let OpenEntityHandle::Open(buffer) = buffer
 973                && let Some(buffer) = buffer.upgrade() {
 974                    let channel_buffer = buffer.read(cx);
 975                    let buffer = channel_buffer.buffer().read(cx);
 976                    buffer_versions.push(proto::ChannelBufferVersion {
 977                        channel_id: channel_buffer.channel_id.0,
 978                        epoch: channel_buffer.epoch(),
 979                        version: language::proto::serialize_version(&buffer.version()),
 980                    });
 981                }
 982        }
 983
 984        if buffer_versions.is_empty() {
 985            return Task::ready(Ok(()));
 986        }
 987
 988        let response = self.client.request(proto::RejoinChannelBuffers {
 989            buffers: buffer_versions,
 990        });
 991
 992        cx.spawn(async move |this, cx| {
 993            let mut response = response.await?;
 994
 995            this.update(cx, |this, cx| {
 996                this.opened_buffers.retain(|_, buffer| match buffer {
 997                    OpenEntityHandle::Open(channel_buffer) => {
 998                        let Some(channel_buffer) = channel_buffer.upgrade() else {
 999                            return false;
1000                        };
1001
1002                        channel_buffer.update(cx, |channel_buffer, cx| {
1003                            let channel_id = channel_buffer.channel_id;
1004                            if let Some(remote_buffer) = response
1005                                .buffers
1006                                .iter_mut()
1007                                .find(|buffer| buffer.channel_id == channel_id.0)
1008                            {
1009                                let channel_id = channel_buffer.channel_id;
1010                                let remote_version =
1011                                    language::proto::deserialize_version(&remote_buffer.version);
1012
1013                                channel_buffer.replace_collaborators(
1014                                    mem::take(&mut remote_buffer.collaborators),
1015                                    cx,
1016                                );
1017
1018                                let operations = channel_buffer
1019                                    .buffer()
1020                                    .update(cx, |buffer, cx| {
1021                                        let outgoing_operations =
1022                                            buffer.serialize_ops(Some(remote_version), cx);
1023                                        let incoming_operations =
1024                                            mem::take(&mut remote_buffer.operations)
1025                                                .into_iter()
1026                                                .map(language::proto::deserialize_operation)
1027                                                .collect::<Result<Vec<_>>>()?;
1028                                        buffer.apply_ops(incoming_operations, cx);
1029                                        anyhow::Ok(outgoing_operations)
1030                                    })
1031                                    .log_err();
1032
1033                                if let Some(operations) = operations {
1034                                    channel_buffer.connected(cx);
1035                                    let client = this.client.clone();
1036                                    cx.background_spawn(async move {
1037                                        let operations = operations.await;
1038                                        for chunk in language::proto::split_operations(operations) {
1039                                            client
1040                                                .send(proto::UpdateChannelBuffer {
1041                                                    channel_id: channel_id.0,
1042                                                    operations: chunk,
1043                                                })
1044                                                .ok();
1045                                        }
1046                                    })
1047                                    .detach();
1048                                    return true;
1049                                }
1050                            }
1051
1052                            channel_buffer.disconnect(cx);
1053                            false
1054                        })
1055                    }
1056                    OpenEntityHandle::Loading(_) => true,
1057                });
1058            })
1059            .ok();
1060            anyhow::Ok(())
1061        })
1062    }
1063
1064    fn handle_disconnect(&mut self, wait_for_reconnect: bool, cx: &mut Context<Self>) {
1065        cx.notify();
1066        self.did_subscribe = false;
1067        self.disconnect_channel_buffers_task.get_or_insert_with(|| {
1068            cx.spawn(async move |this, cx| {
1069                if wait_for_reconnect {
1070                    cx.background_executor().timer(RECONNECT_TIMEOUT).await;
1071                }
1072
1073                if let Some(this) = this.upgrade() {
1074                    this.update(cx, |this, cx| {
1075                        for (_, buffer) in &this.opened_buffers {
1076                            if let OpenEntityHandle::Open(buffer) = &buffer
1077                                && let Some(buffer) = buffer.upgrade() {
1078                                    buffer.update(cx, |buffer, cx| buffer.disconnect(cx));
1079                                }
1080                        }
1081                    })
1082                    .ok();
1083                }
1084            })
1085        });
1086    }
1087
1088    #[cfg(any(test, feature = "test-support"))]
1089    pub fn reset(&mut self) {
1090        self.channel_invitations.clear();
1091        self.channel_index.clear();
1092        self.channel_participants.clear();
1093        self.outgoing_invites.clear();
1094        self.opened_buffers.clear();
1095        self.opened_chats.clear();
1096        self.disconnect_channel_buffers_task = None;
1097        self.channel_states.clear();
1098    }
1099
1100    pub(crate) fn update_channels(
1101        &mut self,
1102        payload: proto::UpdateChannels,
1103        cx: &mut Context<ChannelStore>,
1104    ) -> Option<Task<Result<()>>> {
1105        if !payload.remove_channel_invitations.is_empty() {
1106            self.channel_invitations
1107                .retain(|channel| !payload.remove_channel_invitations.contains(&channel.id.0));
1108        }
1109        for channel in payload.channel_invitations {
1110            match self
1111                .channel_invitations
1112                .binary_search_by_key(&channel.id, |c| c.id.0)
1113            {
1114                Ok(ix) => {
1115                    Arc::make_mut(&mut self.channel_invitations[ix]).name = channel.name.into()
1116                }
1117                Err(ix) => self.channel_invitations.insert(
1118                    ix,
1119                    Arc::new(Channel {
1120                        id: ChannelId(channel.id),
1121                        visibility: channel.visibility(),
1122                        name: channel.name.into(),
1123                        parent_path: channel.parent_path.into_iter().map(ChannelId).collect(),
1124                        channel_order: channel.channel_order,
1125                    }),
1126                ),
1127            }
1128        }
1129
1130        let channels_changed = !payload.channels.is_empty()
1131            || !payload.delete_channels.is_empty()
1132            || !payload.latest_channel_message_ids.is_empty()
1133            || !payload.latest_channel_buffer_versions.is_empty();
1134
1135        if channels_changed {
1136            if !payload.delete_channels.is_empty() {
1137                let delete_channels: Vec<ChannelId> =
1138                    payload.delete_channels.into_iter().map(ChannelId).collect();
1139                self.channel_index.delete_channels(&delete_channels);
1140                self.channel_participants
1141                    .retain(|channel_id, _| !delete_channels.contains(channel_id));
1142
1143                for channel_id in &delete_channels {
1144                    let channel_id = *channel_id;
1145                    if payload
1146                        .channels
1147                        .iter()
1148                        .any(|channel| channel.id == channel_id.0)
1149                    {
1150                        continue;
1151                    }
1152                    if let Some(OpenEntityHandle::Open(buffer)) =
1153                        self.opened_buffers.remove(&channel_id)
1154                        && let Some(buffer) = buffer.upgrade() {
1155                            buffer.update(cx, ChannelBuffer::disconnect);
1156                        }
1157                }
1158            }
1159
1160            let mut index = self.channel_index.bulk_insert();
1161            for channel in payload.channels {
1162                let id = ChannelId(channel.id);
1163                let channel_changed = index.insert(channel);
1164
1165                if channel_changed
1166                    && let Some(OpenEntityHandle::Open(buffer)) = self.opened_buffers.get(&id)
1167                        && let Some(buffer) = buffer.upgrade() {
1168                            buffer.update(cx, ChannelBuffer::channel_changed);
1169                        }
1170            }
1171
1172            for latest_buffer_version in payload.latest_channel_buffer_versions {
1173                let version = language::proto::deserialize_version(&latest_buffer_version.version);
1174                self.channel_states
1175                    .entry(ChannelId(latest_buffer_version.channel_id))
1176                    .or_default()
1177                    .update_latest_notes_version(latest_buffer_version.epoch, &version)
1178            }
1179
1180            for latest_channel_message in payload.latest_channel_message_ids {
1181                self.channel_states
1182                    .entry(ChannelId(latest_channel_message.channel_id))
1183                    .or_default()
1184                    .update_latest_message_id(latest_channel_message.message_id);
1185            }
1186
1187            self.channels_loaded.0.try_send(true).log_err();
1188        }
1189
1190        cx.notify();
1191        if payload.channel_participants.is_empty() {
1192            return None;
1193        }
1194
1195        let mut all_user_ids = Vec::new();
1196        let channel_participants = payload.channel_participants;
1197        for entry in &channel_participants {
1198            for user_id in entry.participant_user_ids.iter() {
1199                if let Err(ix) = all_user_ids.binary_search(user_id) {
1200                    all_user_ids.insert(ix, *user_id);
1201                }
1202            }
1203        }
1204
1205        let users = self
1206            .user_store
1207            .update(cx, |user_store, cx| user_store.get_users(all_user_ids, cx));
1208        Some(cx.spawn(async move |this, cx| {
1209            let users = users.await?;
1210
1211            this.update(cx, |this, cx| {
1212                for entry in &channel_participants {
1213                    let mut participants: Vec<_> = entry
1214                        .participant_user_ids
1215                        .iter()
1216                        .filter_map(|user_id| {
1217                            users
1218                                .binary_search_by_key(&user_id, |user| &user.id)
1219                                .ok()
1220                                .map(|ix| users[ix].clone())
1221                        })
1222                        .collect();
1223
1224                    participants.sort_by_key(|u| u.id);
1225
1226                    this.channel_participants
1227                        .insert(ChannelId(entry.channel_id), participants);
1228                }
1229
1230                cx.notify();
1231            })
1232        }))
1233    }
1234}
1235
1236impl ChannelState {
1237    fn set_role(&mut self, role: ChannelRole) {
1238        self.role = Some(role);
1239    }
1240
1241    fn has_channel_buffer_changed(&self) -> bool {
1242        self.latest_notes_version.epoch > self.observed_notes_version.epoch
1243            || (self.latest_notes_version.epoch == self.observed_notes_version.epoch
1244                && self
1245                    .latest_notes_version
1246                    .version
1247                    .changed_since(&self.observed_notes_version.version))
1248    }
1249
1250    fn has_new_messages(&self) -> bool {
1251        let latest_message_id = self.latest_chat_message;
1252        let observed_message_id = self.observed_chat_message;
1253
1254        latest_message_id.is_some_and(|latest_message_id| {
1255            latest_message_id > observed_message_id.unwrap_or_default()
1256        })
1257    }
1258
1259    fn last_acknowledged_message_id(&self) -> Option<u64> {
1260        self.observed_chat_message
1261    }
1262
1263    fn acknowledge_message_id(&mut self, message_id: u64) {
1264        let observed = self.observed_chat_message.get_or_insert(message_id);
1265        *observed = (*observed).max(message_id);
1266    }
1267
1268    fn update_latest_message_id(&mut self, message_id: u64) {
1269        self.latest_chat_message =
1270            Some(message_id.max(self.latest_chat_message.unwrap_or_default()));
1271    }
1272
1273    fn acknowledge_notes_version(&mut self, epoch: u64, version: &clock::Global) {
1274        if self.observed_notes_version.epoch == epoch {
1275            self.observed_notes_version.version.join(version);
1276        } else {
1277            self.observed_notes_version = NotesVersion {
1278                epoch,
1279                version: version.clone(),
1280            };
1281        }
1282    }
1283
1284    fn update_latest_notes_version(&mut self, epoch: u64, version: &clock::Global) {
1285        if self.latest_notes_version.epoch == epoch {
1286            self.latest_notes_version.version.join(version);
1287        } else {
1288            self.latest_notes_version = NotesVersion {
1289                epoch,
1290                version: version.clone(),
1291            };
1292        }
1293    }
1294}