Skip to main content

kanban_backend/
lib.rs

1pub mod factory;
2pub mod local_persistence;
3pub mod remote_writes;
4pub use factory::{KanbanBackendFactory, KanbanBackendRegistry};
5pub use local_persistence::LocalPersistence;
6pub use remote_writes::RemoteWrites;
7
8use async_trait::async_trait;
9use kanban_domain::command_store::CommandStore;
10use kanban_domain::data_store::DataStore;
11use kanban_domain::{KanbanError, KanbanResult};
12use uuid::Uuid;
13
14/// Combines the entity-level CRUD interface (`DataStore`) with the command
15/// log (`CommandStore`) and lifecycle methods needed for pluggable backends.
16///
17/// # Lifecycle methods
18///
19/// - `flush()`: persist in-memory state to durable storage. For SQLite this
20///   runs an explicit WAL checkpoint (TRUNCATE); for JSON this serialises the
21///   cache to disk.
22/// - `reload()`: discard cached state so the next read re-fetches from
23///   durable storage. For SQLite this is a no-op (reads are always live).
24/// - `needs_flush()`: returns `true` when there are uncommitted writes that
25///   a subsequent `flush()` would persist.
26/// - `needs_save_worker()`: returns `true` for backends (JSON) that require
27///   a background worker to call `flush()` asynchronously after mutations.
28/// - `instance_id()`: stable ID used to distinguish file writes by this
29///   instance from external modifications.
30#[async_trait]
31pub trait KanbanBackend: DataStore + CommandStore + Send + Sync {
32    /// Upcast to `&dyn DataStore`.
33    fn as_data_store(&self) -> &dyn DataStore;
34
35    /// Persist any cached writes to durable storage.
36    async fn flush(&self) -> KanbanResult<()> {
37        Ok(())
38    }
39
40    /// Discard cached state so the next read re-fetches from storage.
41    async fn reload(&self) -> KanbanResult<()> {
42        Ok(())
43    }
44
45    /// Returns `true` when there are writes that have not been flushed yet.
46    fn needs_flush(&self) -> bool {
47        false
48    }
49
50    /// Returns `true` for backends (JSON) that require a background flush
51    /// worker. Always `false` for write-through backends (SQLite, in-memory).
52    fn needs_save_worker(&self) -> bool {
53        false
54    }
55
56    /// Stable instance UUID used for own-write detection in file watchers.
57    fn instance_id(&self) -> Uuid {
58        Uuid::nil()
59    }
60
61    /// Some(...) when this backend can report format version, writer kanban
62    /// version, writer commit, and last save time (JSON, SQLite). `None`
63    /// (the default) for backends with no durable local store (InMemory,
64    /// Http) or that don't track it (MockBackend).
65    fn local_persistence(&self) -> Option<&dyn crate::LocalPersistence> {
66        None
67    }
68
69    /// Returns a health checker for this backend, if supported.
70    /// The default returns `None`; backends that can self-diagnose
71    /// (file readable, connection pool alive) override this.
72    fn health_checker(&self) -> Option<Box<dyn kanban_core::HealthChecker>> {
73        None
74    }
75
76    /// Some(...) when this backend wants create/update/delete for board/column/
77    /// card to bypass local command execution entirely (an HTTP backend, where
78    /// the remote server is authoritative). `None` (the default) for every local
79    /// backend — zero behavior change for JSON/SQLite/InMemory.
80    fn remote_writes(&self) -> Option<&dyn crate::RemoteWrites> {
81        None
82    }
83
84    /// Run `f` as an atomic batch: every mutation commits or rolls
85    /// back together. The default impl snapshots state before `f`
86    /// runs and restores it on failure — cheap for in-memory backends,
87    /// expensive on disk. Disk-backed backends should override with a
88    /// native transaction.
89    fn with_transaction(&self, f: &mut dyn FnMut() -> KanbanResult<()>) -> KanbanResult<()> {
90        let before = self.snapshot()?;
91        match f() {
92            Ok(()) => Ok(()),
93            Err(e) => {
94                if let Err(rollback_err) = self.apply_snapshot(before) {
95                    return Err(KanbanError::Internal(format!(
96                        "Batch failed ({e}) and rollback also failed ({rollback_err}). State may be inconsistent."
97                    )));
98                }
99                Err(e)
100            }
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use kanban_domain::command_batch::CommandBatch;
109    use kanban_domain::*;
110
111    struct StubBackend;
112
113    impl DataStore for StubBackend {
114        fn get_board(&self, _id: Uuid) -> KanbanResult<Option<Board>> {
115            unimplemented!()
116        }
117        fn list_boards(&self) -> KanbanResult<Vec<Board>> {
118            unimplemented!()
119        }
120        fn upsert_board(&self, _board: Board) -> KanbanResult<()> {
121            unimplemented!()
122        }
123        fn delete_board(&self, _id: Uuid) -> KanbanResult<()> {
124            unimplemented!()
125        }
126        fn get_column(&self, _id: Uuid) -> KanbanResult<Option<Column>> {
127            unimplemented!()
128        }
129        fn list_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Column>> {
130            unimplemented!()
131        }
132        fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
133            unimplemented!()
134        }
135        fn upsert_column(&self, _column: Column) -> KanbanResult<()> {
136            unimplemented!()
137        }
138        fn delete_column(&self, _id: Uuid) -> KanbanResult<()> {
139            unimplemented!()
140        }
141        fn delete_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
142            unimplemented!()
143        }
144        fn get_card(&self, _id: Uuid) -> KanbanResult<Option<Card>> {
145            unimplemented!()
146        }
147        fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
148            unimplemented!()
149        }
150        fn list_cards_by_column(&self, _column_id: Uuid) -> KanbanResult<Vec<Card>> {
151            unimplemented!()
152        }
153        fn list_cards_by_sprint(&self, _sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
154            unimplemented!()
155        }
156        fn count_cards_in_column(&self, _column_id: Uuid) -> KanbanResult<usize> {
157            unimplemented!()
158        }
159        fn count_cards_in_column_excluding(
160            &self,
161            _column_id: Uuid,
162            _exclude: &[Uuid],
163        ) -> KanbanResult<usize> {
164            unimplemented!()
165        }
166        fn upsert_card(&self, _card: Card) -> KanbanResult<()> {
167            unimplemented!()
168        }
169        fn delete_card(&self, _id: Uuid) -> KanbanResult<()> {
170            unimplemented!()
171        }
172        fn delete_cards_by_columns(&self, _column_ids: &[Uuid]) -> KanbanResult<()> {
173            unimplemented!()
174        }
175        fn clear_sprint_from_cards(
176            &self,
177            _sprint_id: Uuid,
178            _timestamp: chrono::DateTime<chrono::Utc>,
179        ) -> KanbanResult<()> {
180            unimplemented!()
181        }
182        fn get_archived_card(&self, _card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
183            unimplemented!()
184        }
185        fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
186            unimplemented!()
187        }
188        fn insert_archived_card(&self, _ac: ArchivedCard) -> KanbanResult<()> {
189            unimplemented!()
190        }
191        fn delete_archived_card(&self, _card_id: Uuid) -> KanbanResult<()> {
192            unimplemented!()
193        }
194        fn get_sprint(&self, _id: Uuid) -> KanbanResult<Option<Sprint>> {
195            unimplemented!()
196        }
197        fn list_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
198            unimplemented!()
199        }
200        fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
201            unimplemented!()
202        }
203        fn upsert_sprint(&self, _sprint: Sprint) -> KanbanResult<()> {
204            unimplemented!()
205        }
206        fn delete_sprint(&self, _id: Uuid) -> KanbanResult<()> {
207            unimplemented!()
208        }
209        fn delete_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
210            unimplemented!()
211        }
212        fn get_graph(&self) -> KanbanResult<DependencyGraph> {
213            unimplemented!()
214        }
215        fn set_graph(&self, _graph: DependencyGraph) -> KanbanResult<()> {
216            unimplemented!()
217        }
218        fn snapshot(&self) -> KanbanResult<Snapshot> {
219            unimplemented!()
220        }
221        fn apply_snapshot(&self, _snapshot: Snapshot) -> KanbanResult<()> {
222            unimplemented!()
223        }
224    }
225
226    impl CommandStore for StubBackend {
227        fn append_batch(&self, _batch: &CommandBatch) -> KanbanResult<u64> {
228            unimplemented!()
229        }
230        fn batch_count(&self) -> KanbanResult<u64> {
231            unimplemented!()
232        }
233        fn load_batches(&self, _offset: u64, _limit: u64) -> KanbanResult<Vec<CommandBatch>> {
234            unimplemented!()
235        }
236    }
237
238    impl KanbanBackend for StubBackend {
239        fn as_data_store(&self) -> &dyn DataStore {
240            self
241        }
242    }
243
244    #[test]
245    fn test_backend_without_local_persistence_returns_none() {
246        let backend = StubBackend;
247        let backend: &dyn KanbanBackend = &backend;
248        assert!(backend.local_persistence().is_none());
249    }
250}