vector_core/db/
id_cache.rs1use std::collections::HashMap;
7use std::sync::{Arc, RwLock};
8
9use crate::profile::NpubMap;
10
11struct ChatIds;
15struct UserIds;
16
17fn chat_id_cache() -> Arc<RwLock<HashMap<String, i64>>> {
18 crate::db::current_session().scoped::<ChatIds, _>()
19}
20
21fn user_id_cache() -> Arc<RwLock<NpubMap<i64>>> {
22 crate::db::current_session().scoped::<UserIds, _>()
23}
24
25pub fn forget_chat_id(chat_identifier: &str) {
28 chat_id_cache().write().unwrap().remove(chat_identifier);
29}
30
31pub fn get_chat_id_by_identifier(chat_identifier: &str) -> Result<i64, String> {
33 {
35 let owner = chat_id_cache();
36 let cache = owner.read().unwrap();
37 if let Some(&id) = cache.get(chat_identifier) {
38 return Ok(id);
39 }
40 }
41
42 let conn = super::get_db_connection_guard_static()?;
44 let id: i64 = conn.query_row(
45 "SELECT id FROM chats WHERE chat_identifier = ?1",
46 rusqlite::params![chat_identifier],
47 |row| row.get(0)
48 ).map_err(|_| format!("Chat not found: {}", chat_identifier))?;
49
50 {
52 let owner = chat_id_cache();
53 let mut cache = owner.write().unwrap();
54 cache.insert(chat_identifier.to_string(), id);
55 }
56
57 Ok(id)
58}
59
60pub fn get_or_create_chat_id(chat_identifier: &str) -> Result<i64, String> {
62 {
64 let owner = chat_id_cache();
65 let cache = owner.read().unwrap();
66 if let Some(&id) = cache.get(chat_identifier) {
67 return Ok(id);
68 }
69 }
70
71 let conn = super::get_db_connection_guard_static()?;
72
73 let existing: Option<i64> = conn.query_row(
75 "SELECT id FROM chats WHERE chat_identifier = ?1",
76 rusqlite::params![chat_identifier],
77 |row| row.get(0)
78 ).ok();
79
80 let id = if let Some(id) = existing {
81 id
82 } else {
83 let now = crate::clock::now_secs() as i64;
88 let chat_type: i32 = if chat_identifier.starts_with("npub1") { 0 } else { 2 };
89
90 let participants = if chat_type == 0 {
94 format!("[\"{}\"]", chat_identifier)
95 } else {
96 "[]".to_string()
97 };
98
99 conn.execute(
100 "INSERT INTO chats (chat_identifier, chat_type, participants, created_at) VALUES (?1, ?2, ?3, ?4)",
101 rusqlite::params![chat_identifier, chat_type, participants, now],
102 ).map_err(|e| format!("Failed to create chat stub: {}", e))?;
103
104 conn.last_insert_rowid()
105 };
106
107 {
109 let owner = chat_id_cache();
110 let mut cache = owner.write().unwrap();
111 cache.insert(chat_identifier.to_string(), id);
112 }
113
114 Ok(id)
115}
116
117pub fn get_or_create_user_id(npub: &str) -> Result<Option<i64>, String> {
119 if npub.is_empty() {
120 return Ok(None);
121 }
122
123 {
125 let owner = user_id_cache();
126 let cache = owner.read().unwrap();
127 if let Some(&id) = cache.get(npub) {
128 return Ok(Some(id));
129 }
130 }
131
132 let conn = super::get_db_connection_guard_static()?;
133
134 let existing: Option<i64> = conn.query_row(
135 "SELECT id FROM profiles WHERE npub = ?1",
136 rusqlite::params![npub],
137 |row| row.get(0)
138 ).ok();
139
140 let id = if let Some(id) = existing {
141 id
142 } else {
143 conn.execute(
144 "INSERT INTO profiles (npub, name, display_name) VALUES (?1, '', '')",
145 rusqlite::params![npub],
146 ).map_err(|e| format!("Failed to create profile stub: {}", e))?;
147 conn.last_insert_rowid()
148 };
149
150 {
152 let owner = user_id_cache();
153 let mut cache = owner.write().unwrap();
154 cache.insert(npub, id);
155 }
156
157 Ok(Some(id))
158}
159
160pub fn preload_id_caches() -> Result<(), String> {
162 let conn = match super::get_db_connection_guard_static() {
163 Ok(c) => c,
164 Err(_) => return Ok(()), };
166
167 {
169 let mut stmt = conn.prepare("SELECT chat_identifier, id FROM chats")
170 .map_err(|e| format!("Failed to prepare chat query: {}", e))?;
171 let rows = stmt.query_map([], |row| {
172 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
173 }).map_err(|e| format!("Failed to query chats: {}", e))?;
174
175 let owner = chat_id_cache();
176 let mut cache = owner.write().unwrap();
177 for row in rows.flatten() {
178 cache.insert(row.0, row.1);
179 }
180 }
181
182 {
184 let mut stmt = conn.prepare("SELECT npub, id FROM profiles")
185 .map_err(|e| format!("Failed to prepare user query: {}", e))?;
186 let rows = stmt.query_map([], |row| {
187 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
188 }).map_err(|e| format!("Failed to query profiles: {}", e))?;
189
190 let owner = user_id_cache();
191 let mut cache = owner.write().unwrap();
192 for row in rows.flatten() {
193 cache.insert(&row.0, row.1);
194 }
195 }
196
197 Ok(())
198}
199
200pub fn clear_id_caches() {
202 chat_id_cache().write().unwrap().clear();
203 user_id_cache().write().unwrap().clear();
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209 use nostr_sdk::prelude::{Keys, ToBech32};
210
211 fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
212 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
213 crate::db::close_database();
214 crate::db::clear_id_caches();
215 let tmp = tempfile::tempdir().unwrap();
216 let account = Keys::generate().public_key().to_bech32().unwrap();
217 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
218 crate::db::set_current_account(account.clone()).unwrap();
219 crate::db::init_database(&account).unwrap();
220 (tmp, guard)
221 }
222
223 fn drop_row(npub: &str) {
224 crate::db::get_write_connection_guard_static()
225 .unwrap()
226 .execute("DELETE FROM profiles WHERE npub = ?1", rusqlite::params![npub])
227 .unwrap();
228 }
229
230 #[test]
231 fn user_ids_are_cached_per_npub_and_never_merged() {
232 let (_tmp, _guard) = init_test_db();
233 let a = Keys::generate().public_key().to_bech32().unwrap();
234 let b = Keys::generate().public_key().to_bech32().unwrap();
235 let id_a = get_or_create_user_id(&a).unwrap().unwrap();
236 let id_b = get_or_create_user_id(&b).unwrap().unwrap();
237 assert_ne!(id_a, id_b);
238
239 let upper = a.to_uppercase();
240 let id_upper = get_or_create_user_id(&upper).unwrap().unwrap();
241 assert_ne!(id_upper, id_a, "another spelling is another row, never the same key");
242 let id_fake = get_or_create_user_id("npub1notbech32").unwrap().unwrap();
243
244 for npub in [&a, &b, &upper] {
245 drop_row(npub);
246 }
247 drop_row("npub1notbech32");
248 assert_eq!(get_or_create_user_id(&a).unwrap(), Some(id_a), "served from the cache");
249 assert_eq!(get_or_create_user_id(&b).unwrap(), Some(id_b));
250 assert_eq!(get_or_create_user_id(&upper).unwrap(), Some(id_upper));
251 assert_eq!(get_or_create_user_id("npub1notbech32").unwrap(), Some(id_fake));
252 assert_eq!(get_or_create_user_id("").unwrap(), None);
253 }
254
255 #[test]
256 fn preload_fills_the_user_cache_from_the_table() {
257 let (_tmp, _guard) = init_test_db();
258 let a = Keys::generate().public_key().to_bech32().unwrap();
259 let id_a = get_or_create_user_id(&a).unwrap().unwrap();
260 let id_fake = get_or_create_user_id("npub1legacy").unwrap().unwrap();
261 clear_id_caches();
262 preload_id_caches().unwrap();
263 drop_row(&a);
264 drop_row("npub1legacy");
265 assert_eq!(get_or_create_user_id(&a).unwrap(), Some(id_a));
266 assert_eq!(get_or_create_user_id("npub1legacy").unwrap(), Some(id_fake));
267 }
268}