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