Skip to main content

vector_core/db/
id_cache.rs

1//! ID cache — maps chat identifiers and npubs to SQLite row IDs.
2//!
3//! All lookups are cached in memory after first DB hit. Caches are
4//! preloaded at boot and cleared on account switch.
5
6use std::collections::HashMap;
7use std::sync::{Arc, RwLock};
8
9use crate::profile::NpubMap;
10
11// Row ids belong to ONE account's database. Resolving a chat or npub against
12// another account's cache returns a live id for the wrong row, which reads and
13// writes then follow silently.
14struct 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
25/// Drop a chat's cached identifier→id mapping. Call after deleting a chat row so
26/// a later recreate doesn't reuse the stale (now-deleted) integer id.
27pub fn forget_chat_id(chat_identifier: &str) {
28    chat_id_cache().write().unwrap().remove(chat_identifier);
29}
30
31/// Lookup-only: get integer chat ID from identifier. Errors if not found.
32pub fn get_chat_id_by_identifier(chat_identifier: &str) -> Result<i64, String> {
33    // Fast path: cache hit
34    {
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    // Cache miss: query DB
43    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    // Update cache
51    {
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
60/// Get or create integer chat ID from identifier.
61pub fn get_or_create_chat_id(chat_identifier: &str) -> Result<i64, String> {
62    // Fast path: cache hit
63    {
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    // Try existing
74    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        // Create stub chat entry. Discriminant must match ChatType::to_i32:
84        // 0 = DirectMessage (npub), 2 = Community (non-npub). Value 1 was the
85        // retired MlsGroup variant and is dropped by the get_all_chats load filter,
86        // so a non-npub stub MUST be 2 or the chat vanishes on reload.
87        let now = crate::clock::now_secs() as i64;
88        let chat_type: i32 = if chat_identifier.starts_with("npub1") { 0 } else { 2 };
89
90        // A DM stub's id IS its counterparty: write the participant now, or the
91        // row boots with an empty roster and every participant-keyed lookup
92        // (attachment downloads) misses forever.
93        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    // Update cache
108    {
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
117/// Get or create integer user ID from npub. Returns None for empty npub.
118pub fn get_or_create_user_id(npub: &str) -> Result<Option<i64>, String> {
119    if npub.is_empty() {
120        return Ok(None);
121    }
122
123    // Fast path: cache hit
124    {
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    // Update cache
151    {
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
160/// Preload all ID mappings into memory cache (call at boot).
161pub fn preload_id_caches() -> Result<(), String> {
162    let conn = match super::get_db_connection_guard_static() {
163        Ok(c) => c,
164        Err(_) => return Ok(()), // No DB yet, skip
165    };
166
167    // Load chat ID mappings
168    {
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    // Load user ID mappings
183    {
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
200/// Clear all ID caches (call on account switch).
201pub 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}