1use crate::config;
2use crate::AppConfig;
3use kanban_domain::{DataStore, KanbanError};
4use kanban_persistence::{snapshot_from_json_bytes, PersistenceStore, StoreRegistry};
5use std::sync::Arc;
6
7pub struct StoreManager {
14 registry: Arc<StoreRegistry>,
15 backends: Arc<kanban_backend::KanbanBackendRegistry>,
16}
17
18impl StoreManager {
19 pub fn new(registry: StoreRegistry, backends: kanban_backend::KanbanBackendRegistry) -> Self {
23 Self {
24 registry: Arc::new(registry),
25 backends: Arc::new(backends),
26 }
27 }
28
29 pub fn registry(&self) -> &StoreRegistry {
32 &self.registry
33 }
34
35 pub fn has_backends(&self) -> bool {
37 !self.backends.is_empty()
38 }
39
40 pub fn backend_names(&self) -> Vec<&str> {
43 self.backends.names()
44 }
45
46 pub fn local_backend_names(&self) -> Vec<&str> {
49 self.backends.local_names()
50 }
51
52 pub fn is_sqlite(&self, locator: &str) -> bool {
56 match self.detect_backend(locator).as_deref() {
57 Some("sqlite") => true,
58 None => {
59 locator.ends_with(".sqlite")
60 || locator.ends_with(".sqlite3")
61 || locator.ends_with(".db")
62 }
63 _ => false,
64 }
65 }
66
67 pub fn detect_backend(&self, locator: &str) -> Option<String> {
71 if let Some(name) = self.registry.detect_backend(locator) {
72 return Some(name.to_string());
73 }
74 self.backends
75 .for_locator(locator)
76 .map(|f| f.name().to_string())
77 }
78
79 pub fn sync_backend_with_file(&self, locator: &str, config: &mut AppConfig) -> bool {
82 if let Some(detected) = self.detect_backend(locator) {
83 if detected != config.effective_storage_backend() {
84 config.storage_backend = Some(detected);
85 return true;
86 }
87 }
88 false
89 }
90
91 pub async fn make_backend(
95 &self,
96 locator: &str,
97 config: &AppConfig,
98 ) -> Result<std::sync::Arc<dyn crate::backend::KanbanBackend>, KanbanError> {
99 let factory = self.backends.for_locator(locator).ok_or_else(|| {
100 KanbanError::Internal(format!(
101 "no registered backend handles '{locator}'; registered: {:?}",
102 self.backends.names()
103 ))
104 })?;
105 factory.create(locator, config).await
106 }
107
108 pub async fn make_backend_named(
111 &self,
112 backend: &str,
113 locator: &str,
114 config: &AppConfig,
115 ) -> Result<std::sync::Arc<dyn crate::backend::KanbanBackend>, KanbanError> {
116 let factory = self.backends.for_name(backend).ok_or_else(|| {
117 KanbanError::Internal(format!(
118 "no registered backend named '{backend}'; registered: {:?}",
119 self.backends.names()
120 ))
121 })?;
122 factory.create(locator, config).await
123 }
124
125 pub fn make_store(
128 &self,
129 backend: &str,
130 locator: &str,
131 ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, KanbanError> {
132 Ok(self.registry.create_store(backend, locator)?)
133 }
134
135 pub fn make_store_with_config(
140 &self,
141 file: Option<&str>,
142 config: &AppConfig,
143 ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, KanbanError> {
144 let locator = match file {
145 Some(path) => path.to_string(),
146 None => config::resolve_storage_location(config),
147 };
148 let backend = self
149 .detect_backend(&locator)
150 .unwrap_or_else(|| config.effective_storage_backend().to_string());
151 self.make_store(&backend, &locator)
152 }
153
154 pub async fn validate_store_readable(
167 &self,
168 backend: &str,
169 path: &str,
170 ) -> Result<(), KanbanError> {
171 if matches!(backend, "sqlite" | "sqlite3" | "db") {
172 #[cfg(feature = "sqlite")]
173 {
174 if !std::path::Path::new(path).exists() {
175 return Err(std::io::Error::new(
176 std::io::ErrorKind::NotFound,
177 format!("Storage file does not exist: {}", path),
178 )
179 .into());
180 }
181 let sqlite_backend = kanban_persistence_sqlite::SqliteBackend::open(path).await?;
185 sqlite_backend.list_boards()?;
186 return Ok(());
187 }
188 #[cfg(not(feature = "sqlite"))]
189 return Err(KanbanError::validation("sqlite feature not compiled in"));
190 }
191 let store = self.make_store(backend, path)?;
192 if !store.exists().await {
193 return Err(std::io::Error::new(
194 std::io::ErrorKind::NotFound,
195 format!("Storage file does not exist: {}", path),
196 )
197 .into());
198 }
199 let (snapshot, _metadata) = store.load().await?;
200 snapshot_from_json_bytes(&snapshot.data)?;
201 Ok(())
202 }
203
204 pub async fn export_to_sqlite(
209 &self,
210 export: kanban_domain::export::AllBoardsExport,
211 filename: &str,
212 config: &AppConfig,
213 ) -> Result<(), KanbanError> {
214 #[cfg(feature = "sqlite")]
215 {
216 use kanban_domain::export::BoardImporter;
217 use kanban_domain::{DependencyGraph, Snapshot};
218
219 if std::path::Path::new(filename).exists() {
225 return Err(std::io::Error::new(
226 std::io::ErrorKind::AlreadyExists,
227 format!(
228 "Destination already exists: {filename}. Remove it first or use a different path."
229 ),
230 )
231 .into());
232 }
233
234 let mut entities = BoardImporter::extract_entities(export);
235 entities.cards = entities
236 .cards
237 .iter()
238 .map(|c| {
239 kanban_domain::stamp_card_prefix(
240 c,
241 &entities.columns,
242 &entities.boards,
243 &entities.sprints,
244 )
245 })
246 .collect();
247 let prefixes = kanban_domain::counters_implied_by(
251 &entities.cards,
252 &entities.columns,
253 &entities.sprints,
254 &entities.boards,
255 Some(config.effective_default_sprint_prefix()),
256 );
257 let snapshot = Snapshot {
258 archived_boards: entities.archived_boards,
259 boards: entities.boards,
260 columns: entities.columns,
261 cards: entities.cards,
262 archived_cards: entities.archived_cards,
263 sprints: entities.sprints,
264 graph: DependencyGraph::default(),
265 prefixes,
266 };
267 self.write_sqlite_destination(filename, snapshot).await
268 }
269 #[cfg(not(feature = "sqlite"))]
270 {
271 let _ = export;
272 let _ = filename;
273 Err(KanbanError::validation("sqlite feature not compiled in"))
274 }
275 }
276
277 pub async fn migrate_store(
287 &self,
288 from_backend: &str,
289 from_path: &str,
290 to_backend: &str,
291 to_path: &str,
292 ) -> Result<(), KanbanError> {
293 let from = std::path::Path::new(from_path);
294 let to = std::path::Path::new(to_path);
295 if !from.exists() {
296 return Err(std::io::Error::new(
297 std::io::ErrorKind::NotFound,
298 format!("Source file not found: {}", from.display()),
299 )
300 .into());
301 }
302 if to.exists() {
303 return Err(std::io::Error::new(
304 std::io::ErrorKind::AlreadyExists,
305 format!(
306 "Destination already exists: {}. Remove it first or use a different path.",
307 to.display()
308 ),
309 )
310 .into());
311 }
312
313 let leg = MigrationLeg::of(from_backend, to_backend);
314 let source_is_sqlite = matches!(
315 leg,
316 MigrationLeg::SqliteToSqlite | MigrationLeg::SqliteToJson
317 );
318 let dest_is_sqlite = matches!(
319 leg,
320 MigrationLeg::SqliteToSqlite | MigrationLeg::JsonToSqlite
321 );
322
323 if !leg.round_trips_through_json() {
328 #[cfg(feature = "sqlite")]
329 {
330 let snapshot = self.read_sqlite_source(from_path).await?;
331 return self.write_sqlite_destination(to_path, snapshot).await;
332 }
333 #[cfg(not(feature = "sqlite"))]
334 return Err(KanbanError::validation("sqlite feature not compiled in"));
335 }
336
337 let mut snapshot: kanban_domain::Snapshot = if source_is_sqlite {
340 #[cfg(feature = "sqlite")]
341 {
342 self.read_sqlite_source(from_path).await?
343 }
344 #[cfg(not(feature = "sqlite"))]
345 return Err(KanbanError::validation("sqlite feature not compiled in"));
346 } else {
347 let backend = self.make_backend(from_path, &AppConfig::default()).await?;
348 let snap = crate::store_adapter::read_full_snapshot(backend.as_data_store());
349 drop(backend);
350 snap?
351 };
352
353 crate::store_adapter::repair_fks(&mut snapshot)?;
354
355 if dest_is_sqlite {
356 #[cfg(feature = "sqlite")]
357 {
358 return self.write_sqlite_destination(to_path, snapshot).await;
359 }
360 #[cfg(not(feature = "sqlite"))]
361 return Err(KanbanError::validation("sqlite feature not compiled in"));
362 }
363
364 self.write_registry_destination(to_backend, to_path, snapshot)
365 .await
366 }
367
368 #[cfg(feature = "sqlite")]
375 async fn read_sqlite_source(
376 &self,
377 from_path: &str,
378 ) -> Result<kanban_domain::Snapshot, KanbanError> {
379 use kanban_backend::KanbanBackend;
380
381 let backend = kanban_persistence_sqlite::SqliteBackend::open(from_path).await?;
382 let snapshot = crate::store_adapter::read_full_snapshot(backend.as_data_store());
383 backend.close().await;
384 drop(backend);
385 snapshot
386 }
387
388 #[cfg(feature = "sqlite")]
399 async fn write_sqlite_destination(
400 &self,
401 to_path: &str,
402 snapshot: kanban_domain::Snapshot,
403 ) -> Result<(), KanbanError> {
404 use kanban_backend::KanbanBackend;
405
406 let created_here = !std::path::Path::new(to_path).exists();
407
408 let backend = kanban_persistence_sqlite::SqliteBackend::open(to_path).await?;
409 let outcome = backend.with_transaction(Box::new(|| {
410 crate::store_adapter::write_full_snapshot(backend.as_data_store(), snapshot)
411 }));
412 backend.close().await;
413 drop(backend);
414 if let Err(e) = outcome {
415 if created_here {
416 cleanup_destination_files(to_path).await;
417 }
418 return Err(e);
419 }
420 Ok(())
421 }
422
423 async fn write_registry_destination(
427 &self,
428 to_backend: &str,
429 to_path: &str,
430 snapshot: kanban_domain::Snapshot,
431 ) -> Result<(), KanbanError> {
432 let created_here = !std::path::Path::new(to_path).exists();
433
434 let backend = self
435 .make_backend_named(to_backend, to_path, &AppConfig::default())
436 .await?;
437 let outcome = match backend.with_transaction(Box::new(|| {
438 crate::store_adapter::write_full_snapshot(backend.as_data_store(), snapshot)
439 })) {
440 Ok(()) => backend.flush().await,
441 Err(e) => Err(e),
442 };
443 drop(backend);
444 if let Err(e) = outcome {
445 if created_here {
446 cleanup_destination_files(to_path).await;
447 }
448 return Err(e);
449 }
450 Ok(())
451 }
452}
453
454impl Clone for StoreManager {
455 fn clone(&self) -> Self {
456 Self {
457 registry: Arc::clone(&self.registry),
458 backends: Arc::clone(&self.backends),
459 }
460 }
461}
462
463async fn remove_file_with_windows_retry(path: &std::path::Path) {
468 for delay_ms in [0u64, 50, 100, 200, 400] {
469 if delay_ms > 0 {
470 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
471 }
472 if std::fs::remove_file(path).is_ok() {
473 return;
474 }
475 if !path.exists() {
476 return;
477 }
478 }
479 tracing::warn!(
480 path = %path.display(),
481 "failed to remove file after retry backoff; orphan may remain on disk"
482 );
483}
484
485fn is_sqlite_backend(name: &str) -> bool {
490 matches!(name, "sqlite" | "sqlite3" | "db")
491}
492
493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
496pub(crate) enum MigrationLeg {
497 SqliteToSqlite,
498 SqliteToJson,
499 JsonToSqlite,
500 JsonToJson,
501}
502
503impl MigrationLeg {
504 pub(crate) fn of(from_backend: &str, to_backend: &str) -> Self {
505 match (
506 is_sqlite_backend(from_backend),
507 is_sqlite_backend(to_backend),
508 ) {
509 (true, true) => Self::SqliteToSqlite,
510 (true, false) => Self::SqliteToJson,
511 (false, true) => Self::JsonToSqlite,
512 (false, false) => Self::JsonToJson,
513 }
514 }
515
516 pub(crate) fn round_trips_through_json(self) -> bool {
521 !matches!(self, Self::SqliteToSqlite)
522 }
523}
524
525async fn cleanup_destination_files(to_path: &str) {
526 remove_file_with_windows_retry(std::path::Path::new(to_path)).await;
527 let wal = format!("{}-wal", to_path);
528 let shm = format!("{}-shm", to_path);
529 remove_file_with_windows_retry(std::path::Path::new(&wal)).await;
530 remove_file_with_windows_retry(std::path::Path::new(&shm)).await;
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use kanban_persistence::StoreRegistry;
537 use tempfile::tempdir;
538
539 #[test]
540 fn test_sqlite_to_sqlite_leg_does_not_round_trip_through_json() {
541 for (from, to) in [("sqlite", "sqlite"), ("sqlite3", "db"), ("db", "sqlite3")] {
546 let leg = MigrationLeg::of(from, to);
547 assert_eq!(leg, MigrationLeg::SqliteToSqlite, "{from} -> {to}");
548 assert!(
549 !leg.round_trips_through_json(),
550 "{from} -> {to} must not serialise through JSON"
551 );
552 }
553 }
554
555 #[test]
556 fn test_every_leg_with_json_on_one_end_round_trips_through_json() {
557 for (from, to, expected) in [
559 ("sqlite", "json", MigrationLeg::SqliteToJson),
560 ("json", "sqlite", MigrationLeg::JsonToSqlite),
561 ("json", "json", MigrationLeg::JsonToJson),
562 ] {
563 let leg = MigrationLeg::of(from, to);
564 assert_eq!(leg, expected, "{from} -> {to}");
565 assert!(
566 leg.round_trips_through_json(),
567 "{from} -> {to} carries a StoreSnapshot, so FK repair applies"
568 );
569 }
570 }
571
572 fn make_sm() -> StoreManager {
573 let mut registry = StoreRegistry::new();
574 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
575 let mut backends = kanban_backend::KanbanBackendRegistry::new();
576 #[cfg(feature = "sqlite")]
577 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
578 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
579 StoreManager::new(registry, backends)
580 }
581
582 #[tokio::test(flavor = "multi_thread")]
583 async fn test_make_backend_errors_for_unregistered_locator() {
584 let dir = tempdir().unwrap();
585 let path = dir.path().join("test.json");
586 let sm = StoreManager::new(
587 StoreRegistry::new(),
588 kanban_backend::KanbanBackendRegistry::new(),
589 );
590 let cfg = AppConfig::default();
591 let err = sm
592 .make_backend(path.to_str().unwrap(), &cfg)
593 .await
594 .err()
595 .expect("empty registry must not silently pick a backend");
596 let msg = err.to_string();
597 assert!(
598 msg.contains("no registered backend handles"),
599 "expected unregistered-locator error, got: {msg}"
600 );
601 }
602
603 #[tokio::test(flavor = "multi_thread")]
604 async fn test_make_backend_json_path_returns_json_data_store() {
605 let dir = tempdir().unwrap();
606 let path = dir.path().join("test.json");
607 let sm = make_sm();
608 let cfg = AppConfig::default();
609 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
610 assert!(!backend.needs_flush(), "new JSON backend starts clean");
611 assert!(
612 backend.needs_save_worker(),
613 "JSON backend requires a background flush worker"
614 );
615 }
616
617 #[cfg(feature = "sqlite")]
618 mod sqlite_backend_tests {
619 use super::*;
620
621 #[tokio::test(flavor = "multi_thread")]
622 async fn test_make_backend_sqlite_path_returns_sqlite_store() {
623 let dir = tempdir().unwrap();
624 let path = dir.path().join("test.sqlite");
625 let sm = make_sm();
626 let cfg = AppConfig::default();
627 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
628 assert!(!backend.needs_flush(), "new SQLite backend starts clean");
629 assert!(
630 !backend.needs_save_worker(),
631 "SQLite backend is write-through and does not need a save worker"
632 );
633 }
634
635 #[tokio::test(flavor = "multi_thread")]
636 async fn test_make_backend_detects_sqlite_by_magic_bytes() {
637 let dir = tempdir().unwrap();
638 let path = dir.path().join("noext");
639
640 kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
643 .await
644 .unwrap();
645
646 let sm = make_sm();
647 let cfg = AppConfig::default();
648 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
649 assert!(
650 !backend.needs_save_worker(),
651 "magic-byte SQLite detection should yield a write-through backend"
652 );
653 let boards = backend.list_boards().unwrap();
654 assert!(boards.is_empty());
655 }
656
657 #[tokio::test(flavor = "multi_thread")]
658 async fn test_make_backend_detects_json_by_content() {
659 use kanban_persistence::{PersistenceMetadata, PersistenceStore, StoreSnapshot};
660 let dir = tempdir().unwrap();
661 let path = dir.path().join("noext");
662
663 {
666 let jfs = kanban_persistence_json::JsonFileStore::new(&path);
667 let snap = kanban_domain::Snapshot::new();
668 let data = kanban_persistence::snapshot_to_json_bytes(&snap).unwrap();
669 let meta = PersistenceMetadata::new(uuid::Uuid::new_v4());
670 jfs.save(StoreSnapshot {
671 data,
672 metadata: meta,
673 })
674 .await
675 .unwrap();
676 }
677
678 let sm = make_sm();
679 let cfg = AppConfig::default();
680 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
681 assert!(
682 backend.needs_save_worker(),
683 "content-sniffed JSON backend requires a save worker"
684 );
685 let boards = backend.list_boards().unwrap();
686 assert!(boards.is_empty());
687 }
688
689 #[tokio::test(flavor = "multi_thread")]
690 async fn test_sqlite_locator_resolves_without_a_store_factory() {
691 let mut registry = StoreRegistry::new();
692 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
693 let mut backends = kanban_backend::KanbanBackendRegistry::new();
694 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
695 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
696 let sm = StoreManager::new(registry, backends);
697
698 let dir = tempdir().unwrap();
699 let path = dir.path().join("test.db");
700 let cfg = AppConfig::default();
701 let backend = sm
702 .make_backend(path.to_str().unwrap(), &cfg)
703 .await
704 .expect("make_backend must resolve a sqlite locator without a store-level factory registered");
705 let boards = backend.list_boards().unwrap();
706 assert!(boards.is_empty());
707 }
708
709 #[test]
710 fn test_detect_backend_on_a_nonexistent_db_path_returns_sqlite() {
711 let sm = make_sm();
712 let dir = tempdir().unwrap();
713 let path = dir.path().join("does_not_exist.db");
714 assert_eq!(
715 sm.detect_backend(path.to_str().unwrap()),
716 Some("sqlite".to_string())
717 );
718 }
719
720 #[tokio::test(flavor = "multi_thread")]
721 async fn test_detect_backend_on_an_existing_sqlite_file_still_returns_sqlite() {
722 let dir = tempdir().unwrap();
723 let path = dir.path().join("existing.db");
724 kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
725 .await
726 .unwrap();
727
728 let sm = make_sm();
729 assert_eq!(
730 sm.detect_backend(path.to_str().unwrap()),
731 Some("sqlite".to_string())
732 );
733 }
734
735 #[test]
736 fn test_detect_backend_with_no_registered_factories_returns_none() {
737 let sm = StoreManager::new(
738 StoreRegistry::new(),
739 kanban_backend::KanbanBackendRegistry::new(),
740 );
741
742 assert_eq!(sm.detect_backend("whatever.db"), None);
743 }
744
745 #[tokio::test(flavor = "multi_thread")]
746 async fn test_make_backend_named_ignores_the_locator_header() {
747 let dir = tempdir().unwrap();
748 let path = dir.path().join("dest.db");
749 let sm = make_sm();
750 let cfg = AppConfig::default();
751
752 let named = sm
753 .make_backend_named("json", path.to_str().unwrap(), &cfg)
754 .await
755 .unwrap();
756 assert!(
757 named.needs_save_worker(),
758 "make_backend_named(\"json\", ...) must build a JSON backend regardless of the .db extension"
759 );
760
761 let sniffed = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
762 assert!(
763 !sniffed.needs_save_worker(),
764 "make_backend on the same nonexistent .db path sniffs sqlite by extension"
765 );
766 }
767
768 #[test]
769 fn test_detect_backend_for_a_db_path_without_a_sqlite_backend_falls_back_to_json() {
770 let mut registry = StoreRegistry::new();
771 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
772 let mut backends = kanban_backend::KanbanBackendRegistry::new();
773 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
774 let sm = StoreManager::new(registry, backends);
775
776 assert_eq!(sm.detect_backend("whatever.db"), Some("json".to_string()));
777 }
778 }
779
780 struct RemoteStub;
781
782 #[async_trait::async_trait]
783 impl kanban_backend::KanbanBackendFactory for RemoteStub {
784 fn name(&self) -> &str {
785 "remote"
786 }
787
788 fn is_remote(&self) -> bool {
789 true
790 }
791
792 async fn create(
793 &self,
794 locator: &str,
795 _config: &AppConfig,
796 ) -> Result<Arc<dyn crate::backend::KanbanBackend>, KanbanError> {
797 Err(KanbanError::validation(format!(
798 "remote factory reached with {locator}"
799 )))
800 }
801 }
802
803 #[test]
804 fn test_local_backend_names_excludes_a_remote_factory() {
805 let mut registry = StoreRegistry::new();
806 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
807 let mut backends = kanban_backend::KanbanBackendRegistry::new();
808 #[cfg(feature = "sqlite")]
809 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
810 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
811 backends.register(Box::new(RemoteStub));
812 let sm = StoreManager::new(registry, backends);
813
814 assert!(sm.backend_names().contains(&"remote"));
815 assert!(!sm.local_backend_names().contains(&"remote"));
816 assert!(sm.local_backend_names().contains(&"json"));
817 #[cfg(feature = "sqlite")]
818 assert!(sm.local_backend_names().contains(&"sqlite"));
819 }
820}