Skip to main content

kanban_persistence/
traits.rs

1use crate::PersistenceResult;
2use async_trait::async_trait;
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use std::path::{Path, PathBuf};
6use uuid::Uuid;
7
8/// Metadata for persistence operations
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct PersistenceMetadata {
11    /// ID of the instance that performed the save
12    pub instance_id: Uuid,
13    /// When this data was saved
14    pub saved_at: DateTime<Utc>,
15    /// Semver of the kanban that wrote this file. `None` on legacy files
16    /// written before the stamp was introduced.
17    #[serde(default)]
18    pub writer_version: Option<String>,
19    /// Git commit of the kanban that wrote this file. `None` on legacy files
20    /// or builds without a git checkout (`"unknown"` is also possible).
21    #[serde(default)]
22    pub writer_commit: Option<String>,
23    /// Format version of the loaded file as the backend understands it
24    /// (JSON envelope version, SQLite schema_version). `None` when not
25    /// populated by the backend. Display-only — backends still own version
26    /// negotiation.
27    #[serde(default, skip_serializing)]
28    pub format_version: Option<u32>,
29}
30
31impl PersistenceMetadata {
32    pub fn new(instance_id: Uuid) -> Self {
33        Self {
34            instance_id,
35            saved_at: Utc::now(),
36            writer_version: None,
37            writer_commit: None,
38            format_version: None,
39        }
40    }
41
42    /// Stamp the writer identity onto the metadata. Backends call this on the
43    /// save path so the saved file remembers which kanban produced it.
44    pub fn with_writer_stamp(
45        mut self,
46        version: impl Into<String>,
47        commit: impl Into<String>,
48    ) -> Self {
49        self.writer_version = Some(version.into());
50        self.writer_commit = Some(commit.into());
51        self
52    }
53}
54
55/// Point-in-time snapshot of all data that needs to be persisted
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct StoreSnapshot {
58    /// Raw JSON bytes representing all boards, columns, cards, etc.
59    pub data: Vec<u8>,
60    /// Metadata about this snapshot
61    pub metadata: PersistenceMetadata,
62}
63
64/// Events that can be emitted during persistence operations
65#[derive(Debug, Clone)]
66pub enum PersistenceEvent {
67    /// Data was successfully saved
68    Saved(PersistenceMetadata),
69    /// External changes were detected
70    ExternalChangeDetected {
71        path: PathBuf,
72        saved_at: DateTime<Utc>,
73    },
74    /// A conflict occurred (our changes vs external changes)
75    ConflictDetected { reason: String },
76    /// An error occurred during persistence
77    Error(String),
78}
79
80/// Trait for abstract storage operations
81/// Implementations handle different backend storage (file, database, etc.)
82#[async_trait]
83pub trait PersistenceStore: Send + Sync {
84    /// Save a snapshot to the store
85    async fn save(&self, snapshot: StoreSnapshot) -> PersistenceResult<PersistenceMetadata>;
86
87    /// Load the current snapshot from the store
88    async fn load(&self) -> PersistenceResult<(StoreSnapshot, PersistenceMetadata)>;
89
90    /// Check if the store file exists
91    async fn exists(&self) -> bool;
92
93    /// Get the path to the store file
94    fn path(&self) -> &Path;
95
96    /// Get the unique instance ID for this store
97    fn instance_id(&self) -> uuid::Uuid;
98
99    /// Load the store synchronously (no async runtime required).
100    /// Returns `Ok(None)` when the backing file does not exist.
101    ///
102    /// The default implementation returns an error; backends that support
103    /// synchronous loading (e.g. `JsonFileStore`) override this.
104    #[allow(clippy::type_complexity)]
105    fn load_sync(&self) -> PersistenceResult<Option<(StoreSnapshot, PersistenceMetadata)>> {
106        Err(crate::PersistenceError::Unsupported(
107            "load_sync not supported by this backend".into(),
108        ))
109    }
110
111    /// Drain any open connections / file handles before the backing file is
112    /// unlinked. Required on Windows: the OS refuses to delete files that
113    /// still have live handles, and async resources (e.g. an `sqlx` pool)
114    /// outlive synchronous `Drop` because the runtime needs time to close
115    /// each connection.
116    ///
117    /// The default is a no-op; backends with long-lived handles (e.g.
118    /// `SqliteStore`) override this.
119    async fn close(&self) {}
120}
121
122/// Trait for detecting changes to the storage file
123/// Used for multi-instance coordination
124#[async_trait]
125pub trait ChangeDetector: Send + Sync {
126    /// Start watching the file for changes
127    async fn start_watching(&self, path: PathBuf) -> PersistenceResult<()>;
128
129    /// Stop watching the file
130    async fn stop_watching(&self) -> PersistenceResult<()>;
131
132    /// Subscribe to change events
133    /// Returns a broadcast receiver that yields `ChangeEvent` when the file changes
134    fn subscribe(&self) -> tokio::sync::broadcast::Receiver<ChangeEvent>;
135
136    /// Check if currently watching
137    fn is_watching(&self) -> bool;
138}
139
140/// Event indicating a change to the watched file
141#[derive(Debug, Clone)]
142pub struct ChangeEvent {
143    /// Path to the file that changed
144    pub path: PathBuf,
145    /// When the change was detected
146    pub detected_at: DateTime<Utc>,
147}
148
149/// Trait for serialization/deserialization strategies
150/// Allows swapping JSON for binary formats, databases, etc.
151pub trait Serializer<T: Send + Sync>: Send + Sync {
152    /// Serialize data to bytes
153    fn serialize(&self, data: &T) -> PersistenceResult<Vec<u8>>;
154
155    /// Deserialize data from bytes
156    fn deserialize(&self, bytes: &[u8]) -> PersistenceResult<T>;
157}
158
159/// Format versions for migration tracking
160#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
161pub enum FormatVersion {
162    V1,
163    V2,
164    V3,
165    V4,
166    V5,
167    /// V6 splits the dependency graph from a single edge-type-tagged list
168    /// (`graph.cards.edges`) into three sub-graphs keyed by edge kind
169    /// (`graph.parent_child`, `graph.blocks`, `graph.relates`).
170    V6,
171    /// V7 renames the spawns sub-graph bucket from `parent_child` to
172    /// `spawns` so the wire format matches the `SpawnsEdge` struct,
173    /// the `spawns_edges()` accessor, and the SQLite `spawns_edges`
174    /// table. Pure key rename — edge contents are unchanged.
175    V7,
176    /// V8 promotes archived cards to a first-class discrete collection:
177    /// each `archived_cards` entry carries its own `board_id`, backfilled
178    /// from `original_column_id`→column→board for historical files (nil
179    /// when the original column no longer resolves), and is guaranteed not
180    /// to be duplicated inside the `cards` array.
181    V8,
182    /// V9 marks the format as archived-board-capable. The `archived_boards`
183    /// collection is additive (serde-default), but the bump makes a pre-V9
184    /// binary reject the file rather than silently drop archived boards on save.
185    V9,
186    /// V10 collapses the archival wrapper into a PURE MARKER (F3b). Historical
187    /// `archived_cards` / `archived_boards` entries EMBEDDED their entity (under
188    /// `entity`, legacy alias `card`/`board`) and did not carry it in the live
189    /// `cards`/`boards` arrays. V10 lifts each embedded entity into the live
190    /// collection and rewrites each wrapper as a reference marker
191    /// (`{ entity_id, archived_at, board_id? }`), dropping the retired
192    /// `original_column_id`/`original_position` restore context.
193    V10,
194    /// V11 backfills `board_id` onto each historical `cards` entry that lacks
195    /// it, mirroring V8's `archived_cards.board_id` backfill one layer
196    /// earlier: `Card.board_id` is now a durable field set at creation and
197    /// kept in sync on every move (KAN-963), independent of `column_id` --
198    /// derived here from `column_id`→column→`board_id` for files predating
199    /// the field (nil when the column no longer resolves).
200    V11,
201}
202
203impl FormatVersion {
204    /// The highest format version this binary can read or produce.
205    pub const MAX: Self = Self::V11;
206
207    pub fn as_u32(self) -> u32 {
208        match self {
209            Self::V1 => 1,
210            Self::V2 => 2,
211            Self::V3 => 3,
212            Self::V4 => 4,
213            Self::V5 => 5,
214            Self::V6 => 6,
215            Self::V7 => 7,
216            Self::V8 => 8,
217            Self::V9 => 9,
218            Self::V10 => 10,
219            Self::V11 => 11,
220        }
221    }
222
223    pub fn from_u32(v: u32) -> Option<Self> {
224        match v {
225            1 => Some(Self::V1),
226            2 => Some(Self::V2),
227            3 => Some(Self::V3),
228            4 => Some(Self::V4),
229            5 => Some(Self::V5),
230            6 => Some(Self::V6),
231            7 => Some(Self::V7),
232            8 => Some(Self::V8),
233            9 => Some(Self::V9),
234            10 => Some(Self::V10),
235            11 => Some(Self::V11),
236            _ => None,
237        }
238    }
239}
240
241/// Trait for migration strategies between format versions
242#[async_trait]
243pub trait MigrationStrategy: Send + Sync {
244    /// Detect the version of a file on disk
245    async fn detect_version(&self, path: &Path) -> PersistenceResult<FormatVersion>;
246
247    /// Migrate from one version to another
248    /// Returns the path to the migrated file
249    async fn migrate(
250        &self,
251        from: FormatVersion,
252        to: FormatVersion,
253        path: &Path,
254    ) -> PersistenceResult<PathBuf>;
255}
256
257/// Trait for conflict resolution between local and external changes
258pub trait ConflictResolver: Send + Sync {
259    /// Determine whether local or external change wins
260    /// Returns true if external changes should be used, false for local changes
261    fn should_use_external(
262        &self,
263        local_metadata: &PersistenceMetadata,
264        external_metadata: &PersistenceMetadata,
265    ) -> bool;
266
267    /// Get a human-readable description of the conflict resolution
268    fn explain_resolution(
269        &self,
270        local_metadata: &PersistenceMetadata,
271        external_metadata: &PersistenceMetadata,
272    ) -> String;
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn test_format_version_max_equals_v11() {
281        assert_eq!(FormatVersion::MAX, FormatVersion::V11);
282    }
283
284    #[test]
285    fn test_format_version_max_as_u32_matches_largest_variant() {
286        assert_eq!(FormatVersion::MAX.as_u32(), 11);
287    }
288
289    #[test]
290    fn test_from_u32_accepts_11_rejects_12() {
291        assert_eq!(FormatVersion::from_u32(10), Some(FormatVersion::V10));
292        assert_eq!(FormatVersion::from_u32(11), Some(FormatVersion::V11));
293        assert_eq!(FormatVersion::from_u32(12), None);
294    }
295
296    #[test]
297    fn test_default_metadata_has_no_writer_stamp() {
298        let md = PersistenceMetadata::new(Uuid::nil());
299        assert!(md.writer_version.is_none());
300        assert!(md.writer_commit.is_none());
301    }
302
303    #[test]
304    fn test_with_writer_stamp_populates_both_fields() {
305        let md = PersistenceMetadata::new(Uuid::nil()).with_writer_stamp("0.6.0", "abc1234");
306        assert_eq!(md.writer_version.as_deref(), Some("0.6.0"));
307        assert_eq!(md.writer_commit.as_deref(), Some("abc1234"));
308    }
309
310    #[test]
311    fn test_metadata_serde_round_trips_with_writer_stamp() {
312        let md = PersistenceMetadata::new(Uuid::nil()).with_writer_stamp("0.6.0", "abc1234");
313        let json = serde_json::to_string(&md).unwrap();
314        let parsed: PersistenceMetadata = serde_json::from_str(&json).unwrap();
315        assert_eq!(parsed.writer_version.as_deref(), Some("0.6.0"));
316        assert_eq!(parsed.writer_commit.as_deref(), Some("abc1234"));
317    }
318
319    #[test]
320    fn test_metadata_deserialize_legacy_envelope_missing_stamp_fields() {
321        // Old files lack writer_version / writer_commit. They must still parse.
322        let legacy = serde_json::json!({
323            "instance_id": "550e8400-e29b-41d4-a716-446655440000",
324            "saved_at": "2024-01-01T00:00:00Z"
325        });
326        let parsed: PersistenceMetadata = serde_json::from_value(legacy).unwrap();
327        assert!(parsed.writer_version.is_none());
328        assert!(parsed.writer_commit.is_none());
329    }
330}