1use 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
49static 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#[cfg(test)]
69pub(crate) fn shared_test_data_dir() -> &'static std::path::Path {
70 static DIR: OnceLock<tempfile::TempDir> = OnceLock::new();
71 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#[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 #[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
102static 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
111static DOWNLOAD_DIR_OVERRIDE: OnceLock<PathBuf> = OnceLock::new();
116
117pub fn set_download_dir(path: PathBuf) {
121 let _ = DOWNLOAD_DIR_OVERRIDE.set(path);
122}
123
124static 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
136pub 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
142pub 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 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
171static CURRENT_ACCOUNT: LazyLock<Arc<RwLock<Option<String>>>> = LazyLock::new(|| Arc::new(RwLock::new(None)));
176const ACTIVE_ACCOUNT_FILE: &str = "active_account";
181
182fn 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
201pub 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
213pub fn clear_current_account_in_memory() {
217 *CURRENT_ACCOUNT.write().unwrap() = None;
218}
219
220pub 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
231pub 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
237pub 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
243pub 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#[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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 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
645pub struct Session {
663 id: u64,
670 db_path: Option<PathBuf>,
674 read_pool: Mutex<Vec<rusqlite::Connection>>,
675 reader_free: std::sync::Condvar,
677 readers_out: std::sync::atomic::AtomicUsize,
679 write_conn: Mutex<Option<rusqlite::Connection>>,
680 writer_free: std::sync::Condvar,
682 writers_out: std::sync::atomic::AtomicUsize,
684 chat_state: Arc<tokio::sync::Mutex<crate::state::ChatState>>,
687 scoped: RwLock<std::collections::HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>>,
689 stopped: SessionStop,
691}
692
693#[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 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 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 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 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 pub fn id(&self) -> u64 {
810 self.id
811 }
812
813 pub fn db_path(&self) -> Option<PathBuf> {
815 self.db_path.clone()
816 }
817
818 pub fn stopped(&self) -> bool {
828 self.stopped.flag.load(std::sync::atomic::Ordering::Acquire)
829 }
830
831 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 pub fn is_live(&self) -> bool {
857 self.id == CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
858 }
859
860 pub fn chat_state(&self) -> Arc<tokio::sync::Mutex<crate::state::ChatState>> {
866 self.chat_state.clone()
867 }
868
869 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 #[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 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 #[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 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 #[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 #[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 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
989static CURRENT_SESSION: LazyLock<RwLock<Arc<Session>>> = LazyLock::new(|| RwLock::new(Session::empty()));
992
993tokio::task_local! {
994 static TASK_SESSION: Arc<Session>;
1000}
1001
1002pub 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
1016pub 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
1041pub 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 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
1066pub 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#[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
1090pub 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 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
1112pub fn session_stopped() -> bool {
1117 current_session().stopped()
1118}
1119
1120pub fn current_session_id() -> u64 {
1122 current_session().id
1123}
1124
1125pub fn live_session() -> Arc<Session> {
1127 CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).clone()
1128}
1129
1130pub fn live_session_id() -> u64 {
1132 CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
1133}
1134
1135pub fn session_is_live() -> bool {
1143 current_session().id == CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
1144}
1145
1146pub 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
1160fn replace_session() {
1164 install(Session::empty());
1165}
1166
1167fn install(next: Arc<Session>) {
1169 let (prev, next_id) = {
1170 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(¤t);
1178 }
1179 let prev = current.id;
1180 let next_id = next.id;
1181 *current = next;
1182 (prev, next_id)
1183 };
1184 crate::transport::on_session_installed(prev, next_id);
1186 crate::profile::sync::wake_processor();
1187}
1188
1189pub struct ConnectionGuard {
1198 conn: Option<rusqlite::Connection>,
1199 session: Arc<Session>,
1200 pooled: bool,
1202 _not_send: std::marker::PhantomData<*const ()>,
1203 #[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
1232const MAX_READERS: usize = 8;
1234const READER_WAIT: std::time::Duration = std::time::Duration::from_millis(50);
1236const WRITER_WAIT: std::time::Duration = std::time::Duration::from_millis(250);
1238
1239thread_local! {
1240 static WRITERS_HERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1242 static READERS_HERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1244 static NEVER_WAIT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1247}
1248
1249pub fn never_wait_on_this_thread() {
1252 NEVER_WAIT.with(|f| f.set(true));
1253}
1254
1255fn 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
1265const IDLE_CACHE_BYTES: i32 = 2 << 20;
1269
1270fn page_cache_bytes(conn: &rusqlite::Connection) -> i32 {
1271 let (mut used, mut peak) = (0, 0);
1272 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 #[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
1319pub struct WriteConnectionGuard {
1323 conn: Option<rusqlite::Connection>,
1324 session: Arc<Session>,
1325 _not_send: std::marker::PhantomData<*const ()>,
1326 #[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 if slot.is_none() {
1377 *slot = Some(conn);
1378 self.session.writer_free.notify_one();
1379 } else {
1380 spare = Some(conn);
1381 }
1382 }
1383 drop(spare);
1385 }
1386 }
1387}
1388
1389pub 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#[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 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
1425pub 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
1437fn 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 #[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#[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#[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 conn.execute_batch("PRAGMA busy_timeout=5000;")
1499 .map_err(|e| format!("Failed to set busy_timeout: {}", e))?;
1500
1501 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 conn.set_prepared_statement_cache_capacity(64);
1512
1513 #[cfg(target_pointer_width = "64")]
1516 let _ = conn.execute_batch("PRAGMA mmap_size=268435456;");
1517
1518 Ok(conn)
1519}
1520
1521#[track_caller]
1523pub fn get_db_connection_guard_static() -> Result<ConnectionGuard, String> {
1524 current_session().acquire_read()
1525}
1526
1527#[cfg(test)]
1533pub(crate) static DB_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
1534
1535#[track_caller]
1537pub fn get_write_connection_guard_static() -> Result<WriteConnectionGuard, String> {
1538 current_session().acquire_write()
1539}
1540
1541const LAST_APP_VERSION_KEY: &str = "last_app_version";
1547
1548#[derive(Debug, Clone, serde::Serialize)]
1554pub struct DowngradeBlock {
1555 pub db_schema: u32,
1557 pub supported_schema: u32,
1559 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
1579fn 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
1598pub fn inspect_downgrade(npub: &str) -> Result<Option<DowngradeBlock>, String> {
1604 let db_path = account_dir(npub)?.join("vector.db");
1605 #[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
1617pub 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 conn.execute_batch("PRAGMA busy_timeout=30000;")
1641 .map_err(|e| format!("Failed to set migration busy_timeout: {}", e))?;
1642
1643 if let Some(block) = downgrade_block(&conn) {
1647 return Err(block.to_string());
1648 }
1649
1650 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 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 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 let _ = conn.execute_batch("PRAGMA optimize=0x10002;");
1682
1683 {
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 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 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 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 install_writer(&session, create_connection(&db_path)?);
1742
1743 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 crate::notify::warm();
1754
1755 crate::profile::sync::wake_processor();
1756 Ok(())
1757}
1758
1759pub fn close_database() {
1765 replace_session();
1766}
1767
1768pub 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
1780pub 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 if entry.path().join("vector.db").exists() {
1799 accounts.push(name);
1800 }
1801 }
1802 }
1803 }
1804 }
1805
1806 Ok(accounts)
1807 }
1808}
1809
1810pub 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
1824pub fn get_database_path(npub: &str) -> Result<PathBuf, String> {
1826 Ok(get_profile_directory(npub)?.join("vector.db"))
1827}
1828
1829pub fn clear_id_caches() {
1838 id_cache::clear_id_caches();
1839 community::clear_banlist_cache();
1840 community::clear_channel_community_cache();
1841}
1842
1843#[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 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 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 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 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 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 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 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 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 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 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 let old = Session::empty();
2180 let new_session = Session::empty();
2181
2182 let guard = ConnectionGuard::new(fake_conn(), old.clone(), true);
2183 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 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 let guard = session_a.acquire_read().expect("acquire against the held session");
2205 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, ¤t_session()), "the live session really did move on");
2212 }
2213
2214 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 #[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 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, ¤t_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 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 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 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 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 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 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 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 #[test]
2385 fn binding_a_future_does_not_embed_it() {
2386 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 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); }
2412
2413 #[test]
2414 fn a_stale_write_guard_cannot_clobber_the_new_accounts_connection() {
2415 let old = Session::empty();
2419 let new_session = Session::empty();
2420
2421 let stale_guard = WriteConnectionGuard::new(fake_conn(), old.clone());
2422 *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 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 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 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 #[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 init_database(&acct).unwrap();
2505 assert!(inspect_downgrade(&acct).unwrap().is_none());
2506 }
2507
2508 #[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 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 #[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 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}