BlueGit

ict rusty-teams

Files

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

people.rs

people.rs 15.1 KiB Download Raw
1use std::collections::HashSet;
2use std::time::{Duration, Instant};
3
4use graph::{Tag, User};
5
6use crate::engine::{Conversation, META_USER_ID, SyncEngine};
7use crate::error::Result;
8use crate::remote::Remote;
9
10const DIRECTORY_CACHE_TTL: Duration = Duration::from_secs(300);
11const DIRECTORY_CACHE_MAX_QUERIES: usize = 64;
12const DIRECTORY_MIN_QUERY_CHARS: usize = 2;
13const RECENT_SENDERS_SCANNED: usize = 200;
14const TAG_CACHE_TTL: Duration = Duration::from_secs(300);
15const GROUP_CHAT_KIND: &str = "group";
16pub const EVERYONE_MENTION_TEXT: &str = "Everyone";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum PersonSource {
20 Member,
21 Directory,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct PersonCandidate {
26 pub user_id: String,
27 pub display_name: String,
28 pub mail: Option<String>,
29 pub job_title: Option<String>,
30 pub source: PersonSource,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum MentionCandidate {
35 Person(PersonCandidate),
36 Channel {
37 channel_id: String,
38 name: String,
39 },
40 Team {
41 team_id: String,
42 name: String,
43 },
44 Everyone {
45 chat_id: String,
46 },
47 Tag {
48 tag_id: String,
49 name: String,
50 member_count: Option<u32>,
51 },
52}
53
54impl MentionCandidate {
55 pub fn display_name(&self) -> &str {
56 match self {
57 MentionCandidate::Person(person) => &person.display_name,
58 MentionCandidate::Channel { name, .. }
59 | MentionCandidate::Team { name, .. }
60 | MentionCandidate::Tag { name, .. } => name,
61 MentionCandidate::Everyone { .. } => EVERYONE_MENTION_TEXT,
62 }
63 }
64
65 /// Ready to pass to the send, reply and edit calls.
66 pub fn to_mention(&self) -> crate::MentionInput {
67 match self {
68 MentionCandidate::Person(person) => {
69 crate::MentionInput::user(&person.user_id, &person.display_name)
70 }
71 MentionCandidate::Channel { channel_id, name } => {
72 crate::MentionInput::channel(channel_id, name)
73 }
74 MentionCandidate::Team { team_id, name } => crate::MentionInput::team(team_id, name),
75 MentionCandidate::Everyone { chat_id } => {
76 crate::MentionInput::everyone(chat_id, EVERYONE_MENTION_TEXT)
77 }
78 MentionCandidate::Tag { tag_id, name, .. } => crate::MentionInput::tag(tag_id, name),
79 }
80 }
81}
82
83#[derive(Default)]
84pub(crate) struct TagCache {
85 entries: std::collections::HashMap<String, (Instant, Vec<Tag>)>,
86}
87
88impl TagCache {
89 fn get(&self, team_id: &str) -> Option<Vec<Tag>> {
90 let (stored_at, tags) = self.entries.get(team_id)?;
91 (stored_at.elapsed() < TAG_CACHE_TTL).then(|| tags.clone())
92 }
93
94 fn put(&mut self, team_id: &str, tags: Vec<Tag>) {
95 self.entries
96 .insert(team_id.to_owned(), (Instant::now(), tags));
97 }
98}
99
100pub(crate) struct DirectoryCache {
101 entries: std::collections::HashMap<String, (Instant, Vec<User>)>,
102}
103
104impl DirectoryCache {
105 pub(crate) fn new() -> Self {
106 DirectoryCache {
107 entries: std::collections::HashMap::new(),
108 }
109 }
110
111 fn get(&self, query: &str) -> Option<Vec<User>> {
112 let (stored_at, users) = self.entries.get(query)?;
113 (stored_at.elapsed() < DIRECTORY_CACHE_TTL).then(|| users.clone())
114 }
115
116 fn put(&mut self, query: &str, users: Vec<User>) {
117 if self.entries.len() >= DIRECTORY_CACHE_MAX_QUERIES {
118 self.entries
119 .retain(|_, (stored_at, _)| stored_at.elapsed() < DIRECTORY_CACHE_TTL);
120 }
121 if self.entries.len() >= DIRECTORY_CACHE_MAX_QUERIES {
122 self.entries.clear();
123 }
124 self.entries
125 .insert(query.to_owned(), (Instant::now(), users));
126 }
127}
128
129impl<R: Remote> SyncEngine<R> {
130 /// Directory search, answers are cached in memory for five minutes per query.
131 pub async fn search_people(&self, query: &str) -> Result<Vec<User>> {
132 let key = query.trim().to_lowercase();
133 if let Some(cached) = self.directory_lock().get(&key) {
134 return Ok(cached);
135 }
136 let users = self.remote.search_people(query).await?;
137 self.directory_lock().put(&key, users.clone());
138 Ok(users)
139 }
140
141 /// The team's tags, cached in memory for five minutes per team; a failed load is cached as no tags.
142 pub async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
143 if let Some(cached) = self.tag_lock().get(team_id) {
144 return Ok(cached);
145 }
146 let tags = self.remote.team_tags(team_id).await;
147 self.tag_lock()
148 .put(team_id, tags.as_ref().cloned().unwrap_or_default());
149 tags
150 }
151
152 /// Autocomplete for `@`: Everyone in a group chat, members of the conversation, then (channels) the channel,
153 /// its team and the team's tags, then the directory. A failing tag or directory lookup still returns the local part.
154 pub async fn mention_candidates(
155 &self,
156 conversation_id: &str,
157 query: &str,
158 limit: usize,
159 ) -> Result<Vec<MentionCandidate>> {
160 let conversation = self.resolve(conversation_id).await?;
161 let typed = query.trim().trim_start_matches('@').trim().to_lowercase();
162 let query = crate::search_fold(&typed);
163 let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();
164 let mut seen: HashSet<String> = HashSet::from([my_user_id]);
165
166 let mut candidates: Vec<MentionCandidate> =
167 ranked(self.everyone_entry(conversation_id)?.into_iter(), &query);
168 candidates.extend(ranked(
169 self.local_people(conversation_id)?
170 .into_iter()
171 .filter(|person| seen.insert(person.user_id.clone()))
172 .map(MentionCandidate::Person),
173 &query,
174 ));
175 if let Conversation::Channel { team_id } = &conversation {
176 candidates.extend(ranked(
177 self.scope_entries(conversation_id, team_id)?,
178 &query,
179 ));
180 if let Ok(tags) = self.team_tags(team_id).await {
181 candidates.extend(ranked(tags.into_iter().map(tag_candidate), &query));
182 }
183 }
184 let local_people = candidates
185 .iter()
186 .filter(|candidate| matches!(candidate, MentionCandidate::Person(_)))
187 .count();
188 if query.chars().count() >= DIRECTORY_MIN_QUERY_CHARS
189 && local_people < limit
190 && let Ok(users) = self.search_people(&typed).await
191 {
192 let directory = users
193 .into_iter()
194 .filter(|user| seen.insert(user.id.clone()))
195 .map(directory_person)
196 .map(MentionCandidate::Person);
197 candidates.extend(ranked(directory, &query));
198 }
199 candidates.truncate(limit);
200 Ok(candidates)
201 }
202
203 fn local_people(&self, conversation_id: &str) -> Result<Vec<PersonCandidate>> {
204 let member = |user_id: &str, display_name: &str| PersonCandidate {
205 user_id: user_id.to_owned(),
206 display_name: display_name.to_owned(),
207 mail: None,
208 job_title: None,
209 source: PersonSource::Member,
210 };
211 if let Some(chat) = self.store.chat(conversation_id)? {
212 return Ok(chat
213 .members
214 .iter()
215 .filter_map(|record| Some(member(record.user_id.as_deref()?, &record.display_name)))
216 .collect());
217 }
218 let mut recent = self
219 .store
220 .messages(conversation_id, None, RECENT_SENDERS_SCANNED)?;
221 recent.reverse();
222 Ok(recent
223 .iter()
224 .filter_map(|record| {
225 Some(member(
226 record.sender_id.as_deref()?,
227 record.sender_name.as_deref()?,
228 ))
229 })
230 .collect())
231 }
232
233 fn everyone_entry(&self, conversation_id: &str) -> Result<Option<MentionCandidate>> {
234 Ok(self
235 .store
236 .chat(conversation_id)?
237 .filter(|chat| chat.kind.eq_ignore_ascii_case(GROUP_CHAT_KIND))
238 .map(|chat| MentionCandidate::Everyone { chat_id: chat.id }))
239 }
240
241 fn scope_entries(
242 &self,
243 channel_id: &str,
244 team_id: &str,
245 ) -> Result<impl Iterator<Item = MentionCandidate> + use<R>> {
246 let channel = self
247 .store
248 .channel(channel_id)?
249 .map(|channel| MentionCandidate::Channel {
250 channel_id: channel.id,
251 name: channel.name,
252 });
253 let team = self
254 .store
255 .team(team_id)?
256 .map(|team| MentionCandidate::Team {
257 team_id: team.id,
258 name: team.name,
259 });
260 Ok(channel.into_iter().chain(team))
261 }
262
263 fn tag_lock(&self) -> std::sync::MutexGuard<'_, TagCache> {
264 self.tag_cache
265 .lock()
266 .unwrap_or_else(|poisoned| poisoned.into_inner())
267 }
268
269 fn directory_lock(&self) -> std::sync::MutexGuard<'_, DirectoryCache> {
270 self.directory_cache
271 .lock()
272 .unwrap_or_else(|poisoned| poisoned.into_inner())
273 }
274}
275
276fn tag_candidate(tag: Tag) -> MentionCandidate {
277 MentionCandidate::Tag {
278 tag_id: tag.id,
279 name: tag.display_name,
280 member_count: tag.member_count,
281 }
282}
283
284fn directory_person(user: User) -> PersonCandidate {
285 PersonCandidate {
286 display_name: user
287 .display_name
288 .or_else(|| user.mail.clone())
289 .or(user.user_principal_name)
290 .unwrap_or_default(),
291 mail: user.mail,
292 job_title: user.job_title,
293 user_id: user.id,
294 source: PersonSource::Directory,
295 }
296}
297
298/// The directory matched it on a field we do not hold, like the alias "bto"; Teams lists it too.
299const DIRECTORY_MATCH_TIER: u8 = 5;
300
301/// Keeps matches only. Best match first, the incoming order breaks ties.
302fn ranked(
303 candidates: impl Iterator<Item = MentionCandidate>,
304 query: &str,
305) -> Vec<MentionCandidate> {
306 let mut scored: Vec<(u8, MentionCandidate)> = candidates
307 .filter_map(|candidate| Some((match_tier(&candidate, query)?, candidate)))
308 .collect();
309 scored.sort_by_key(|(tier, _)| *tier);
310 scored.into_iter().map(|(_, candidate)| candidate).collect()
311}
312
313fn match_tier(candidate: &MentionCandidate, query: &str) -> Option<u8> {
314 if query.is_empty() {
315 return Some(0);
316 }
317 let name = crate::search_fold(candidate.display_name());
318 if name.starts_with(query) {
319 return Some(0);
320 }
321 if name
322 .split(|character: char| !character.is_alphanumeric())
323 .any(|word| word.starts_with(query))
324 {
325 return Some(1);
326 }
327 if name.contains(query) {
328 return Some(2);
329 }
330 let MentionCandidate::Person(person) = candidate else {
331 return None;
332 };
333 let mail = person.mail.as_deref().map(str::to_lowercase);
334 match mail {
335 Some(mail) if mail.starts_with(query) => Some(3),
336 Some(mail) if mail.contains(query) => Some(4),
337 _ => (person.source == PersonSource::Directory).then_some(DIRECTORY_MATCH_TIER),
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344
345 fn person(user_id: &str, name: &str, mail: Option<&str>) -> MentionCandidate {
346 MentionCandidate::Person(PersonCandidate {
347 user_id: user_id.to_owned(),
348 display_name: name.to_owned(),
349 mail: mail.map(str::to_owned),
350 job_title: None,
351 source: PersonSource::Member,
352 })
353 }
354
355 fn names(candidates: Vec<MentionCandidate>) -> Vec<String> {
356 candidates
357 .iter()
358 .map(|candidate| candidate.display_name().to_owned())
359 .collect()
360 }
361
362 #[test]
363 fn prefix_beats_word_start_beats_contains() {
364 let ranked = ranked(
365 [
366 person("1", "Maria Adams", None),
367 person("2", "Madame Curie", None),
368 person("3", "Ada Example", None),
369 person("4", "Nobody", None),
370 ]
371 .into_iter(),
372 "ada",
373 );
374 assert_eq!(
375 names(ranked),
376 ["Ada Example", "Maria Adams", "Madame Curie"]
377 );
378 }
379
380 #[test]
381 fn names_match_without_their_diacritics() {
382 let ranked = ranked(
383 [person("1", "Şeyma Öztürk", None)].into_iter(),
384 &crate::search_fold("ozturk"),
385 );
386 assert_eq!(names(ranked), ["Şeyma Öztürk"]);
387 }
388
389 #[test]
390 fn mail_matches_rank_after_name_matches() {
391 let ranked = ranked(
392 [
393 person("1", "Zed", Some("ada@example.com")),
394 person("2", "Ada", None),
395 ]
396 .into_iter(),
397 "ada",
398 );
399 assert_eq!(names(ranked), ["Ada", "Zed"]);
400 }
401
402 #[test]
403 fn a_directory_hit_on_the_alias_stays_after_the_name_matches() {
404 let MentionCandidate::Person(mut alias_hit) = person("1", "Bogdan Example", None) else {
405 unreachable!()
406 };
407 alias_hit.source = PersonSource::Directory;
408 let ranked = ranked(
409 [
410 MentionCandidate::Person(alias_hit),
411 person("2", "Bto Member", None),
412 person("3", "Nobody", None),
413 ]
414 .into_iter(),
415 "bto",
416 );
417 assert_eq!(names(ranked), ["Bto Member", "Bogdan Example"]);
418 }
419
420 #[test]
421 fn empty_query_keeps_the_incoming_order() {
422 let ranked = ranked(
423 [person("1", "B", None), person("2", "A", None)].into_iter(),
424 "",
425 );
426 assert_eq!(names(ranked), ["B", "A"]);
427 }
428
429 #[test]
430 fn candidates_convert_to_the_matching_mention() {
431 let team = MentionCandidate::Team {
432 team_id: "t".to_owned(),
433 name: "Squad".to_owned(),
434 };
435 assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad"));
436 let everyone = MentionCandidate::Everyone {
437 chat_id: "19:g".to_owned(),
438 };
439 assert_eq!(
440 everyone.to_mention(),
441 crate::MentionInput::everyone("19:g", "Everyone")
442 );
443 let tag = MentionCandidate::Tag {
444 tag_id: "tag-1".to_owned(),
445 name: "Design".to_owned(),
446 member_count: Some(3),
447 };
448 assert_eq!(
449 tag.to_mention(),
450 crate::MentionInput::tag("tag-1", "Design")
451 );
452 }
453
454 #[test]
455 fn everyone_matches_its_name_like_any_candidate() {
456 let everyone = || MentionCandidate::Everyone {
457 chat_id: "19:g".to_owned(),
458 };
459 assert_eq!(ranked([everyone()].into_iter(), "ev").len(), 1);
460 assert_eq!(ranked([everyone()].into_iter(), "").len(), 1);
461 assert!(ranked([everyone()].into_iter(), "ada").is_empty());
462 }
463
464 #[test]
465 fn the_directory_cache_expires_and_is_bounded() {
466 let mut cache = DirectoryCache::new();
467 cache.put("ada", Vec::new());
468 assert!(cache.get("ada").is_some());
469 assert!(cache.get("bo").is_none());
470 for index in 0..DIRECTORY_CACHE_MAX_QUERIES + 1 {
471 cache.put(&format!("q{index}"), Vec::new());
472 }
473 assert!(cache.entries.len() <= DIRECTORY_CACHE_MAX_QUERIES);
474 }
475}