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 back
85    /// together.
86    ///
87    /// `f` runs at most once — never twice, so it may consume what it
88    /// captures, and possibly not at all. Anything that stops a batch from
89    /// being atomic fails *before* `f` is invoked rather than running the
90    /// mutations unprotected: a backend that cannot offer a transaction at all
91    /// (`HttpBackend`, where the remote server owns the state) declines with an
92    /// unsupported error, and one that can will still bail if it fails to open
93    /// the transaction. Do not rely on a side effect inside `f` having happened
94    /// unless this returned `Ok`.
95    ///
96    /// There is deliberately no default implementation. A generic one can only
97    /// roll back by snapshotting the whole store and restoring it, which is
98    /// cheap in memory and ruinous on disk; making the method required forces
99    /// each backend to answer with its own native mechanism, and turns a new
100    /// backend that forgot to into a compile error rather than a silent
101    /// whole-store copy.
102    ///
103    /// # Single-writer requirement
104    ///
105    /// Implementations that roll back by restoring a whole-store snapshot
106    /// cannot tell the batch's own writes apart from anyone else's, so a
107    /// mutation committed by another task between the capture and the failure
108    /// is reverted along with the batch. Every consumer today serialises its
109    /// mutations (`kanban-server` and `kanban-mcp` behind
110    /// `Arc<Mutex<KanbanContext>>`, the TUI on its main loop), which is what
111    /// makes this sound. Any new concurrent access to a shared backend must
112    /// serialise too, and must revisit `SqliteStore::db_conn`, whose ambient
113    /// transaction fails the same way but worse.
114    fn with_transaction(&self, f: TransactionFn<'_>) -> KanbanResult<()>;
115}
116
117/// Closure passed to [`KanbanBackend::with_transaction`], boxed so the method
118/// stays callable on `dyn KanbanBackend`. `FnOnce` because the batch never runs
119/// twice and closures need to move owned values in.
120pub type TransactionFn<'f> = Box<dyn FnOnce() -> KanbanResult<()> + 'f>;
121
122/// Combines a batch failure with a failure to roll it back. Shared by the
123/// snapshot-restoring backends so the wording of the one message a user sees
124/// when the store is left in an unknown state cannot drift between them.
125pub fn rollback_failed(batch_err: KanbanError, rollback_err: KanbanError) -> KanbanError {
126    KanbanError::Internal(format!(
127        "Batch failed ({batch_err}) and rollback also failed ({rollback_err}). State may be inconsistent."
128    ))
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use kanban_domain::command_batch::CommandBatch;
135    use kanban_domain::*;
136
137    #[test]
138    fn test_rollback_failed_names_both_the_batch_and_the_rollback_error() {
139        let err = rollback_failed(
140            KanbanError::Internal("batch boom".into()),
141            KanbanError::Internal("restore boom".into()),
142        );
143
144        let msg = err.to_string();
145        assert!(
146            msg.contains("batch boom"),
147            "batch error lost (got: {msg:?})"
148        );
149        assert!(
150            msg.contains("restore boom"),
151            "rollback error lost (got: {msg:?})"
152        );
153        assert!(
154            msg.contains("State may be inconsistent"),
155            "a failed rollback must say the store is left in an unknown state \
156             (got: {msg:?})"
157        );
158    }
159
160    struct StubBackend;
161
162    impl DataStore for StubBackend {
163        fn get_prefix(&self, _name: &str) -> KanbanResult<Option<kanban_domain::Prefix>> {
164            unimplemented!()
165        }
166        fn list_prefixes(&self) -> KanbanResult<Vec<kanban_domain::Prefix>> {
167            unimplemented!()
168        }
169        fn upsert_prefix(&self, _prefix: kanban_domain::Prefix) -> KanbanResult<()> {
170            unimplemented!()
171        }
172        fn get_board(&self, _id: Uuid) -> KanbanResult<Option<Board>> {
173            unimplemented!()
174        }
175        fn list_boards(&self) -> KanbanResult<Vec<Board>> {
176            unimplemented!()
177        }
178        fn upsert_board(&self, _board: Board) -> KanbanResult<()> {
179            unimplemented!()
180        }
181        fn delete_board(&self, _id: Uuid) -> KanbanResult<()> {
182            unimplemented!()
183        }
184        fn get_column(&self, _id: Uuid) -> KanbanResult<Option<Column>> {
185            unimplemented!()
186        }
187        fn list_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Column>> {
188            unimplemented!()
189        }
190        fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
191            unimplemented!()
192        }
193        fn upsert_column(&self, _column: Column) -> KanbanResult<()> {
194            unimplemented!()
195        }
196        fn delete_column(&self, _id: Uuid) -> KanbanResult<()> {
197            unimplemented!()
198        }
199        fn delete_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
200            unimplemented!()
201        }
202        fn get_card(&self, _id: Uuid) -> KanbanResult<Option<Card>> {
203            unimplemented!()
204        }
205        fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
206            unimplemented!()
207        }
208        fn list_cards_by_column(&self, _column_id: Uuid) -> KanbanResult<Vec<Card>> {
209            unimplemented!()
210        }
211        fn list_cards_by_sprint(&self, _sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
212            unimplemented!()
213        }
214        fn count_cards_in_column(&self, _column_id: Uuid) -> KanbanResult<usize> {
215            unimplemented!()
216        }
217        fn count_cards_in_column_excluding(
218            &self,
219            _column_id: Uuid,
220            _exclude: &[Uuid],
221        ) -> KanbanResult<usize> {
222            unimplemented!()
223        }
224        fn upsert_card(&self, _card: Card) -> KanbanResult<()> {
225            unimplemented!()
226        }
227        fn delete_card(&self, _id: Uuid) -> KanbanResult<()> {
228            unimplemented!()
229        }
230        fn delete_cards_by_columns(&self, _column_ids: &[Uuid]) -> KanbanResult<()> {
231            unimplemented!()
232        }
233        fn clear_sprint_from_cards(
234            &self,
235            _sprint_id: Uuid,
236            _timestamp: chrono::DateTime<chrono::Utc>,
237        ) -> KanbanResult<()> {
238            unimplemented!()
239        }
240        fn get_archived_card(&self, _card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
241            unimplemented!()
242        }
243        fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
244            unimplemented!()
245        }
246        fn insert_archived_card(&self, _ac: ArchivedCard) -> KanbanResult<()> {
247            unimplemented!()
248        }
249        fn delete_archived_card(&self, _card_id: Uuid) -> KanbanResult<()> {
250            unimplemented!()
251        }
252        fn get_sprint(&self, _id: Uuid) -> KanbanResult<Option<Sprint>> {
253            unimplemented!()
254        }
255        fn list_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
256            unimplemented!()
257        }
258        fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
259            unimplemented!()
260        }
261        fn upsert_sprint(&self, _sprint: Sprint) -> KanbanResult<()> {
262            unimplemented!()
263        }
264        fn delete_sprint(&self, _id: Uuid) -> KanbanResult<()> {
265            unimplemented!()
266        }
267        fn delete_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
268            unimplemented!()
269        }
270        fn get_graph(&self) -> KanbanResult<DependencyGraph> {
271            unimplemented!()
272        }
273        fn set_graph(&self, _graph: DependencyGraph) -> KanbanResult<()> {
274            unimplemented!()
275        }
276        fn snapshot(&self) -> KanbanResult<Snapshot> {
277            unimplemented!()
278        }
279        fn apply_snapshot(&self, _snapshot: Snapshot) -> KanbanResult<()> {
280            unimplemented!()
281        }
282    }
283
284    impl CommandStore for StubBackend {
285        fn append_batch(&self, _batch: &CommandBatch) -> KanbanResult<u64> {
286            unimplemented!()
287        }
288        fn batch_count(&self) -> KanbanResult<u64> {
289            unimplemented!()
290        }
291        fn load_batches(&self, _offset: u64, _limit: u64) -> KanbanResult<Vec<CommandBatch>> {
292            unimplemented!()
293        }
294    }
295
296    impl KanbanBackend for StubBackend {
297        fn as_data_store(&self) -> &dyn DataStore {
298            self
299        }
300        fn with_transaction(&self, _f: TransactionFn<'_>) -> KanbanResult<()> {
301            unimplemented!()
302        }
303    }
304
305    #[test]
306    fn test_backend_without_local_persistence_returns_none() {
307        let backend = StubBackend;
308        let backend: &dyn KanbanBackend = &backend;
309        assert!(backend.local_persistence().is_none());
310    }
311}