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/// Trait for abstract storage operations
65/// Implementations handle different backend storage (file, database, etc.)
66#[async_trait]
67pub trait PersistenceStore: Send + Sync {
68 /// Save a snapshot to the store
69 async fn save(&self, snapshot: StoreSnapshot) -> PersistenceResult<PersistenceMetadata>;
70
71 /// Load the current snapshot from the store
72 async fn load(&self) -> PersistenceResult<(StoreSnapshot, PersistenceMetadata)>;
73
74 /// Check if the store file exists
75 async fn exists(&self) -> bool;
76
77 /// Get the path to the store file
78 fn path(&self) -> &Path;
79
80 /// Get the unique instance ID for this store
81 fn instance_id(&self) -> uuid::Uuid;
82
83 /// Load the store synchronously (no async runtime required).
84 /// Returns `Ok(None)` when the backing file does not exist.
85 ///
86 /// The default implementation returns an error; backends that support
87 /// synchronous loading (e.g. `JsonFileStore`) override this.
88 #[allow(clippy::type_complexity)]
89 fn load_sync(&self) -> PersistenceResult<Option<(StoreSnapshot, PersistenceMetadata)>> {
90 Err(crate::PersistenceError::Unsupported(
91 "load_sync not supported by this backend".into(),
92 ))
93 }
94
95 /// Drain any open connections / file handles before the backing file is
96 /// unlinked. Required on Windows: the OS refuses to delete files that
97 /// still have live handles, and async resources (e.g. an `sqlx` pool)
98 /// outlive synchronous `Drop` because the runtime needs time to close
99 /// each connection.
100 ///
101 /// The default is a no-op; backends with long-lived handles (e.g.
102 /// `SqliteStore`) override this.
103 async fn close(&self) {}
104}
105
106/// Trait for detecting changes to the storage file
107/// Used for multi-instance coordination
108#[async_trait]
109pub trait ChangeDetector: Send + Sync {
110 /// Start watching the file for changes
111 async fn start_watching(&self, path: PathBuf) -> PersistenceResult<()>;
112
113 /// Stop watching the file
114 async fn stop_watching(&self) -> PersistenceResult<()>;
115
116 /// Subscribe to change events
117 /// Returns a broadcast receiver that yields `ChangeEvent` when the file changes
118 fn subscribe(&self) -> tokio::sync::broadcast::Receiver<ChangeEvent>;
119
120 /// Check if currently watching
121 fn is_watching(&self) -> bool;
122}
123
124/// Event indicating a change to the watched file
125#[derive(Debug, Clone)]
126pub struct ChangeEvent {
127 /// Path to the file that changed
128 pub path: PathBuf,
129 /// When the change was detected
130 pub detected_at: DateTime<Utc>,
131}
132
133/// Trait for serialization/deserialization strategies
134/// Allows swapping JSON for binary formats, databases, etc.
135pub trait Serializer<T: Send + Sync>: Send + Sync {
136 /// Serialize data to bytes
137 fn serialize(&self, data: &T) -> PersistenceResult<Vec<u8>>;
138
139 /// Deserialize data from bytes
140 fn deserialize(&self, bytes: &[u8]) -> PersistenceResult<T>;
141}
142
143/// Format versions for migration tracking
144#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
145pub enum FormatVersion {
146 V1,
147 V2,
148 V3,
149 V4,
150 V5,
151 /// V6 splits the dependency graph from a single edge-type-tagged list
152 /// (`graph.cards.edges`) into three sub-graphs keyed by edge kind
153 /// (`graph.parent_child`, `graph.blocks`, `graph.relates`).
154 V6,
155 /// V7 renames the spawns sub-graph bucket from `parent_child` to
156 /// `spawns` so the wire format matches the `SpawnsEdge` struct,
157 /// the `spawns_edges()` accessor, and the SQLite `spawns_edges`
158 /// table. Pure key rename — edge contents are unchanged.
159 V7,
160 /// V8 promotes archived cards to a first-class discrete collection:
161 /// each `archived_cards` entry carries its own `board_id`, backfilled
162 /// from `original_column_id`→column→board for historical files (nil
163 /// when the original column no longer resolves), and is guaranteed not
164 /// to be duplicated inside the `cards` array.
165 V8,
166 /// V9 marks the format as archived-board-capable. The `archived_boards`
167 /// collection is additive (serde-default), but the bump makes a pre-V9
168 /// binary reject the file rather than silently drop archived boards on save.
169 V9,
170 /// V10 collapses the archival wrapper into a PURE MARKER (F3b). Historical
171 /// `archived_cards` / `archived_boards` entries EMBEDDED their entity (under
172 /// `entity`, legacy alias `card`/`board`) and did not carry it in the live
173 /// `cards`/`boards` arrays. V10 lifts each embedded entity into the live
174 /// collection and rewrites each wrapper as a reference marker
175 /// (`{ entity_id, archived_at, board_id? }`), dropping the retired
176 /// `original_column_id`/`original_position` restore context.
177 V10,
178 /// V11 backfills `board_id` onto each historical `cards` entry that lacks
179 /// it, mirroring V8's `archived_cards.board_id` backfill one layer
180 /// earlier: `Card.board_id` is now a durable field set at creation and
181 /// kept in sync on every move (KAN-963), independent of `column_id` --
182 /// derived here from `column_id`→column→`board_id` for files predating
183 /// the field (nil when the column no longer resolves).
184 V11,
185 /// V12 makes `Board.completion_column_ids` durable: each board's legacy
186 /// `completion_column_id` key is removed and replaced by
187 /// `completion_column_ids`, a one-element list backfilled from that
188 /// legacy id when it still names a live column of the board, otherwise
189 /// from the board's last column ordered by `position`, then
190 /// `created_at`, then `id` — the same deterministic ordering
191 /// `sorted_board_columns` uses everywhere else, replacing the
192 /// non-deterministic tie-break of the old runtime fallback.
193 V12,
194 /// V13 makes `Column.default_status` durable: every existing column gets
195 /// a `default_status: null` key (behaviour-preserving backfill, never
196 /// inferred from the column name), and the field stops being
197 /// `#[serde(default)]` on `ColumnRecord` — a file missing the key is now
198 /// rejected rather than silently defaulting.
199 V13,
200 /// V14 derives every column's `default_status` from its board's
201 /// `completion_column_ids`: a column already carrying a non-null
202 /// `default_status` keeps it, a column whose id is in
203 /// `completion_column_ids` gets `Done`, everything else gets `Todo`.
204 /// `completion_column_ids` is left in place.
205 V14,
206 /// V15 backfills a `prefixes` array, one row per currently-effective
207 /// prefix (every board's `card_prefix` or the `"task"` fallback, plus
208 /// every sprint override), seeding each row's counters from the
209 /// owner's existing counter and resolving a same-name collision by
210 /// appending an incrementing numeric suffix (`task`, `task2`, ...).
211 /// `boards.card_counter` and the sprint-counter equivalent are left in
212 /// place; this migration is additive only.
213 V15,
214 /// V16 stamps every card with the prefix it is addressed by, freezing its
215 /// identifier so a later board rename cannot change it.
216 V16,
217 /// V17 drops the per-board `card_counter` and `sprint_counters` keys. The
218 /// `prefixes` rows seeded by V15 are the sole source of numbering, so the
219 /// board-level counters carry nothing. V15 must have run first, which the
220 /// chain order guarantees: it reads `card_counter` off the raw envelope to
221 /// seed those rows, and this strips the key afterwards.
222 V17,
223 /// V18 repairs the `prefixes` array: every namespace a card names gets a
224 /// row whose counters cover the cards naming it, raising an existing row
225 /// rather than replacing or renaming it, and stamps any card still
226 /// carrying no prefix with the one it is addressed by.
227 V18,
228}
229
230impl FormatVersion {
231 /// The highest format version this binary can read or produce.
232 pub const MAX: Self = Self::V18;
233
234 pub fn as_u32(self) -> u32 {
235 match self {
236 Self::V1 => 1,
237 Self::V2 => 2,
238 Self::V3 => 3,
239 Self::V4 => 4,
240 Self::V5 => 5,
241 Self::V6 => 6,
242 Self::V7 => 7,
243 Self::V8 => 8,
244 Self::V9 => 9,
245 Self::V10 => 10,
246 Self::V11 => 11,
247 Self::V12 => 12,
248 Self::V13 => 13,
249 Self::V14 => 14,
250 Self::V15 => 15,
251 Self::V16 => 16,
252 Self::V17 => 17,
253 Self::V18 => 18,
254 }
255 }
256
257 pub fn from_u32(v: u32) -> Option<Self> {
258 match v {
259 1 => Some(Self::V1),
260 2 => Some(Self::V2),
261 3 => Some(Self::V3),
262 4 => Some(Self::V4),
263 5 => Some(Self::V5),
264 6 => Some(Self::V6),
265 7 => Some(Self::V7),
266 8 => Some(Self::V8),
267 9 => Some(Self::V9),
268 10 => Some(Self::V10),
269 11 => Some(Self::V11),
270 12 => Some(Self::V12),
271 13 => Some(Self::V13),
272 14 => Some(Self::V14),
273 15 => Some(Self::V15),
274 16 => Some(Self::V16),
275 17 => Some(Self::V17),
276 18 => Some(Self::V18),
277 _ => None,
278 }
279 }
280}
281
282/// Trait for migration strategies between format versions
283#[async_trait]
284pub trait MigrationStrategy: Send + Sync {
285 /// Detect the version of a file on disk
286 async fn detect_version(&self, path: &Path) -> PersistenceResult<FormatVersion>;
287
288 /// Migrate from one version to another
289 /// Returns the path to the migrated file
290 async fn migrate(
291 &self,
292 from: FormatVersion,
293 to: FormatVersion,
294 path: &Path,
295 ) -> PersistenceResult<PathBuf>;
296}
297
298/// Trait for conflict resolution between local and external changes
299pub trait ConflictResolver: Send + Sync {
300 /// Determine whether local or external change wins
301 /// Returns true if external changes should be used, false for local changes
302 fn should_use_external(
303 &self,
304 local_metadata: &PersistenceMetadata,
305 external_metadata: &PersistenceMetadata,
306 ) -> bool;
307
308 /// Get a human-readable description of the conflict resolution
309 fn explain_resolution(
310 &self,
311 local_metadata: &PersistenceMetadata,
312 external_metadata: &PersistenceMetadata,
313 ) -> String;
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319
320 #[test]
321 fn test_format_version_max_equals_the_newest_variant() {
322 assert_eq!(FormatVersion::MAX, FormatVersion::V18);
323 }
324
325 #[test]
326 fn test_format_version_max_as_u32_matches_largest_variant() {
327 assert_eq!(FormatVersion::MAX.as_u32(), 18);
328 }
329
330 #[test]
331 fn test_from_u32_accepts_the_newest_and_rejects_beyond_it() {
332 assert_eq!(FormatVersion::from_u32(17), Some(FormatVersion::V17));
333 assert_eq!(FormatVersion::from_u32(18), Some(FormatVersion::V18));
334 assert_eq!(FormatVersion::from_u32(19), None);
335 }
336
337 #[test]
338 fn test_default_metadata_has_no_writer_stamp() {
339 let md = PersistenceMetadata::new(Uuid::nil());
340 assert!(md.writer_version.is_none());
341 assert!(md.writer_commit.is_none());
342 }
343
344 #[test]
345 fn test_with_writer_stamp_populates_both_fields() {
346 let md = PersistenceMetadata::new(Uuid::nil()).with_writer_stamp("0.6.0", "abc1234");
347 assert_eq!(md.writer_version.as_deref(), Some("0.6.0"));
348 assert_eq!(md.writer_commit.as_deref(), Some("abc1234"));
349 }
350
351 #[test]
352 fn test_metadata_serde_round_trips_with_writer_stamp() {
353 let md = PersistenceMetadata::new(Uuid::nil()).with_writer_stamp("0.6.0", "abc1234");
354 let json = serde_json::to_string(&md).unwrap();
355 let parsed: PersistenceMetadata = serde_json::from_str(&json).unwrap();
356 assert_eq!(parsed.writer_version.as_deref(), Some("0.6.0"));
357 assert_eq!(parsed.writer_commit.as_deref(), Some("abc1234"));
358 }
359
360 #[test]
361 fn test_metadata_deserialize_legacy_envelope_missing_stamp_fields() {
362 // Old files lack writer_version / writer_commit. They must still parse.
363 let legacy = serde_json::json!({
364 "instance_id": "550e8400-e29b-41d4-a716-446655440000",
365 "saved_at": "2024-01-01T00:00:00Z"
366 });
367 let parsed: PersistenceMetadata = serde_json::from_value(legacy).unwrap();
368 assert!(parsed.writer_version.is_none());
369 assert!(parsed.writer_commit.is_none());
370 }
371}