BlueGit

ict rusty-teams

Files

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

people.rs

people.rs 14.0 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/// Keeps matches only. Best match first, the incoming order breaks ties.
298fn ranked(
299 candidates: impl Iterator<Item = MentionCandidate>,
300 query: &str,
301) -> Vec<MentionCandidate> {
302 let mut scored: Vec<(u8, MentionCandidate)> = candidates
303 .filter_map(|candidate| Some((match_tier(&candidate, query)?, candidate)))
304 .collect();
305 scored.sort_by_key(|(tier, _)| *tier);
306 scored.into_iter().map(|(_, candidate)| candidate).collect()
307}
308
309fn match_tier(candidate: &MentionCandidate, query: &str) -> Option<u8> {
310 if query.is_empty() {
311 return Some(0);
312 }
313 let name = candidate.display_name().to_lowercase();
314 if name.starts_with(query) {
315 return Some(0);
316 }
317 if name
318 .split(|character: char| !character.is_alphanumeric())
319 .any(|word| word.starts_with(query))
320 {
321 return Some(1);
322 }
323 if name.contains(query) {
324 return Some(2);
325 }
326 let MentionCandidate::Person(person) = candidate else {
327 return None;
328 };
329 let mail = person.mail.as_deref()?.to_lowercase();
330 if mail.starts_with(query) {
331 Some(3)
332 } else {
333 mail.contains(query).then_some(4)
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 fn person(user_id: &str, name: &str, mail: Option<&str>) -> MentionCandidate {
342 MentionCandidate::Person(PersonCandidate {
343 user_id: user_id.to_owned(),
344 display_name: name.to_owned(),
345 mail: mail.map(str::to_owned),
346 job_title: None,
347 source: PersonSource::Directory,
348 })
349 }
350
351 fn names(candidates: Vec<MentionCandidate>) -> Vec<String> {
352 candidates
353 .iter()
354 .map(|candidate| candidate.display_name().to_owned())
355 .collect()
356 }
357
358 #[test]
359 fn prefix_beats_word_start_beats_contains() {
360 let ranked = ranked(
361 [
362 person("1", "Maria Adams", None),
363 person("2", "Madame Curie", None),
364 person("3", "Ada Example", None),
365 person("4", "Nobody", None),
366 ]
367 .into_iter(),
368 "ada",
369 );
370 assert_eq!(
371 names(ranked),
372 ["Ada Example", "Maria Adams", "Madame Curie"]
373 );
374 }
375
376 #[test]
377 fn mail_matches_rank_after_name_matches() {
378 let ranked = ranked(
379 [
380 person("1", "Zed", Some("ada@example.com")),
381 person("2", "Ada", None),
382 ]
383 .into_iter(),
384 "ada",
385 );
386 assert_eq!(names(ranked), ["Ada", "Zed"]);
387 }
388
389 #[test]
390 fn empty_query_keeps_the_incoming_order() {
391 let ranked = ranked(
392 [person("1", "B", None), person("2", "A", None)].into_iter(),
393 "",
394 );
395 assert_eq!(names(ranked), ["B", "A"]);
396 }
397
398 #[test]
399 fn candidates_convert_to_the_matching_mention() {
400 let team = MentionCandidate::Team {
401 team_id: "t".to_owned(),
402 name: "Squad".to_owned(),
403 };
404 assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad"));
405 let everyone = MentionCandidate::Everyone {
406 chat_id: "19:g".to_owned(),
407 };
408 assert_eq!(
409 everyone.to_mention(),
410 crate::MentionInput::everyone("19:g", "Everyone")
411 );
412 let tag = MentionCandidate::Tag {
413 tag_id: "tag-1".to_owned(),
414 name: "Design".to_owned(),
415 member_count: Some(3),
416 };
417 assert_eq!(
418 tag.to_mention(),
419 crate::MentionInput::tag("tag-1", "Design")
420 );
421 }
422
423 #[test]
424 fn everyone_matches_its_name_like_any_candidate() {
425 let everyone = || MentionCandidate::Everyone {
426 chat_id: "19:g".to_owned(),
427 };
428 assert_eq!(ranked([everyone()].into_iter(), "ev").len(), 1);
429 assert_eq!(ranked([everyone()].into_iter(), "").len(), 1);
430 assert!(ranked([everyone()].into_iter(), "ada").is_empty());
431 }
432
433 #[test]
434 fn the_directory_cache_expires_and_is_bounded() {
435 let mut cache = DirectoryCache::new();
436 cache.put("ada", Vec::new());
437 assert!(cache.get("ada").is_some());
438 assert!(cache.get("bo").is_none());
439 for index in 0..DIRECTORY_CACHE_MAX_QUERIES + 1 {
440 cache.put(&format!("q{index}"), Vec::new());
441 }
442 assert!(cache.entries.len() <= DIRECTORY_CACHE_MAX_QUERIES);
443 }
444}