BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / receipts.rs

receipts.rs

receipts.rs 9.2 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Mutex;
3use std::time::Duration;
4
5use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};
6use chrono::{DateTime, Utc};
7use store::{MessageRecord, ReadHorizonRecord};
8
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10use crate::error::Result;
11use crate::events::CoreEvent;
12use crate::remote::Remote;
13
14pub const DEFAULT_RECEIPT_DEBOUNCE: Duration = Duration::from_millis(500);
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ReceiptReader {
18 pub name: String,
19 pub at: DateTime<Utc>,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum ReceiptState {
24 Sent,
25 Read {
26 readers: Vec<ReceiptReader>,
27 total_others: usize,
28 },
29 Unknown,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33struct OtherMember {
34 name: String,
35 read_until: DateTime<Utc>,
36 read_at: DateTime<Utc>,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40struct ConversationReceipts {
41 my_user_id: String,
42 others: Vec<OtherMember>,
43 total_others: usize,
44}
45
46pub(crate) struct ReceiptCache {
47 conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,
48 pending: Mutex<HashSet<String>>,
49 read_from_store: Mutex<HashSet<String>>,
50 pub(crate) debounce: Duration,
51}
52
53impl Default for ReceiptCache {
54 fn default() -> Self {
55 ReceiptCache {
56 conversations: Mutex::new(HashMap::new()),
57 pending: Mutex::new(HashSet::new()),
58 read_from_store: Mutex::new(HashSet::new()),
59 debounce: DEFAULT_RECEIPT_DEBOUNCE,
60 }
61 }
62}
63
64pub(crate) fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
65 mutex
66 .lock()
67 .unwrap_or_else(|poisoned| poisoned.into_inner())
68}
69
70fn same_user(left: &str, right: &str) -> bool {
71 left.eq_ignore_ascii_case(right)
72}
73
74fn user_of(member_id: &str) -> &str {
75 member_id.rsplit(':').next().unwrap_or(member_id)
76}
77
78fn stored_horizon(horizon: MemberHorizon) -> ReadHorizonRecord {
79 ReadHorizonRecord {
80 member_id: horizon.member_id,
81 read_until: horizon.read_until,
82 read_at: horizon.read_at,
83 }
84}
85
86fn build(
87 my_user_id: &str,
88 horizons: &[ReadHorizonRecord],
89 members: &[store::MemberRecord],
90) -> Option<ConversationReceipts> {
91 let mut others: Vec<OtherMember> = horizons
92 .iter()
93 .filter(|horizon| !same_user(user_of(&horizon.member_id), my_user_id))
94 .map(|horizon| {
95 let user_id = user_of(&horizon.member_id);
96 let name = members
97 .iter()
98 .find(|member| {
99 member
100 .user_id
101 .as_deref()
102 .is_some_and(|known| same_user(known, user_id))
103 })
104 .map(|member| member.display_name.clone())
105 .unwrap_or_default();
106 OtherMember {
107 name,
108 read_until: horizon.read_until,
109 read_at: horizon.read_at.unwrap_or(horizon.read_until),
110 }
111 })
112 .collect();
113 if others.is_empty() {
114 return None;
115 }
116 others.sort_by(|left, right| left.name.cmp(&right.name));
117 let known_others = members
118 .iter()
119 .filter(|member| {
120 member
121 .user_id
122 .as_deref()
123 .is_none_or(|known| !same_user(known, my_user_id))
124 })
125 .count();
126 Some(ConversationReceipts {
127 my_user_id: my_user_id.to_owned(),
128 total_others: known_others.max(others.len()),
129 others,
130 })
131}
132
133fn state_of(receipts: &ConversationReceipts, record: &MessageRecord) -> ReceiptState {
134 let own = record
135 .sender_id
136 .as_deref()
137 .is_some_and(|sender| same_user(sender, &receipts.my_user_id));
138 if !own || record.deleted {
139 return ReceiptState::Unknown;
140 }
141 let mut readers: Vec<ReceiptReader> = receipts
142 .others
143 .iter()
144 .filter(|member| member.read_until >= record.created_at)
145 .map(|member| ReceiptReader {
146 name: member.name.clone(),
147 at: member.read_at,
148 })
149 .collect();
150 if readers.is_empty() {
151 return ReceiptState::Sent;
152 }
153 readers.sort_by(|left, right| {
154 left.at
155 .cmp(&right.at)
156 .then_with(|| left.name.cmp(&right.name))
157 });
158 ReceiptState::Read {
159 readers,
160 total_others: receipts.total_others,
161 }
162}
163
164impl<R: Remote> SyncEngine<R> {
165 pub fn with_receipt_debounce(mut self, debounce: Duration) -> Self {
166 self.receipts.debounce = debounce;
167 self
168 }
169
170 /// Own messages in chats only. Unknown for others' messages, channels, deleted messages and disabled receipts.
171 pub fn receipt_state(&self, conversation_id: &str, message_id: &str) -> ReceiptState {
172 let record = self
173 .store
174 .messages_by_id(conversation_id, &[message_id.to_owned()])
175 .ok()
176 .and_then(|mut found| found.remove(message_id));
177 record.map_or(ReceiptState::Unknown, |record| {
178 self.receipt_state_for(&record)
179 })
180 }
181
182 /// Memory first; the stored horizons of a chat are read once per session, so receipts show before the refresh.
183 pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {
184 self.load_stored_receipts(&record.conversation_id);
185 let conversations = locked(&self.receipts.conversations);
186 match conversations.get(&record.conversation_id) {
187 Some(Some(receipts)) => state_of(receipts, record),
188 _ => ReceiptState::Unknown,
189 }
190 }
191
192 fn load_stored_receipts(&self, conversation_id: &str) {
193 if !locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()) {
194 return;
195 }
196 if locked(&self.receipts.conversations).contains_key(conversation_id) {
197 return;
198 }
199 let Some(cached) = self.stored_receipts(conversation_id) else {
200 return;
201 };
202 locked(&self.receipts.conversations)
203 .entry(conversation_id.to_owned())
204 .or_insert(Some(cached));
205 }
206
207 fn stored_receipts(&self, conversation_id: &str) -> Option<ConversationReceipts> {
208 let horizons = self.store.read_horizons(conversation_id).ok()?;
209 if horizons.is_empty() {
210 return None;
211 }
212 let my_user_id = self.store.meta(META_USER_ID).ok()??;
213 let members = self.store.chat(conversation_id).ok()??.members;
214 build(&my_user_id, &horizons, &members)
215 }
216
217 /// Call when a chat opens. Channels are skipped.
218 pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {
219 if matches!(
220 self.resolve(conversation_id).await?,
221 Conversation::Channel { .. }
222 ) {
223 return Ok(());
224 }
225 let my_user_id = self.my_user_id().await?;
226 let horizons: Vec<ReadHorizonRecord> = self
227 .remote
228 .consumption_horizons(conversation_id)
229 .await?
230 .into_iter()
231 .map(stored_horizon)
232 .collect();
233 self.store.set_read_horizons(conversation_id, &horizons)?;
234 locked(&self.receipts.read_from_store).insert(conversation_id.to_owned());
235 let members = self
236 .store
237 .chat(conversation_id)?
238 .map(|chat| chat.members)
239 .unwrap_or_default();
240 let fresh = build(&my_user_id, &horizons, &members);
241 let changed = locked(&self.receipts.conversations)
242 .insert(conversation_id.to_owned(), fresh.clone())
243 .is_none_or(|previous| previous != fresh);
244 if changed {
245 let _ = self.events.send(CoreEvent::ReceiptsChanged {
246 conversation_id: conversation_id.to_owned(),
247 });
248 }
249 Ok(())
250 }
251
252 /// Calls within the debounce window return at once, the first call does the single refresh.
253 pub async fn refresh_receipts_debounced(&self, conversation_id: &str) -> Result<()> {
254 if !locked(&self.receipts.pending).insert(conversation_id.to_owned()) {
255 return Ok(());
256 }
257 tokio::time::sleep(self.receipts.debounce).await;
258 locked(&self.receipts.pending).remove(conversation_id);
259 self.refresh_receipts(conversation_id).await
260 }
261
262 /// Only conversations opened before are refreshed. Opening a chat fetches anyway.
263 pub async fn handle_receipt_event(&self, event: &MessageEvent) {
264 if event.kind != EventKind::ReadReceipt {
265 return;
266 }
267 let Some(conversation_id) = event.conversation_id.as_deref() else {
268 return;
269 };
270 if locked(&self.receipts.conversations).contains_key(conversation_id) {
271 let _ = self.refresh_receipts_debounced(conversation_id).await;
272 }
273 }
274
275 /// Refetches every known conversation after a reconnect or lost messages.
276 pub async fn handle_receipt_status(&self, status: &StatusEvent) {
277 if !matches!(status.kind, StatusKind::Connected | StatusKind::MessageLoss) {
278 return;
279 }
280 let known: Vec<String> = locked(&self.receipts.conversations)
281 .keys()
282 .cloned()
283 .collect();
284 for conversation_id in known {
285 let _ = self.refresh_receipts(&conversation_id).await;
286 }
287 }
288}