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_and_load_store(
152 &self,
153 backend: &str,
154 path: &str,
155 ) -> Result<kanban_domain::Snapshot, KanbanError> {
156 if matches!(backend, "sqlite" | "sqlite3" | "db") {
157 #[cfg(feature = "sqlite")]
158 {
159 if !std::path::Path::new(path).exists() {
160 return Err(std::io::Error::new(
161 std::io::ErrorKind::NotFound,
162 format!("Storage file does not exist: {}", path),
163 )
164 .into());
165 }
166 let store = kanban_persistence_sqlite::SqliteStore::open(path).await?;
167 return store.snapshot();
168 }
169 #[cfg(not(feature = "sqlite"))]
170 return Err(KanbanError::validation("sqlite feature not compiled in"));
171 }
172 let store = self.make_store(backend, path)?;
173 if !store.exists().await {
174 return Err(std::io::Error::new(
175 std::io::ErrorKind::NotFound,
176 format!("Storage file does not exist: {}", path),
177 )
178 .into());
179 }
180 let (snapshot, _metadata) = store.load().await?;
181 let data = snapshot_from_json_bytes(&snapshot.data)?;
182 Ok(data)
183 }
184
185 pub async fn export_to_sqlite(
190 &self,
191 export: kanban_domain::export::AllBoardsExport,
192 filename: &str,
193 ) -> Result<(), KanbanError> {
194 #[cfg(feature = "sqlite")]
195 {
196 use kanban_domain::export::BoardImporter;
197 use kanban_domain::{DependencyGraph, Snapshot};
198
199 let entities = BoardImporter::extract_entities(export);
200 let snapshot = Snapshot {
201 archived_boards: entities.archived_boards,
202 boards: entities.boards,
203 columns: entities.columns,
204 cards: entities.cards,
205 archived_cards: entities.archived_cards,
206 sprints: entities.sprints,
207 graph: DependencyGraph::default(),
208 };
209 let store = kanban_persistence_sqlite::SqliteStore::open(filename).await?;
210 store.apply_snapshot(snapshot)?;
211 Ok(())
212 }
213 #[cfg(not(feature = "sqlite"))]
214 {
215 let _ = export;
216 let _ = filename;
217 Err(KanbanError::validation("sqlite feature not compiled in"))
218 }
219 }
220
221 pub async fn migrate_store(
228 &self,
229 from_backend: &str,
230 from_path: &str,
231 to_backend: &str,
232 to_path: &str,
233 ) -> Result<(), KanbanError> {
234 let from = std::path::Path::new(from_path);
235 let to = std::path::Path::new(to_path);
236 if !from.exists() {
237 return Err(std::io::Error::new(
238 std::io::ErrorKind::NotFound,
239 format!("Source file not found: {}", from.display()),
240 )
241 .into());
242 }
243 if to.exists() {
244 return Err(std::io::Error::new(
245 std::io::ErrorKind::AlreadyExists,
246 format!(
247 "Destination already exists: {}. Remove it first or use a different path.",
248 to.display()
249 ),
250 )
251 .into());
252 }
253
254 let mut store_snapshot: StoreSnapshot = match from_backend {
256 "sqlite" | "sqlite3" | "db" => {
257 #[cfg(feature = "sqlite")]
258 {
259 use kanban_persistence::PersistenceMetadata;
260 let store = kanban_persistence_sqlite::SqliteStore::open(from_path).await?;
270 let snapshot = store.snapshot()?;
271 let data = kanban_persistence::snapshot_to_json_bytes(&snapshot)?;
272 StoreSnapshot {
273 data,
274 metadata: PersistenceMetadata::new(uuid::Uuid::new_v4()),
275 }
276 }
277 #[cfg(not(feature = "sqlite"))]
278 return Err(KanbanError::validation("sqlite feature not compiled in"));
279 }
280 _ => {
281 let source = self.make_store(from_backend, from_path)?;
282 let (snap, _) = source.load().await?;
283 snap
284 }
285 };
286
287 repair_snapshot_fks(&mut store_snapshot)?;
288
289 match to_backend {
291 "sqlite" | "sqlite3" | "db" => {
292 #[cfg(feature = "sqlite")]
293 {
294 let repaired = snapshot_from_json_bytes(&store_snapshot.data)?;
295 let store = kanban_persistence_sqlite::SqliteStore::open(to_path).await?;
296 let outcome = store.apply_snapshot(repaired.clone());
297 store.close().await;
298 drop(store);
299 if let Err(e) = outcome {
300 cleanup_destination_files(to_path).await;
301 return Err(e);
302 }
303 }
304 #[cfg(not(feature = "sqlite"))]
305 return Err(KanbanError::validation("sqlite feature not compiled in"));
306 }
307 _ => {
308 let target = self.make_store(to_backend, to_path)?;
309 let outcome = target.save(store_snapshot).await;
310 target.close().await;
311 drop(target);
312 if let Err(e) = outcome {
313 cleanup_destination_files(to_path).await;
314 return Err(e.into());
315 }
316 }
317 }
318 Ok(())
319 }
320}
321
322impl Clone for StoreManager {
323 fn clone(&self) -> Self {
324 Self {
325 registry: Arc::clone(&self.registry),
326 backends: Arc::clone(&self.backends),
327 }
328 }
329}
330
331async fn remove_file_with_windows_retry(path: &std::path::Path) {
336 for delay_ms in [0u64, 50, 100, 200, 400] {
337 if delay_ms > 0 {
338 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
339 }
340 if std::fs::remove_file(path).is_ok() {
341 return;
342 }
343 if !path.exists() {
344 return;
345 }
346 }
347 tracing::warn!(
348 path = %path.display(),
349 "failed to remove file after retry backoff; orphan may remain on disk"
350 );
351}
352
353async fn cleanup_destination_files(to_path: &str) {
358 remove_file_with_windows_retry(std::path::Path::new(to_path)).await;
359 let wal = format!("{}-wal", to_path);
360 let shm = format!("{}-shm", to_path);
361 remove_file_with_windows_retry(std::path::Path::new(&wal)).await;
362 remove_file_with_windows_retry(std::path::Path::new(&shm)).await;
363}
364
365fn repair_snapshot_fks(snapshot: &mut StoreSnapshot) -> Result<(), KanbanError> {
366 let mut data: serde_json::Value = serde_json::from_slice(&snapshot.data).map_err(|e| {
367 KanbanError::validation(format!("Failed to parse snapshot for FK repair: {e}"))
368 })?;
369
370 let valid_columns: HashSet<String> = data["columns"]
371 .as_array()
372 .map(|arr| {
373 arr.iter()
374 .filter_map(|c| c["id"].as_str().map(String::from))
375 .collect()
376 })
377 .unwrap_or_default();
378
379 let valid_sprints: HashSet<String> = data["sprints"]
380 .as_array()
381 .map(|arr| {
382 arr.iter()
383 .filter_map(|s| s["id"].as_str().map(String::from))
384 .collect()
385 })
386 .unwrap_or_default();
387
388 let fallback_column: Option<String> = data["columns"].as_array().and_then(|arr| {
389 arr.iter()
390 .min_by_key(|c| c["position"].as_i64().unwrap_or(i64::MAX))
391 .and_then(|c| c["id"].as_str())
392 .map(String::from)
393 });
394
395 if let Some(cards) = data["cards"].as_array_mut() {
396 for card in cards.iter_mut() {
397 fix_card_fks(
398 card,
399 &valid_columns,
400 &valid_sprints,
401 fallback_column.as_deref(),
402 );
403 }
404 let orphaned = cards
413 .iter()
414 .filter(|card| {
415 card["column_id"]
416 .as_str()
417 .is_some_and(|c| !valid_columns.contains(c))
418 })
419 .count();
420 if orphaned > 0 {
421 return Err(KanbanError::validation(format!(
422 "cannot migrate: {orphaned} live card(s) reference a column that does not \
423 exist and there is no column to reassign them to"
424 )));
425 }
426 }
427
428 snapshot.data = serde_json::to_vec(&data).map_err(|e| {
433 KanbanError::validation(format!("Failed to serialize repaired snapshot: {e}"))
434 })?;
435
436 Ok(())
437}
438
439fn fix_card_fks(
440 card: &mut serde_json::Value,
441 valid_columns: &HashSet<String>,
442 valid_sprints: &HashSet<String>,
443 fallback_column: Option<&str>,
444) {
445 if let Some(sprint_id) = card["sprint_id"].as_str() {
446 if !valid_sprints.contains(sprint_id) {
447 card["sprint_id"] = serde_json::Value::Null;
448 }
449 }
450 if let Some(col_id) = card["column_id"].as_str() {
451 if !valid_columns.contains(col_id) {
452 if let Some(fb) = fallback_column {
453 card["column_id"] = serde_json::Value::String(fb.to_string());
454 }
455 }
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use super::*;
462 use kanban_persistence::{PersistenceMetadata, StoreRegistry};
463 use tempfile::tempdir;
464 use uuid::Uuid;
465
466 fn make_snapshot_with_json(data: serde_json::Value) -> StoreSnapshot {
467 StoreSnapshot {
468 data: serde_json::to_vec(&data).unwrap(),
469 metadata: PersistenceMetadata::new(Uuid::new_v4()),
470 }
471 }
472
473 #[test]
477 fn test_repair_snapshot_fks_repairs_live_row_of_archived_card() {
478 let valid_col_id = Uuid::new_v4().to_string();
479 let dangling_col_id = Uuid::new_v4().to_string();
480 let card_id = Uuid::new_v4().to_string();
481 let board_id = Uuid::new_v4().to_string();
482
483 let data = serde_json::json!({
484 "boards": [{"id": board_id}],
485 "columns": [{"id": valid_col_id, "position": 0}],
486 "sprints": [],
487 "cards": [{
488 "id": card_id,
489 "column_id": dangling_col_id,
490 "sprint_id": null
491 }],
492 "archived_cards": [{
493 "entity_id": card_id,
494 "board_id": board_id,
495 "archived_at": "2024-01-01T00:00:00Z"
496 }]
497 });
498
499 let mut snapshot = make_snapshot_with_json(data);
500 repair_snapshot_fks(&mut snapshot)
501 .expect("repair must succeed for archived card with dangling column");
502
503 let repaired: serde_json::Value = serde_json::from_slice(&snapshot.data).unwrap();
504
505 assert_eq!(
506 repaired["cards"][0]["column_id"].as_str().unwrap(),
507 valid_col_id,
508 "live card row must be reassigned to fallback column"
509 );
510 let marker = &repaired["archived_cards"][0];
511 assert!(
512 marker.get("card").is_none(),
513 "marker must have no embedded `card` key (pure marker shape)"
514 );
515 assert_eq!(marker["entity_id"].as_str().unwrap(), card_id);
516 assert_eq!(marker["board_id"].as_str().unwrap(), board_id);
517 }
518
519 #[test]
523 fn test_repair_snapshot_fks_marker_archived_cards_pass_through_unchanged() {
524 let col_id = Uuid::new_v4().to_string();
525 let card_id = Uuid::new_v4().to_string();
526 let board_id = Uuid::new_v4().to_string();
527
528 let archived_entry = serde_json::json!({
529 "entity_id": card_id,
530 "board_id": board_id,
531 "archived_at": "2024-01-01T00:00:00Z"
532 });
533
534 let data = serde_json::json!({
535 "boards": [],
536 "columns": [{"id": col_id, "position": 0}],
537 "sprints": [],
538 "cards": [{"id": card_id, "column_id": col_id, "sprint_id": null}],
539 "archived_cards": [archived_entry.clone()]
540 });
541
542 let mut snapshot = make_snapshot_with_json(data);
543 repair_snapshot_fks(&mut snapshot).expect("repair must succeed");
544
545 let repaired: serde_json::Value = serde_json::from_slice(&snapshot.data).unwrap();
546 let marker_after = &repaired["archived_cards"][0];
547
548 assert_eq!(
549 marker_after["entity_id"].as_str().unwrap(),
550 card_id,
551 "entity_id must be unchanged"
552 );
553 assert_eq!(
554 marker_after["board_id"].as_str().unwrap(),
555 board_id,
556 "board_id must be unchanged"
557 );
558 assert!(
559 marker_after.get("card").is_none(),
560 "no `card` embed must be present before or after repair"
561 );
562 }
563
564 fn make_sm() -> StoreManager {
565 let mut registry = StoreRegistry::new();
566 #[cfg(feature = "sqlite")]
567 registry.register(Box::new(kanban_persistence_sqlite::SqliteStoreFactory));
568 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
573 let mut backends = kanban_backend::KanbanBackendRegistry::new();
574 #[cfg(feature = "sqlite")]
575 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
576 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
577 StoreManager::new(registry, backends)
578 }
579
580 #[tokio::test(flavor = "multi_thread")]
581 async fn test_make_backend_errors_for_unregistered_locator() {
582 let dir = tempdir().unwrap();
583 let path = dir.path().join("test.json");
584 let sm = StoreManager::new(
585 StoreRegistry::new(),
586 kanban_backend::KanbanBackendRegistry::new(),
587 );
588 let cfg = AppConfig::default();
589 let err = sm
590 .make_backend(path.to_str().unwrap(), &cfg)
591 .await
592 .err()
593 .expect("empty registry must not silently pick a backend");
594 let msg = err.to_string();
595 assert!(
596 msg.contains("no registered backend handles"),
597 "expected unregistered-locator error, got: {msg}"
598 );
599 }
600
601 #[tokio::test(flavor = "multi_thread")]
602 async fn test_make_backend_json_path_returns_json_data_store() {
603 let dir = tempdir().unwrap();
604 let path = dir.path().join("test.json");
605 let sm = make_sm();
606 let cfg = AppConfig::default();
607 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
608 assert!(!backend.needs_flush(), "new JSON backend starts clean");
609 assert!(
610 backend.needs_save_worker(),
611 "JSON backend requires a background flush worker"
612 );
613 }
614
615 #[cfg(feature = "sqlite")]
616 mod sqlite_backend_tests {
617 use super::*;
618
619 #[tokio::test(flavor = "multi_thread")]
620 async fn test_make_backend_sqlite_path_returns_sqlite_store() {
621 let dir = tempdir().unwrap();
622 let path = dir.path().join("test.sqlite");
623 let sm = make_sm();
624 let cfg = AppConfig::default();
625 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
626 assert!(!backend.needs_flush(), "new SQLite backend starts clean");
627 assert!(
628 !backend.needs_save_worker(),
629 "SQLite backend is write-through and does not need a save worker"
630 );
631 }
632
633 #[tokio::test(flavor = "multi_thread")]
634 async fn test_make_backend_detects_sqlite_by_magic_bytes() {
635 let dir = tempdir().unwrap();
636 let path = dir.path().join("noext");
637
638 kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
641 .await
642 .unwrap();
643
644 let sm = make_sm();
645 let cfg = AppConfig::default();
646 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
647 assert!(
648 !backend.needs_save_worker(),
649 "magic-byte SQLite detection should yield a write-through backend"
650 );
651 let boards = backend.list_boards().unwrap();
652 assert!(boards.is_empty());
653 }
654
655 #[tokio::test(flavor = "multi_thread")]
656 async fn test_make_backend_detects_json_by_content() {
657 use kanban_persistence::{PersistenceMetadata, PersistenceStore, StoreSnapshot};
658 let dir = tempdir().unwrap();
659 let path = dir.path().join("noext");
660
661 {
664 let jfs = kanban_persistence_json::JsonFileStore::new(&path);
665 let snap = kanban_domain::Snapshot::new();
666 let data = kanban_persistence::snapshot_to_json_bytes(&snap).unwrap();
667 let meta = PersistenceMetadata::new(uuid::Uuid::new_v4());
668 jfs.save(StoreSnapshot {
669 data,
670 metadata: meta,
671 })
672 .await
673 .unwrap();
674 }
675
676 let sm = make_sm();
677 let cfg = AppConfig::default();
678 let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
679 assert!(
680 backend.needs_save_worker(),
681 "content-sniffed JSON backend requires a save worker"
682 );
683 let boards = backend.list_boards().unwrap();
684 assert!(boards.is_empty());
685 }
686 }
687}