BlueGit

ict rusty-teams

Files

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

people.rs

987f0c4d History
people.rs 14.8 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 query = query.trim().trim_start_matches('@').trim().to_lowercase();
162 let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();
163 let mut seen: HashSet<String> = HashSet::from([my_user_id]);
164
165 let mut candidates: Vec<MentionCandidate> =
166 ranked(self.everyone_entry(conversation_id)?.into_iter(), &query);
167 candidates.extend(ranked(
168 self.local_people(conversation_id)?
169 .into_iter()
170 .filter(|person| seen.insert(person.user_id.clone()))
171 .map(MentionCandidate::Person),
172 &query,
173 ));
174 if let Conversation::Channel { team_id } = &conversation {
175 candidates.extend(ranked(
176 self.scope_entries(conversation_id, team_id)?,
177 &query,
178 ));
179 if let Ok(tags) = self.team_tags(team_id).await {
180 candidates.extend(ranked(tags.into_iter().map(tag_candidate), &query));
181 }
182 }
183 let local_people = candidates
184 .iter()
185 .filter(|candidate| matches!(candidate, MentionCandidate::Person(_)))
186 .count();
187 if query.chars().count() >= DIRECTORY_MIN_QUERY_CHARS
188 && local_people < limit
189 && let Ok(users) = self.search_people(&query).await
190 {
191 let directory = users
192 .into_iter()
193 .filter(|user| seen.insert(user.id.clone()))
194 .map(directory_person)
195 .map(MentionCandidate::Person);
196 candidates.extend(ranked(directory, &query));
197 }
198 candidates.truncate(limit);
199 Ok(candidates)
200 }
201
202 fn local_people(&self, conversation_id: &str) -> Result<Vec<PersonCandidate>> {
203 let member = |user_id: &str, display_name: &str| PersonCandidate {
204 user_id: user_id.to_owned(),
205 display_name: display_name.to_owned(),
206 mail: None,
207 job_title: None,
208 source: PersonSource::Member,
209 };
210 if let Some(chat) = self.store.chat(conversation_id)? {
211 return Ok(chat
212 .members
213 .iter()
214 .filter_map(|record| Some(member(record.user_id.as_deref()?, &record.display_name)))
215 .collect());
216 }
217 let mut recent = self
218 .store
219 .messages(conversation_id, None, RECENT_SENDERS_SCANNED)?;
220 recent.reverse();
221 Ok(recent
222 .iter()
223 .filter_map(|record| {
224 Some(member(
225 record.sender_id.as_deref()?,
226 record.sender_name.as_deref()?,
227 ))
228 })
229 .collect())
230 }
231
232 fn everyone_entry(&self, conversation_id: &str) -> Result<Option<MentionCandidate>> {
233 Ok(self
234 .store
235 .chat(conversation_id)?
236 .filter(|chat| chat.kind.eq_ignore_ascii_case(GROUP_CHAT_KIND))
237 .map(|chat| MentionCandidate::Everyone { chat_id: chat.id }))
238 }
239
240 fn scope_entries(
241 &self,
242 channel_id: &str,
243 team_id: &str,
244 ) -> Result<impl Iterator<Item = MentionCandidate> + use<R>> {
245 let channel = self
246 .store
247 .channel(channel_id)?
248 .map(|channel| MentionCandidate::Channel {
249 channel_id: channel.id,
250 name: channel.name,
251 });
252 let team = self
253 .store
254 .team(team_id)?
255 .map(|team| MentionCandidate::Team {
256 team_id: team.id,
257 name: team.name,
258 });
259 Ok(channel.into_iter().chain(team))
260 }
261
262 fn tag_lock(&self) -> std::sync::MutexGuard<'_, TagCache> {
263 self.tag_cache
264 .lock()
265 .unwrap_or_else(|poisoned| poisoned.into_inner())
266 }
267
268 fn directory_lock(&self) -> std::sync::MutexGuard<'_, DirectoryCache> {
269 self.directory_cache
270 .lock()
271 .unwrap_or_else(|poisoned| poisoned.into_inner())
272 }
273}
274
275fn tag_candidate(tag: Tag) -> MentionCandidate {
276 MentionCandidate::Tag {
277 tag_id: tag.id,
278 name: tag.display_name,
279 member_count: tag.member_count,
280 }
281}
282
283fn directory_person(user: User) -> PersonCandidate {
284 PersonCandidate {
285 display_name: user
286 .display_name
287 .or_else(|| user.mail.clone())
288 .or(user.user_principal_name)
289 .unwrap_or_default(),
290 mail: user.mail,
291 job_title: user.job_title,
292 user_id: user.id,
293 source: PersonSource::Directory,
294 }
295}
296
297/// The directory matched it on a field we do not hold, like the alias "bto"; Teams lists it too.
298const DIRECTORY_MATCH_TIER: u8 = 5;
299
300/// Keeps matches only. Best match first, the incoming order breaks ties.
301fn ranked(
302 candidates: impl Iterator<Item = MentionCandidate>,
303 query: &str,
304) -> Vec<MentionCandidate> {
305 let mut scored: Vec<(u8, MentionCandidate)> = candidates
306 .filter_map(|candidate| Some((match_tier(&candidate, query)?, candidate)))
307 .collect();
308 scored.sort_by_key(|(tier, _)| *tier);
309 scored.into_iter().map(|(_, candidate)| candidate).collect()
310}
311
312fn match_tier(candidate: &MentionCandidate, query: &str) -> Option<u8> {
313 if query.is_empty() {
314 return Some(0);
315 }
316 let name = candidate.display_name().to_lowercase();
317 if name.starts_with(query) {
318 return Some(0);
319 }
320 if name
321 .split(|character: char| !character.is_alphanumeric())
322 .any(|word| word.starts_with(query))
323 {
324 return Some(1);
325 }
326 if name.contains(query) {
327 return Some(2);
328 }
329 let MentionCandidate::Person(person) = candidate else {
330 return None;
331 };
332 let mail = person.mail.as_deref().map(str::to_lowercase);
333 match mail {
334 Some(mail) if mail.starts_with(query) => Some(3),
335 Some(mail) if mail.contains(query) => Some(4),
336 _ => (person.source == PersonSource::Directory).then_some(DIRECTORY_MATCH_TIER),
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 fn person(user_id: &str, name: &str, mail: Option<&str>) -> MentionCandidate {
345 MentionCandidate::Person(PersonCandidate {
346 user_id: user_id.to_owned(),
347 display_name: name.to_owned(),
348 mail: mail.map(str::to_owned),
349 job_title: None,
350 source: PersonSource::Member,
351 })
352 }
353
354 fn names(candidates: Vec<MentionCandidate>) -> Vec<String> {
355 candidates
356 .iter()
357 .map(|candidate| candidate.display_name().to_owned())
358 .collect()
359 }
360
361 #[test]
362 fn prefix_beats_word_start_beats_contains() {
363 let ranked = ranked(
364 [
365 person("1", "Maria Adams", None),
366 person("2", "Madame Curie", None),
367 person("3", "Ada Example", None),
368 person("4", "Nobody", None),
369 ]
370 .into_iter(),
371 "ada",
372 );
373 assert_eq!(
374 names(ranked),
375 ["Ada Example", "Maria Adams", "Madame Curie"]
376 );
377 }
378
379 #[test]
380 fn mail_matches_rank_after_name_matches() {
381 let ranked = ranked(
382 [
383 person("1", "Zed", Some("ada@example.com")),
384 person("2", "Ada", None),
385 ]
386 .into_iter(),
387 "ada",
388 );
389 assert_eq!(names(ranked), ["Ada", "Zed"]);
390 }
391
392 #[test]
393 fn a_directory_hit_on_the_alias_stays_after_the_name_matches() {
394 let MentionCandidate::Person(mut alias_hit) = person("1", "Bogdan Example", None) else {
395 unreachable!()
396 };
397 alias_hit.source = PersonSource::Directory;
398 let ranked = ranked(
399 [
400 MentionCandidate::Person(alias_hit),
401 person("2", "Bto Member", None),
402 person("3", "Nobody", None),
403 ]
404 .into_iter(),
405 "bto",
406 );
407 assert_eq!(names(ranked), ["Bto Member", "Bogdan Example"]);
408 }
409
410 #[test]
411 fn empty_query_keeps_the_incoming_order() {
412 let ranked = ranked(
413 [person("1", "B", None), person("2", "A", None)].into_iter(),
414 "",
415 );
416 assert_eq!(names(ranked), ["B", "A"]);
417 }
418
419 #[test]
420 fn candidates_convert_to_the_matching_mention() {
421 let team = MentionCandidate::Team {
422 team_id: "t".to_owned(),
423 name: "Squad".to_owned(),
424 };
425 assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad"));
426 let everyone = MentionCandidate::Everyone {
427 chat_id: "19:g".to_owned(),
428 };
429 assert_eq!(
430 everyone.to_mention(),
431 crate::MentionInput::everyone("19:g", "Everyone")
432 );
433 let tag = MentionCandidate::Tag {
434 tag_id: "tag-1".to_owned(),
435 name: "Design".to_owned(),
436 member_count: Some(3),
437 };
438 assert_eq!(
439 tag.to_mention(),
440 crate::MentionInput::tag("tag-1", "Design")
441 );
442 }
443
444 #[test]
445 fn everyone_matches_its_name_like_any_candidate() {
446 let everyone = || MentionCandidate::Everyone {
447 chat_id: "19:g".to_owned(),
448 };
449 assert_eq!(ranked([everyone()].into_iter(), "ev").len(), 1);
450 assert_eq!(ranked([everyone()].into_iter(), "").len(), 1);
451 assert!(ranked([everyone()].into_iter(), "ada").is_empty());
452 }
453
454 #[test]
455 fn the_directory_cache_expires_and_is_bounded() {
456 let mut cache = DirectoryCache::new();
457 cache.put("ada", Vec::new());
458 assert!(cache.get("ada").is_some());
459 assert!(cache.get("bo").is_none());
460 for index in 0..DIRECTORY_CACHE_MAX_QUERIES + 1 {
461 cache.put(&format!("q{index}"), Vec::new());
462 }
463 assert!(cache.entries.len() <= DIRECTORY_CACHE_MAX_QUERIES);
464 }
465}