1use crate::config;
2use crate::AppConfig;
3use kanban_domain::{DataStore, KanbanError};
4use kanban_persistence::{
5 snapshot_from_json_bytes, PersistenceStore, StoreRegistry, StoreSnapshot,
6};
7use std::collections::HashSet;
8use std::sync::Arc;
9
10pub struct StoreManager {
17 registry: Arc<StoreRegistry>,
18 backends: Arc<kanban_backend::KanbanBackendRegistry>,
19}
20
21impl StoreManager {
22 pub fn new(registry: StoreRegistry, backends: kanban_backend::KanbanBackendRegistry) -> Self {
26 Self {
27 registry: Arc::new(registry),
28 backends: Arc::new(backends),
29 }
30 }
31
32 pub fn registry(&self) -> &StoreRegistry {
35 &self.registry
36 }
37
38 pub fn has_backends(&self) -> bool {
40 !self.backends.is_empty()
41 }
42
43 pub fn backend_names(&self) -> Vec<&str> {
45 self.registry.backend_names()
46 }
47
48 pub fn is_sqlite(&self, locator: &str) -> bool {
52 match self.detect_backend(locator).as_deref() {
53 Some("sqlite") => true,
54 None => {
55 locator.ends_with(".sqlite")
56 || locator.ends_with(".sqlite3")
57 || locator.ends_with(".db")
58 }
59 _ => false,
60 }
61 }
62
63 pub fn detect_backend(&self, locator: &str) -> Option<String> {
67 if let Some(name) = self.registry.detect_backend(locator) {
68 return Some(name.to_string());
69 }
70 #[cfg(feature = "sqlite")]
71 {
72 let path = std::path::Path::new(locator);
73 if path.exists() {
74 if let Ok(mut f) = std::fs::File::open(path) {
75 use std::io::Read;
76 let mut hdr = [0u8; 16];
77 let n = f.read(&mut hdr).unwrap_or(0);
78 if hdr[..n].starts_with(b"SQLite format 3\0") {
79 return Some("sqlite".to_string());
80 }
81 }
82 }
83 }
84 None
85 }
86
87 pub fn sync_backend_with_file(&self, locator: &str, config: &mut AppConfig) -> bool {
90 if let Some(detected) = self.detect_backend(locator) {
91 if detected != config.effective_storage_backend() {
92 config.storage_backend = Some(detected);
93 return true;
94 }
95 }
96 false
97 }
98
99 pub async fn make_backend(
103 &self,
104 locator: &str,
105 config: &AppConfig,
106 ) -> Result<std::sync::Arc<dyn crate::backend::KanbanBackend>, KanbanError> {
107 let factory = self.backends.for_locator(locator).ok_or_else(|| {
108 KanbanError::Internal(format!(
109 "no registered backend handles '{locator}'; registered: {:?}",
110 self.backends.names()
111 ))
112 })?;
113 factory.create(locator, config).await
114 }
115
116 pub fn make_store(
119 &self,
120 backend: &str,
121 locator: &str,
122 ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, KanbanError> {
123 Ok(self.registry.create_store(backend, locator)?)
124 }
125
126 pub fn make_store_with_config(
131 &self,
132 file: Option<&str>,
133 config: &AppConfig,
134 ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, KanbanError> {
135 let locator = match file {
136 Some(path) => path.to_string(),
137 None => config::resolve_storage_location(config),
138 };
139 let backend = self
140 .detect_backend(&locator)
141 .unwrap_or_else(|| config.effective_storage_backend().to_string());
142 self.make_store(&backend, &locator)
143 }
144
145 pub async fn validate_store_readable(
158 &self,
159 backend: &str,
160 path: &str,
161 ) -> Result<(), KanbanError> {
162 if matches!(backend, "sqlite" | "sqlite3" | "db") {
163 #[cfg(feature = "sqlite")]
164 {
165 if !std::path::Path::new(path).exists() {
166 return Err(std::io::Error::new(
167 std::io::ErrorKind::NotFound,
168 format!("Storage file does not exist: {}", path),
169 )
170 .into());
171 }
172 let sqlite_backend = kanban_persistence_sqlite::SqliteBackend::open(path).await?;
176 sqlite_backend.list_boards()?;
177 return Ok(());
178 }
179 #[cfg(not(feature = "sqlite"))]
180 return Err(KanbanError::validation("sqlite feature not compiled in"));
181 }
182 let store = self.make_store(backend, path)?;
183 if !store.exists().await {
184 return Err(std::io::Error::new(
185 std::io::ErrorKind::NotFound,
186 format!("Storage file does not exist: {}", path),
187 )
188 .into());
189 }
190 let (snapshot, _metadata) = store.load().await?;
191 snapshot_from_json_bytes(&snapshot.data)?;
192 Ok(())
193 }
194
195 pub async fn export_to_sqlite(
200 &self,
201 export: kanban_domain::export::AllBoardsExport,
202 filename: &str,
203 config: &AppConfig,
204 ) -> Result<(), KanbanError> {
205 #[cfg(feature = "sqlite")]
206 {
207 use kanban_domain::export::BoardImporter;
208 use kanban_domain::{DependencyGraph, Snapshot};
209
210 if std::path::Path::new(filename).exists() {
216 return Err(std::io::Error::new(
217 std::io::ErrorKind::AlreadyExists,
218 format!(
219 "Destination already exists: {filename}. Remove it first or use a different path."
220 ),
221 )
222 .into());
223 }
224
225 let mut entities = BoardImporter::extract_entities(export);
226 entities.cards = entities
227 .cards
228 .iter()
229 .map(|c| {
230 kanban_domain::stamp_card_prefix(
231 c,
232 &entities.columns,
233 &entities.boards,
234 &entities.sprints,
235 )
236 })
237 .collect();
238 let prefixes = kanban_domain::counters_implied_by(
242 &entities.cards,
243 &entities.columns,
244 &entities.sprints,
245 &entities.boards,
246 Some(config.effective_default_sprint_prefix()),
247 );
248 let snapshot = Snapshot {
249 archived_boards: entities.archived_boards,
250 boards: entities.boards,
251 columns: entities.columns,
252 cards: entities.cards,
253 archived_cards: entities.archived_cards,
254 sprints: entities.sprints,
255 graph: DependencyGraph::default(),
256 prefixes,
257 };
258 self.write_sqlite_destination(filename, snapshot).await
259 }
260 #[cfg(not(feature = "sqlite"))]
261 {
262 let _ = export;
263 let _ = filename;
264 Err(KanbanError::validation("sqlite feature not compiled in"))
265 }
266 }
267
268 pub async fn migrate_store(
275 &self,
276 from_backend: &str,
277 from_path: &str,
278 to_backend: &str,
279 to_path: &str,
280 ) -> Result<(), KanbanError> {
281 let from = std::path::Path::new(from_path);
282 let to = std::path::Path::new(to_path);
283 if !from.exists() {
284 return Err(std::io::Error::new(
285 std::io::ErrorKind::NotFound,
286 format!("Source file not found: {}", from.display()),
287 )
288 .into());
289 }
290 if to.exists() {
291 return Err(std::io::Error::new(
292 std::io::ErrorKind::AlreadyExists,
293 format!(
294 "Destination already exists: {}. Remove it first or use a different path.",
295 to.display()
296 ),
297 )
298 .into());
299 }
300
301 let leg = MigrationLeg::of(from_backend, to_backend);
302 let source_is_sqlite = matches!(
303 leg,
304 MigrationLeg::SqliteToSqlite | MigrationLeg::SqliteToJson
305 );
306 let dest_is_sqlite = matches!(
307 leg,
308 MigrationLeg::SqliteToSqlite | MigrationLeg::JsonToSqlite
309 );
310
311 if !leg.round_trips_through_json() {
316 #[cfg(feature = "sqlite")]
317 {
318 let snapshot = self.read_sqlite_source(from_path).await?;
319 return self.write_sqlite_destination(to_path, snapshot).await;
320 }
321 #[cfg(not(feature = "sqlite"))]
322 return Err(KanbanError::validation("sqlite feature not compiled in"));
323 }
324
325 let mut store_snapshot: StoreSnapshot = if source_is_sqlite {
328 #[cfg(feature = "sqlite")]
329 {
330 use kanban_persistence::PersistenceMetadata;
331 let snapshot = self.read_sqlite_source(from_path).await?;
332 StoreSnapshot {
333 data: kanban_persistence::snapshot_to_json_bytes(&snapshot)?,
334 metadata: PersistenceMetadata::new(uuid::Uuid::new_v4()),
335 }
336 }
337 #[cfg(not(feature = "sqlite"))]
338 return Err(KanbanError::validation("sqlite feature not compiled in"));
339 } else {
340 let source = self.make_store(from_backend, from_path)?;
341 let (snap, _) = source.load().await?;
342 snap
343 };
344
345 repair_snapshot_fks(&mut store_snapshot)?;
346
347 if dest_is_sqlite {
348 #[cfg(feature = "sqlite")]
349 {
350 let repaired = snapshot_from_json_bytes(&store_snapshot.data)?;
351 return self.write_sqlite_destination(to_path, repaired).await;
352 }
353 #[cfg(not(feature = "sqlite"))]
354 return Err(KanbanError::validation("sqlite feature not compiled in"));
355 }
356
357 let target = self.make_store(to_backend, to_path)?;
358 let outcome = target.save(store_snapshot).await;
359 target.close().await;
360 drop(target);
361 if let Err(e) = outcome {
362 cleanup_destination_files(to_path).await;
363 return Err(e.into());
364 }
365 Ok(())
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
424impl Clone for StoreManager {
425 fn clone(&self) -> Self {
426 Self {
427 registry: Arc::clone(&self.registry),
428 backends: Arc::clone(&self.backends),
429 }
430 }
431}
432
433async fn remove_file_with_windows_retry(path: &std::path::Path) {
438 for delay_ms in [0u64, 50, 100, 200, 400] {
439 if delay_ms > 0 {
440 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
441 }
442 if std::fs::remove_file(path).is_ok() {
443 return;
444 }
445 if !path.exists() {
446 return;
447 }
448 }
449 tracing::warn!(
450 path = %path.display(),
451 "failed to remove file after retry backoff; orphan may remain on disk"
452 );
453}
454
455fn is_sqlite_backend(name: &str) -> bool {
460 matches!(name, "sqlite" | "sqlite3" | "db")
461}
462
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466pub(crate) enum MigrationLeg {
467 SqliteToSqlite,
468 SqliteToJson,
469 JsonToSqlite,
470 JsonToJson,
471}
472
473impl MigrationLeg {
474 pub(crate) fn of(from_backend: &str, to_backend: &str) -> Self {
475 match (
476 is_sqlite_backend(from_backend),
477 is_sqlite_backend(to_backend),
478 ) {
479 (true, true) => Self::SqliteToSqlite,
480 (true, false) => Self::SqliteToJson,
481 (false, true) => Self::JsonToSqlite,
482 (false, false) => Self::JsonToJson,
483 }
484 }
485
486 pub(crate) fn round_trips_through_json(self) -> bool {
491 !matches!(self, Self::SqliteToSqlite)
492 }
493}
494
495async fn cleanup_destination_files(to_path: &str) {
496 remove_file_with_windows_retry(std::path::Path::new(to_path)).await;
497 let wal = format!("{}-wal", to_path);
498 let shm = format!("{}-shm", to_path);
499 remove_file_with_windows_retry(std::path::Path::new(&wal)).await;
500 remove_file_with_windows_retry(std::path::Path::new(&shm)).await;
501}
502
503fn repair_snapshot_fks(snapshot: &mut StoreSnapshot) -> Result<(), KanbanError> {
504 let mut data: serde_json::Value = serde_json::from_slice(&snapshot.data).map_err(|e| {
505 KanbanError::validation(format!("Failed to parse snapshot for FK repair: {e}"))
506 })?;
507
508 let valid_columns: HashSet<String> = data["columns"]
509 .as_array()
510 .map(|arr| {
511 arr.iter()
512 .filter_map(|c| c["id"].as_str().map(String::from))
513 .collect()
514 })
515 .unwrap_or_default();
516
517 let valid_sprints: HashSet<String> = data["sprints"]
518 .as_array()
519 .map(|arr| {
520 arr.iter()
521 .filter_map(|s| s["id"].as_str().map(String::from))
522 .collect()
523 })
524 .unwrap_or_default();
525
526 let fallback_column: Option<String> = data["columns"].as_array().and_then(|arr| {
527 arr.iter()
528 .min_by_key(|c| c["position"].as_i64().unwrap_or(i64::MAX))
529 .and_then(|c| c["id"].as_str())
530 .map(String::from)
531 });
532
533 if let Some(cards) = data["cards"].as_array_mut() {
534 for card in cards.iter_mut() {
535 fix_card_fks(
536 card,
537 &valid_columns,
538 &valid_sprints,
539 fallback_column.as_deref(),
540 );
541 }
542 let orphaned = cards
551 .iter()
552 .filter(|card| {
553 card["column_id"]
554 .as_str()
555 .is_some_and(|c| !valid_columns.contains(c))
556 })
557 .count();
558 if orphaned > 0 {
559 return Err(KanbanError::validation(format!(
560 "cannot migrate: {orphaned} live card(s) reference a column that does not \
561 exist and there is no column to reassign them to"
562 )));
563 }
564 }
565
566 snapshot.data = serde_json::to_vec(&data).map_err(|e| {
571 KanbanError::validation(format!("Failed to serialize repaired snapshot: {e}"))
572 })?;
573
574 Ok(())
575}
576
577fn fix_card_fks(
578 card: &mut serde_json::Value,
579 valid_columns: &HashSet<String>,
580 valid_sprints: &HashSet<String>,
581 fallback_column: Option<&str>,
582) {
583 if let Some(sprint_id) = card["sprint_id"].as_str() {
584 if !valid_sprints.contains(sprint_id) {
585 card["sprint_id"] = serde_json::Value::Null;
586 }
587 }
588 if let Some(col_id) = card["column_id"].as_str() {
589 if !valid_columns.contains(col_id) {
590 if let Some(fb) = fallback_column {
591 card["column_id"] = serde_json::Value::String(fb.to_string());
592 }
593 }
594 }
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600 use kanban_persistence::{PersistenceMetadata, StoreRegistry};
601 use tempfile::tempdir;
602 use uuid::Uuid;
603
604 #[test]
605 fn test_sqlite_to_sqlite_leg_does_not_round_trip_through_json() {
606 for (from, to) in [("sqlite", "sqlite"), ("sqlite3", "db"), ("db", "sqlite3")] {
611 let leg = MigrationLeg::of(from, to);
612 assert_eq!(leg, MigrationLeg::SqliteToSqlite, "{from} -> {to}");
613 assert!(
614 !leg.round_trips_through_json(),
615 "{from} -> {to} must not serialise through JSON"
616 );
617 }
618 }
619
620 #[test]
621 fn test_every_leg_with_json_on_one_end_round_trips_through_json() {
622 for (from, to, expected) in [
624 ("sqlite", "json", MigrationLeg::SqliteToJson),
625 ("json", "sqlite", MigrationLeg::JsonToSqlite),
626 ("json", "json", MigrationLeg::JsonToJson),
627 ] {
628 let leg = MigrationLeg::of(from, to);
629 assert_eq!(leg, expected, "{from} -> {to}");
630 assert!(
631 leg.round_trips_through_json(),
632 "{from} -> {to} carries a StoreSnapshot, so FK repair applies"
633 );
634 }
635 }
636
637 fn make_snapshot_with_json(data: serde_json::Value) -> StoreSnapshot {
638 StoreSnapshot {
639 data: serde_json::to_vec(&data).unwrap(),
640 metadata: PersistenceMetadata::new(Uuid::new_v4()),
641 }
642 }
643
644 #[test]
648 fn test_repair_snapshot_fks_repairs_live_row_of_archived_card() {
649 let valid_col_id = Uuid::new_v4().to_string();
650 let dangling_col_id = Uuid::new_v4().to_string();
651 let card_id = Uuid::new_v4().to_string();
652 let board_id = Uuid::new_v4().to_string();
653
654 let data = serde_json::json!({
655 "boards": [{"id": board_id}],
656 "columns": [{"id": valid_col_id, "position": 0}],
657 "sprints": [],
658 "cards": [{
659 "id": card_id,
660 "column_id": dangling_col_id,
661 "sprint_id": null
662 }],
663 "archived_cards": [{
664 "entity_id": card_id,
665 "board_id": board_id,
666 "archived_at": "2024-01-01T00:00:00Z"
667 }]
668 });
669
670 let mut snapshot = make_snapshot_with_json(data);
671 repair_snapshot_fks(&mut snapshot)
672 .expect("repair must succeed for archived card with dangling column");
673
674 let repaired: serde_json::Value = serde_json::from_slice(&snapshot.data).unwrap();
675
676 assert_eq!(
677 repaired["cards"][0]["column_id"].as_str().unwrap(),
678 valid_col_id,
679 "live card row must be reassigned to fallback column"
680 );
681 let marker = &repaired["archived_cards"][0];
682 assert!(
683 marker.get("card").is_none(),
684 "marker must have no embedded `card` key (pure marker shape)"
685 );
686 assert_eq!(marker["entity_id"].as_str().unwrap(), card_id);
687 assert_eq!(marker["board_id"].as_str().unwrap(), board_id);
688 }
689
690 #[test]
694 fn test_repair_snapshot_fks_marker_archived_cards_pass_through_unchanged() {
695 let col_id = Uuid::new_v4().to_string();
696 let card_id = Uuid::new_v4().to_string();
697 let board_id = Uuid::new_v4().to_string();
698
699 let archived_entry = serde_json::json!({
700 "entity_id": card_id,
701 "board_id": board_id,
702 "archived_at": "2024-01-01T00:00:00Z"
703 });
704
705 let data = serde_json::json!({
706 "boards": [],
707 "columns": [{"id": col_id, "position": 0}],
708 "sprints": [],
709 "cards": [{"id": card_id, "column_id": col_id, "sprint_id": null}],
710 "archived_cards": [archived_entry.clone()]
711 });
712
713 let mut snapshot = make_snapshot_with_json(data);
714 repair_snapshot_fks(&mut snapshot).expect("repair must succeed");
715
716 let repaired: serde_json::Value = serde_json::from_slice(&snapshot.data).unwrap();
717 let marker_after = &repaired["archived_cards"][0];
718
719 assert_eq!(
720 marker_after["entity_id"].as_str().unwrap(),
721 card_id,
722 "entity_id must be unchanged"
723 );
724 assert_eq!(
725 marker_after["board_id"].as_str().unwrap(),
726 board_id,
727 "board_id must be unchanged"
728 );
729 assert!(
730 marker_after.get("card").is_none(),
731 "no `card` embed must be present before or after repair"
732 );
733 }
734
735 fn make_sm() -> StoreManager {
736 let mut registry = StoreRegistry::new();
737 #[cfg(feature = "sqlite")]
738 registry.register(Box::new(kanban_persistence_sqlite::SqliteStoreFactory));
739 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
744 let mut backends = kanban_backend::KanbanBackendRegistry::new();
745 #[cfg(feature = "sqlite")]
746 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
747 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
748 StoreManager::new(registry, backends)
749 }
750
751 #[tokio::test(flavor = "multi_thread")]
752 async fn test_make_backend_errors_for_unregistered_locator() {
753 let dir = tempdir().unwrap();
754 let path = dir.path().join("test.json");
755 let sm = StoreManager::new(
756 StoreRegistry::new(),
757 kanban_backend::KanbanBackendRegistry::new(),
758 );
759 let cfg = AppConfig::default();
760 let err = sm
761 .make_backend(path.to_str().unwrap(), &cfg)
762 .await
763 .err()
764 .expect("empty registry must not silently pick a backend");
765 let msg = err.to_string();
766 assert!(
767 msg.contains("no registered backend handles"),
768 "expected unregistered-locator error, got: {msg}"
769 );
770 }
771
772 #[tokio::test(flavor = "multi_thread")]
773 async fn test_make_backend_json_path_returns_json_data_store() {
774 let dir = tempdir().unwrap();
775 let path = dir.path().join("test.json");
776 let sm = make_sm();
777 let cfg = AppConfig::default();
778 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
779 assert!(!backend.needs_flush(), "new JSON backend starts clean");
780 assert!(
781 backend.needs_save_worker(),
782 "JSON backend requires a background flush worker"
783 );
784 }
785
786 #[cfg(feature = "sqlite")]
787 mod sqlite_backend_tests {
788 use super::*;
789
790 #[tokio::test(flavor = "multi_thread")]
791 async fn test_make_backend_sqlite_path_returns_sqlite_store() {
792 let dir = tempdir().unwrap();
793 let path = dir.path().join("test.sqlite");
794 let sm = make_sm();
795 let cfg = AppConfig::default();
796 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
797 assert!(!backend.needs_flush(), "new SQLite backend starts clean");
798 assert!(
799 !backend.needs_save_worker(),
800 "SQLite backend is write-through and does not need a save worker"
801 );
802 }
803
804 #[tokio::test(flavor = "multi_thread")]
805 async fn test_make_backend_detects_sqlite_by_magic_bytes() {
806 let dir = tempdir().unwrap();
807 let path = dir.path().join("noext");
808
809 kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
812 .await
813 .unwrap();
814
815 let sm = make_sm();
816 let cfg = AppConfig::default();
817 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
818 assert!(
819 !backend.needs_save_worker(),
820 "magic-byte SQLite detection should yield a write-through backend"
821 );
822 let boards = backend.list_boards().unwrap();
823 assert!(boards.is_empty());
824 }
825
826 #[tokio::test(flavor = "multi_thread")]
827 async fn test_make_backend_detects_json_by_content() {
828 use kanban_persistence::{PersistenceMetadata, PersistenceStore, StoreSnapshot};
829 let dir = tempdir().unwrap();
830 let path = dir.path().join("noext");
831
832 {
835 let jfs = kanban_persistence_json::JsonFileStore::new(&path);
836 let snap = kanban_domain::Snapshot::new();
837 let data = kanban_persistence::snapshot_to_json_bytes(&snap).unwrap();
838 let meta = PersistenceMetadata::new(uuid::Uuid::new_v4());
839 jfs.save(StoreSnapshot {
840 data,
841 metadata: meta,
842 })
843 .await
844 .unwrap();
845 }
846
847 let sm = make_sm();
848 let cfg = AppConfig::default();
849 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
850 assert!(
851 backend.needs_save_worker(),
852 "content-sniffed JSON backend requires a save worker"
853 );
854 let boards = backend.list_boards().unwrap();
855 assert!(boards.is_empty());
856 }
857 }
858}