Skip to main content

vector_core/db/
mod.rs

1//! Database layer — SQLite with per-account databases.
2//!
3//! Architecture:
4//! - Read pool: multiple connections for parallel reads (WAL mode)
5//! - Write pool: single Mutex-protected connection (serialized writes)
6//! - RAII guards: auto-return connections to pools on drop
7//!
8//! All connection functions use static `DATA_DIR` — no Tauri AppHandle required.
9
10use std::path::PathBuf;
11use std::sync::{Arc, Mutex, OnceLock, LazyLock, RwLock};
12use std::ops::{Deref, DerefMut};
13
14use serde::{Deserialize, Serialize};
15
16pub mod settings;
17pub mod at_rest;
18pub mod miniapps;
19pub mod schema;
20pub mod profiles;
21pub mod id_cache;
22pub mod events;
23pub mod attachments;
24pub mod media_store;
25pub mod chats;
26pub mod wrappers;
27pub mod nip17_keys;
28pub mod community;
29pub mod v1_purge;
30pub mod bots;
31pub mod notify;
32pub mod saved;
33#[cfg(target_arch = "wasm32")]
34pub mod webfs;
35#[cfg(target_arch = "wasm32")]
36use webfs::{clear_active_account_file_in, list_account_npubs_in, read_active_account_file_in, write_active_account_file_in};
37
38pub use settings::{
39    get_sql_setting, set_sql_setting, advance_u64_setting, get_pkey, set_pkey, get_seed, set_seed, remove_setting,
40    get_signer_type, set_signer_type,
41    get_bunker_url, set_bunker_url,
42    get_bunker_remote_pubkey, set_bunker_remote_pubkey,
43    commit_bunker_account_setup,
44    get_nip55_user_pubkey, set_nip55_user_pubkey,
45    get_nip55_signer_package, set_nip55_signer_package,
46    commit_nip55_account_setup, commit_external_signer_setup,
47};
48
49// ============================================================================
50// App Data Directory
51// ============================================================================
52
53static APP_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
54
55pub fn set_app_data_dir(path: PathBuf) {
56    let _ = APP_DATA_DIR.set(path);
57}
58
59/// The data dir every test must use — ONE per process, alive for its whole life.
60///
61/// `APP_DATA_DIR` is set-once, so in a test binary only the first
62/// `set_app_data_dir` ever takes effect: every later helper silently kept using
63/// the FIRST test's `TempDir`, which was deleted the moment that test returned,
64/// leaving the rest to build account dirs under a path that no longer existed.
65/// Which test drew the short straw depended on thread scheduling, so the failures
66/// wandered. Tests already isolate by account subdirectory, so sharing the root is
67/// safe; what they cannot share is a lifetime owned by one of them.
68#[cfg(test)]
69pub(crate) fn shared_test_data_dir() -> &'static std::path::Path {
70    static DIR: OnceLock<tempfile::TempDir> = OnceLock::new();
71    // Never dropped: process-lifetime by construction, so no test can pull it out
72    // from under another. Named by process, so the next run can clear what it left.
73    DIR.get_or_init(|| {
74        sweep_dead_test_dirs();
75        tempfile::Builder::new().prefix(&format!("vector-test-{}-", std::process::id())).tempdir().expect("test data dir")
76    })
77    .path()
78}
79
80/// Earlier runs' roots: every test process leaves one, and the OS is slow to reclaim them.
81#[cfg(test)]
82fn sweep_dead_test_dirs() {
83    let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else { return };
84    for entry in entries.flatten() {
85        let name = entry.file_name().to_string_lossy().into_owned();
86        let Some(pid) = name.strip_prefix("vector-test-").and_then(|r| r.split('-').next()).and_then(|p| p.parse::<i32>().ok()) else { continue };
87        // SAFETY: signal 0 delivers nothing; it only asks whether the process exists.
88        #[cfg(unix)]
89        let gone = unsafe { libc::kill(pid, 0) } == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
90        #[cfg(not(unix))]
91        let gone = { let _ = pid; false };
92        if gone {
93            let _ = std::fs::remove_dir_all(entry.path());
94        }
95    }
96}
97
98pub fn get_app_data_dir() -> Result<&'static PathBuf, String> {
99    APP_DATA_DIR.get().ok_or_else(|| "App data directory not initialized".to_string())
100}
101
102/// Host app version, stamped into each account on open so a later downgrade can
103/// name what wrote the schema. Optional: the downgrade guard keys off the
104/// migration high-water mark, never this.
105static APP_VERSION: OnceLock<String> = OnceLock::new();
106
107pub fn set_app_version(version: impl Into<String>) {
108    let _ = APP_VERSION.set(version.into());
109}
110
111/// Host-installed override for the download directory. Tauri sets this
112/// at boot via `set_download_dir()` so platform conventions (XDG on
113/// Linux, Known Folders on Windows) are honored. Headless callers
114/// (vector-agent CLI, tests) fall through to the env-var path.
115static DOWNLOAD_DIR_OVERRIDE: OnceLock<PathBuf> = OnceLock::new();
116
117/// Install the host-resolved download directory. Must be called at
118/// startup before any `get_download_dir()` consumer runs; callers that
119/// run earlier hit the fallback.
120pub fn set_download_dir(path: PathBuf) {
121    let _ = DOWNLOAD_DIR_OVERRIDE.set(path);
122}
123
124/// Where the user's own copies go: Saves, and media kept unencrypted. Android's public
125/// `Download/Vector`, which outlives the app; elsewhere the download directory.
126static PUBLIC_DIR_OVERRIDE: OnceLock<PathBuf> = OnceLock::new();
127
128pub fn set_public_dir(path: PathBuf) {
129    let _ = PUBLIC_DIR_OVERRIDE.set(path);
130}
131
132pub fn get_public_dir() -> PathBuf {
133    PUBLIC_DIR_OVERRIDE.get().cloned().unwrap_or_else(get_download_dir)
134}
135
136/// Every folder Vector writes plain files into: the download directory, then the public one.
137pub fn download_roots() -> Vec<PathBuf> {
138    let (download, public) = (get_download_dir(), get_public_dir());
139    if public == download { vec![download] } else { vec![download, public] }
140}
141
142/// Platform-appropriate download directory for file attachments.
143///
144/// Prefers the host-installed override (honors `xdg-user-dirs`,
145/// `FOLDERID_Downloads`, `NSDownloadsDirectory`, `NSDocumentDirectory`).
146/// Falls back to `$HOME/Downloads/vector` on desktop, then
147/// `<app_data>/vector_downloads` on mobile / pre-init.
148pub fn get_download_dir() -> PathBuf {
149    if let Some(installed) = DOWNLOAD_DIR_OVERRIDE.get() {
150        return installed.clone();
151    }
152    #[cfg(any(target_os = "macos", target_os = "linux"))]
153    {
154        if let Ok(home) = std::env::var("HOME") {
155            return PathBuf::from(home).join("Downloads/vector");
156        }
157    }
158    #[cfg(target_os = "windows")]
159    {
160        if let Ok(profile) = std::env::var("USERPROFILE") {
161            return PathBuf::from(profile).join("Downloads").join("vector");
162        }
163    }
164    // Mobile / fallback: use data dir
165    if let Ok(data_dir) = get_app_data_dir() {
166        return data_dir.join("vector_downloads");
167    }
168    PathBuf::from("/tmp/vector_downloads")
169}
170
171// ============================================================================
172// Current Account
173// ============================================================================
174
175static CURRENT_ACCOUNT: LazyLock<Arc<RwLock<Option<String>>>> = LazyLock::new(|| Arc::new(RwLock::new(None)));
176// PENDING_ACCOUNT lives exclusively in src-tauri's account_manager —
177// any "pending account" check must go through that crate, not here.
178
179/// Filename for the persistent active-account marker. Plain text, just the npub.
180const ACTIVE_ACCOUNT_FILE: &str = "active_account";
181
182/// npub bech32 form: `npub1` + 58 chars from the bech32 alphabet (no `1`, `b`, `i`, `o`).
183fn is_valid_npub(s: &str) -> bool {
184    if s.len() != 63 || !s.starts_with("npub1") {
185        return false;
186    }
187    s.bytes().skip(5).all(|c| matches!(c,
188        b'q' | b'p' | b'z' | b'r' | b'y' | b'9' | b'x' | b'8' |
189        b'g' | b'f' | b'2' | b't' | b'v' | b'd' | b'w' | b'0' |
190        b's' | b'3' | b'j' | b'n' | b'5' | b'4' | b'k' | b'h' |
191        b'c' | b'e' | b'6' | b'm' | b'u' | b'a' | b'7' | b'l'
192    ))
193}
194
195pub fn get_current_account() -> Result<String, String> {
196    CURRENT_ACCOUNT.read().unwrap()
197        .as_ref().cloned()
198        .ok_or_else(|| "No active account".to_string())
199}
200
201/// Set the currently-active npub for THIS process AND persist it to the
202/// `<app_data>/active_account` marker so the next boot picks the same account.
203///
204/// Every call site asserts user intent ("this account is now active"); the
205/// marker write is idempotent and gracefully no-ops when `APP_DATA_DIR` is
206/// not yet configured (e.g. during in-process unit tests).
207pub fn set_current_account(npub: String) -> Result<(), String> {
208    *CURRENT_ACCOUNT.write().unwrap() = Some(npub.clone());
209    let _ = write_active_account_file(&npub);
210    Ok(())
211}
212
213/// Clear the in-memory active account WITHOUT touching the on-disk marker.
214/// Used by `reset_session()` so the next-boot marker stays intact while
215/// in-process state is torn down for an inline account swap.
216pub fn clear_current_account_in_memory() {
217    *CURRENT_ACCOUNT.write().unwrap() = None;
218}
219
220/// Read the active-account marker file. Returns the stored npub if it exists,
221/// is well-formed, AND the corresponding account directory still exists.
222/// Any failure path returns Ok(None) so boot falls back to single-account or picker.
223pub fn read_active_account_file() -> Result<Option<String>, String> {
224    let app_data = match get_app_data_dir() {
225        Ok(p) => p,
226        Err(_) => return Ok(None),
227    };
228    read_active_account_file_in(app_data)
229}
230
231/// Atomic write of the active-account marker (temp + rename).
232pub fn write_active_account_file(npub: &str) -> Result<(), String> {
233    let app_data = get_app_data_dir()?.clone();
234    write_active_account_file_in(&app_data, npub)
235}
236
237/// Remove the active-account marker. Used after deleting the active account.
238pub fn clear_active_account_file() -> Result<(), String> {
239    let app_data = get_app_data_dir()?;
240    clear_active_account_file_in(app_data)
241}
242
243/// Scan the app data directory for valid npub directories. Strict bech32 regex
244/// rejects typos and stray subdirectories. Does NOT validate that each account
245/// has a usable database — callers do that separately.
246pub fn list_account_npubs() -> Result<Vec<String>, String> {
247    let app_data = get_app_data_dir()?;
248    Ok(list_account_npubs_in(app_data))
249}
250
251// ----- path-parameterized internals (kept private so tests can inject a temp dir) -----
252
253/// Bound on bytes read from the active-account marker. A valid marker
254/// is 63 bytes (canonical npub) plus optional trailing newline. The
255/// marker lives in a user-writable dir, so accidental / malicious
256/// multi-gigabyte writes are a realistic OOM vector if read unbounded.
257#[cfg(not(target_arch = "wasm32"))]
258const MARKER_MAX_BYTES: u64 = 256;
259
260#[cfg(not(target_arch = "wasm32"))]
261fn read_active_account_file_in(app_data: &std::path::Path) -> Result<Option<String>, String> {
262    use std::io::Read;
263
264    let path = app_data.join(ACTIVE_ACCOUNT_FILE);
265    if !path.exists() {
266        return Ok(None);
267    }
268    // Pre-check size, then belt-and-suspenders cap via `take()` to
269    // cover the TOCTOU window between metadata and open. Metadata
270    // failures fail-safe to "missing".
271    if let Ok(meta) = std::fs::metadata(&path) {
272        if meta.len() > MARKER_MAX_BYTES {
273            return Ok(None);
274        }
275    } else {
276        return Ok(None);
277    }
278    let mut buf = String::new();
279    let file = match std::fs::File::open(&path) {
280        Ok(f) => f,
281        Err(_) => return Ok(None),
282    };
283    if file.take(MARKER_MAX_BYTES).read_to_string(&mut buf).is_err() {
284        return Ok(None);
285    }
286    let npub = buf.trim().to_string();
287    if !is_valid_npub(&npub) {
288        return Ok(None);
289    }
290    // `symlink_metadata` instead of `is_dir()` (which follows links): a
291    // crafted symlink at `<app_data>/<valid-npub-name>` pointing at
292    // `~/Documents` etc. would otherwise pass, and downstream
293    // `remove_dir_all` in delete_account / logout would traverse it.
294    // Bech32 validation alone is insufficient — the attacker controls
295    // the filename, not the npub semantic.
296    match std::fs::symlink_metadata(app_data.join(&npub)) {
297        Ok(meta) if meta.file_type().is_dir() && !meta.file_type().is_symlink() => {}
298        _ => return Ok(None),
299    }
300    Ok(Some(npub))
301}
302
303#[cfg(not(target_arch = "wasm32"))]
304fn write_active_account_file_in(app_data: &std::path::Path, npub: &str) -> Result<(), String> {
305    if !is_valid_npub(npub) {
306        return Err(format!("Invalid npub format: {}", npub));
307    }
308    if !app_data.exists() {
309        std::fs::create_dir_all(app_data)
310            .map_err(|e| format!("Failed to create app data dir: {}", e))?;
311    }
312    // Refuse to point the marker at a directory that doesn't exist as a
313    // real subfolder. Closes the race where a concurrent `delete_account`
314    // for `npub` runs between the caller's existence check and this write.
315    // `symlink_metadata` (matching the read path) so a crafted
316    // `<app_data>/<valid-npub-name>` symlink can't satisfy the check.
317    match std::fs::symlink_metadata(app_data.join(npub)) {
318        Ok(meta) if meta.file_type().is_dir() && !meta.file_type().is_symlink() => {}
319        _ => return Err(format!("Account directory missing or invalid: {}", npub)),
320    }
321    let tmp = app_data.join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE));
322    let final_path = app_data.join(ACTIVE_ACCOUNT_FILE);
323
324    // Trailing newline so `cat` doesn't mangle the shell prompt and so editors
325    // that auto-strip trailing newlines don't dirty-mark the file on save.
326    let mut payload = String::with_capacity(npub.len() + 1);
327    payload.push_str(npub);
328    payload.push('\n');
329
330    if let Err(e) = std::fs::write(&tmp, payload.as_bytes()) {
331        let _ = std::fs::remove_file(&tmp);
332        return Err(format!("Failed to write active account temp file: {}", e));
333    }
334
335    // Retry the rename a few times. On Windows, transient antivirus or backup
336    // scans can hold a brief sharing-violation lock on the destination file.
337    let mut last_err = None;
338    for attempt in 0..3 {
339        match std::fs::rename(&tmp, &final_path) {
340            Ok(_) => return Ok(()),
341            Err(e) => {
342                last_err = Some(e);
343                if attempt < 2 {
344                    std::thread::sleep(std::time::Duration::from_millis(50));
345                }
346            }
347        }
348    }
349
350    // Don't leave the temp file behind if every attempt failed.
351    let _ = std::fs::remove_file(&tmp);
352    Err(format!(
353        "Failed to rename active account file: {}",
354        last_err.map(|e| e.to_string()).unwrap_or_default()
355    ))
356}
357
358#[cfg(not(target_arch = "wasm32"))]
359fn clear_active_account_file_in(app_data: &std::path::Path) -> Result<(), String> {
360    let path = app_data.join(ACTIVE_ACCOUNT_FILE);
361    if path.exists() {
362        std::fs::remove_file(&path)
363            .map_err(|e| format!("Failed to remove active account file: {}", e))?;
364    }
365    Ok(())
366}
367
368#[cfg(not(target_arch = "wasm32"))]
369fn list_account_npubs_in(app_data: &std::path::Path) -> Vec<String> {
370    let mut out = Vec::new();
371    if let Ok(entries) = std::fs::read_dir(app_data) {
372        for entry in entries.flatten() {
373            if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
374                let name = entry.file_name().to_string_lossy().to_string();
375                if is_valid_npub(&name) {
376                    out.push(name);
377                }
378            }
379        }
380    }
381    out
382}
383
384#[cfg(test)]
385mod active_account_tests {
386    use super::*;
387    use std::fs;
388    use tempfile::TempDir;
389
390    /// Real npub from the project's own test fixtures (matches bech32 regex).
391    const VALID_A: &str = "npub16ye7evyevwnl0fc9hujsxf9zym72e063awn0pvde0huvpyec5nyq4dg4wn";
392    const VALID_B: &str = "npub12w73tzcqgpr2pcy4el5x60d2emeud4cyeeayynzqgg2fefzgytaqm4ktz3";
393
394    fn touch_account_dir(base: &std::path::Path, npub: &str) {
395        fs::create_dir_all(base.join(npub)).unwrap();
396    }
397
398    #[test]
399    fn npub_validator_accepts_canonical_form() {
400        assert!(is_valid_npub(VALID_A));
401        assert!(is_valid_npub(VALID_B));
402    }
403
404    #[test]
405    fn npub_validator_rejects_wrong_length() {
406        assert!(!is_valid_npub("npub1abc"));
407        assert!(!is_valid_npub(&format!("{}x", VALID_A)));
408        assert!(!is_valid_npub(""));
409    }
410
411    #[test]
412    fn npub_validator_rejects_missing_prefix() {
413        let body = &VALID_A[5..];
414        assert!(!is_valid_npub(&format!("nsec1{}", body)));
415        assert!(!is_valid_npub(&format!("xxxx1{}", body)));
416    }
417
418    #[test]
419    fn npub_validator_rejects_non_bech32_chars() {
420        // Replace one char in the body with each disallowed bech32 letter.
421        for bad in ['1', 'b', 'i', 'o', 'B', 'I', 'O', '!', '*', ' '] {
422            let mut s = String::from(VALID_A);
423            s.replace_range(10..11, &bad.to_string());
424            assert!(!is_valid_npub(&s), "should reject character {:?}", bad);
425        }
426    }
427
428    #[test]
429    fn write_then_read_round_trips() {
430        let tmp = TempDir::new().unwrap();
431        touch_account_dir(tmp.path(), VALID_A);
432
433        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
434        assert_eq!(
435            read_active_account_file_in(tmp.path()).unwrap(),
436            Some(VALID_A.to_string())
437        );
438    }
439
440    #[test]
441    fn write_rejects_invalid_npub() {
442        let tmp = TempDir::new().unwrap();
443        let err = write_active_account_file_in(tmp.path(), "npub1nope").unwrap_err();
444        assert!(err.contains("Invalid"));
445        // No file should have been created (neither final nor temp).
446        assert!(!tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());
447        assert!(!tmp.path().join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE)).exists());
448    }
449
450    #[test]
451    fn write_rejects_missing_account_dir() {
452        // A concurrent `delete_account` between the caller's existence check
453        // and write_active_account_file would otherwise leave a stale marker
454        // pointing at a now-deleted account.
455        let tmp = TempDir::new().unwrap();
456        let err = write_active_account_file_in(tmp.path(), VALID_A).unwrap_err();
457        assert!(err.contains("missing or invalid"),
458            "expected account-dir-missing error, got: {}", err);
459        // Marker must not have been written.
460        assert!(!tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());
461        assert!(!tmp.path().join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE)).exists());
462    }
463
464    #[test]
465    fn write_rejects_symlinked_account_dir() {
466        // A crafted `<app_data>/<valid-npub-name>` symlink to ~/Documents
467        // would otherwise pass `is_dir()` and let the marker point at an
468        // attacker-controlled location, which downstream delete/logout paths
469        // would then traverse.
470        let tmp = TempDir::new().unwrap();
471        let target = TempDir::new().unwrap();
472        let link = tmp.path().join(VALID_A);
473        #[cfg(unix)]
474        {
475            std::os::unix::fs::symlink(target.path(), &link).unwrap();
476            let err = write_active_account_file_in(tmp.path(), VALID_A).unwrap_err();
477            assert!(err.contains("missing or invalid"),
478                "expected symlink rejection, got: {}", err);
479        }
480        // On Windows symlink creation may require elevated privileges; skip
481        // the assertion there rather than gate the whole test on platform.
482        #[cfg(not(unix))]
483        let _ = (target, link);
484    }
485
486    #[test]
487    fn read_returns_none_when_marker_missing() {
488        let tmp = TempDir::new().unwrap();
489        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
490    }
491
492    #[test]
493    fn read_returns_none_when_marker_is_garbage() {
494        let tmp = TempDir::new().unwrap();
495        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), b"not-an-npub\n").unwrap();
496        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
497    }
498
499    #[test]
500    fn read_returns_none_when_account_dir_missing() {
501        // Marker exists, npub is well-formed, but the account directory was
502        // deleted out from under us. Boot must fall through to picker, never crash.
503        let tmp = TempDir::new().unwrap();
504        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), VALID_A).unwrap();
505        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
506    }
507
508    #[test]
509    fn read_returns_none_when_marker_oversized() {
510        // Marker lives in a user-writable directory — guard against a giant
511        // file OOMing the app. Anything past MARKER_MAX_BYTES is treated as
512        // corrupt.
513        let tmp = TempDir::new().unwrap();
514        let payload = vec![b'x'; (MARKER_MAX_BYTES + 1024) as usize];
515        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), &payload).unwrap();
516        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
517    }
518
519    #[test]
520    fn read_trims_whitespace() {
521        let tmp = TempDir::new().unwrap();
522        touch_account_dir(tmp.path(), VALID_A);
523        fs::write(
524            tmp.path().join(ACTIVE_ACCOUNT_FILE),
525            format!("  {}\n", VALID_A),
526        ).unwrap();
527        assert_eq!(
528            read_active_account_file_in(tmp.path()).unwrap(),
529            Some(VALID_A.to_string())
530        );
531    }
532
533    #[test]
534    fn read_handles_crlf_line_endings() {
535        let tmp = TempDir::new().unwrap();
536        touch_account_dir(tmp.path(), VALID_A);
537        fs::write(
538            tmp.path().join(ACTIVE_ACCOUNT_FILE),
539            format!("{}\r\n", VALID_A),
540        ).unwrap();
541        assert_eq!(
542            read_active_account_file_in(tmp.path()).unwrap(),
543            Some(VALID_A.to_string())
544        );
545    }
546
547    #[test]
548    fn npub_validator_rejects_uppercase_prefix() {
549        let upper = format!("NPUB1{}", &VALID_A[5..]);
550        assert!(!is_valid_npub(&upper));
551    }
552
553    #[test]
554    fn write_then_read_round_trips_with_newline() {
555        // Belt-and-braces check: confirms our own writer (which appends \n)
556        // round-trips through our own reader (which trims) with no surprises.
557        let tmp = TempDir::new().unwrap();
558        touch_account_dir(tmp.path(), VALID_A);
559        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
560
561        let raw = fs::read_to_string(tmp.path().join(ACTIVE_ACCOUNT_FILE)).unwrap();
562        assert!(raw.ends_with('\n'));
563
564        assert_eq!(
565            read_active_account_file_in(tmp.path()).unwrap(),
566            Some(VALID_A.to_string())
567        );
568    }
569
570    #[test]
571    fn write_overwrites_previous_marker_atomically() {
572        let tmp = TempDir::new().unwrap();
573        touch_account_dir(tmp.path(), VALID_A);
574        touch_account_dir(tmp.path(), VALID_B);
575
576        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
577        write_active_account_file_in(tmp.path(), VALID_B).unwrap();
578
579        assert_eq!(
580            read_active_account_file_in(tmp.path()).unwrap(),
581            Some(VALID_B.to_string())
582        );
583        // The temp file used for atomic rename should not linger.
584        assert!(!tmp.path().join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE)).exists());
585    }
586
587    #[test]
588    fn clear_removes_marker_and_is_idempotent() {
589        let tmp = TempDir::new().unwrap();
590        touch_account_dir(tmp.path(), VALID_A);
591        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
592        assert!(tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());
593
594        clear_active_account_file_in(tmp.path()).unwrap();
595        assert!(!tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());
596
597        // Calling clear again on an already-clean state must not error.
598        clear_active_account_file_in(tmp.path()).unwrap();
599    }
600
601    #[test]
602    fn list_npubs_finds_valid_dirs_only() {
603        let tmp = TempDir::new().unwrap();
604        touch_account_dir(tmp.path(), VALID_A);
605        touch_account_dir(tmp.path(), VALID_B);
606        // Decoys: stray dirs and files that must NOT be picked up.
607        fs::create_dir_all(tmp.path().join("npub1tooshort")).unwrap();
608        fs::create_dir_all(tmp.path().join("not-an-npub-dir")).unwrap();
609        fs::create_dir_all(tmp.path().join("tor")).unwrap();
610        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), VALID_A).unwrap();
611
612        let mut found = list_account_npubs_in(tmp.path());
613        found.sort();
614        let mut expected = vec![VALID_A.to_string(), VALID_B.to_string()];
615        expected.sort();
616        assert_eq!(found, expected);
617    }
618
619    #[test]
620    fn list_npubs_skips_dirs_containing_invalid_chars() {
621        let tmp = TempDir::new().unwrap();
622        // Insert a 'b', 'i', 'o', or '1' into the body — invalid bech32 chars.
623        let mut bogus = String::from(VALID_A);
624        bogus.replace_range(10..11, "b");
625        fs::create_dir_all(tmp.path().join(&bogus)).unwrap();
626
627        let found = list_account_npubs_in(tmp.path());
628        assert!(found.is_empty(), "found unexpected entries: {:?}", found);
629    }
630
631    #[test]
632    fn write_creates_app_data_dir_if_missing() {
633        let tmp = TempDir::new().unwrap();
634        let nested = tmp.path().join("does/not/exist/yet");
635        // Parent app_data is auto-created by mkdir_all; the account dir must
636        // also exist by the time we write, so the marker can't end up
637        // pointing at a non-existent account.
638        std::fs::create_dir_all(&nested).unwrap();
639        touch_account_dir(&nested, VALID_A);
640        write_active_account_file_in(&nested, VALID_A).unwrap();
641        assert!(nested.join(ACTIVE_ACCOUNT_FILE).exists());
642    }
643}
644
645// pending-account accessors removed — see comment above the static decl.
646// All callers use `src-tauri::account_manager::{get,set,clear}_pending_account`.
647
648// ============================================================================
649// Connection Pools
650// ============================================================================
651
652/// One account's database resources, held behind an `Arc`.
653///
654/// The connections an account uses are reachable ONLY through its own
655/// `Session`, so a task that captured one keeps talking to the account it
656/// started with even after a swap — it cannot be handed the next account's
657/// database, because it never asks "who is current?" again.
658///
659/// That makes teardown structural: swapping installs a new `Session` and drops
660/// the reference to the old one, whose pool closes when the last in-flight
661/// guard finishes with it. Nothing to clear, nothing to remember to clear.
662pub struct Session {
663    /// Identity for "is this the account on screen?".
664    ///
665    /// Not the `Arc` address: binding a session to a database builds a new one
666    /// holding the same state (see `rebound`), and a task bound to the session
667    /// it grew from is still that account's. Comparing addresses would make
668    /// those tasks silently stop painting after a re-initialise.
669    id: u64,
670    /// The database this session opens, resolved ONCE when it is built.
671    /// `None` only before an account is bound, where there is nothing better
672    /// than the ambient lookup to fall back to.
673    db_path: Option<PathBuf>,
674    read_pool: Mutex<Vec<rusqlite::Connection>>,
675    /// Signalled when a reader comes home, for a read waiting on one.
676    reader_free: std::sync::Condvar,
677    /// Pooled readers out right now; with the idle ones, never past [`MAX_READERS`].
678    readers_out: std::sync::atomic::AtomicUsize,
679    write_conn: Mutex<Option<rusqlite::Connection>>,
680    /// Signalled when the writer comes home, for a write waiting on it.
681    writer_free: std::sync::Condvar,
682    /// Writer guards out right now: none out and none home means nothing to wait for.
683    writers_out: std::sync::atomic::AtomicUsize,
684    /// This account's chats and profiles in memory — the DB's read-through
685    /// cache, and so bound to the same account for the same reason.
686    chat_state: Arc<tokio::sync::Mutex<crate::state::ChatState>>,
687    /// Everything else the account owns, keyed by type. See [`Session::scoped`].
688    scoped: RwLock<std::collections::HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>>,
689    /// Raised when this account stops being the one on screen.
690    stopped: SessionStop,
691}
692
693/// "This account is no longer current" — a flag long work polls, and a signal
694/// it can await.
695#[derive(Default)]
696struct SessionStop {
697    flag: std::sync::atomic::AtomicBool,
698    wake: tokio::sync::Notify,
699}
700
701impl Session {
702    pub(crate) fn empty() -> Arc<Self> {
703        let s = Arc::new(Session {
704            id: next_session_id(),
705            db_path: None,
706            read_pool: Mutex::new(Vec::new()),
707            reader_free: std::sync::Condvar::new(),
708            readers_out: std::sync::atomic::AtomicUsize::new(0),
709            write_conn: Mutex::new(None),
710            writer_free: std::sync::Condvar::new(),
711            writers_out: std::sync::atomic::AtomicUsize::new(0),
712            chat_state: Arc::new(tokio::sync::Mutex::new(crate::state::ChatState::new())),
713            scoped: RwLock::new(std::collections::HashMap::new()),
714            stopped: SessionStop::default(),
715        });
716        crate::transport::prefs::attach(&s);
717        crate::media::ram::attach(&s);
718        crate::media::store::attach(&s);
719        crate::media::pending::attach(&s);
720        s
721    }
722
723    /// A session bound to one account's database file, with a fresh in-memory
724    /// state — the caller loads it from that database.
725    fn bound(db_path: PathBuf) -> Arc<Self> {
726        let s = Arc::new(Session {
727            id: next_session_id(),
728            db_path: Some(db_path),
729            read_pool: Mutex::new(Vec::new()),
730            reader_free: std::sync::Condvar::new(),
731            readers_out: std::sync::atomic::AtomicUsize::new(0),
732            write_conn: Mutex::new(None),
733            writer_free: std::sync::Condvar::new(),
734            writers_out: std::sync::atomic::AtomicUsize::new(0),
735            chat_state: Arc::new(tokio::sync::Mutex::new(crate::state::ChatState::new())),
736            scoped: RwLock::new(std::collections::HashMap::new()),
737            stopped: SessionStop::default(),
738        });
739        crate::transport::prefs::attach(&s);
740        crate::media::ram::attach(&s);
741        crate::media::store::attach(&s);
742        crate::media::pending::attach(&s);
743        s
744    }
745
746    /// The same account's session, pointed at its database, keeping everything
747    /// it already holds.
748    ///
749    /// Two callers need this. Re-initialising an account that is already open —
750    /// `init_database` is documented idempotent, and the schema check and
751    /// Android's background sync both re-run it — must not empty the chat list
752    /// under a running app. And a login legitimately fills a session before the
753    /// account's database exists: creating an account installs its keys and
754    /// client first, and only reaches `init_database` once the user has chosen
755    /// a PIN. Binding the session it was filling is a promotion, not a swap.
756    fn rebound(&self, db_path: PathBuf) -> Arc<Self> {
757        Arc::new(Session {
758            id: self.id,
759            db_path: Some(db_path),
760            read_pool: Mutex::new(Vec::new()),
761            reader_free: std::sync::Condvar::new(),
762            readers_out: std::sync::atomic::AtomicUsize::new(0),
763            write_conn: Mutex::new(None),
764            writer_free: std::sync::Condvar::new(),
765            writers_out: std::sync::atomic::AtomicUsize::new(0),
766            chat_state: self.chat_state.clone(),
767            scoped: RwLock::new(self.scoped.read().unwrap_or_else(|e| e.into_inner()).clone()),
768            stopped: SessionStop::default(),
769        })
770    }
771
772    /// This account's instance of `T`, built on first touch.
773    ///
774    /// The home for anything an account owns beyond its database: caches keyed
775    /// by its row ids, queues holding its work, routing tables holding its
776    /// keys. Previously these were process globals with a hand-written clear in
777    /// two teardown paths, which is how they drifted — one path cleared fields
778    /// the other did not, and a cache added without a clear leaked into the
779    /// next account. Here there is nothing to clear: the account's instances go
780    /// when its session does.
781    ///
782    /// Keyed by a marker type the owning module declares, so the session never
783    /// has to know what any of this is, and two modules storing the same SHAPE
784    /// (say a `Mutex<HashMap<PublicKey, _>>`) can't collide on one slot.
785    ///
786    /// ```ignore
787    /// struct InboxRelayCache;               // the key, private to this module
788    /// fn cache() -> Arc<Mutex<HashMap<PublicKey, CachedRelays>>> {
789    ///     db::current_session().scoped::<InboxRelayCache, _>()
790    /// }
791    /// ```
792    pub fn scoped<K: 'static, T: Default + Send + Sync + 'static>(self: &Arc<Self>) -> Arc<T> {
793        let key = std::any::TypeId::of::<(K, T)>();
794        if let Some(existing) = self.scoped.read().unwrap_or_else(|e| e.into_inner()).get(&key) {
795            return existing.clone().downcast::<T>().expect("keyed by its own TypeId");
796        }
797        let mut map = self.scoped.write().unwrap_or_else(|e| e.into_inner());
798        // Another thread may have inserted while the read lock was released.
799        map.entry(key)
800            .or_insert_with(|| Arc::new(T::default()) as Arc<dyn std::any::Any + Send + Sync>)
801            .clone()
802            .downcast::<T>()
803            .expect("keyed by its own TypeId")
804    }
805
806    /// This session's identity. Stable across a re-initialise of the same
807    /// account, distinct for every other. Callers that key a cache by "which
808    /// account is this" use it in place of the old generation counter.
809    pub fn id(&self) -> u64 {
810        self.id
811    }
812
813    /// The database this session opens, once it is bound to one.
814    pub fn db_path(&self) -> Option<PathBuf> {
815        self.db_path.clone()
816    }
817
818    /// Whether this account has been switched away from.
819    ///
820    /// Purely an efficiency signal. Work that continues past it is still
821    /// CORRECT — it writes to this account's own storage and paints nothing —
822    /// it is just no longer work anyone is waiting for. Long syncs poll this at
823    /// their loop heads so a swap stops the relay traffic and the decryption
824    /// rather than grinding on for a screen nobody is looking at.
825    ///
826    /// Never use it to decide whether a write is SAFE. That is structural now.
827    pub fn stopped(&self) -> bool {
828        self.stopped.flag.load(std::sync::atomic::Ordering::Acquire)
829    }
830
831    /// Resolves once this account is switched away from — for `select!` against
832    /// a fetch, so an in-flight request is dropped instead of awaited out.
833    pub async fn on_stop(&self) {
834        loop {
835            let waiting = self.stopped.wake.notified();
836            if self.stopped() {
837                return;
838            }
839            waiting.await;
840            if self.stopped() {
841                return;
842            }
843        }
844    }
845
846    fn stop(&self) {
847        self.stopped.flag.store(true, std::sync::atomic::Ordering::Release);
848        self.stopped.wake.notify_waiters();
849    }
850
851    /// Whether this session is the account currently on screen.
852    ///
853    /// For code holding a session it captured earlier — a drop handler, a
854    /// callback fired by a relay OK — where there is no await to be bound
855    /// across and the question is "is what I captured still current?".
856    pub fn is_live(&self) -> bool {
857        self.id == CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
858    }
859
860    /// This account's in-memory chats and profiles.
861    ///
862    /// Reached through the session, so a task bound to account A keeps reading
863    /// and writing A's chats after a swap. Its state is then an orphan nothing
864    /// displays, rather than corruption in the account now on screen.
865    pub fn chat_state(&self) -> Arc<tokio::sync::Mutex<crate::state::ChatState>> {
866        self.chat_state.clone()
867    }
868
869    /// Where THIS session opens connections. A bound session never consults the
870    /// ambient account, so a pool miss after a swap still opens the file this
871    /// session belongs to rather than the incoming account's.
872    fn path(&self) -> Result<PathBuf, String> {
873        match &self.db_path {
874            Some(p) => Ok(p.clone()),
875            None => get_current_db_path(),
876        }
877    }
878
879    /// Take a READ connection from this session, opening one against this
880    /// session's own database if the pool is empty.
881    ///
882    /// The pool grows to `MAX_READERS` and stays: a reader closed later would free its
883    /// schema and caches into pages shared with long-lived data, holes the system never
884    /// takes back. Past the cap a read waits for one to come home (queries take micro- to
885    /// milliseconds); a nested read on this thread, or a wait past `READER_WAIT`, opens a
886    /// passing connection that closes on return.
887    #[track_caller]
888    pub fn acquire_read(self: &Arc<Self>) -> Result<ConnectionGuard, String> {
889        use std::sync::atomic::Ordering;
890        let nested = READERS_HERE.with(|n| n.get() > 0) || NEVER_WAIT.with(std::cell::Cell::get);
891        let deadline = web_time::Instant::now() + READER_WAIT;
892        let mut pool = self.read_pool.lock().unwrap_or_else(|e| e.into_inner());
893        let pooled = loop {
894            // The most recently used: the rest stay cold.
895            if let Some(conn) = pool.pop() {
896                self.readers_out.fetch_add(1, Ordering::Relaxed);
897                return Ok(ConnectionGuard::new(conn, self.clone(), true));
898            }
899            if self.readers_out.load(Ordering::Relaxed) < MAX_READERS {
900                break true;
901            }
902            if nested {
903                break false;
904            }
905            // One thread on the web: nothing else could bring a reader back.
906            #[cfg(target_arch = "wasm32")]
907            break false;
908            #[cfg(not(target_arch = "wasm32"))]
909            {
910                let left = deadline.saturating_duration_since(web_time::Instant::now());
911                if left.is_zero() {
912                    break false;
913                }
914                pool = self.reader_free.wait_timeout(pool, left).unwrap_or_else(|e| e.into_inner()).0;
915            }
916        };
917        #[cfg(target_arch = "wasm32")]
918        let _ = deadline;
919        // Counted before the lock goes, so the cap holds against a read arriving meanwhile.
920        let path = self.path()?;
921        if pooled {
922            self.readers_out.fetch_add(1, Ordering::Relaxed);
923        }
924        drop(pool);
925        match create_connection(&path) {
926            Ok(conn) => Ok(ConnectionGuard::new(conn, self.clone(), pooled)),
927            Err(e) => {
928                if pooled {
929                    let _held = self.read_pool.lock().unwrap_or_else(|e| e.into_inner());
930                    self.readers_out.fetch_sub(1, Ordering::Relaxed);
931                    self.reader_free.notify_all();
932                }
933                Err(e)
934            }
935        }
936    }
937
938    /// Take THE write connection from this session, opening one against this
939    /// session's own database if the slot is empty.
940    ///
941    /// SQLite takes one writer at a time, so a second connection gains nothing: it parses
942    /// the schema, then sleeps in SQLite's busy poll. Waiting here wakes the moment the
943    /// writer returns. A nested write on this thread, or a holder past `WRITER_WAIT`,
944    /// opens its own.
945    #[track_caller]
946    pub fn acquire_write(self: &Arc<Self>) -> Result<WriteConnectionGuard, String> {
947        use std::sync::atomic::Ordering;
948        let nested = WRITERS_HERE.with(|n| n.get() > 0) || NEVER_WAIT.with(std::cell::Cell::get);
949        let deadline = web_time::Instant::now() + WRITER_WAIT;
950        let mut slot = self.write_conn.lock().unwrap_or_else(|e| e.into_inner());
951        loop {
952            if let Some(conn) = slot.take() {
953                self.writers_out.fetch_add(1, Ordering::Relaxed);
954                return Ok(WriteConnectionGuard::new(conn, self.clone()));
955            }
956            if nested || self.writers_out.load(Ordering::Relaxed) == 0 {
957                break;
958            }
959            // One thread on the web: nothing else could bring the writer back.
960            #[cfg(target_arch = "wasm32")]
961            break;
962            #[cfg(not(target_arch = "wasm32"))]
963            {
964                let left = deadline.saturating_duration_since(web_time::Instant::now());
965                if left.is_zero() {
966                    break;
967                }
968                slot = self.writer_free.wait_timeout(slot, left).unwrap_or_else(|e| e.into_inner()).0;
969            }
970        }
971        #[cfg(target_arch = "wasm32")]
972        let _ = deadline;
973        // Counted before the lock goes, so a write arriving meanwhile waits for this one.
974        let path = self.path()?;
975        self.writers_out.fetch_add(1, Ordering::Relaxed);
976        drop(slot);
977        match create_connection(&path) {
978            Ok(conn) => Ok(WriteConnectionGuard::new(conn, self.clone())),
979            Err(e) => {
980                let _held = self.write_conn.lock().unwrap_or_else(|e| e.into_inner());
981                self.writers_out.fetch_sub(1, Ordering::Relaxed);
982                self.writer_free.notify_all();
983                Err(e)
984            }
985        }
986    }
987}
988
989/// The account whose resources new work binds to. Read once at the START of a
990/// unit of work; hold the `Arc` for its duration.
991static CURRENT_SESSION: LazyLock<RwLock<Arc<Session>>> = LazyLock::new(|| RwLock::new(Session::empty()));
992
993tokio::task_local! {
994    /// The session this task is bound to, installed by [`spawn_bound`].
995    ///
996    /// Readable from any code running on the task, including the synchronous
997    /// `db::` helpers an async body calls — which is what lets every existing
998    /// call site become account-correct without growing a parameter.
999    static TASK_SESSION: Arc<Session>;
1000}
1001
1002/// The session THIS work belongs to.
1003///
1004/// A task bound by [`spawn_bound`] gets the account it started under, for its
1005/// whole life, however many awaits it spans and whoever logs in meanwhile. That
1006/// is the property the std::sync::Arc<crate::db::Session> checks were approximating by hand.
1007///
1008/// Unbound callers (startup, the UI command that performs the swap itself) get
1009/// the live account, which for them is the correct and only meaningful answer.
1010pub fn current_session() -> Arc<Session> {
1011    TASK_SESSION
1012        .try_with(Arc::clone)
1013        .unwrap_or_else(|_| CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).clone())
1014}
1015
1016/// Run `fut` pinned to the CURRENT account, without spawning.
1017///
1018/// The counterpart to [`spawn_bound`] for work that is NOT a task we started:
1019/// a Tauri command, an SDK call, a JNI entry point. Nothing installs a session
1020/// for those, so every `db::` call inside them re-resolves the live account and
1021/// a swap mid-operation silently moves the rest of their writes. Wrapping the
1022/// body fixes the account for its whole duration — a swap then leaves the
1023/// operation completing against the account that asked for it, which is both
1024/// the correct outcome and the one the user intended.
1025///
1026/// This is what makes the hand-written "did the account change?" checks
1027/// unnecessary rather than merely redundant.
1028/// NOT an `async fn`, and that is load-bearing. An `async fn` stores its
1029/// parameters in the state machine it returns, so `scoped` would be sized to
1030/// hold the body it binds — and nesting would multiply, exactly as passing the
1031/// future to `scope` unboxed does. A plain fn returning `impl Future` hands
1032/// back a wrapper around a `Pin<Box<_>>`: a pointer, whatever the body.
1033///
1034/// This is not hypothetical. Boot crashed with a stack overflow on BOTH Android
1035/// and macOS, several layers into the community sync, on stacks every test here
1036/// runs on happily. `binding_a_future_does_not_embed_it` is the guard.
1037pub fn scoped<F: std::future::Future>(fut: F) -> impl std::future::Future<Output = F::Output> {
1038    TASK_SESSION.scope(current_session(), Box::pin(fut))
1039}
1040
1041/// [`scoped`], but the RESULT is refused if the account changed while it ran.
1042///
1043/// For an operation whose value goes back to the UI. The work itself completed
1044/// correctly against its own account; what must not happen is that value being
1045/// painted into, or acted on by, the account now on screen. One wrapper in
1046/// place of a check before every write.
1047pub fn scoped_result<T, E, F>(fut: F) -> impl std::future::Future<Output = Result<T, E>>
1048where
1049    F: std::future::Future<Output = Result<T, E>>,
1050    E: From<String>,
1051{
1052    let session = current_session();
1053    let id = session.id;
1054    // Bind first, so the async block below holds only the (pointer-sized)
1055    // bound future rather than the body. See `scoped`.
1056    let bound = TASK_SESSION.scope(session, Box::pin(fut));
1057    async move {
1058        let out = bound.await;
1059        if id != CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id {
1060            return Err(E::from("account changed during the operation".to_string()));
1061        }
1062        out
1063    }
1064}
1065
1066/// Run `fut` pinned to a session you already hold.
1067///
1068/// For code that captured a session earlier and wants to finish that account's
1069/// work through it — and for tests, which need to read an account's storage
1070/// after the live session has moved on.
1071pub fn with_session<F: std::future::Future>(
1072    session: Arc<Session>,
1073    fut: F,
1074) -> impl std::future::Future<Output = F::Output> {
1075    TASK_SESSION.scope(session, Box::pin(fut))
1076}
1077
1078/// Run blocking `f` on the blocking pool as the CURRENT account's work: a pool thread carries
1079/// no task binding of its own.
1080#[cfg(not(target_arch = "wasm32"))]
1081pub async fn blocking_bound<T, F>(f: F) -> Result<T, String>
1082where
1083    F: FnOnce() -> T + Send + 'static,
1084    T: Send + 'static,
1085{
1086    let session = current_session();
1087    tokio::task::spawn_blocking(move || TASK_SESSION.sync_scope(session, f)).await.map_err(|e| e.to_string())
1088}
1089
1090/// Spawn a task pinned to the CURRENT account.
1091///
1092/// Everything it does through `db::` resolves to that account for as long as it
1093/// runs, so an account switch mid-flight can no longer redirect its writes. Use
1094/// this for any task that touches per-account state; a bare `tokio::spawn`
1095/// leaves the task reading whoever is live at the moment it asks.
1096pub fn spawn_bound<F>(fut: F) -> crate::rt::JoinHandle<F::Output>
1097where
1098    F: std::future::Future + crate::rt::MaybeSend + 'static,
1099    F::Output: crate::rt::MaybeSend + 'static,
1100{
1101    let session = current_session();
1102    // spawn-detached: this IS the binding — it installs the session it just read.
1103    crate::rt::spawn(TASK_SESSION.scope(session, fut))
1104}
1105
1106impl std::fmt::Debug for Session {
1107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1108        f.debug_struct("Session").field("id", &self.id).field("db", &self.db_path).finish()
1109    }
1110}
1111
1112/// Has the account this work belongs to been switched away from?
1113///
1114/// Check it at the head of a long loop — a sync page, a relay in a fan-out, a
1115/// channel in a sweep — and stop. Continuing is safe, just wasteful.
1116pub fn session_stopped() -> bool {
1117    current_session().stopped()
1118}
1119
1120/// The live account's session id — for caches keyed by "which account is this".
1121pub fn current_session_id() -> u64 {
1122    current_session().id
1123}
1124
1125/// The session on screen, ignoring the task binding: what unbound network code acts for.
1126pub fn live_session() -> Arc<Session> {
1127    CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).clone()
1128}
1129
1130/// [`live_session`]'s id.
1131pub fn live_session_id() -> u64 {
1132    CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
1133}
1134
1135/// Whether the work running here belongs to the account currently on screen.
1136///
1137/// There is exactly one UI, showing one account. A task bound to a previous
1138/// account keeps working correctly — its database, its chats, its client — but
1139/// what it produces must not be painted into the account the user is now
1140/// looking at. Every emission asks this, which is why almost none of them has
1141/// to ask it by hand.
1142pub fn session_is_live() -> bool {
1143    current_session().id == CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
1144}
1145
1146/// Whether THIS work writes to the account on screen. The at-rest vault and the encryption flag
1147/// describe that account only, so sealing for any other is refused. A rebind of the same account
1148/// keeps its database, so it still counts.
1149pub fn writes_to_live_account() -> bool {
1150    let mine = current_session();
1151    let live = CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner());
1152    mine.id == live.id || (mine.db_path.is_some() && mine.db_path == live.db_path)
1153}
1154
1155fn next_session_id() -> u64 {
1156    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1157    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1158}
1159
1160/// Install a fresh session, dropping the reference to the previous one. Any
1161/// guard still outstanding against the old session returns its connection
1162/// there, and that pool closes with it.
1163fn replace_session() {
1164    install(Session::empty());
1165}
1166
1167/// Install `next` and tell the outgoing account's work to stop.
1168fn install(next: Arc<Session>) {
1169    let (prev, next_id) = {
1170        // Sealed writes check the live account under a ticket; waiting them out here means none
1171        // straddles the switch.
1172        let _switch = crate::crypto::gate::switching();
1173        crate::crypto::forget_previous_key();
1174        let mut current = CURRENT_SESSION.write().unwrap_or_else(|e| e.into_inner());
1175        if current.id != next.id {
1176            current.stop();
1177            crate::media::ram::clear_for(&current);
1178        }
1179        let prev = current.id;
1180        let next_id = next.id;
1181        *current = next;
1182        (prev, next_id)
1183    };
1184    // After the write lock: the epoch bump reads the live id.
1185    crate::transport::on_session_installed(prev, next_id);
1186    crate::profile::sync::wake_processor();
1187}
1188
1189/// RAII guard for READ connections — auto-returns to its OWN session's pool.
1190///
1191/// Holding the `Arc` is what makes the return safe: the connection goes back
1192/// where it came from, so a guard outstanding across an account swap can never
1193/// hand account A's connection to account B. When that older session has no
1194/// references left, its pool closes with it.
1195/// Not `Send`, like the writer's: a reader stays on its thread, so a nested read on that
1196/// thread is always seen as one.
1197pub struct ConnectionGuard {
1198    conn: Option<rusqlite::Connection>,
1199    session: Arc<Session>,
1200    /// A pool member, rather than a passing connection that closes on return.
1201    pooled: bool,
1202    _not_send: std::marker::PhantomData<*const ()>,
1203    /// When and where it was taken, to name a holder that keeps other reads waiting.
1204    #[cfg(debug_assertions)]
1205    taken: (web_time::Instant, &'static std::panic::Location<'static>),
1206}
1207
1208impl ConnectionGuard {
1209    #[track_caller]
1210    fn new(conn: rusqlite::Connection, session: Arc<Session>, pooled: bool) -> Self {
1211        READERS_HERE.with(|n| n.set(n.get() + 1));
1212        Self {
1213            conn: Some(conn),
1214            session,
1215            pooled,
1216            _not_send: std::marker::PhantomData,
1217            #[cfg(debug_assertions)]
1218            taken: (web_time::Instant::now(), std::panic::Location::caller()),
1219        }
1220    }
1221}
1222
1223impl Deref for ConnectionGuard {
1224    type Target = rusqlite::Connection;
1225    fn deref(&self) -> &Self::Target { self.conn.as_ref().expect("Connection already taken") }
1226}
1227
1228impl DerefMut for ConnectionGuard {
1229    fn deref_mut(&mut self) -> &mut Self::Target { self.conn.as_mut().expect("Connection already taken") }
1230}
1231
1232/// Readers a session pools. The boot burst asks for more at once; they wait their turn.
1233const MAX_READERS: usize = 8;
1234/// How long a read waits for a pooled reader before opening a passing one.
1235const READER_WAIT: std::time::Duration = std::time::Duration::from_millis(50);
1236/// How long a write waits for the writer before opening a connection of its own.
1237const WRITER_WAIT: std::time::Duration = std::time::Duration::from_millis(250);
1238
1239thread_local! {
1240    /// Writer guards this thread holds: a nested write must not wait on itself.
1241    static WRITERS_HERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1242    /// Reader guards this thread holds: a nested read must not wait on its own pool.
1243    static READERS_HERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1244    /// A thread that must never block on the pools (the UI's): it opens a passing
1245    /// connection rather than wait.
1246    static NEVER_WAIT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1247}
1248
1249/// Marks the calling thread as one that never waits on a pool. A host calls it from its UI
1250/// thread, where synchronous commands run: a wait there freezes the window.
1251pub fn never_wait_on_this_thread() {
1252    NEVER_WAIT.with(|f| f.set(true));
1253}
1254
1255/// Homes a session's writer. A write may already be waiting on it (the session goes live
1256/// before its writer does), and one already returned is kept.
1257fn install_writer(session: &Session, conn: rusqlite::Connection) {
1258    let mut slot = session.write_conn.lock().unwrap_or_else(|e| e.into_inner());
1259    if slot.is_none() {
1260        *slot = Some(conn);
1261        session.writer_free.notify_all();
1262    }
1263}
1264
1265/// Page cache a connection keeps once it goes idle. A burst (an archival sync, a re-encryption
1266/// sweep) has the full `cache_size` while it runs; what it leaves behind goes on return. The
1267/// bundled build's page cache is one pool per process, so a trim hands back every idle page.
1268const IDLE_CACHE_BYTES: i32 = 2 << 20;
1269
1270fn page_cache_bytes(conn: &rusqlite::Connection) -> i32 {
1271    let (mut used, mut peak) = (0, 0);
1272    // SAFETY: the handle lives as long as the borrow, and CACHE_USED only reads pager stats.
1273    unsafe {
1274        rusqlite::ffi::sqlite3_db_status(
1275            conn.handle(),
1276            rusqlite::ffi::SQLITE_DBSTATUS_CACHE_USED,
1277            &mut used,
1278            &mut peak,
1279            0,
1280        );
1281    }
1282    used
1283}
1284
1285fn trim_for_idle(conn: &rusqlite::Connection) {
1286    if page_cache_bytes(conn) > IDLE_CACHE_BYTES {
1287        let _ = conn.release_memory();
1288    }
1289}
1290
1291impl Drop for ConnectionGuard {
1292    fn drop(&mut self) {
1293        READERS_HERE.with(|n| n.set(n.get().saturating_sub(1)));
1294        #[cfg(debug_assertions)]
1295        {
1296            let held = self.taken.0.elapsed();
1297            if held >= READER_WAIT {
1298                crate::log_warn!("[DB] reader held {} ms from {}", held.as_millis(), self.taken.1);
1299            }
1300        }
1301        let Some(conn) = self.conn.take() else { return };
1302        if !self.pooled {
1303            return;
1304        }
1305        trim_for_idle(&conn);
1306        let mut pool = self.session.read_pool.lock().unwrap_or_else(|e| e.into_inner());
1307        // fetch_update: its rename, try_update, is newer than the toolchains Vector builds with.
1308        #[allow(deprecated)]
1309        let _ = self.session.readers_out.fetch_update(
1310            std::sync::atomic::Ordering::Relaxed,
1311            std::sync::atomic::Ordering::Relaxed,
1312            |n| n.checked_sub(1),
1313        );
1314        pool.push(conn);
1315        self.session.reader_free.notify_one();
1316    }
1317}
1318
1319/// RAII guard for the WRITE connection — auto-returns on drop.
1320/// Not `Send`: a writer stays on its thread, so it is never held across an `.await` and a
1321/// nested write on that thread is always seen as one.
1322pub struct WriteConnectionGuard {
1323    conn: Option<rusqlite::Connection>,
1324    session: Arc<Session>,
1325    _not_send: std::marker::PhantomData<*const ()>,
1326    /// When and where it was taken, to name a holder that makes other writes wait.
1327    #[cfg(debug_assertions)]
1328    taken: (web_time::Instant, &'static std::panic::Location<'static>),
1329}
1330
1331impl WriteConnectionGuard {
1332    #[track_caller]
1333    fn new(conn: rusqlite::Connection, session: Arc<Session>) -> Self {
1334        WRITERS_HERE.with(|n| n.set(n.get() + 1));
1335        Self {
1336            conn: Some(conn),
1337            session,
1338            _not_send: std::marker::PhantomData,
1339            #[cfg(debug_assertions)]
1340            taken: (web_time::Instant::now(), std::panic::Location::caller()),
1341        }
1342    }
1343}
1344
1345impl Deref for WriteConnectionGuard {
1346    type Target = rusqlite::Connection;
1347    fn deref(&self) -> &Self::Target { self.conn.as_ref().expect("Write connection already taken") }
1348}
1349
1350impl DerefMut for WriteConnectionGuard {
1351    fn deref_mut(&mut self) -> &mut Self::Target { self.conn.as_mut().expect("Write connection already taken") }
1352}
1353
1354impl Drop for WriteConnectionGuard {
1355    fn drop(&mut self) {
1356        WRITERS_HERE.with(|n| n.set(n.get().saturating_sub(1)));
1357        #[cfg(debug_assertions)]
1358        {
1359            let held = self.taken.0.elapsed();
1360            if held >= WRITER_WAIT {
1361                crate::log_warn!("[DB] writer held {} ms from {}", held.as_millis(), self.taken.1);
1362            }
1363        }
1364        if let Some(conn) = self.conn.take() {
1365            trim_for_idle(&conn);
1366            let mut spare = None;
1367            {
1368                let mut slot = self.session.write_conn.lock().unwrap_or_else(|e| e.into_inner());
1369                #[allow(deprecated)]
1370                let _ = self.session.writers_out.fetch_update(
1371                    std::sync::atomic::Ordering::Relaxed,
1372                    std::sync::atomic::Ordering::Relaxed,
1373                    |n| n.checked_sub(1),
1374                );
1375                // The slot may already hold a connection installed meanwhile.
1376                if slot.is_none() {
1377                    *slot = Some(conn);
1378                    self.session.writer_free.notify_one();
1379                } else {
1380                    spare = Some(conn);
1381                }
1382            }
1383            // Closed outside the lock.
1384            drop(spare);
1385        }
1386    }
1387}
1388
1389// ============================================================================
1390// Connection Factory
1391// ============================================================================
1392
1393/// Single source of truth for per-account directories. Every per-account
1394/// subsystem (DB, Tor state) resolves its path through this;
1395/// compose further subpaths with `.join(...)` — never insert layers
1396/// between `<app_data>` and `<npub>`.
1397///
1398/// Validates npub format before joining as defence-in-depth against
1399/// path traversal: a crafted IPC input like `"../../etc"` would
1400/// otherwise yield `<app_data>/../../etc` and downstream
1401/// `remove_dir_all` (delete_account, logout) would walk arbitrary dirs.
1402pub fn account_dir(npub: &str) -> Result<PathBuf, String> {
1403    if !is_valid_npub(npub) {
1404        return Err(format!("Invalid npub format: {}", npub));
1405    }
1406    Ok(get_app_data_dir()?.join(npub))
1407}
1408
1409/// Make every commit so far durable: the write-ahead log synced to disk. Commits are only
1410/// written, not synced, until a checkpoint; this is for a step that can't be undone after them.
1411#[cfg(not(target_arch = "wasm32"))]
1412pub fn sync_wal() -> Result<(), String> {
1413    let db = current_account_dir()?.join("vector.db");
1414    for path in [db.with_file_name("vector.db-wal"), db] {
1415        // Windows flushes only a handle opened for writing.
1416        match std::fs::OpenOptions::new().read(true).write(true).open(&path) {
1417            Ok(file) => file.sync_all().map_err(|e| format!("sync {}: {e}", path.display()))?,
1418            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1419            Err(e) => return Err(format!("sync {}: {e}", path.display())),
1420        }
1421    }
1422    Ok(())
1423}
1424
1425/// The directory of the account this task belongs to, for files that are that
1426/// account's alone. Resolved through the session, never the account on screen.
1427pub fn current_account_dir() -> Result<PathBuf, String> {
1428    let db = current_session().path()?;
1429    db.parent().map(PathBuf::from).ok_or_else(|| "account directory unknown".to_string())
1430}
1431
1432fn get_current_db_path() -> Result<PathBuf, String> {
1433    let npub = get_current_account()?;
1434    Ok(account_dir(&npub)?.join("vector.db"))
1435}
1436
1437/// Open a connection, riding out a TRANSIENT lock on the file.
1438///
1439/// `busy_timeout` governs waits inside a connection that already exists; it
1440/// cannot help the open itself, and `journal_mode=WAL` needs the lock briefly.
1441/// A task started under the previous account can still be holding this file for
1442/// a moment — it resolves the CURRENT account when it takes a connection, so a
1443/// swap points it here — and failing outright turns that into a failed login or
1444/// a failed account switch. Bounded: a genuinely stuck holder still surfaces.
1445fn create_connection(path: &PathBuf) -> Result<rusqlite::Connection, String> {
1446    const OPEN_RETRIES: u32 = 4;
1447    let mut last_err = String::new();
1448    for attempt in 0..OPEN_RETRIES {
1449        match open_connection(path) {
1450            Ok(conn) => return Ok(conn),
1451            Err(e) if e.contains("locked") || e.contains("busy") => {
1452                last_err = e;
1453                // One thread on the web: nothing else can release the lock while we wait.
1454                #[cfg(not(target_arch = "wasm32"))]
1455                std::thread::sleep(std::time::Duration::from_millis(50 * u64::from(attempt + 1)));
1456                #[cfg(target_arch = "wasm32")]
1457                let _ = attempt;
1458            }
1459            Err(e) => return Err(e),
1460        }
1461    }
1462    Err(last_err)
1463}
1464
1465/// A fresh connection to `path`, for reads that must not go through a session's pool.
1466#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1467pub(crate) fn connect_at(path: &std::path::Path) -> Result<rusqlite::Connection, String> {
1468    create_connection(&path.to_path_buf())
1469}
1470
1471/// Set by a web build whose storage never syncs to disk itself (IndexedDB
1472/// mirroring, memory): SQLite must not ask it to, which IndexedDB refuses, and
1473/// with no shared memory there is no WAL, only a journal best kept in memory.
1474#[cfg(target_arch = "wasm32")]
1475static RELAXED_DURABILITY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1476
1477#[cfg(target_arch = "wasm32")]
1478pub fn set_relaxed_durability(on: bool) {
1479    RELAXED_DURABILITY.store(on, std::sync::atomic::Ordering::Relaxed);
1480}
1481
1482fn durability_pragmas() -> &'static str {
1483    #[cfg(target_arch = "wasm32")]
1484    if RELAXED_DURABILITY.load(std::sync::atomic::Ordering::Relaxed) {
1485        return "PRAGMA journal_mode=MEMORY; PRAGMA synchronous=OFF;";
1486    }
1487    "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;"
1488}
1489
1490fn open_connection(path: &PathBuf) -> Result<rusqlite::Connection, String> {
1491    let conn = rusqlite::Connection::open(path)
1492        .map_err(|e| format!("Failed to open database: {}", e))?;
1493
1494    // busy_timeout FIRST, alone: `journal_mode=WAL` takes a brief exclusive lock,
1495    // and until the timeout is set it is still 0 — so a connection opened while
1496    // another is active failed outright ("database is locked") instead of waiting
1497    // the moment or two the other needed. Every pragma below now waits too.
1498    conn.execute_batch("PRAGMA busy_timeout=5000;")
1499        .map_err(|e| format!("Failed to set busy_timeout: {}", e))?;
1500
1501    // WAL for concurrent reads. cache_size negative = KiB: 16 MiB is a burst's ceiling, so a
1502    // big transaction never spills mid-write (an idle connection is trimmed, see
1503    // IDLE_CACHE_BYTES); temp_store=MEMORY keeps GROUP BY / sort scratch off disk.
1504    conn.execute_batch(&format!(
1505        "{} PRAGMA foreign_keys=ON; PRAGMA cache_size=-16000; PRAGMA temp_store=MEMORY;",
1506        durability_pragmas()
1507    ))
1508        .map_err(|e| format!("Failed to set pragmas: {}", e))?;
1509    // Room for every hot statement: page loads, unread counts and the persist path together
1510    // outgrow rusqlite's default of 16, and an evicted statement re-prepares on its next use.
1511    conn.set_prepared_statement_cache_capacity(64);
1512
1513    // Memory-mapped reads skip a copy and a syscall per page. 64-bit only: each pooled connection
1514    // maps the file separately, which a 32-bit address space can't spare.
1515    #[cfg(target_pointer_width = "64")]
1516    let _ = conn.execute_batch("PRAGMA mmap_size=268435456;");
1517
1518    Ok(conn)
1519}
1520
1521/// Get a READ connection (headless-safe — no AppHandle).
1522#[track_caller]
1523pub fn get_db_connection_guard_static() -> Result<ConnectionGuard, String> {
1524    current_session().acquire_read()
1525}
1526
1527/// Process-wide serialization lock for tests that install into the global DB pool.
1528/// Any test calling `init_database` must hold this for its whole body — otherwise
1529/// concurrent inits race on the shared account/data-dir state and clobber each other.
1530/// One shared guard across every module (community, ...) so cross-module test
1531/// parallelism can't collide.
1532#[cfg(test)]
1533pub(crate) static DB_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
1534
1535/// Get the WRITE connection (headless-safe — no AppHandle).
1536#[track_caller]
1537pub fn get_write_connection_guard_static() -> Result<WriteConnectionGuard, String> {
1538    current_session().acquire_write()
1539}
1540
1541// ============================================================================
1542// Downgrade guard
1543// ============================================================================
1544
1545/// Where each build stamps its version after successfully opening an account.
1546const LAST_APP_VERSION_KEY: &str = "last_app_version";
1547
1548/// A newer Vector already opened this account's database.
1549///
1550/// Vector has no downgrade path: older builds neither recognise nor preserve
1551/// newer schema, and the corruption that follows is silent until the user opens
1552/// the wrong chat.
1553#[derive(Debug, Clone, serde::Serialize)]
1554pub struct DowngradeBlock {
1555    /// Migration high-water mark found in the account's DB.
1556    pub db_schema: u32,
1557    /// Highest migration this build can apply.
1558    pub supported_schema: u32,
1559    /// App version that last opened it, when one was stamped.
1560    pub last_app_version: Option<String>,
1561}
1562
1563impl std::fmt::Display for DowngradeBlock {
1564    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1565        write!(f, "This account was last opened by a newer version of Vector")?;
1566        if let Some(version) = &self.last_app_version {
1567            write!(f, " ({version})")?;
1568        }
1569        write!(
1570            f,
1571            ". Its database is at schema {} and this build only understands {}. \
1572             Opening it would corrupt your messages, so Vector has stopped. \
1573             Reinstall the newer version to continue.",
1574            self.db_schema, self.supported_schema
1575        )
1576    }
1577}
1578
1579/// The check itself, against an already-open connection.
1580fn downgrade_block(conn: &rusqlite::Connection) -> Option<DowngradeBlock> {
1581    let db_schema = schema::applied_migration_high_water(conn);
1582    if db_schema <= schema::HIGHEST_MIGRATION_ID {
1583        return None;
1584    }
1585    Some(DowngradeBlock {
1586        db_schema,
1587        supported_schema: schema::HIGHEST_MIGRATION_ID,
1588        last_app_version: conn
1589            .query_row(
1590                "SELECT value FROM settings WHERE key = ?1",
1591                rusqlite::params![LAST_APP_VERSION_KEY],
1592                |row| row.get::<_, String>(0),
1593            )
1594            .ok(),
1595    })
1596}
1597
1598/// Whether this account's DB was written by a newer Vector.
1599///
1600/// Read-only and side-effect free, so a host can call it before
1601/// [`init_database`] and put a real dialog in front of the user rather than
1602/// surfacing a failed boot.
1603pub fn inspect_downgrade(npub: &str) -> Result<Option<DowngradeBlock>, String> {
1604    let db_path = account_dir(npub)?.join("vector.db");
1605    // Never create the file just to inspect it.
1606    #[cfg(target_arch = "wasm32")]
1607    let exists = webfs::db_exists(&db_path);
1608    #[cfg(not(target_arch = "wasm32"))]
1609    let exists = db_path.exists();
1610    if !exists {
1611        return Ok(None);
1612    }
1613    let conn = create_connection(&db_path)?;
1614    Ok(downgrade_block(&conn))
1615}
1616
1617// ============================================================================
1618// Database Initialization
1619// ============================================================================
1620
1621/// Initialize the database for a given account (creates tables if needed).
1622pub fn init_database(npub: &str) -> Result<(), String> {
1623    let profile_dir = account_dir(npub)?;
1624
1625    #[cfg(not(target_arch = "wasm32"))]
1626    if !profile_dir.exists() {
1627        std::fs::create_dir_all(&profile_dir)
1628            .map_err(|e| format!("Failed to create profile directory: {}", e))?;
1629    }
1630    #[cfg(target_arch = "wasm32")]
1631    webfs::register_account(get_app_data_dir()?, npub)?;
1632
1633    let db_path = profile_dir.join("vector.db");
1634    let mut conn = create_connection(&db_path)?;
1635
1636    // Migrations are boot-time, one-shot work: if another connection holds the
1637    // write lock (a straggling task from the previous session, a slow host),
1638    // waiting longer is strictly better than failing account init. The 5s
1639    // default is tuned for steady-state queries, not this.
1640    conn.execute_batch("PRAGMA busy_timeout=30000;")
1641        .map_err(|e| format!("Failed to set migration busy_timeout: {}", e))?;
1642
1643    // Before ANY write. SQL_SCHEMA is all CREATE TABLE IF NOT EXISTS, so an
1644    // older build would resurrect tables newer migrations dropped and then
1645    // start writing rows against a schema it cannot see.
1646    if let Some(block) = downgrade_block(&conn) {
1647        return Err(block.to_string());
1648    }
1649
1650    // No tables yet is a new account. One from before Keep Media was a choice kept every
1651    // download, so it goes on keeping media and its old downloads move in.
1652    let fresh = conn
1653        .query_row("SELECT 1 FROM sqlite_master WHERE type='table' AND name='settings'", [], |_| Ok(()))
1654        .is_err();
1655
1656    conn.execute_batch(schema::SQL_SCHEMA)
1657        .map_err(|e| format!("Failed to create schema: {}", e))?;
1658
1659    // Run migrations
1660    schema::run_migrations(&mut conn)?;
1661
1662    let _ = conn.execute(
1663        "INSERT OR IGNORE INTO settings (key, value) VALUES ('keep_media', ?1)",
1664        [if fresh { "false" } else { "true" }],
1665    );
1666
1667    // Stamped after migrations, so it names the build whose schema is now on
1668    // disk. A blocked build never reaches here, so this only ever records a
1669    // version that could actually read what it wrote.
1670    if let Some(version) = APP_VERSION.get() {
1671        let _ = conn.execute(
1672            "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
1673            rusqlite::params![LAST_APP_VERSION_KEY, version],
1674        );
1675    }
1676
1677    // SQLite's prescribed open-time step for long-lived connections: analyze every table that needs
1678    // it (missing stats, or grown/shrunk 10x), bounded by a temporary analysis_limit so it stays
1679    // fast. The 0x10000 bit forces checking all tables since a fresh connection has no query history;
1680    // this also satisfies the "run optimize after CREATE INDEX" guidance for the migrations above.
1681    let _ = conn.execute_batch("PRAGMA optimize=0x10002;");
1682
1683    // Seed the in-session delete-tombstone set from this account's durable rows,
1684    // so ingest keeps refusing deleted messages across restarts (the swap's
1685    // session bump cleared the set; a fresh boot starts empty).
1686    {
1687        let mut stmt = conn.prepare("SELECT event_id FROM deleted_messages")
1688            .map_err(|e| format!("tombstone seed prepare: {}", e))?;
1689        let ids = stmt.query_map([], |row| row.get::<_, String>(0))
1690            .map_err(|e| format!("tombstone seed query: {}", e))?
1691            .filter_map(|r| r.ok());
1692        crate::state::seed_message_tombstones(ids);
1693    }
1694
1695    // MLS is fully removed. Migration 41 drops the relational tables, but the OpenMLS/MDK
1696    // crypto store lived in a SEPARATE per-account file (`<account>/mls/`) that no migration
1697    // can reach. Purge it here: it's dead weight (can run to hundreds of MB) and, worse,
1698    // stale MLS private key material lingering for a feature that no longer exists. Best-effort
1699    // and idempotent — a cleanup failure must never block account init.
1700    let mls_dir = profile_dir.join("mls");
1701    if mls_dir.exists() {
1702        match std::fs::remove_dir_all(&mls_dir) {
1703            Ok(()) => crate::log_info!("[db] purged orphaned MLS store for account"),
1704            Err(e) => crate::log_warn!("[db] could not purge orphaned MLS store: {}", e),
1705        }
1706    }
1707
1708    // Install a NEW session before opening anything: guards still outstanding
1709    // against the previous one return their connections there, and that pool
1710    // closes with it. Nothing from the old account can reach the new pool.
1711    //
1712    // A session already pointed at this database, or not yet pointed at one at
1713    // all, is THIS account's — bind it and keep what it holds (see `rebound`).
1714    // Only a session belonging to a different account starts over.
1715    let session = {
1716        let next = {
1717            let current = CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner());
1718            match current.db_path.as_deref() {
1719                Some(p) if p != db_path => Session::bound(db_path.clone()),
1720                _ => current.rebound(db_path.clone()),
1721            }
1722        };
1723        install(next.clone());
1724        next
1725    };
1726
1727    // Pre-warm readers, opened outside the pool's lock and only up to its cap: the session
1728    // is live already, and a read may have opened one meanwhile.
1729    let warm: Vec<_> = (0..4).filter_map(|_| create_connection(&db_path).ok()).collect();
1730    {
1731        let mut pool = session.read_pool.lock().unwrap_or_else(|e| e.into_inner());
1732        for c in warm {
1733            if pool.len() + session.readers_out.load(std::sync::atomic::Ordering::Relaxed) < MAX_READERS {
1734                pool.push(c);
1735            }
1736        }
1737        session.reader_free.notify_all();
1738    }
1739
1740    // Set write connection
1741    install_writer(&session, create_connection(&db_path)?);
1742
1743    // Straight from `db_path` into `session`: switch_account opens the database before it
1744    // marks the account current, and the task may be bound to the previous session.
1745    crate::transport::prefs::hydrate(&session, &db_path);
1746    if let Ok(conn) = create_connection(&db_path) {
1747        crate::media::store::load_index(&session, &conn);
1748    }
1749
1750    // Read the notification preferences now: every badge recount resolves every
1751    // chat against them, so a lazy first read would land a SQLite round trip on
1752    // that path with the chat state lock held.
1753    crate::notify::warm();
1754
1755    crate::profile::sync::wake_processor();
1756    Ok(())
1757}
1758
1759/// Drop this account's database resources.
1760///
1761/// Installing a fresh session IS the teardown: the previous one is released,
1762/// and its connections close once the last outstanding guard returns. A guard
1763/// still in flight keeps serving the account it began under.
1764pub fn close_database() {
1765    replace_session();
1766}
1767
1768/// Run plain `PRAGMA optimize` on the live write connection — the periodic top-up SQLite recommends
1769/// for long-lived connections (the heavy lifting is the `optimize=0x10002` at connection open).
1770/// Best-effort and cheap: re-analyzes only tables whose stats the planner used and that changed
1771/// materially since the last run.
1772pub fn optimize_database() {
1773    let session = current_session();
1774    let guard = session.write_conn.lock().unwrap_or_else(|e| e.into_inner());
1775    if let Some(conn) = guard.as_ref() {
1776        let _ = conn.execute_batch("PRAGMA optimize;");
1777    }
1778}
1779
1780/// Get all available accounts (npub directories in app data).
1781pub fn get_accounts() -> Result<Vec<String>, String> {
1782    let app_data = get_app_data_dir()?;
1783    #[cfg(target_arch = "wasm32")]
1784    return Ok(list_account_npubs_in(app_data)
1785        .into_iter()
1786        .filter(|npub| webfs::db_exists(&app_data.join(npub).join("vector.db")))
1787        .collect());
1788    #[cfg(not(target_arch = "wasm32"))]
1789    {
1790        let mut accounts = Vec::new();
1791
1792        if let Ok(entries) = std::fs::read_dir(app_data) {
1793            for entry in entries.flatten() {
1794                if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
1795                    let name = entry.file_name().to_string_lossy().to_string();
1796                    if name.starts_with("npub1") {
1797                        // Check if vector.db exists
1798                        if entry.path().join("vector.db").exists() {
1799                            accounts.push(name);
1800                        }
1801                    }
1802                }
1803            }
1804        }
1805
1806        Ok(accounts)
1807    }
1808}
1809
1810/// Get the profile directory path for a given npub.
1811pub fn get_profile_directory(npub: &str) -> Result<PathBuf, String> {
1812    if !npub.starts_with("npub1") {
1813        return Err(format!("Invalid npub format: {}", npub));
1814    }
1815    let dir = account_dir(npub)?;
1816    #[cfg(not(target_arch = "wasm32"))]
1817    if !dir.exists() {
1818        std::fs::create_dir_all(&dir)
1819            .map_err(|e| format!("Failed to create profile directory: {}", e))?;
1820    }
1821    Ok(dir)
1822}
1823
1824/// Get database path for a given npub.
1825pub fn get_database_path(npub: &str) -> Result<PathBuf, String> {
1826    Ok(get_profile_directory(npub)?.join("vector.db"))
1827}
1828
1829// ============================================================================
1830// ID Caches
1831// ============================================================================
1832
1833/// Clear every id cache on account switch. Row ids are PER-ACCOUNT (each account
1834/// has its own DB + id sequence), so a stale entry after a swap points into the
1835/// wrong DB: writes FK-fail silently and reads hit the wrong row. The caches live
1836/// in `id_cache`; this is the public entry the swap path + callers already use.
1837pub fn clear_id_caches() {
1838    id_cache::clear_id_caches();
1839    community::clear_banlist_cache();
1840    community::clear_channel_community_cache();
1841}
1842
1843// ============================================================================
1844// System Event Types
1845// ============================================================================
1846
1847#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1848#[repr(u8)]
1849pub enum SystemEventType {
1850    MemberLeft = 0,
1851    MemberJoined = 1,
1852    MemberRemoved = 2,
1853    WallpaperChanged = 3,
1854}
1855
1856impl SystemEventType {
1857    pub fn display_message(&self, display_name: &str) -> String {
1858        match self {
1859            SystemEventType::MemberLeft => format!("{} has left", display_name),
1860            SystemEventType::MemberJoined => format!("{} has joined", display_name),
1861            SystemEventType::MemberRemoved => format!("{} was removed", display_name),
1862            SystemEventType::WallpaperChanged => format!("{} changed the wallpaper", display_name),
1863        }
1864    }
1865
1866    pub fn as_u8(&self) -> u8 { *self as u8 }
1867}
1868
1869#[cfg(test)]
1870mod pool_generation_tests {
1871    use super::*;
1872
1873    /// Build a minimal in-memory SQLite connection — just enough to drop
1874    /// a connection through the guard machinery. We don't run schema or
1875    /// migrations because we only care about the guard's Drop pathway.
1876    fn fake_conn() -> rusqlite::Connection {
1877        rusqlite::Connection::open_in_memory().unwrap()
1878    }
1879
1880    #[test]
1881    fn a_new_session_wakes_the_idle_profile_processor() {
1882        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1883        let wakes = || crate::profile::sync::SESSION_WAKES.load(std::sync::atomic::Ordering::SeqCst);
1884        let before = wakes();
1885        close_database();
1886        assert!(
1887            wakes() > before,
1888            "a session going live must wake the processor, or queued profiles wait for its next timer"
1889        );
1890    }
1891
1892    #[test]
1893    fn close_database_installs_a_fresh_session() {
1894        // The guard is the POINT here, not boilerplate: `close_database`
1895        // replaces the process-global session, so running unguarded yanks the
1896        // database out from under whichever test is mid-query.
1897        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1898        let before = current_session();
1899        close_database();
1900        let after = current_session();
1901        assert!(
1902            !Arc::ptr_eq(&before, &after),
1903            "close_database must install a NEW session — the old one is what in-flight guards return to"
1904        );
1905    }
1906
1907    #[test]
1908    fn a_guard_returns_its_connection_to_its_own_session() {
1909        let session = Session::empty();
1910        drop(ConnectionGuard::new(fake_conn(), session.clone(), true));
1911        assert_eq!(session.read_pool.lock().unwrap().len(), 1, "the connection goes home");
1912    }
1913
1914    #[test]
1915    fn the_burst_reuses_the_reader_it_just_returned() {
1916        let session = Session::empty();
1917        let a = ConnectionGuard::new(fake_conn(), session.clone(), true);
1918        let b = ConnectionGuard::new(fake_conn(), session.clone(), true);
1919        // SAFETY: only compared, never dereferenced.
1920        let b_handle = unsafe { b.handle() } as usize;
1921        drop(a);
1922        drop(b);
1923        let next = session.acquire_read().unwrap();
1924        assert_eq!(unsafe { next.handle() } as usize, b_handle, "most recently used first, so the oldest can age out");
1925    }
1926
1927    fn writer_session(dir: &tempfile::TempDir) -> Arc<Session> {
1928        let path = dir.path().join("vector.db");
1929        drop(open_connection(&path).unwrap());
1930        Session::bound(path)
1931    }
1932
1933    fn handle_of(w: &WriteConnectionGuard) -> usize {
1934        // SAFETY: only compared, never dereferenced.
1935        unsafe { w.handle() as usize }
1936    }
1937
1938    #[test]
1939    fn a_write_waits_for_the_writer_instead_of_opening_another() {
1940        let dir = tempfile::tempdir().unwrap();
1941        let session = writer_session(&dir);
1942        let first = session.acquire_write().unwrap();
1943        let held = handle_of(&first);
1944        let s2 = session.clone();
1945        let waiter = std::thread::spawn(move || {
1946            let t = web_time::Instant::now();
1947            let w = s2.acquire_write().unwrap();
1948            (handle_of(&w), t.elapsed())
1949        });
1950        std::thread::sleep(std::time::Duration::from_millis(60));
1951        drop(first);
1952        let (got, waited) = waiter.join().unwrap();
1953        assert_eq!(got, held, "the same writer, handed over");
1954        assert!(waited < WRITER_WAIT, "woken by the return, not the timeout: {waited:?}");
1955    }
1956
1957    #[test]
1958    fn a_first_write_with_nothing_out_opens_at_once() {
1959        let dir = tempfile::tempdir().unwrap();
1960        let t = web_time::Instant::now();
1961        let _w = writer_session(&dir).acquire_write().unwrap();
1962        assert!(t.elapsed() < WRITER_WAIT / 2, "{:?}", t.elapsed());
1963    }
1964
1965    #[test]
1966    fn a_write_waiting_at_login_wakes_when_the_writer_is_installed() {
1967        let dir = tempfile::tempdir().unwrap();
1968        let session = writer_session(&dir);
1969        let early = session.acquire_write().unwrap();
1970        let s2 = session.clone();
1971        let waiter = std::thread::spawn(move || {
1972            let t = web_time::Instant::now();
1973            let w = s2.acquire_write().unwrap();
1974            (handle_of(&w), t.elapsed())
1975        });
1976        std::thread::sleep(std::time::Duration::from_millis(40));
1977        let installed = open_connection(&dir.path().join("vector.db")).unwrap();
1978        // SAFETY: only compared, never dereferenced.
1979        let installed_handle = unsafe { installed.handle() } as usize;
1980        install_writer(&session, installed);
1981        let (got, waited) = waiter.join().unwrap();
1982        assert_eq!(got, installed_handle);
1983        assert!(waited < WRITER_WAIT, "woken by the install: {waited:?}");
1984        drop(early);
1985    }
1986
1987    #[test]
1988    fn the_pool_stops_at_its_cap_and_a_read_waits_for_one_back() {
1989        let dir = tempfile::tempdir().unwrap();
1990        let session = writer_session(&dir);
1991        let s2 = session.clone();
1992        let (tx, rx) = std::sync::mpsc::channel();
1993        let (go, wait) = std::sync::mpsc::channel::<()>();
1994        let holder = std::thread::spawn(move || {
1995            let held: Vec<_> = (0..MAX_READERS).map(|_| s2.acquire_read().unwrap()).collect();
1996            // SAFETY: only compared, never dereferenced.
1997            tx.send(held.iter().map(|g| unsafe { g.handle() } as usize).collect::<Vec<_>>()).unwrap();
1998            wait.recv().unwrap();
1999            drop(held);
2000        });
2001        let held = rx.recv().unwrap();
2002        let s3 = session.clone();
2003        let reader = std::thread::spawn(move || {
2004            let t = web_time::Instant::now();
2005            let r = s3.acquire_read().unwrap();
2006            (unsafe { r.handle() } as usize, t.elapsed())
2007        });
2008        std::thread::sleep(std::time::Duration::from_millis(5));
2009        go.send(()).unwrap();
2010        holder.join().unwrap();
2011        let (got, waited) = reader.join().unwrap();
2012        assert!(held.contains(&got), "one of the pool's own, not a new connection");
2013        assert!(waited < READER_WAIT, "woken by the return: {waited:?}");
2014        assert_eq!(session.read_pool.lock().unwrap().len(), MAX_READERS, "the pool never grew past its cap");
2015        assert_eq!(session.readers_out.load(std::sync::atomic::Ordering::Relaxed), 0, "every reader counted home");
2016    }
2017
2018    #[test]
2019    fn a_nested_read_never_waits_and_its_passing_connection_closes() {
2020        let dir = tempfile::tempdir().unwrap();
2021        let session = writer_session(&dir);
2022        let held: Vec<_> = (0..MAX_READERS).map(|_| session.acquire_read().unwrap()).collect();
2023        let t = web_time::Instant::now();
2024        let passing = session.acquire_read().unwrap();
2025        assert!(t.elapsed() < READER_WAIT / 2, "{:?}", t.elapsed());
2026        drop(passing);
2027        drop(held);
2028        assert_eq!(session.read_pool.lock().unwrap().len(), MAX_READERS, "the passing one closed instead of joining");
2029        assert_eq!(session.readers_out.load(std::sync::atomic::Ordering::Relaxed), 0, "every reader counted home");
2030    }
2031
2032    #[test]
2033    fn a_read_kept_waiting_past_the_bound_opens_a_passing_connection() {
2034        let dir = tempfile::tempdir().unwrap();
2035        let session = writer_session(&dir);
2036        let s2 = session.clone();
2037        let (tx, rx) = std::sync::mpsc::channel();
2038        let (go, wait) = std::sync::mpsc::channel::<()>();
2039        let holder = std::thread::spawn(move || {
2040            let held: Vec<_> = (0..MAX_READERS).map(|_| s2.acquire_read().unwrap()).collect();
2041            tx.send(()).unwrap();
2042            wait.recv().unwrap();
2043            drop(held);
2044        });
2045        rx.recv().unwrap();
2046        let t = web_time::Instant::now();
2047        let r = session.acquire_read().unwrap();
2048        assert!(t.elapsed() >= READER_WAIT, "{:?}", t.elapsed());
2049        drop(r);
2050        go.send(()).unwrap();
2051        holder.join().unwrap();
2052        assert_eq!(session.read_pool.lock().unwrap().len(), MAX_READERS);
2053    }
2054
2055    #[test]
2056    fn the_ui_thread_never_waits_on_a_full_pool() {
2057        let dir = tempfile::tempdir().unwrap();
2058        let session = writer_session(&dir);
2059        let s2 = session.clone();
2060        let (tx, rx) = std::sync::mpsc::channel();
2061        let (go, wait) = std::sync::mpsc::channel::<()>();
2062        let holder = std::thread::spawn(move || {
2063            let r: Vec<_> = (0..MAX_READERS).map(|_| s2.acquire_read().unwrap()).collect();
2064            let w = s2.acquire_write().unwrap();
2065            tx.send(()).unwrap();
2066            wait.recv().unwrap();
2067            drop((r, w));
2068        });
2069        rx.recv().unwrap();
2070        let ui = std::thread::spawn(move || {
2071            never_wait_on_this_thread();
2072            let t = web_time::Instant::now();
2073            let r = session.acquire_read().unwrap();
2074            let w = session.acquire_write().unwrap();
2075            drop((r, w));
2076            t.elapsed()
2077        });
2078        let took = ui.join().unwrap();
2079        go.send(()).unwrap();
2080        holder.join().unwrap();
2081        assert!(took < READER_WAIT / 2, "{took:?}");
2082    }
2083
2084    #[test]
2085    fn a_failed_open_gives_its_place_back() {
2086        let dir = tempfile::tempdir().unwrap();
2087        let session = Session::bound(dir.path().join("missing").join("vector.db"));
2088        assert!(session.acquire_read().is_err());
2089        assert!(session.acquire_write().is_err());
2090        assert_eq!(session.readers_out.load(std::sync::atomic::Ordering::Relaxed), 0);
2091        assert_eq!(session.writers_out.load(std::sync::atomic::Ordering::Relaxed), 0);
2092    }
2093
2094    #[test]
2095    fn a_nested_write_never_waits_on_itself() {
2096        let dir = tempfile::tempdir().unwrap();
2097        let session = writer_session(&dir);
2098        let outer = session.acquire_write().unwrap();
2099        let t = web_time::Instant::now();
2100        let inner = session.acquire_write().unwrap();
2101        assert!(t.elapsed() < WRITER_WAIT / 2, "{:?}", t.elapsed());
2102        assert_ne!(handle_of(&inner), handle_of(&outer));
2103    }
2104
2105    #[test]
2106    fn a_writer_held_past_the_wait_lets_another_write_open_its_own() {
2107        let dir = tempfile::tempdir().unwrap();
2108        let session = writer_session(&dir);
2109        let first = session.acquire_write().unwrap();
2110        let held = handle_of(&first);
2111        let s2 = session.clone();
2112        let waiter = std::thread::spawn(move || {
2113            let t = web_time::Instant::now();
2114            let w = s2.acquire_write().unwrap();
2115            (handle_of(&w), t.elapsed())
2116        });
2117        let (got, waited) = waiter.join().unwrap();
2118        assert_ne!(got, held);
2119        assert!(waited >= WRITER_WAIT, "{waited:?}");
2120        drop(first);
2121    }
2122
2123    /// A real file database: an in-memory one's pages ARE its storage and never trim.
2124    fn file_conn(dir: &tempfile::TempDir) -> rusqlite::Connection {
2125        let conn = open_connection(&dir.path().join("vector.db")).unwrap();
2126        conn.execute_batch("CREATE TABLE IF NOT EXISTS t(k BLOB PRIMARY KEY, v BLOB);").unwrap();
2127        conn
2128    }
2129
2130    /// One transaction of ~6 MiB: past the idle cap, inside `cache_size`.
2131    const BURST: &str = "BEGIN; WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000) \
2132                         INSERT INTO t SELECT randomblob(16), randomblob(3000) FROM n; COMMIT;";
2133
2134    #[test]
2135    fn the_writer_keeps_a_small_cache_warm_and_hands_back_a_burst() {
2136        // One page cache per process: a parallel trim or close would empty this test's.
2137        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2138        let dir = tempfile::tempdir().unwrap();
2139        let session = Session::empty();
2140        let parked = |s: &Arc<Session>| s.write_conn.lock().unwrap().as_ref().map(page_cache_bytes).unwrap();
2141
2142        let w = WriteConnectionGuard::new(file_conn(&dir), session.clone());
2143        w.execute("INSERT INTO t VALUES (randomblob(16), randomblob(100))", []).unwrap();
2144        let small = page_cache_bytes(&w);
2145        assert!(small > 0);
2146        drop(w);
2147        assert_eq!(parked(&session), small, "everyday use stays warm");
2148
2149        let w = WriteConnectionGuard::new(session.write_conn.lock().unwrap().take().unwrap(), session.clone());
2150        w.execute_batch(BURST).unwrap();
2151        assert!(page_cache_bytes(&w) > IDLE_CACHE_BYTES, "the burst had its headroom");
2152        drop(w);
2153        assert!(parked(&session) < IDLE_CACHE_BYTES);
2154    }
2155
2156    #[test]
2157    fn a_reader_hands_back_a_burst_when_it_goes_idle() {
2158        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2159        let dir = tempfile::tempdir().unwrap();
2160        let session = Session::empty();
2161        file_conn(&dir).execute_batch(BURST).unwrap();
2162
2163        let r = ConnectionGuard::new(file_conn(&dir), session.clone(), true);
2164        // Unmapped, so every page it scans lands in its own cache.
2165        r.execute_batch("PRAGMA mmap_size=0;").unwrap();
2166        let _: i64 = r.query_row("SELECT sum(length(v)) FROM t", [], |row| row.get(0)).unwrap();
2167        assert!(page_cache_bytes(&r) > IDLE_CACHE_BYTES);
2168        drop(r);
2169        assert!(page_cache_bytes(&session.read_pool.lock().unwrap()[0]) < IDLE_CACHE_BYTES);
2170    }
2171
2172    #[test]
2173    fn a_guard_outstanding_across_a_swap_returns_to_the_session_it_came_from() {
2174        // The property that replaced the generation counter, and a stronger
2175        // one: the old design could only assert a stale connection did NOT
2176        // pollute the new pool. Holding the Arc says where it actually went,
2177        // so account A's connection is unreachable from account B by
2178        // construction rather than by a comparison someone has to remember.
2179        let old = Session::empty();
2180        let new_session = Session::empty();
2181
2182        let guard = ConnectionGuard::new(fake_conn(), old.clone(), true);
2183        // ...the account switches while the guard is still in flight...
2184        drop(guard);
2185
2186        assert_eq!(old.read_pool.lock().unwrap().len(), 1, "returned to the session it was taken from");
2187        assert_eq!(new_session.read_pool.lock().unwrap().len(), 0, "never reachable from the new account");
2188    }
2189
2190    #[test]
2191    fn a_pool_miss_after_a_swap_opens_the_sessions_own_database() {
2192        // The other half of the guarantee. Returning a connection was already
2193        // safe; ACQUIRING one was not, because a miss resolved the ambient
2194        // account and could open the incoming account's file into the outgoing
2195        // account's pool. A bound session never asks what is current.
2196        let dir = tempfile::tempdir().unwrap();
2197        let path_a = dir.path().join("a.db");
2198        let path_b = dir.path().join("b.db");
2199
2200        let session_a = Session::bound(path_a.clone());
2201        let _unrelated = Session::bound(path_b.clone());
2202
2203        // A task still holding A misses A's (empty) pool and opens a connection.
2204        let guard = session_a.acquire_read().expect("acquire against the held session");
2205        // Compare by filename: macOS reports the /private-resolved path.
2206        let opened = guard.path().expect("a file-backed connection").to_string();
2207        assert!(
2208            opened.ends_with("a.db") && !opened.ends_with("b.db"),
2209            "a miss opens the session's OWN database, never the incoming account's (opened {opened})"
2210        );
2211        assert!(!Arc::ptr_eq(&session_a, &current_session()), "the live session really did move on");
2212    }
2213
2214    /// Run `fut` bound to `session`, exactly as `spawn_bound` would.
2215    ///
2216    /// These tests never install their throwaway sessions globally. They used
2217    /// to, and every other test in the binary reads chats, caches and keys
2218    /// through the live session — so one of these swapping it mid-run pulled
2219    /// them out from under whatever was executing in parallel. Binding proves
2220    /// the same property without a global write.
2221    async fn bound_to<F: std::future::Future>(session: Arc<Session>, fut: F) -> F::Output {
2222        TASK_SESSION.scope(session, fut).await
2223    }
2224
2225    /// Every task that touches per-account state must be bound to an account.
2226    ///
2227    /// The worklist is empty: every spawn in this crate either binds or says on
2228    /// the line why it owns no account state. See [`crate::spawn_audit`].
2229    #[test]
2230    fn per_account_tasks_are_spawned_bound_to_their_account() {
2231        crate::spawn_audit::assert_all_spawns_bound(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
2232    }
2233
2234    #[tokio::test]
2235    async fn a_bound_task_keeps_its_account_across_a_swap() {
2236        // What the std::sync::Arc<crate::db::Session> checks were approximating by hand: the task
2237        // began under account A, so its work resolves to A however many awaits
2238        // it spans and whoever logs in meanwhile. No check, nothing to forget.
2239        // The live session stands in for whoever logged in next.
2240        let dir = tempfile::tempdir().unwrap();
2241        let a = Session::bound(dir.path().join("a.db"));
2242
2243        let seen = bound_to(a.clone(), async {
2244            crate::rt::yield_now().await;
2245            current_session()
2246        })
2247        .await;
2248
2249        assert!(Arc::ptr_eq(&seen, &a), "the task still sees the account it started under");
2250        assert!(!Arc::ptr_eq(&seen, &current_session()), "the live account is not reachable from it");
2251    }
2252
2253    #[tokio::test]
2254    async fn a_bound_tasks_chat_writes_cannot_reach_the_new_account() {
2255        // The bug this closes, in the form it actually took: a task holding a
2256        // chat id from account A finishes after the swap and inserts it into
2257        // whatever STATE it finds. The group chats that appeared in a freshly
2258        // created account arrived exactly this way.
2259        use crate::chat::{Chat, ChatType};
2260        let dir = tempfile::tempdir().unwrap();
2261        let a = Session::bound(dir.path().join("a.db"));
2262        let live_before = current_session().chat_state().lock().await.chats.len();
2263
2264        bound_to(a.clone(), async {
2265            crate::rt::yield_now().await;
2266            crate::state::STATE.lock().await.chats.push(Chat::new("a-chat".into(), ChatType::DirectMessage, Vec::new()));
2267        })
2268        .await;
2269
2270        assert_eq!(
2271            a.chat_state().lock().await.chats.len(),
2272            1,
2273            "it landed in the state of the account the task began under"
2274        );
2275        assert_eq!(
2276            current_session().chat_state().lock().await.chats.len(),
2277            live_before,
2278            "and nothing reached the account on screen"
2279        );
2280    }
2281
2282    #[tokio::test]
2283    async fn a_bound_task_cannot_publish_through_the_new_accounts_client() {
2284        // The client carries the signer, so reaching the wrong one means
2285        // publishing account A's payload under account B's identity. A bound
2286        // task reaches the client it started with, which the swap has already
2287        // shut down — its send fails instead of succeeding as the wrong person.
2288        use nostr_sdk::prelude::*;
2289        let dir = tempfile::tempdir().unwrap();
2290        let a = Session::bound(dir.path().join("a.db"));
2291        let a_identity = Keys::generate().public_key();
2292
2293        let seen = bound_to(a.clone(), async move {
2294            crate::state::set_my_public_key(a_identity);
2295            crate::rt::yield_now().await;
2296            crate::state::my_public_key()
2297        })
2298        .await;
2299
2300        assert_eq!(seen, Some(a_identity), "the task signs as the account it began under");
2301        assert_ne!(crate::state::my_public_key(), Some(a_identity), "and the live account is someone else");
2302    }
2303
2304    #[test]
2305    fn binding_an_unbound_session_to_a_database_keeps_what_it_holds() {
2306        // Creating an account installs its keys and client BEFORE its database
2307        // exists — `init_database` only runs once the user has chosen a PIN.
2308        // Replacing the session there would discard the login in progress.
2309        let dir = tempfile::tempdir().unwrap();
2310        let staging = Session::empty();
2311        let held = staging.scoped::<Session, Mutex<u8>>();
2312        *held.lock().unwrap() = 7;
2313
2314        let promoted = staging.rebound(dir.path().join("a.db"));
2315        assert_eq!(*promoted.scoped::<Session, Mutex<u8>>().lock().unwrap(), 7, "the login survives being bound");
2316        assert!(promoted.db_path.is_some(), "and it now has a database");
2317        assert_eq!(promoted.id, staging.id, "and it is still the same account, so its tasks keep painting");
2318    }
2319
2320    #[tokio::test]
2321    async fn a_bound_task_paints_nothing_into_the_account_on_screen() {
2322        // Binding fixes where work LANDS; it cannot fix what the user SEES,
2323        // because there is one UI showing one account. So emission asks once,
2324        // centrally, and a task belonging to a previous account goes quiet.
2325        let dir = tempfile::tempdir().unwrap();
2326        let previous = Session::bound(dir.path().join("previous.db"));
2327        assert!(session_is_live(), "work for the account on screen paints");
2328
2329        let painted = bound_to(previous, async {
2330            crate::rt::yield_now().await;
2331            session_is_live()
2332        })
2333        .await;
2334
2335        assert!(!painted, "a task bound to another account paints nothing");
2336        assert!(session_is_live(), "and the account now on screen still does");
2337    }
2338
2339    #[tokio::test]
2340    async fn switching_accounts_tells_the_previous_one_to_stop() {
2341        // Purely an efficiency signal — the work would still be correct — but a
2342        // boot sync is minutes of relay traffic and decryption, and after a swap
2343        // nobody is waiting for any of it.
2344        let _serialized = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2345        let previous = current_session();
2346        assert!(!previous.stopped(), "running work is not told to stop");
2347
2348        // `on_stop` must be pending until the switch, then resolve.
2349        let waiter = { let p = previous.clone(); crate::rt::spawn(async move { p.on_stop().await }) };
2350        crate::rt::yield_now().await;
2351        assert!(!waiter.is_finished(), "nothing to report while the account is current");
2352
2353        close_database();
2354
2355        assert!(previous.stopped(), "the outgoing account is told to stop");
2356        assert!(!current_session().stopped(), "the incoming one is not");
2357        crate::rt::time::timeout(std::time::Duration::from_secs(5), waiter)
2358            .await
2359            .expect("on_stop resolves on the switch")
2360            .expect("without panicking");
2361    }
2362
2363    #[test]
2364    fn re_initialising_the_same_account_does_not_tell_it_to_stop() {
2365        // `init_database` runs more than once per account — the schema check at
2366        // boot, Android's background sync. Reading that as a swap would abort a
2367        // sync that is still perfectly wanted.
2368        let dir = tempfile::tempdir().unwrap();
2369        let staging = Session::empty();
2370        let promoted = staging.rebound(dir.path().join("a.db"));
2371        assert!(!staging.stopped(), "binding a session is not switching away from it");
2372        assert_eq!(promoted.id, staging.id);
2373    }
2374
2375    /// Binding must not grow with what it binds.
2376    ///
2377    /// `scope` takes the future BY VALUE, so an unboxed `scoped` embeds the
2378    /// whole inner state machine in its caller's. Nesting then multiplies, and
2379    /// a deep chain of bound calls overflows a worker stack — which is exactly
2380    /// what happened: boot crashed on BOTH Android and macOS, several layers
2381    /// into the community sync, on stacks every one of these tests runs on
2382    /// happily. Sizes are what the compiler gives us; the invariant is that the
2383    /// wrapper adds a bounded amount regardless of the body.
2384    #[test]
2385    fn binding_a_future_does_not_embed_it() {
2386        // A deliberately fat body: 8KB of state the future must carry.
2387        let fat = async {
2388            let block = [0u8; 8192];
2389            crate::rt::yield_now().await;
2390            block[0]
2391        };
2392        let fat_size = std::mem::size_of_val(&fat);
2393        assert!(fat_size >= 8192, "the body really is large ({fat_size})");
2394
2395        let bound = scoped(fat);
2396        let bound_size = std::mem::size_of_val(&bound);
2397        assert!(
2398            bound_size < 1024,
2399            "binding must cost a pointer, not a copy of the body \
2400             (body {fat_size} bytes, bound {bound_size})"
2401        );
2402    }
2403
2404    #[test]
2405    fn a_dropped_session_closes_its_pool() {
2406        // Teardown IS the drop: no clearing step to forget.
2407        let session = Session::empty();
2408        drop(ConnectionGuard::new(fake_conn(), session.clone(), true));
2409        assert_eq!(Arc::strong_count(&session), 1, "the guard released its reference");
2410        drop(session); // pool + connections close here
2411    }
2412
2413    #[test]
2414    fn a_stale_write_guard_cannot_clobber_the_new_accounts_connection() {
2415        // Under the old design the stale guard and the fresh connection shared
2416        // one global slot, so the guard's Drop had to be talked out of
2417        // overwriting it. They are now in different sessions and cannot meet.
2418        let old = Session::empty();
2419        let new_session = Session::empty();
2420
2421        let stale_guard = WriteConnectionGuard::new(fake_conn(), old.clone());
2422        // init_database installs the new account's write connection.
2423        *new_session.write_conn.lock().unwrap() = Some(fake_conn());
2424
2425        drop(stale_guard);
2426
2427        assert!(
2428            new_session.write_conn.lock().unwrap().is_some(),
2429            "the new account's write connection is untouched"
2430        );
2431        assert!(
2432            old.write_conn.lock().unwrap().is_some(),
2433            "the stale guard returned to its own session's slot"
2434        );
2435    }
2436
2437    #[test]
2438    fn a_new_accounts_empty_write_slot_stays_empty() {
2439        // The old worry: a stale guard filling the fresh account's empty slot
2440        // with a connection pointing at a different database. It has no way to
2441        // reach that slot now — it only knows its own session.
2442        let old = Session::empty();
2443        let new_session = Session::empty();
2444
2445        let stale_guard = WriteConnectionGuard::new(fake_conn(), old.clone());
2446        drop(stale_guard);
2447
2448        assert!(
2449            new_session.write_conn.lock().unwrap().is_none(),
2450            "the new account's slot is untouched by the previous account's guard"
2451        );
2452    }
2453}
2454
2455#[cfg(test)]
2456mod downgrade_tests {
2457    use super::*;
2458
2459    fn test_account() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, String) {
2460        let guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2461        close_database();
2462        clear_id_caches();
2463        let tmp = tempfile::tempdir().unwrap();
2464        // Bases must not collide across test modules: APP_DATA_DIR is a
2465        // OnceLock shared by the whole binary, and this generator collapses
2466        // after ~4 chars, so nearby seeds yield near-identical npubs.
2467        // Taken: 0, 900, 5_000, 50_000, 70_000, 71_000, 81_000, 90_000.
2468        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(61_000);
2469        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2470        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
2471        let mut acct = String::from("npub1");
2472        let mut v = n as usize;
2473        for _ in 0..58 {
2474            acct.push(B[v % 32] as char);
2475            v = v / 32 + 7;
2476        }
2477        set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
2478        set_current_account(acct.clone()).unwrap();
2479        (tmp, guard, acct)
2480    }
2481
2482    #[tokio::test]
2483    async fn re_initialising_the_same_account_keeps_its_loaded_state() {
2484        // init_database is documented idempotent, and callers lean on that —
2485        // the schema check and Android's background sync both re-run it against
2486        // an account already loaded. Dropping its chats there would empty the
2487        // list under a running app.
2488        use crate::chat::{Chat, ChatType};
2489        let (_dir, _lock, acct) = test_account();
2490        init_database(&acct).unwrap();
2491        crate::state::STATE.lock().await.chats.push(Chat::new("kept".into(), ChatType::DirectMessage, Vec::new()));
2492
2493        init_database(&acct).unwrap();
2494        assert_eq!(crate::state::STATE.lock().await.chats.len(), 1, "same account, same in-memory state");
2495    }
2496
2497    /// A DB this build fully understands must open, or the guard is useless.
2498    #[test]
2499    fn an_equal_schema_opens_normally() {
2500        let (_tmp, _guard, acct) = test_account();
2501        init_database(&acct).unwrap();
2502        assert!(inspect_downgrade(&acct).unwrap().is_none());
2503        // Re-opening is still fine: the stamp write must not trip the guard.
2504        init_database(&acct).unwrap();
2505        assert!(inspect_downgrade(&acct).unwrap().is_none());
2506    }
2507
2508    /// Absent DB is not a downgrade; it must not be created just to look.
2509    #[test]
2510    fn a_missing_database_is_not_a_downgrade() {
2511        let (_tmp, _guard, acct) = test_account();
2512        assert!(inspect_downgrade(&acct).unwrap().is_none());
2513        assert!(!account_dir(&acct).unwrap().join("vector.db").exists());
2514    }
2515
2516    #[test]
2517    fn a_newer_schema_blocks_the_open_and_names_the_build() {
2518        let (_tmp, _guard, acct) = test_account();
2519        init_database(&acct).unwrap();
2520
2521        // Stand in for a newer Vector having run one migration past this build.
2522        let db_path = account_dir(&acct).unwrap().join("vector.db");
2523        {
2524            let conn = create_connection(&db_path).unwrap();
2525            conn.execute(
2526                "INSERT OR REPLACE INTO schema_migrations (id, applied_at) VALUES (?1, 0)",
2527                rusqlite::params![schema::HIGHEST_MIGRATION_ID + 1],
2528            )
2529            .unwrap();
2530            conn.execute(
2531                "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
2532                rusqlite::params![LAST_APP_VERSION_KEY, "9.9.9"],
2533            )
2534            .unwrap();
2535        }
2536        close_database();
2537
2538        let block = inspect_downgrade(&acct)
2539            .unwrap()
2540            .expect("a higher migration id must read as a downgrade");
2541        assert_eq!(block.db_schema, schema::HIGHEST_MIGRATION_ID + 1);
2542        assert_eq!(block.supported_schema, schema::HIGHEST_MIGRATION_ID);
2543        assert_eq!(block.last_app_version.as_deref(), Some("9.9.9"));
2544
2545        let err = init_database(&acct).unwrap_err();
2546        assert!(err.contains("9.9.9"), "must name the newer build: {err}");
2547    }
2548
2549    /// The guard has to fire before SQL_SCHEMA runs: its CREATE TABLE IF NOT
2550    /// EXISTS statements would otherwise resurrect tables newer migrations drop.
2551    #[test]
2552    fn a_blocked_open_writes_nothing() {
2553        let (_tmp, _guard, acct) = test_account();
2554        init_database(&acct).unwrap();
2555        let db_path = account_dir(&acct).unwrap().join("vector.db");
2556        {
2557            let conn = create_connection(&db_path).unwrap();
2558            conn.execute(
2559                "INSERT OR REPLACE INTO schema_migrations (id, applied_at) VALUES (?1, 0)",
2560                rusqlite::params![schema::HIGHEST_MIGRATION_ID + 5],
2561            )
2562            .unwrap();
2563            conn.execute("DROP TABLE IF EXISTS settings", []).unwrap();
2564        }
2565        close_database();
2566
2567        assert!(init_database(&acct).is_err());
2568
2569        // SQL_SCHEMA would have recreated `settings`; it must still be gone.
2570        let conn = create_connection(&db_path).unwrap();
2571        let exists: bool = conn
2572            .query_row(
2573                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='settings'",
2574                [],
2575                |_| Ok(true),
2576            )
2577            .unwrap_or(false);
2578        assert!(!exists, "a blocked open must not write to the database");
2579    }
2580}