Skip to main content

kanban_backend/
lib.rs

1pub mod compatibility;
2pub mod factory;
3pub mod local_persistence;
4pub mod remote_writes;
5pub use compatibility::CompatibilityNotice;
6pub use factory::{KanbanBackendFactory, KanbanBackendRegistry};
7pub use local_persistence::LocalPersistence;
8pub use remote_writes::{
9    RemoteBatchOutcome, RemoteBatchWrites, RemoteBoardWrites, RemoteCardWrites, RemoteGraphWrites,
10    RemoteSprintWrites, RemoteWrites,
11};
12
13use async_trait::async_trait;
14use kanban_domain::command_store::CommandStore;
15use kanban_domain::data_store::DataStore;
16use kanban_domain::{KanbanError, KanbanResult};
17use uuid::Uuid;
18
19/// Combines the entity-level CRUD interface (`DataStore`) with the command
20/// log (`CommandStore`) and lifecycle methods needed for pluggable backends.
21///
22/// # Lifecycle methods
23///
24/// - `flush()`: persist in-memory state to durable storage. For SQLite this
25///   runs an explicit WAL checkpoint (TRUNCATE); for JSON this serialises the
26///   cache to disk.
27/// - `reload()`: discard cached state so the next read re-fetches from
28///   durable storage. For SQLite this is a no-op (reads are always live).
29/// - `needs_flush()`: returns `true` when there are uncommitted writes that
30///   a subsequent `flush()` would persist.
31/// - `needs_save_worker()`: returns `true` for backends (JSON) that require
32///   a background worker to call `flush()` asynchronously after mutations.
33/// - `instance_id()`: stable ID used to distinguish file writes by this
34///   instance from external modifications.
35#[async_trait]
36pub trait KanbanBackend: DataStore + CommandStore + Send + Sync {
37    /// Upcast to `&dyn DataStore`.
38    fn as_data_store(&self) -> &dyn DataStore;
39
40    /// Persist any cached writes to durable storage.
41    async fn flush(&self) -> KanbanResult<()> {
42        Ok(())
43    }
44
45    /// Discard cached state so the next read re-fetches from storage.
46    async fn reload(&self) -> KanbanResult<()> {
47        Ok(())
48    }
49
50    /// Forces one cheap I/O so a broken backend fails at construction
51    /// instead of on first use. The default reads the command log, which
52    /// every local backend loads lazily; a remote backend overrides this
53    /// with a network liveness check.
54    async fn probe(&self) -> KanbanResult<()> {
55        self.batch_count().map(|_| ())
56    }
57
58    /// Marks the backend dirty without performing a write, so a subsequent
59    /// `flush()` (or `needs_save_worker()`-driven background flush) picks it
60    /// up. No-op by default for write-through backends that have no dirty
61    /// flag to set.
62    fn mark_dirty(&self) {}
63
64    /// Returns `true` when there are writes that have not been flushed yet.
65    fn needs_flush(&self) -> bool {
66        false
67    }
68
69    /// Returns `true` for backends (JSON) that require a background flush
70    /// worker. Always `false` for write-through backends (SQLite, in-memory).
71    fn needs_save_worker(&self) -> bool {
72        false
73    }
74
75    /// Stable instance UUID used for own-write detection in file watchers.
76    fn instance_id(&self) -> Uuid {
77        Uuid::nil()
78    }
79
80    /// Some(...) when this backend can report format version, writer kanban
81    /// version, writer commit, and last save time (JSON, SQLite). `None`
82    /// (the default) for backends with no durable local store (InMemory,
83    /// Http) or that don't track it (MockBackend).
84    fn local_persistence(&self) -> Option<&dyn crate::LocalPersistence> {
85        None
86    }
87
88    /// Some(...) when the last `probe()` found the remote server older than
89    /// this binary, or unable to report a comparable version.
90    fn compatibility_notice(&self) -> Option<crate::CompatibilityNotice> {
91        None
92    }
93
94    /// Returns a health checker for this backend, if supported.
95    /// The default returns `None`; backends that can self-diagnose
96    /// (file readable, connection pool alive) override this.
97    fn health_checker(&self) -> Option<Box<dyn kanban_core::HealthChecker>> {
98        None
99    }
100
101    /// Some(...) when this backend wants create/update/delete for board/column/
102    /// card to bypass local command execution entirely (an HTTP backend, where
103    /// the remote server is authoritative). `None` (the default) for every local
104    /// backend — zero behavior change for JSON/SQLite/InMemory.
105    fn remote_writes(&self) -> Option<&dyn crate::RemoteWrites> {
106        None
107    }
108
109    /// Per-family counterparts to `remote_writes()`. `None` by default for
110    /// every backend; a backend overrides only the families it supports.
111    fn remote_board_writes(&self) -> Option<&dyn crate::RemoteBoardWrites> {
112        None
113    }
114
115    /// See `remote_board_writes()`.
116    fn remote_card_writes(&self) -> Option<&dyn crate::RemoteCardWrites> {
117        None
118    }
119
120    /// See `remote_board_writes()`.
121    fn remote_batch_writes(&self) -> Option<&dyn crate::RemoteBatchWrites> {
122        None
123    }
124
125    /// See `remote_board_writes()`.
126    fn remote_sprint_writes(&self) -> Option<&dyn crate::RemoteSprintWrites> {
127        None
128    }
129
130    /// See `remote_board_writes()`.
131    fn remote_graph_writes(&self) -> Option<&dyn crate::RemoteGraphWrites> {
132        None
133    }
134
135    /// Some(...) when a caller needs to downcast to the concrete backend type.
136    /// `None` (the default) for backends that offer no such hook.
137    fn as_any(&self) -> Option<&dyn std::any::Any> {
138        None
139    }
140
141    /// Run `f` as an atomic batch: every mutation commits or rolls back
142    /// together.
143    ///
144    /// `f` runs at most once — never twice, so it may consume what it
145    /// captures, and possibly not at all. Anything that stops a batch from
146    /// being atomic fails *before* `f` is invoked rather than running the
147    /// mutations unprotected: a backend that cannot offer a transaction at all
148    /// (`HttpBackend`, where the remote server owns the state) declines with an
149    /// unsupported error, and one that can will still bail if it fails to open
150    /// the transaction. Do not rely on a side effect inside `f` having happened
151    /// unless this returned `Ok`.
152    ///
153    /// There is deliberately no default implementation. A generic one can only
154    /// roll back by snapshotting the whole store and restoring it, which is
155    /// cheap in memory and ruinous on disk; making the method required forces
156    /// each backend to answer with its own native mechanism, and turns a new
157    /// backend that forgot to into a compile error rather than a silent
158    /// whole-store copy.
159    ///
160    /// # Single-writer requirement
161    ///
162    /// Implementations that roll back by restoring a whole-store snapshot
163    /// cannot tell the batch's own writes apart from anyone else's, so a
164    /// mutation committed by another task between the capture and the failure
165    /// is reverted along with the batch. Every consumer today serialises its
166    /// mutations (`kanban-server` and `kanban-mcp` behind
167    /// `Arc<Mutex<KanbanContext>>`, the TUI on its main loop), which is what
168    /// makes this sound. Any new concurrent access to a shared backend must
169    /// serialise too, and must revisit `SqliteStore::db_conn`, whose ambient
170    /// transaction fails the same way but worse.
171    fn with_transaction(&self, f: TransactionFn<'_>) -> KanbanResult<()>;
172}
173
174/// Closure passed to [`KanbanBackend::with_transaction`], boxed so the method
175/// stays callable on `dyn KanbanBackend`. `FnOnce` because the batch never runs
176/// twice and closures need to move owned values in.
177pub type TransactionFn<'f> = Box<dyn FnOnce() -> KanbanResult<()> + 'f>;
178
179/// Combines a batch failure with a failure to roll it back. Shared by the
180/// snapshot-restoring backends so the wording of the one message a user sees
181/// when the store is left in an unknown state cannot drift between them.
182pub fn rollback_failed(batch_err: KanbanError, rollback_err: KanbanError) -> KanbanError {
183    KanbanError::Internal(format!(
184        "Batch failed ({batch_err}) and rollback also failed ({rollback_err}). State may be inconsistent."
185    ))
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use kanban_domain::command_batch::CommandBatch;
192    use kanban_domain::*;
193
194    #[test]
195    fn test_rollback_failed_names_both_the_batch_and_the_rollback_error() {
196        let err = rollback_failed(
197            KanbanError::Internal("batch boom".into()),
198            KanbanError::Internal("restore boom".into()),
199        );
200
201        let msg = err.to_string();
202        assert!(
203            msg.contains("batch boom"),
204            "batch error lost (got: {msg:?})"
205        );
206        assert!(
207            msg.contains("restore boom"),
208            "rollback error lost (got: {msg:?})"
209        );
210        assert!(
211            msg.contains("State may be inconsistent"),
212            "a failed rollback must say the store is left in an unknown state \
213             (got: {msg:?})"
214        );
215    }
216
217    #[derive(Default)]
218    struct StubBackend {
219        batch_count_calls: std::sync::atomic::AtomicUsize,
220        batch_count_fails: bool,
221    }
222
223    impl DataStore for StubBackend {
224        fn get_prefix(&self, _name: &str) -> KanbanResult<Option<kanban_domain::Prefix>> {
225            unimplemented!()
226        }
227        fn list_prefixes(&self) -> KanbanResult<Vec<kanban_domain::Prefix>> {
228            unimplemented!()
229        }
230        fn upsert_prefix(&self, _prefix: kanban_domain::Prefix) -> KanbanResult<()> {
231            unimplemented!()
232        }
233        fn get_board(&self, _id: Uuid) -> KanbanResult<Option<Board>> {
234            unimplemented!()
235        }
236        fn list_boards(&self) -> KanbanResult<Vec<Board>> {
237            unimplemented!()
238        }
239        fn upsert_board(&self, _board: Board) -> KanbanResult<()> {
240            unimplemented!()
241        }
242        fn delete_board(&self, _id: Uuid) -> KanbanResult<()> {
243            unimplemented!()
244        }
245        fn get_column(&self, _id: Uuid) -> KanbanResult<Option<Column>> {
246            unimplemented!()
247        }
248        fn list_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Column>> {
249            unimplemented!()
250        }
251        fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
252            unimplemented!()
253        }
254        fn upsert_column(&self, _column: Column) -> KanbanResult<()> {
255            unimplemented!()
256        }
257        fn delete_column(&self, _id: Uuid) -> KanbanResult<()> {
258            unimplemented!()
259        }
260        fn delete_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
261            unimplemented!()
262        }
263        fn get_card(&self, _id: Uuid) -> KanbanResult<Option<Card>> {
264            unimplemented!()
265        }
266        fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
267            unimplemented!()
268        }
269        fn list_cards_by_column(&self, _column_id: Uuid) -> KanbanResult<Vec<Card>> {
270            unimplemented!()
271        }
272        fn list_cards_by_sprint(&self, _sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
273            unimplemented!()
274        }
275        fn count_cards_in_column(&self, _column_id: Uuid) -> KanbanResult<usize> {
276            unimplemented!()
277        }
278        fn count_cards_in_column_excluding(
279            &self,
280            _column_id: Uuid,
281            _exclude: &[Uuid],
282        ) -> KanbanResult<usize> {
283            unimplemented!()
284        }
285        fn upsert_card(&self, _card: Card) -> KanbanResult<()> {
286            unimplemented!()
287        }
288        fn delete_card(&self, _id: Uuid) -> KanbanResult<()> {
289            unimplemented!()
290        }
291        fn delete_cards_by_columns(&self, _column_ids: &[Uuid]) -> KanbanResult<()> {
292            unimplemented!()
293        }
294        fn clear_sprint_from_cards(
295            &self,
296            _sprint_id: Uuid,
297            _timestamp: chrono::DateTime<chrono::Utc>,
298        ) -> KanbanResult<()> {
299            unimplemented!()
300        }
301        fn get_archived_card(&self, _card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
302            unimplemented!()
303        }
304        fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
305            unimplemented!()
306        }
307        fn insert_archived_card(&self, _ac: ArchivedCard) -> KanbanResult<()> {
308            unimplemented!()
309        }
310        fn delete_archived_card(&self, _card_id: Uuid) -> KanbanResult<()> {
311            unimplemented!()
312        }
313        fn list_archived_boards(&self) -> KanbanResult<Vec<kanban_domain::ArchivedBoard>> {
314            unimplemented!()
315        }
316        fn get_sprint(&self, _id: Uuid) -> KanbanResult<Option<Sprint>> {
317            unimplemented!()
318        }
319        fn list_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
320            unimplemented!()
321        }
322        fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
323            unimplemented!()
324        }
325        fn upsert_sprint(&self, _sprint: Sprint) -> KanbanResult<()> {
326            unimplemented!()
327        }
328        fn delete_sprint(&self, _id: Uuid) -> KanbanResult<()> {
329            unimplemented!()
330        }
331        fn delete_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
332            unimplemented!()
333        }
334        fn get_graph(&self) -> KanbanResult<DependencyGraph> {
335            unimplemented!()
336        }
337        fn set_graph(&self, _graph: DependencyGraph) -> KanbanResult<()> {
338            unimplemented!()
339        }
340    }
341
342    impl CommandStore for StubBackend {
343        fn append_batch(&self, _batch: &CommandBatch) -> KanbanResult<u64> {
344            unimplemented!()
345        }
346        fn batch_count(&self) -> KanbanResult<u64> {
347            self.batch_count_calls
348                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
349            if self.batch_count_fails {
350                Err(KanbanError::Internal("stub batch_count boom".into()))
351            } else {
352                Ok(0)
353            }
354        }
355        fn load_batches(&self, _offset: u64, _limit: u64) -> KanbanResult<Vec<CommandBatch>> {
356            unimplemented!()
357        }
358    }
359
360    impl KanbanBackend for StubBackend {
361        fn as_data_store(&self) -> &dyn DataStore {
362            self
363        }
364        fn with_transaction(&self, _f: TransactionFn<'_>) -> KanbanResult<()> {
365            unimplemented!()
366        }
367    }
368
369    #[test]
370    fn test_backend_without_local_persistence_returns_none() {
371        let backend = StubBackend::default();
372        let backend: &dyn KanbanBackend = &backend;
373        assert!(backend.local_persistence().is_none());
374    }
375
376    #[test]
377    fn test_default_compatibility_notice_is_none() {
378        let backend = StubBackend::default();
379        let backend: &dyn KanbanBackend = &backend;
380        assert!(backend.compatibility_notice().is_none());
381    }
382
383    #[test]
384    fn test_kanban_backend_as_any_defaults_to_none() {
385        let backend = StubBackend::default();
386        let backend: &dyn KanbanBackend = &backend;
387        assert!(backend.as_any().is_none());
388    }
389
390    #[test]
391    fn test_mark_dirty_is_callable_on_a_backend_that_does_not_override_it() {
392        let backend = StubBackend::default();
393        let backend: &dyn KanbanBackend = &backend;
394        backend.mark_dirty();
395    }
396
397    #[tokio::test]
398    async fn test_default_probe_delegates_to_batch_count() {
399        let backend = StubBackend::default();
400        let b: &dyn KanbanBackend = &backend;
401
402        let result = b.probe().await;
403
404        assert!(
405            result.is_ok(),
406            "expected probe() to succeed, got: {result:?}"
407        );
408        assert_eq!(
409            backend
410                .batch_count_calls
411                .load(std::sync::atomic::Ordering::Relaxed),
412            1,
413            "expected the default probe to call batch_count exactly once"
414        );
415    }
416
417    #[tokio::test]
418    async fn test_default_probe_propagates_a_batch_count_error() {
419        let backend = StubBackend {
420            batch_count_fails: true,
421            ..Default::default()
422        };
423        let b: &dyn KanbanBackend = &backend;
424
425        let result = b.probe().await;
426
427        match result {
428            Err(e) => assert!(
429                e.to_string().contains("stub batch_count boom"),
430                "expected the batch_count error to propagate, got: {e}"
431            ),
432            Ok(_) => panic!("expected probe() to propagate the batch_count failure"),
433        }
434    }
435}