channel_buffer.rs

  1use crate::{Channel, ChannelStore};
  2use anyhow::Result;
  3use client::{ChannelId, Client, Collaborator, UserStore, ZED_ALWAYS_ACTIVE};
  4use collections::HashMap;
  5use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Task};
  6use language::proto::serialize_version;
  7use rpc::{
  8    AnyProtoClient, TypedEnvelope,
  9    proto::{self, PeerId},
 10};
 11use std::{sync::Arc, time::Duration};
 12use text::BufferId;
 13use util::ResultExt;
 14
 15pub const ACKNOWLEDGE_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(250);
 16
 17pub(crate) fn init(client: &AnyProtoClient) {
 18    client.add_entity_message_handler(ChannelBuffer::handle_update_channel_buffer);
 19    client.add_entity_message_handler(ChannelBuffer::handle_update_channel_buffer_collaborators);
 20}
 21
 22pub struct ChannelBuffer {
 23    pub channel_id: ChannelId,
 24    connected: bool,
 25    collaborators: HashMap<PeerId, Collaborator>,
 26    user_store: Entity<UserStore>,
 27    channel_store: Entity<ChannelStore>,
 28    buffer: Entity<language::Buffer>,
 29    buffer_epoch: u64,
 30    client: Arc<Client>,
 31    subscription: Option<client::Subscription>,
 32    acknowledge_task: Option<Task<Result<()>>>,
 33}
 34
 35pub enum ChannelBufferEvent {
 36    CollaboratorsChanged,
 37    Disconnected,
 38    Connected,
 39    BufferEdited,
 40    ChannelChanged,
 41}
 42
 43impl EventEmitter<ChannelBufferEvent> for ChannelBuffer {}
 44
 45impl ChannelBuffer {
 46    pub(crate) async fn new(
 47        channel: Arc<Channel>,
 48        client: Arc<Client>,
 49        user_store: Entity<UserStore>,
 50        channel_store: Entity<ChannelStore>,
 51        cx: &mut AsyncApp,
 52    ) -> Result<Entity<Self>> {
 53        let response = client
 54            .request(proto::JoinChannelBuffer {
 55                channel_id: channel.id.0,
 56            })
 57            .await?;
 58        let buffer_id = BufferId::new(response.buffer_id)?;
 59        let base_text = response.base_text;
 60        let operations = response
 61            .operations
 62            .into_iter()
 63            .map(language::proto::deserialize_operation)
 64            .collect::<Result<Vec<_>, _>>()?;
 65
 66        let buffer = cx.new(|cx| {
 67            let capability = channel_store.read(cx).channel_capability(channel.id);
 68            language::Buffer::remote(buffer_id, response.replica_id as u16, capability, base_text)
 69        })?;
 70        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
 71
 72        let subscription = client.subscribe_to_entity(channel.id.0)?;
 73
 74        anyhow::Ok(cx.new(|cx| {
 75            cx.subscribe(&buffer, Self::on_buffer_update).detach();
 76            cx.on_release(Self::release).detach();
 77            let mut this = Self {
 78                buffer,
 79                buffer_epoch: response.epoch,
 80                client,
 81                connected: true,
 82                collaborators: Default::default(),
 83                acknowledge_task: None,
 84                channel_id: channel.id,
 85                subscription: Some(subscription.set_entity(&cx.entity(), &cx.to_async())),
 86                user_store,
 87                channel_store,
 88            };
 89            this.replace_collaborators(response.collaborators, cx);
 90            this
 91        })?)
 92    }
 93
 94    fn release(&mut self, _: &mut App) {
 95        if self.connected {
 96            if let Some(task) = self.acknowledge_task.take() {
 97                task.detach();
 98            }
 99            self.client
100                .send(proto::LeaveChannelBuffer {
101                    channel_id: self.channel_id.0,
102                })
103                .log_err();
104        }
105    }
106
107    pub fn connected(&mut self, cx: &mut Context<Self>) {
108        self.connected = true;
109        if self.subscription.is_none() {
110            let Ok(subscription) = self.client.subscribe_to_entity(self.channel_id.0) else {
111                return;
112            };
113            self.subscription = Some(subscription.set_entity(&cx.entity(), &cx.to_async()));
114            cx.emit(ChannelBufferEvent::Connected);
115        }
116    }
117
118    pub fn remote_id(&self, cx: &App) -> BufferId {
119        self.buffer.read(cx).remote_id()
120    }
121
122    pub fn user_store(&self) -> &Entity<UserStore> {
123        &self.user_store
124    }
125
126    pub(crate) fn replace_collaborators(
127        &mut self,
128        collaborators: Vec<proto::Collaborator>,
129        cx: &mut Context<Self>,
130    ) {
131        let mut new_collaborators = HashMap::default();
132        for collaborator in collaborators {
133            if let Ok(collaborator) = Collaborator::from_proto(collaborator) {
134                new_collaborators.insert(collaborator.peer_id, collaborator);
135            }
136        }
137
138        for old_collaborator in self.collaborators.values() {
139            if !new_collaborators.contains_key(&old_collaborator.peer_id) {
140                self.buffer.update(cx, |buffer, cx| {
141                    buffer.remove_peer(old_collaborator.replica_id, cx)
142                });
143            }
144        }
145        self.collaborators = new_collaborators;
146        cx.emit(ChannelBufferEvent::CollaboratorsChanged);
147        cx.notify();
148    }
149
150    async fn handle_update_channel_buffer(
151        this: Entity<Self>,
152        update_channel_buffer: TypedEnvelope<proto::UpdateChannelBuffer>,
153        mut cx: AsyncApp,
154    ) -> Result<()> {
155        let ops = update_channel_buffer
156            .payload
157            .operations
158            .into_iter()
159            .map(language::proto::deserialize_operation)
160            .collect::<Result<Vec<_>, _>>()?;
161
162        this.update(&mut cx, |this, cx| {
163            cx.notify();
164            this.buffer
165                .update(cx, |buffer, cx| buffer.apply_ops(ops, cx))
166        })?;
167
168        Ok(())
169    }
170
171    async fn handle_update_channel_buffer_collaborators(
172        this: Entity<Self>,
173        message: TypedEnvelope<proto::UpdateChannelBufferCollaborators>,
174        mut cx: AsyncApp,
175    ) -> Result<()> {
176        this.update(&mut cx, |this, cx| {
177            this.replace_collaborators(message.payload.collaborators, cx);
178            cx.emit(ChannelBufferEvent::CollaboratorsChanged);
179            cx.notify();
180        })
181    }
182
183    fn on_buffer_update(
184        &mut self,
185        _: Entity<language::Buffer>,
186        event: &language::BufferEvent,
187        cx: &mut Context<Self>,
188    ) {
189        match event {
190            language::BufferEvent::Operation {
191                operation,
192                is_local: true,
193            } => {
194                if *ZED_ALWAYS_ACTIVE
195                    && let language::Operation::UpdateSelections { selections, .. } = operation
196                    && selections.is_empty()
197                {
198                    return;
199                }
200                let operation = language::proto::serialize_operation(operation);
201                self.client
202                    .send(proto::UpdateChannelBuffer {
203                        channel_id: self.channel_id.0,
204                        operations: vec![operation],
205                    })
206                    .log_err();
207            }
208            language::BufferEvent::Edited => {
209                cx.emit(ChannelBufferEvent::BufferEdited);
210            }
211            _ => {}
212        }
213    }
214
215    pub fn acknowledge_buffer_version(&mut self, cx: &mut Context<ChannelBuffer>) {
216        let buffer = self.buffer.read(cx);
217        let version = buffer.version();
218        let buffer_id = buffer.remote_id().into();
219        let client = self.client.clone();
220        let epoch = self.epoch();
221
222        self.acknowledge_task = Some(cx.spawn(async move |_, cx| {
223            cx.background_executor()
224                .timer(ACKNOWLEDGE_DEBOUNCE_INTERVAL)
225                .await;
226            client
227                .send(proto::AckBufferOperation {
228                    buffer_id,
229                    epoch,
230                    version: serialize_version(&version),
231                })
232                .ok();
233            Ok(())
234        }));
235    }
236
237    pub fn epoch(&self) -> u64 {
238        self.buffer_epoch
239    }
240
241    pub fn buffer(&self) -> Entity<language::Buffer> {
242        self.buffer.clone()
243    }
244
245    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
246        &self.collaborators
247    }
248
249    pub fn channel(&self, cx: &App) -> Option<Arc<Channel>> {
250        self.channel_store
251            .read(cx)
252            .channel_for_id(self.channel_id)
253            .cloned()
254    }
255
256    pub(crate) fn disconnect(&mut self, cx: &mut Context<Self>) {
257        log::info!("channel buffer {} disconnected", self.channel_id);
258        if self.connected {
259            self.connected = false;
260            self.subscription.take();
261            cx.emit(ChannelBufferEvent::Disconnected);
262            cx.notify()
263        }
264    }
265
266    pub(crate) fn channel_changed(&mut self, cx: &mut Context<Self>) {
267        cx.emit(ChannelBufferEvent::ChannelChanged);
268        cx.notify()
269    }
270
271    pub fn is_connected(&self) -> bool {
272        self.connected
273    }
274
275    pub fn replica_id(&self, cx: &App) -> u16 {
276        self.buffer.read(cx).replica_id()
277    }
278}