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 labels: Vec::new(),
267 };
268 self.write_sqlite_destination(filename, snapshot).await
269 }
270 #[cfg(not(feature = "sqlite"))]
271 {
272 let _ = export;
273 let _ = filename;
274 Err(KanbanError::validation("sqlite feature not compiled in"))
275 }
276 }
277
278 pub async fn migrate_store(
288 &self,
289 from_backend: &str,
290 from_path: &str,
291 to_backend: &str,
292 to_path: &str,
293 ) -> Result<(), KanbanError> {
294 let from = std::path::Path::new(from_path);
295 let to = std::path::Path::new(to_path);
296 if !from.exists() {
297 return Err(std::io::Error::new(
298 std::io::ErrorKind::NotFound,
299 format!("Source file not found: {}", from.display()),
300 )
301 .into());
302 }
303 if to.exists() {
304 return Err(std::io::Error::new(
305 std::io::ErrorKind::AlreadyExists,
306 format!(
307 "Destination already exists: {}. Remove it first or use a different path.",
308 to.display()
309 ),
310 )
311 .into());
312 }
313
314 let leg = MigrationLeg::of(from_backend, to_backend);
315 let source_is_sqlite = matches!(
316 leg,
317 MigrationLeg::SqliteToSqlite | MigrationLeg::SqliteToJson
318 );
319 let dest_is_sqlite = matches!(
320 leg,
321 MigrationLeg::SqliteToSqlite | MigrationLeg::JsonToSqlite
322 );
323
324 if !leg.round_trips_through_json() {
329 #[cfg(feature = "sqlite")]
330 {
331 let snapshot = self.read_sqlite_source(from_path).await?;
332 return self.write_sqlite_destination(to_path, snapshot).await;
333 }
334 #[cfg(not(feature = "sqlite"))]
335 return Err(KanbanError::validation("sqlite feature not compiled in"));
336 }
337
338 let mut snapshot: kanban_domain::Snapshot = if source_is_sqlite {
341 #[cfg(feature = "sqlite")]
342 {
343 self.read_sqlite_source(from_path).await?
344 }
345 #[cfg(not(feature = "sqlite"))]
346 return Err(KanbanError::validation("sqlite feature not compiled in"));
347 } else {
348 let backend = self.make_backend(from_path, &AppConfig::default()).await?;
349 let snap = crate::store_adapter::read_full_snapshot(backend.as_data_store());
350 drop(backend);
351 snap?
352 };
353
354 crate::store_adapter::repair_fks(&mut snapshot)?;
355
356 if dest_is_sqlite {
357 #[cfg(feature = "sqlite")]
358 {
359 return self.write_sqlite_destination(to_path, snapshot).await;
360 }
361 #[cfg(not(feature = "sqlite"))]
362 return Err(KanbanError::validation("sqlite feature not compiled in"));
363 }
364
365 self.write_registry_destination(to_backend, to_path, snapshot)
366 .await
367 }
368
369 #[cfg(feature = "sqlite")]
376 async fn read_sqlite_source(
377 &self,
378 from_path: &str,
379 ) -> Result<kanban_domain::Snapshot, KanbanError> {
380 use kanban_backend::KanbanBackend;
381
382 let backend = kanban_persistence_sqlite::SqliteBackend::open(from_path).await?;
383 let snapshot = crate::store_adapter::read_full_snapshot(backend.as_data_store());
384 backend.close().await;
385 drop(backend);
386 snapshot
387 }
388
389 #[cfg(feature = "sqlite")]
400 async fn write_sqlite_destination(
401 &self,
402 to_path: &str,
403 snapshot: kanban_domain::Snapshot,
404 ) -> Result<(), KanbanError> {
405 use kanban_backend::KanbanBackend;
406
407 let created_here = !std::path::Path::new(to_path).exists();
408
409 let backend = kanban_persistence_sqlite::SqliteBackend::open(to_path).await?;
410 let outcome = backend.with_transaction(Box::new(|| {
411 crate::store_adapter::write_full_snapshot(backend.as_data_store(), snapshot)
412 }));
413 backend.close().await;
414 drop(backend);
415 if let Err(e) = outcome {
416 if created_here {
417 cleanup_destination_files(to_path).await;
418 }
419 return Err(e);
420 }
421 Ok(())
422 }
423
424 async fn write_registry_destination(
428 &self,
429 to_backend: &str,
430 to_path: &str,
431 snapshot: kanban_domain::Snapshot,
432 ) -> Result<(), KanbanError> {
433 let created_here = !std::path::Path::new(to_path).exists();
434
435 let backend = self
436 .make_backend_named(to_backend, to_path, &AppConfig::default())
437 .await?;
438 let outcome = match backend.with_transaction(Box::new(|| {
439 crate::store_adapter::write_full_snapshot(backend.as_data_store(), snapshot)
440 })) {
441 Ok(()) => backend.flush().await,
442 Err(e) => Err(e),
443 };
444 drop(backend);
445 if let Err(e) = outcome {
446 if created_here {
447 cleanup_destination_files(to_path).await;
448 }
449 return Err(e);
450 }
451 Ok(())
452 }
453}
454
455impl Clone for StoreManager {
456 fn clone(&self) -> Self {
457 Self {
458 registry: Arc::clone(&self.registry),
459 backends: Arc::clone(&self.backends),
460 }
461 }
462}
463
464async fn remove_file_with_windows_retry(path: &std::path::Path) {
469 for delay_ms in [0u64, 50, 100, 200, 400] {
470 if delay_ms > 0 {
471 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
472 }
473 if std::fs::remove_file(path).is_ok() {
474 return;
475 }
476 if !path.exists() {
477 return;
478 }
479 }
480 tracing::warn!(
481 path = %path.display(),
482 "failed to remove file after retry backoff; orphan may remain on disk"
483 );
484}
485
486fn is_sqlite_backend(name: &str) -> bool {
491 matches!(name, "sqlite" | "sqlite3" | "db")
492}
493
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
497pub(crate) enum MigrationLeg {
498 SqliteToSqlite,
499 SqliteToJson,
500 JsonToSqlite,
501 JsonToJson,
502}
503
504impl MigrationLeg {
505 pub(crate) fn of(from_backend: &str, to_backend: &str) -> Self {
506 match (
507 is_sqlite_backend(from_backend),
508 is_sqlite_backend(to_backend),
509 ) {
510 (true, true) => Self::SqliteToSqlite,
511 (true, false) => Self::SqliteToJson,
512 (false, true) => Self::JsonToSqlite,
513 (false, false) => Self::JsonToJson,
514 }
515 }
516
517 pub(crate) fn round_trips_through_json(self) -> bool {
522 !matches!(self, Self::SqliteToSqlite)
523 }
524}
525
526async fn cleanup_destination_files(to_path: &str) {
527 remove_file_with_windows_retry(std::path::Path::new(to_path)).await;
528 let wal = format!("{}-wal", to_path);
529 let shm = format!("{}-shm", to_path);
530 remove_file_with_windows_retry(std::path::Path::new(&wal)).await;
531 remove_file_with_windows_retry(std::path::Path::new(&shm)).await;
532}
533
534#[cfg(test)]
535mod tests {
536 use super::*;
537 use kanban_persistence::StoreRegistry;
538 use tempfile::tempdir;
539
540 #[test]
541 fn test_sqlite_to_sqlite_leg_does_not_round_trip_through_json() {
542 for (from, to) in [("sqlite", "sqlite"), ("sqlite3", "db"), ("db", "sqlite3")] {
547 let leg = MigrationLeg::of(from, to);
548 assert_eq!(leg, MigrationLeg::SqliteToSqlite, "{from} -> {to}");
549 assert!(
550 !leg.round_trips_through_json(),
551 "{from} -> {to} must not serialise through JSON"
552 );
553 }
554 }
555
556 #[test]
557 fn test_every_leg_with_json_on_one_end_round_trips_through_json() {
558 for (from, to, expected) in [
560 ("sqlite", "json", MigrationLeg::SqliteToJson),
561 ("json", "sqlite", MigrationLeg::JsonToSqlite),
562 ("json", "json", MigrationLeg::JsonToJson),
563 ] {
564 let leg = MigrationLeg::of(from, to);
565 assert_eq!(leg, expected, "{from} -> {to}");
566 assert!(
567 leg.round_trips_through_json(),
568 "{from} -> {to} carries a StoreSnapshot, so FK repair applies"
569 );
570 }
571 }
572
573 fn make_sm() -> StoreManager {
574 let mut registry = StoreRegistry::new();
575 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
576 let mut backends = kanban_backend::KanbanBackendRegistry::new();
577 #[cfg(feature = "sqlite")]
578 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
579 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
580 StoreManager::new(registry, backends)
581 }
582
583 #[tokio::test(flavor = "multi_thread")]
584 async fn test_make_backend_errors_for_unregistered_locator() {
585 let dir = tempdir().unwrap();
586 let path = dir.path().join("test.json");
587 let sm = StoreManager::new(
588 StoreRegistry::new(),
589 kanban_backend::KanbanBackendRegistry::new(),
590 );
591 let cfg = AppConfig::default();
592 let err = sm
593 .make_backend(path.to_str().unwrap(), &cfg)
594 .await
595 .err()
596 .expect("empty registry must not silently pick a backend");
597 let msg = err.to_string();
598 assert!(
599 msg.contains("no registered backend handles"),
600 "expected unregistered-locator error, got: {msg}"
601 );
602 }
603
604 #[tokio::test(flavor = "multi_thread")]
605 async fn test_make_backend_json_path_returns_json_data_store() {
606 let dir = tempdir().unwrap();
607 let path = dir.path().join("test.json");
608 let sm = make_sm();
609 let cfg = AppConfig::default();
610 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
611 assert!(!backend.needs_flush(), "new JSON backend starts clean");
612 assert!(
613 backend.needs_save_worker(),
614 "JSON backend requires a background flush worker"
615 );
616 }
617
618 #[cfg(feature = "sqlite")]
619 mod sqlite_backend_tests {
620 use super::*;
621
622 #[tokio::test(flavor = "multi_thread")]
623 async fn test_make_backend_sqlite_path_returns_sqlite_store() {
624 let dir = tempdir().unwrap();
625 let path = dir.path().join("test.sqlite");
626 let sm = make_sm();
627 let cfg = AppConfig::default();
628 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
629 assert!(!backend.needs_flush(), "new SQLite backend starts clean");
630 assert!(
631 !backend.needs_save_worker(),
632 "SQLite backend is write-through and does not need a save worker"
633 );
634 }
635
636 #[tokio::test(flavor = "multi_thread")]
637 async fn test_make_backend_detects_sqlite_by_magic_bytes() {
638 let dir = tempdir().unwrap();
639 let path = dir.path().join("noext");
640
641 kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
644 .await
645 .unwrap();
646
647 let sm = make_sm();
648 let cfg = AppConfig::default();
649 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
650 assert!(
651 !backend.needs_save_worker(),
652 "magic-byte SQLite detection should yield a write-through backend"
653 );
654 let boards = backend.list_boards().unwrap();
655 assert!(boards.is_empty());
656 }
657
658 #[tokio::test(flavor = "multi_thread")]
659 async fn test_make_backend_detects_json_by_content() {
660 use kanban_persistence::{PersistenceMetadata, PersistenceStore, StoreSnapshot};
661 let dir = tempdir().unwrap();
662 let path = dir.path().join("noext");
663
664 {
667 let jfs = kanban_persistence_json::JsonFileStore::new(&path);
668 let snap = kanban_domain::Snapshot::new();
669 let data = kanban_persistence::snapshot_to_json_bytes(&snap).unwrap();
670 let meta = PersistenceMetadata::new(uuid::Uuid::new_v4());
671 jfs.save(StoreSnapshot {
672 data,
673 metadata: meta,
674 })
675 .await
676 .unwrap();
677 }
678
679 let sm = make_sm();
680 let cfg = AppConfig::default();
681 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
682 assert!(
683 backend.needs_save_worker(),
684 "content-sniffed JSON backend requires a save worker"
685 );
686 let boards = backend.list_boards().unwrap();
687 assert!(boards.is_empty());
688 }
689
690 #[tokio::test(flavor = "multi_thread")]
691 async fn test_sqlite_locator_resolves_without_a_store_factory() {
692 let mut registry = StoreRegistry::new();
693 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
694 let mut backends = kanban_backend::KanbanBackendRegistry::new();
695 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
696 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
697 let sm = StoreManager::new(registry, backends);
698
699 let dir = tempdir().unwrap();
700 let path = dir.path().join("test.db");
701 let cfg = AppConfig::default();
702 let backend = sm
703 .make_backend(path.to_str().unwrap(), &cfg)
704 .await
705 .expect("make_backend must resolve a sqlite locator without a store-level factory registered");
706 let boards = backend.list_boards().unwrap();
707 assert!(boards.is_empty());
708 }
709
710 #[test]
711 fn test_detect_backend_on_a_nonexistent_db_path_returns_sqlite() {
712 let sm = make_sm();
713 let dir = tempdir().unwrap();
714 let path = dir.path().join("does_not_exist.db");
715 assert_eq!(
716 sm.detect_backend(path.to_str().unwrap()),
717 Some("sqlite".to_string())
718 );
719 }
720
721 #[tokio::test(flavor = "multi_thread")]
722 async fn test_detect_backend_on_an_existing_sqlite_file_still_returns_sqlite() {
723 let dir = tempdir().unwrap();
724 let path = dir.path().join("existing.db");
725 kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
726 .await
727 .unwrap();
728
729 let sm = make_sm();
730 assert_eq!(
731 sm.detect_backend(path.to_str().unwrap()),
732 Some("sqlite".to_string())
733 );
734 }
735
736 #[test]
737 fn test_detect_backend_with_no_registered_factories_returns_none() {
738 let sm = StoreManager::new(
739 StoreRegistry::new(),
740 kanban_backend::KanbanBackendRegistry::new(),
741 );
742
743 assert_eq!(sm.detect_backend("whatever.db"), None);
744 }
745
746 #[tokio::test(flavor = "multi_thread")]
747 async fn test_make_backend_named_ignores_the_locator_header() {
748 let dir = tempdir().unwrap();
749 let path = dir.path().join("dest.db");
750 let sm = make_sm();
751 let cfg = AppConfig::default();
752
753 let named = sm
754 .make_backend_named("json", path.to_str().unwrap(), &cfg)
755 .await
756 .unwrap();
757 assert!(
758 named.needs_save_worker(),
759 "make_backend_named(\"json\", ...) must build a JSON backend regardless of the .db extension"
760 );
761
762 let sniffed = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
763 assert!(
764 !sniffed.needs_save_worker(),
765 "make_backend on the same nonexistent .db path sniffs sqlite by extension"
766 );
767 }
768
769 #[test]
770 fn test_detect_backend_for_a_db_path_without_a_sqlite_backend_falls_back_to_json() {
771 let mut registry = StoreRegistry::new();
772 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
773 let mut backends = kanban_backend::KanbanBackendRegistry::new();
774 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
775 let sm = StoreManager::new(registry, backends);
776
777 assert_eq!(sm.detect_backend("whatever.db"), Some("json".to_string()));
778 }
779 }
780
781 struct RemoteStub;
782
783 #[async_trait::async_trait]
784 impl kanban_backend::KanbanBackendFactory for RemoteStub {
785 fn name(&self) -> &str {
786 "remote"
787 }
788
789 fn is_remote(&self) -> bool {
790 true
791 }
792
793 async fn create(
794 &self,
795 locator: &str,
796 _config: &AppConfig,
797 ) -> Result<Arc<dyn crate::backend::KanbanBackend>, KanbanError> {
798 Err(KanbanError::validation(format!(
799 "remote factory reached with {locator}"
800 )))
801 }
802 }
803
804 #[test]
805 fn test_local_backend_names_excludes_a_remote_factory() {
806 let mut registry = StoreRegistry::new();
807 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
808 let mut backends = kanban_backend::KanbanBackendRegistry::new();
809 #[cfg(feature = "sqlite")]
810 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
811 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
812 backends.register(Box::new(RemoteStub));
813 let sm = StoreManager::new(registry, backends);
814
815 assert!(sm.backend_names().contains(&"remote"));
816 assert!(!sm.local_backend_names().contains(&"remote"));
817 assert!(sm.local_backend_names().contains(&"json"));
818 #[cfg(feature = "sqlite")]
819 assert!(sm.local_backend_names().contains(&"sqlite"));
820 }
821}