| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::sync::{Arc, Mutex}; |
| 4 | |
| 5 | use chrono::{DateTime, Duration, Utc}; |
| 6 | use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message}; |
| 7 | use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState}; |
| 8 | use tokio::sync::{OnceCell, broadcast}; |
| 9 | |
| 10 | use crate::error::{Error, Result}; |
| 11 | use crate::events::CoreEvent; |
| 12 | use crate::folders::FolderSource; |
| 13 | use crate::mapping::{flatten_thread, message_record}; |
| 14 | use crate::people::DirectoryCache; |
| 15 | use crate::presence::Presence; |
| 16 | use crate::preview::OwnedPreview; |
| 17 | use crate::receipts::ReceiptCache; |
| 18 | use crate::remote::{Remote, RemotePage}; |
| 19 | |
| 20 | const EVENT_CAPACITY: usize = 64; |
| 21 | pub(crate) const META_USER_ID: &str = "me_user_id"; |
| 22 | const META_TENANT_ID: &str = "me_tenant_id"; |
| 23 | const META_DISPLAY_NAME: &str = "me_display_name"; |
| 24 | |
| 25 | #[derive(Debug, Clone)] |
| 26 | pub struct SyncConfig { |
| 27 | pub chat_limit: usize, |
| 28 | pub chat_page_size: usize, |
| 29 | pub page_size: usize, |
| 30 | pub open_limit: usize, |
| 31 | pub max_catch_up_pages: usize, |
| 32 | pub max_delta_pages: usize, |
| 33 | pub teams_refresh_interval: Duration, |
| 34 | pub team_layout_refresh_interval: Duration, |
| 35 | pub full_chat_refresh_interval: Duration, |
| 36 | } |
| 37 | |
| 38 | impl Default for SyncConfig { |
| 39 | fn default() -> Self { |
| 40 | SyncConfig { |
| 41 | chat_limit: 200, |
| 42 | chat_page_size: 25, |
| 43 | page_size: MESSAGE_PAGE_SIZE, |
| 44 | open_limit: MESSAGE_PAGE_SIZE, |
| 45 | max_catch_up_pages: 10, |
| 46 | max_delta_pages: 20, |
| 47 | teams_refresh_interval: Duration::hours(6), |
| 48 | team_layout_refresh_interval: Duration::minutes(15), |
| 49 | full_chat_refresh_interval: Duration::days(7), |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 55 | pub struct SidebarSummary { |
| 56 | pub chats: usize, |
| 57 | pub chat_pages: usize, |
| 58 | pub full_chat_refresh: bool, |
| 59 | pub teams_refreshed: bool, |
| 60 | pub teams: usize, |
| 61 | pub channels: usize, |
| 62 | pub failed_teams: usize, |
| 63 | } |
| 64 | |
| 65 | #[derive(Debug, Clone, Default, PartialEq)] |
| 66 | pub struct Delta { |
| 67 | pub added: Vec<MessageRecord>, |
| 68 | pub updated: Vec<MessageRecord>, |
| 69 | } |
| 70 | |
| 71 | impl Delta { |
| 72 | pub(crate) fn merge(&mut self, other: Delta) { |
| 73 | for record in other.added { |
| 74 | if !self |
| 75 | .added |
| 76 | .iter() |
| 77 | .any(|known| known.message_id == record.message_id) |
| 78 | { |
| 79 | self.added.push(record); |
| 80 | } |
| 81 | } |
| 82 | for record in other.updated { |
| 83 | self.updated |
| 84 | .retain(|known| known.message_id != record.message_id); |
| 85 | self.updated.push(record); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | pub fn is_empty(&self) -> bool { |
| 90 | self.added.is_empty() && self.updated.is_empty() |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 95 | pub struct Me { |
| 96 | pub user_id: String, |
| 97 | pub display_name: String, |
| 98 | } |
| 99 | |
| 100 | pub(crate) enum Conversation { |
| 101 | Chat, |
| 102 | Channel { team_id: String }, |
| 103 | } |
| 104 | |
| 105 | pub struct SyncEngine<R: Remote = Graph> { |
| 106 | pub(crate) remote: R, |
| 107 | pub(crate) store: Arc<Store>, |
| 108 | pub(crate) config: SyncConfig, |
| 109 | pub(crate) events: broadcast::Sender<CoreEvent>, |
| 110 | my_user_id: OnceCell<String>, |
| 111 | my_tenant_id: OnceCell<String>, |
| 112 | pub(crate) folder_source: Option<Arc<dyn FolderSource>>, |
| 113 | pub(crate) presences: Mutex<HashMap<String, Presence>>, |
| 114 | pub(crate) avatars_in_flight: Mutex<HashSet<String>>, |
| 115 | pub(crate) images_in_flight: Mutex<HashSet<String>>, |
| 116 | pub(crate) image_files: Option<ImageFileCache>, |
| 117 | pub(crate) directory_cache: Mutex<DirectoryCache>, |
| 118 | preview_changed: AtomicBool, |
| 119 | pub(crate) receipts: ReceiptCache, |
| 120 | pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>, |
| 121 | } |
| 122 | |
| 123 | impl<R: Remote> SyncEngine<R> { |
| 124 | pub fn new(remote: R, store: Arc<Store>) -> Self { |
| 125 | Self::with_config(remote, store, SyncConfig::default()) |
| 126 | } |
| 127 | |
| 128 | pub fn with_config(remote: R, store: Arc<Store>, config: SyncConfig) -> Self { |
| 129 | SyncEngine { |
| 130 | remote, |
| 131 | store, |
| 132 | config, |
| 133 | events: broadcast::channel(EVENT_CAPACITY).0, |
| 134 | my_user_id: OnceCell::new(), |
| 135 | my_tenant_id: OnceCell::new(), |
| 136 | folder_source: None, |
| 137 | presences: Mutex::new(HashMap::new()), |
| 138 | avatars_in_flight: Mutex::new(HashSet::new()), |
| 139 | images_in_flight: Mutex::new(HashSet::new()), |
| 140 | image_files: None, |
| 141 | directory_cache: Mutex::new(DirectoryCache::new()), |
| 142 | preview_changed: AtomicBool::new(false), |
| 143 | receipts: ReceiptCache::default(), |
| 144 | channel_folders: Mutex::new(HashMap::new()), |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub fn subscribe(&self) -> broadcast::Receiver<CoreEvent> { |
| 149 | self.events.subscribe() |
| 150 | } |
| 151 | |
| 152 | pub fn store(&self) -> &Arc<Store> { |
| 153 | &self.store |
| 154 | } |
| 155 | |
| 156 | pub fn remote(&self) -> &R { |
| 157 | &self.remote |
| 158 | } |
| 159 | |
| 160 | pub fn sidebar(&self) -> Result<Sidebar> { |
| 161 | Ok(self.store.sidebar()?) |
| 162 | } |
| 163 | |
| 164 | /// Cached page, newest messages last. Call `fetch_newer` afterwards for the network delta. |
| 165 | pub fn open_conversation(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> { |
| 166 | Ok(self |
| 167 | .store |
| 168 | .messages(conversation_id, None, self.config.open_limit)?) |
| 169 | } |
| 170 | |
| 171 | pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> { |
| 172 | let delta = match self.resolve(conversation_id)? { |
| 173 | Conversation::Chat => self.fetch_newer_chat(conversation_id).await?, |
| 174 | Conversation::Channel { team_id } => { |
| 175 | self.fetch_newer_channel(&team_id, conversation_id).await? |
| 176 | } |
| 177 | }; |
| 178 | self.announce(conversation_id, !delta.is_empty()); |
| 179 | Ok(delta) |
| 180 | } |
| 181 | |
| 182 | pub async fn load_older(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> { |
| 183 | let conversation = self.resolve(conversation_id)?; |
| 184 | if self.store.sync_state(conversation_id)?.is_none() { |
| 185 | self.fetch_newer(conversation_id).await?; |
| 186 | } |
| 187 | let state = self.store.sync_state(conversation_id)?.unwrap_or_default(); |
| 188 | if !state.has_more { |
| 189 | return Ok(Vec::new()); |
| 190 | } |
| 191 | let records = match conversation { |
| 192 | Conversation::Chat => self.load_older_chat(conversation_id, state).await?, |
| 193 | Conversation::Channel { .. } => self.load_older_channel(conversation_id, state).await?, |
| 194 | }; |
| 195 | self.announce(conversation_id, !records.is_empty()); |
| 196 | Ok(records) |
| 197 | } |
| 198 | |
| 199 | /// Known after the first sidebar refresh. |
| 200 | pub fn me(&self) -> Option<Me> { |
| 201 | Some(Me { |
| 202 | user_id: self.store.meta(META_USER_ID).ok()??, |
| 203 | display_name: self.store.meta(META_DISPLAY_NAME).ok()??, |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | /// Cached chat messages from others after the last read time, at least 1 for an unread chat. |
| 208 | pub fn unread_count(&self, conversation_id: &str) -> u32 { |
| 209 | let unread_count = || -> Result<usize> { |
| 210 | if let Some(channel) = self.store.channel(conversation_id)? { |
| 211 | return Ok(usize::from(channel.unread)); |
| 212 | } |
| 213 | let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else { |
| 214 | return Ok(0); |
| 215 | }; |
| 216 | let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default(); |
| 217 | let cached = |
| 218 | self.store |
| 219 | .count_messages_after(conversation_id, chat.last_read_at, &my_user_id)?; |
| 220 | Ok(cached.max(1)) |
| 221 | }; |
| 222 | unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX)) |
| 223 | } |
| 224 | |
| 225 | pub(crate) async fn my_user_id(&self) -> Result<String> { |
| 226 | let id = self |
| 227 | .my_user_id |
| 228 | .get_or_try_init(|| async { |
| 229 | if let Some(cached) = self.store.meta(META_USER_ID)? { |
| 230 | return Ok::<_, Error>(cached); |
| 231 | } |
| 232 | self.remember_me().await |
| 233 | }) |
| 234 | .await?; |
| 235 | Ok(id.clone()) |
| 236 | } |
| 237 | |
| 238 | pub(crate) async fn ensure_display_name(&self) -> Result<()> { |
| 239 | if self.store.meta(META_DISPLAY_NAME)?.is_none() { |
| 240 | self.remember_me().await?; |
| 241 | } |
| 242 | Ok(()) |
| 243 | } |
| 244 | |
| 245 | async fn remember_me(&self) -> Result<String> { |
| 246 | let user = self.remote.me().await?; |
| 247 | self.store.set_meta(META_USER_ID, &user.id)?; |
| 248 | if let Some(name) = user.display_name.as_deref() { |
| 249 | self.store.set_meta(META_DISPLAY_NAME, name)?; |
| 250 | } |
| 251 | Ok(user.id) |
| 252 | } |
| 253 | |
| 254 | pub(crate) async fn my_tenant_id(&self, chat_id: &str) -> Result<String> { |
| 255 | let tenant = self |
| 256 | .my_tenant_id |
| 257 | .get_or_try_init(|| async { |
| 258 | if let Some(cached) = self.store.meta(META_TENANT_ID)? { |
| 259 | return Ok::<_, Error>(cached); |
| 260 | } |
| 261 | let my_user_id = self.my_user_id().await?; |
| 262 | let members = self.remote.chat_members(chat_id).await?; |
| 263 | let tenant = members |
| 264 | .iter() |
| 265 | .find(|member| member.user_id.as_deref() == Some(my_user_id.as_str())) |
| 266 | .and_then(|member| member.tenant_id.clone()) |
| 267 | .ok_or(Error::Unsupported("a chat without my tenant id"))?; |
| 268 | self.store.set_meta(META_TENANT_ID, &tenant)?; |
| 269 | Ok(tenant) |
| 270 | }) |
| 271 | .await?; |
| 272 | Ok(tenant.clone()) |
| 273 | } |
| 274 | |
| 275 | pub(crate) fn resolve(&self, conversation_id: &str) -> Result<Conversation> { |
| 276 | if let Some(channel) = self.store.channel(conversation_id)? { |
| 277 | return Ok(Conversation::Channel { |
| 278 | team_id: channel.team_id, |
| 279 | }); |
| 280 | } |
| 281 | if self.store.chat(conversation_id)?.is_some() { |
| 282 | return Ok(Conversation::Chat); |
| 283 | } |
| 284 | Err(Error::UnknownConversation(conversation_id.to_owned())) |
| 285 | } |
| 286 | |
| 287 | async fn fetch_newer_chat(&self, conversation_id: &str) -> Result<Delta> { |
| 288 | let previous = self.store.sync_state(conversation_id)?.unwrap_or_default(); |
| 289 | let mut collected = Vec::new(); |
| 290 | let mut before = None; |
| 291 | let mut oldest_fetched: Option<DateTime<Utc>> = None; |
| 292 | let mut reached_known = false; |
| 293 | let mut has_next = false; |
| 294 | for _ in 0..self.config.max_catch_up_pages.max(1) { |
| 295 | let page = self |
| 296 | .remote |
| 297 | .chat_messages(conversation_id, before, self.config.page_size) |
| 298 | .await?; |
| 299 | let page_oldest = oldest_created(&page); |
| 300 | has_next = page.next_link.is_some(); |
| 301 | collected.extend( |
| 302 | page.items |
| 303 | .iter() |
| 304 | .filter_map(|message| message_record(conversation_id, message)), |
| 305 | ); |
| 306 | oldest_fetched = [oldest_fetched, page_oldest].into_iter().flatten().min(); |
| 307 | let Some(known) = previous.newest_seen else { |
| 308 | break; |
| 309 | }; |
| 310 | reached_known = !has_next || page_oldest.is_none_or(|oldest| oldest <= known); |
| 311 | if reached_known { |
| 312 | break; |
| 313 | } |
| 314 | before = page_oldest; |
| 315 | } |
| 316 | let newest_fetched = collected.iter().map(|record| record.created_at).max(); |
| 317 | let state = match previous.newest_seen { |
| 318 | None => SyncState { |
| 319 | newest_seen: newest_fetched, |
| 320 | oldest_loaded: oldest_fetched, |
| 321 | has_more: has_next, |
| 322 | older_cursor: None, |
| 323 | delta_link: None, |
| 324 | }, |
| 325 | Some(known) if reached_known => SyncState { |
| 326 | newest_seen: Some(known.max(newest_fetched.unwrap_or(known))), |
| 327 | ..previous |
| 328 | }, |
| 329 | Some(known) => SyncState { |
| 330 | newest_seen: Some(known.max(newest_fetched.unwrap_or(known))), |
| 331 | oldest_loaded: oldest_fetched, |
| 332 | has_more: true, |
| 333 | older_cursor: None, |
| 334 | delta_link: None, |
| 335 | }, |
| 336 | }; |
| 337 | let delta = self.ingest(conversation_id, collected)?; |
| 338 | self.store.set_sync_state(conversation_id, &state)?; |
| 339 | Ok(delta) |
| 340 | } |
| 341 | |
| 342 | async fn load_older_chat( |
| 343 | &self, |
| 344 | conversation_id: &str, |
| 345 | state: SyncState, |
| 346 | ) -> Result<Vec<MessageRecord>> { |
| 347 | let page = self |
| 348 | .remote |
| 349 | .chat_messages(conversation_id, state.oldest_loaded, self.config.page_size) |
| 350 | .await?; |
| 351 | let page_oldest = oldest_created(&page); |
| 352 | let has_more = page.next_link.is_some() && page_oldest.is_some(); |
| 353 | let records: Vec<_> = page |
| 354 | .items |
| 355 | .iter() |
| 356 | .filter_map(|message| message_record(conversation_id, message)) |
| 357 | .collect(); |
| 358 | self.ingest(conversation_id, records.clone())?; |
| 359 | self.store.set_sync_state( |
| 360 | conversation_id, |
| 361 | &SyncState { |
| 362 | oldest_loaded: page_oldest.or(state.oldest_loaded), |
| 363 | has_more, |
| 364 | ..state |
| 365 | }, |
| 366 | )?; |
| 367 | Ok(sorted(records)) |
| 368 | } |
| 369 | |
| 370 | pub(crate) fn ingest( |
| 371 | &self, |
| 372 | conversation_id: &str, |
| 373 | records: Vec<MessageRecord>, |
| 374 | ) -> Result<Delta> { |
| 375 | let ids: Vec<String> = records |
| 376 | .iter() |
| 377 | .map(|record| record.message_id.clone()) |
| 378 | .collect(); |
| 379 | let existing = self.store.messages_by_id(conversation_id, &ids)?; |
| 380 | self.store.upsert_messages(&records)?; |
| 381 | self.update_chat_preview(&records)?; |
| 382 | let mut delta = Delta::default(); |
| 383 | for record in sorted(records) { |
| 384 | match existing.get(&record.message_id) { |
| 385 | None => delta.added.push(record), |
| 386 | Some(cached) if *cached != record => delta.updated.push(record), |
| 387 | Some(_) => {} |
| 388 | } |
| 389 | } |
| 390 | Ok(delta) |
| 391 | } |
| 392 | |
| 393 | pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> { |
| 394 | let Some(newest) = records.iter().max_by_key(|record| record.created_at) else { |
| 395 | return Ok(()); |
| 396 | }; |
| 397 | let preview = OwnedPreview::from_record(newest); |
| 398 | let changed = self.store.update_chat_preview( |
| 399 | &newest.conversation_id, |
| 400 | newest.created_at, |
| 401 | &preview.as_store(), |
| 402 | )?; |
| 403 | if changed { |
| 404 | self.preview_changed.store(true, Ordering::SeqCst); |
| 405 | } |
| 406 | Ok(()) |
| 407 | } |
| 408 | |
| 409 | pub(crate) fn announce(&self, conversation_id: &str, changed: bool) { |
| 410 | if changed { |
| 411 | let _ = self.events.send(CoreEvent::MessagesChanged { |
| 412 | conversation_id: conversation_id.to_owned(), |
| 413 | }); |
| 414 | } |
| 415 | if self.preview_changed.swap(false, Ordering::SeqCst) { |
| 416 | let _ = self.events.send(CoreEvent::SidebarChanged); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | pub(crate) fn report(&self, message: String) { |
| 421 | let _ = self.events.send(CoreEvent::Error { message }); |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | fn oldest_created(page: &RemotePage) -> Option<DateTime<Utc>> { |
| 426 | page.items |
| 427 | .iter() |
| 428 | .filter_map(|message| message.created_date_time) |
| 429 | .min() |
| 430 | } |
| 431 | |
| 432 | pub(crate) fn thread_records(channel_id: &str, threads: &[Message]) -> Vec<MessageRecord> { |
| 433 | threads |
| 434 | .iter() |
| 435 | .flat_map(|thread| flatten_thread(channel_id, thread)) |
| 436 | .collect() |
| 437 | } |
| 438 | |
| 439 | pub(crate) fn sorted(mut records: Vec<MessageRecord>) -> Vec<MessageRecord> { |
| 440 | records.sort_by(|left, right| { |
| 441 | left.created_at |
| 442 | .cmp(&right.created_at) |
| 443 | .then_with(|| left.message_id.cmp(&right.message_id)) |
| 444 | }); |
| 445 | records |
| 446 | } |