BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / warm_chats.rs

warm_chats.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
warm_chats.rs 2.6 KiB Download Raw
1use std::collections::HashSet;
2
3use crate::app_state::AppState;
4use crate::runtime;
5
6const RECENT_CHAT_COUNT: usize = 15;
7
8#[derive(Default)]
9pub struct WarmChats {
10 requested: HashSet<String>,
11}
12
13impl WarmChats {
14 fn take_new(&mut self, chat_ids: Vec<String>) -> Vec<String> {
15 chat_ids
16 .into_iter()
17 .filter(|chat_id| self.requested.insert(chat_id.clone()))
18 .collect()
19 }
20}
21
22pub fn recent_chat_ids(chats: &[store::ChatRecord], count: usize) -> Vec<String> {
23 let mut recent: Vec<_> = chats.iter().collect();
24 recent.sort_by(|left, right| right.last_message_at.cmp(&left.last_message_at));
25 recent
26 .into_iter()
27 .take(count)
28 .map(|chat| chat.id.clone())
29 .collect()
30}
31
32impl AppState {
33 pub(crate) fn warm_recent_chats(&mut self) {
34 let chat_ids = recent_chat_ids(&self.sidebar.chats, RECENT_CHAT_COUNT);
35 self.warm(chat_ids);
36 }
37
38 pub fn warm_chat(&mut self, chat_id: &str) {
39 self.warm(vec![chat_id.to_owned()]);
40 }
41
42 fn warm(&mut self, chat_ids: Vec<String>) {
43 let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {
44 return;
45 };
46 let chat_ids = self.warm_chats.take_new(chat_ids);
47 if chat_ids.is_empty() {
48 return;
49 }
50 let store = self.store.clone();
51 runtime::handle().spawn(async move {
52 for chat_id in chat_ids {
53 let cached = store
54 .messages(&chat_id, None, 1)
55 .is_ok_and(|messages| !messages.is_empty());
56 if !cached {
57 let _ = engine.fetch_newer(&chat_id).await;
58 }
59 }
60 });
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use chrono::{TimeZone, Utc};
67 use store::ChatRecord;
68
69 use super::*;
70
71 fn chat(id: &str, hour: Option<u32>) -> ChatRecord {
72 ChatRecord {
73 id: id.to_owned(),
74 last_message_at: hour
75 .map(|hour| Utc.with_ymd_and_hms(2026, 11, 11, hour, 0, 0).unwrap()),
76 ..Default::default()
77 }
78 }
79
80 #[test]
81 fn the_newest_chats_are_warmed_first() {
82 let chats = [
83 chat("old", Some(8)),
84 chat("never", None),
85 chat("new", Some(12)),
86 chat("mid", Some(10)),
87 ];
88 assert_eq!(recent_chat_ids(&chats, 2), ["new", "mid"]);
89 }
90
91 #[test]
92 fn a_chat_is_warmed_only_once() {
93 let mut warm = WarmChats::default();
94 assert_eq!(warm.take_new(vec!["a".into(), "b".into()]), ["a", "b"]);
95 assert_eq!(warm.take_new(vec!["b".into(), "c".into()]), ["c"]);
96 }
97}