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, ReplicaId};
 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(
 69                buffer_id,
 70                ReplicaId::new(response.replica_id as u16),
 71                capability,
 72                base_text,
 73            )
 74        })?;
 75        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
 76
 77        let subscription = client.subscribe_to_entity(channel.id.0)?;
 78
 79        anyhow::Ok(cx.new(|cx| {
 80            cx.subscribe(&buffer, Self::on_buffer_update).detach();
 81            cx.on_release(Self::release).detach();
 82            let mut this = Self {
 83                buffer,
 84                buffer_epoch: response.epoch,
 85                client,
 86                connected: true,
 87                collaborators: Default::default(),
 88                acknowledge_task: None,
 89                channel_id: channel.id,
 90                subscription: Some(subscription.set_entity(&cx.entity(), &cx.to_async())),
 91                user_store,
 92                channel_store,
 93            };
 94            this.replace_collaborators(response.collaborators, cx);
 95            this
 96        })?)
 97    }
 98
 99    fn release(&mut self, _: &mut App) {
100        if self.connected {
101            if let Some(task) = self.acknowledge_task.take() {
102                task.detach();
103            }
104            self.client
105                .send(proto::LeaveChannelBuffer {
106                    channel_id: self.channel_id.0,
107                })
108                .log_err();
109        }
110    }
111
112    pub fn connected(&mut self, cx: &mut Context<Self>) {
113        self.connected = true;
114        if self.subscription.is_none() {
115            let Ok(subscription) = self.client.subscribe_to_entity(self.channel_id.0) else {
116                return;
117            };
118            self.subscription = Some(subscription.set_entity(&cx.entity(), &cx.to_async()));
119            cx.emit(ChannelBufferEvent::Connected);
120        }
121    }
122
123    pub fn remote_id(&self, cx: &App) -> BufferId {
124        self.buffer.read(cx).remote_id()
125    }
126
127    pub fn user_store(&self) -> &Entity<UserStore> {
128        &self.user_store
129    }
130
131    pub(crate) fn replace_collaborators(
132        &mut self,
133        collaborators: Vec<proto::Collaborator>,
134        cx: &mut Context<Self>,
135    ) {
136        let mut new_collaborators = HashMap::default();
137        for collaborator in collaborators {
138            if let Ok(collaborator) = Collaborator::from_proto(collaborator) {
139                new_collaborators.insert(collaborator.peer_id, collaborator);
140            }
141        }
142
143        for old_collaborator in self.collaborators.values() {
144            if !new_collaborators.contains_key(&old_collaborator.peer_id) {
145                self.buffer.update(cx, |buffer, cx| {
146                    buffer.remove_peer(old_collaborator.replica_id, cx)
147                });
148            }
149        }
150        self.collaborators = new_collaborators;
151        cx.emit(ChannelBufferEvent::CollaboratorsChanged);
152        cx.notify();
153    }
154
155    async fn handle_update_channel_buffer(
156        this: Entity<Self>,
157        update_channel_buffer: TypedEnvelope<proto::UpdateChannelBuffer>,
158        mut cx: AsyncApp,
159    ) -> Result<()> {
160        let ops = update_channel_buffer
161            .payload
162            .operations
163            .into_iter()
164            .map(language::proto::deserialize_operation)
165            .collect::<Result<Vec<_>, _>>()?;
166
167        this.update(&mut cx, |this, cx| {
168            cx.notify();
169            this.buffer
170                .update(cx, |buffer, cx| buffer.apply_ops(ops, cx))
171        })?;
172
173        Ok(())
174    }
175
176    async fn handle_update_channel_buffer_collaborators(
177        this: Entity<Self>,
178        message: TypedEnvelope<proto::UpdateChannelBufferCollaborators>,
179        mut cx: AsyncApp,
180    ) -> Result<()> {
181        this.update(&mut cx, |this, cx| {
182            this.replace_collaborators(message.payload.collaborators, cx);
183            cx.emit(ChannelBufferEvent::CollaboratorsChanged);
184            cx.notify();
185        })
186    }
187
188    fn on_buffer_update(
189        &mut self,
190        _: Entity<language::Buffer>,
191        event: &language::BufferEvent,
192        cx: &mut Context<Self>,
193    ) {
194        match event {
195            language::BufferEvent::Operation {
196                operation,
197                is_local: true,
198            } => {
199                if *ZED_ALWAYS_ACTIVE
200                    && let language::Operation::UpdateSelections { selections, .. } = operation
201                    && selections.is_empty()
202                {
203                    return;
204                }
205                let operation = language::proto::serialize_operation(operation);
206                self.client
207                    .send(proto::UpdateChannelBuffer {
208                        channel_id: self.channel_id.0,
209                        operations: vec![operation],
210                    })
211                    .log_err();
212            }
213            language::BufferEvent::Edited => {
214                cx.emit(ChannelBufferEvent::BufferEdited);
215            }
216            _ => {}
217        }
218    }
219
220    pub fn acknowledge_buffer_version(&mut self, cx: &mut Context<ChannelBuffer>) {
221        let buffer = self.buffer.read(cx);
222        let version = buffer.version();
223        let buffer_id = buffer.remote_id().into();
224        let client = self.client.clone();
225        let epoch = self.epoch();
226
227        self.acknowledge_task = Some(cx.spawn(async move |_, cx| {
228            cx.background_executor()
229                .timer(ACKNOWLEDGE_DEBOUNCE_INTERVAL)
230                .await;
231            client
232                .send(proto::AckBufferOperation {
233                    buffer_id,
234                    epoch,
235                    version: serialize_version(&version),
236                })
237                .ok();
238            Ok(())
239        }));
240    }
241
242    pub fn epoch(&self) -> u64 {
243        self.buffer_epoch
244    }
245
246    pub fn buffer(&self) -> Entity<language::Buffer> {
247        self.buffer.clone()
248    }
249
250    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
251        &self.collaborators
252    }
253
254    pub fn channel(&self, cx: &App) -> Option<Arc<Channel>> {
255        self.channel_store
256            .read(cx)
257            .channel_for_id(self.channel_id)
258            .cloned()
259    }
260
261    pub(crate) fn disconnect(&mut self, cx: &mut Context<Self>) {
262        log::info!("channel buffer {} disconnected", self.channel_id);
263        if self.connected {
264            self.connected = false;
265            self.subscription.take();
266            cx.emit(ChannelBufferEvent::Disconnected);
267            cx.notify()
268        }
269    }
270
271    pub(crate) fn channel_changed(&mut self, cx: &mut Context<Self>) {
272        cx.emit(ChannelBufferEvent::ChannelChanged);
273        cx.notify()
274    }
275
276    pub fn is_connected(&self) -> bool {
277        self.connected
278    }
279
280    pub fn replica_id(&self, cx: &App) -> ReplicaId {
281        self.buffer.read(cx).replica_id()
282    }
283}