channel_buffer.rs

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