kanban-backend 0.13.1

KanbanBackend and RemoteWrites abstractions implemented by local and remote kanban backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
pub mod compatibility;
pub mod factory;
pub mod local_persistence;
pub mod remote_writes;
pub use compatibility::CompatibilityNotice;
pub use factory::{KanbanBackendFactory, KanbanBackendRegistry};
pub use local_persistence::LocalPersistence;
pub use remote_writes::{
    RemoteBatchOutcome, RemoteBatchWrites, RemoteBoardWrites, RemoteCardWrites, RemoteGraphWrites,
    RemoteSprintWrites, RemoteWrites,
};

use async_trait::async_trait;
use kanban_domain::command_store::CommandStore;
use kanban_domain::data_store::DataStore;
use kanban_domain::{KanbanError, KanbanResult};
use uuid::Uuid;

/// Combines the entity-level CRUD interface (`DataStore`) with the command
/// log (`CommandStore`) and lifecycle methods needed for pluggable backends.
///
/// # Lifecycle methods
///
/// - `flush()`: persist in-memory state to durable storage. For SQLite this
///   runs an explicit WAL checkpoint (TRUNCATE); for JSON this serialises the
///   cache to disk.
/// - `reload()`: discard cached state so the next read re-fetches from
///   durable storage. For SQLite this is a no-op (reads are always live).
/// - `needs_flush()`: returns `true` when there are uncommitted writes that
///   a subsequent `flush()` would persist.
/// - `needs_save_worker()`: returns `true` for backends (JSON) that require
///   a background worker to call `flush()` asynchronously after mutations.
/// - `instance_id()`: stable ID used to distinguish file writes by this
///   instance from external modifications.
#[async_trait]
pub trait KanbanBackend: DataStore + CommandStore + Send + Sync {
    /// Upcast to `&dyn DataStore`.
    fn as_data_store(&self) -> &dyn DataStore;

    /// Persist any cached writes to durable storage.
    async fn flush(&self) -> KanbanResult<()> {
        Ok(())
    }

    /// Discard cached state so the next read re-fetches from storage.
    async fn reload(&self) -> KanbanResult<()> {
        Ok(())
    }

    /// Forces one cheap I/O so a broken backend fails at construction
    /// instead of on first use. The default reads the command log, which
    /// every local backend loads lazily; a remote backend overrides this
    /// with a network liveness check.
    async fn probe(&self) -> KanbanResult<()> {
        self.batch_count().map(|_| ())
    }

    /// Marks the backend dirty without performing a write, so a subsequent
    /// `flush()` (or `needs_save_worker()`-driven background flush) picks it
    /// up. No-op by default for write-through backends that have no dirty
    /// flag to set.
    fn mark_dirty(&self) {}

    /// Returns `true` when there are writes that have not been flushed yet.
    fn needs_flush(&self) -> bool {
        false
    }

    /// Returns `true` for backends (JSON) that require a background flush
    /// worker. Always `false` for write-through backends (SQLite, in-memory).
    fn needs_save_worker(&self) -> bool {
        false
    }

    /// Stable instance UUID used for own-write detection in file watchers.
    fn instance_id(&self) -> Uuid {
        Uuid::nil()
    }

    /// Some(...) when this backend can report format version, writer kanban
    /// version, writer commit, and last save time (JSON, SQLite). `None`
    /// (the default) for backends with no durable local store (InMemory,
    /// Http) or that don't track it (MockBackend).
    fn local_persistence(&self) -> Option<&dyn crate::LocalPersistence> {
        None
    }

    /// Some(...) when the last `probe()` found the remote server older than
    /// this binary, or unable to report a comparable version.
    fn compatibility_notice(&self) -> Option<crate::CompatibilityNotice> {
        None
    }

    /// Returns a health checker for this backend, if supported.
    /// The default returns `None`; backends that can self-diagnose
    /// (file readable, connection pool alive) override this.
    fn health_checker(&self) -> Option<Box<dyn kanban_core::HealthChecker>> {
        None
    }

    /// Some(...) when this backend wants create/update/delete for board/column/
    /// card to bypass local command execution entirely (an HTTP backend, where
    /// the remote server is authoritative). `None` (the default) for every local
    /// backend — zero behavior change for JSON/SQLite/InMemory.
    fn remote_writes(&self) -> Option<&dyn crate::RemoteWrites> {
        None
    }

    /// Per-family counterparts to `remote_writes()`. `None` by default for
    /// every backend; a backend overrides only the families it supports.
    fn remote_board_writes(&self) -> Option<&dyn crate::RemoteBoardWrites> {
        None
    }

    /// See `remote_board_writes()`.
    fn remote_card_writes(&self) -> Option<&dyn crate::RemoteCardWrites> {
        None
    }

    /// See `remote_board_writes()`.
    fn remote_batch_writes(&self) -> Option<&dyn crate::RemoteBatchWrites> {
        None
    }

    /// See `remote_board_writes()`.
    fn remote_sprint_writes(&self) -> Option<&dyn crate::RemoteSprintWrites> {
        None
    }

    /// See `remote_board_writes()`.
    fn remote_graph_writes(&self) -> Option<&dyn crate::RemoteGraphWrites> {
        None
    }

    /// Some(...) when a caller needs to downcast to the concrete backend type.
    /// `None` (the default) for backends that offer no such hook.
    fn as_any(&self) -> Option<&dyn std::any::Any> {
        None
    }

    /// Run `f` as an atomic batch: every mutation commits or rolls back
    /// together.
    ///
    /// `f` runs at most once — never twice, so it may consume what it
    /// captures, and possibly not at all. Anything that stops a batch from
    /// being atomic fails *before* `f` is invoked rather than running the
    /// mutations unprotected: a backend that cannot offer a transaction at all
    /// (`HttpBackend`, where the remote server owns the state) declines with an
    /// unsupported error, and one that can will still bail if it fails to open
    /// the transaction. Do not rely on a side effect inside `f` having happened
    /// unless this returned `Ok`.
    ///
    /// There is deliberately no default implementation. A generic one can only
    /// roll back by snapshotting the whole store and restoring it, which is
    /// cheap in memory and ruinous on disk; making the method required forces
    /// each backend to answer with its own native mechanism, and turns a new
    /// backend that forgot to into a compile error rather than a silent
    /// whole-store copy.
    ///
    /// # Single-writer requirement
    ///
    /// Implementations that roll back by restoring a whole-store snapshot
    /// cannot tell the batch's own writes apart from anyone else's, so a
    /// mutation committed by another task between the capture and the failure
    /// is reverted along with the batch. Every consumer today serialises its
    /// mutations (`kanban-server` and `kanban-mcp` behind
    /// `Arc<Mutex<KanbanContext>>`, the TUI on its main loop), which is what
    /// makes this sound. Any new concurrent access to a shared backend must
    /// serialise too, and must revisit `SqliteStore::db_conn`, whose ambient
    /// transaction fails the same way but worse.
    fn with_transaction(&self, f: TransactionFn<'_>) -> KanbanResult<()>;
}

/// Closure passed to [`KanbanBackend::with_transaction`], boxed so the method
/// stays callable on `dyn KanbanBackend`. `FnOnce` because the batch never runs
/// twice and closures need to move owned values in.
pub type TransactionFn<'f> = Box<dyn FnOnce() -> KanbanResult<()> + 'f>;

/// Combines a batch failure with a failure to roll it back. Shared by the
/// snapshot-restoring backends so the wording of the one message a user sees
/// when the store is left in an unknown state cannot drift between them.
pub fn rollback_failed(batch_err: KanbanError, rollback_err: KanbanError) -> KanbanError {
    KanbanError::Internal(format!(
        "Batch failed ({batch_err}) and rollback also failed ({rollback_err}). State may be inconsistent."
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use kanban_domain::command_batch::CommandBatch;
    use kanban_domain::*;

    #[test]
    fn test_rollback_failed_names_both_the_batch_and_the_rollback_error() {
        let err = rollback_failed(
            KanbanError::Internal("batch boom".into()),
            KanbanError::Internal("restore boom".into()),
        );

        let msg = err.to_string();
        assert!(
            msg.contains("batch boom"),
            "batch error lost (got: {msg:?})"
        );
        assert!(
            msg.contains("restore boom"),
            "rollback error lost (got: {msg:?})"
        );
        assert!(
            msg.contains("State may be inconsistent"),
            "a failed rollback must say the store is left in an unknown state \
             (got: {msg:?})"
        );
    }

    #[derive(Default)]
    struct StubBackend {
        batch_count_calls: std::sync::atomic::AtomicUsize,
        batch_count_fails: bool,
    }

    impl DataStore for StubBackend {
        fn get_prefix(&self, _name: &str) -> KanbanResult<Option<kanban_domain::Prefix>> {
            unimplemented!()
        }
        fn list_prefixes(&self) -> KanbanResult<Vec<kanban_domain::Prefix>> {
            unimplemented!()
        }
        fn upsert_prefix(&self, _prefix: kanban_domain::Prefix) -> KanbanResult<()> {
            unimplemented!()
        }
        fn get_label(&self, _name: &str) -> KanbanResult<Option<kanban_domain::Label>> {
            unimplemented!()
        }
        fn list_labels(&self) -> KanbanResult<Vec<kanban_domain::Label>> {
            unimplemented!()
        }
        fn upsert_label(&self, _label: kanban_domain::Label) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_label(&self, _name: &str) -> KanbanResult<()> {
            unimplemented!()
        }
        fn get_board(&self, _id: Uuid) -> KanbanResult<Option<Board>> {
            unimplemented!()
        }
        fn list_boards(&self) -> KanbanResult<Vec<Board>> {
            unimplemented!()
        }
        fn upsert_board(&self, _board: Board) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_board(&self, _id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn get_column(&self, _id: Uuid) -> KanbanResult<Option<Column>> {
            unimplemented!()
        }
        fn list_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Column>> {
            unimplemented!()
        }
        fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
            unimplemented!()
        }
        fn upsert_column(&self, _column: Column) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_column(&self, _id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_columns_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn get_card(&self, _id: Uuid) -> KanbanResult<Option<Card>> {
            unimplemented!()
        }
        fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
            unimplemented!()
        }
        fn list_cards_by_column(&self, _column_id: Uuid) -> KanbanResult<Vec<Card>> {
            unimplemented!()
        }
        fn list_cards_by_sprint(&self, _sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
            unimplemented!()
        }
        fn count_cards_in_column(&self, _column_id: Uuid) -> KanbanResult<usize> {
            unimplemented!()
        }
        fn count_cards_in_column_excluding(
            &self,
            _column_id: Uuid,
            _exclude: &[Uuid],
        ) -> KanbanResult<usize> {
            unimplemented!()
        }
        fn upsert_card(&self, _card: Card) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_card(&self, _id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_cards_by_columns(&self, _column_ids: &[Uuid]) -> KanbanResult<()> {
            unimplemented!()
        }
        fn clear_sprint_from_cards(
            &self,
            _sprint_id: Uuid,
            _timestamp: chrono::DateTime<chrono::Utc>,
        ) -> KanbanResult<()> {
            unimplemented!()
        }
        fn get_archived_card(&self, _card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
            unimplemented!()
        }
        fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
            unimplemented!()
        }
        fn insert_archived_card(&self, _ac: ArchivedCard) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_archived_card(&self, _card_id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn list_archived_boards(&self) -> KanbanResult<Vec<kanban_domain::ArchivedBoard>> {
            unimplemented!()
        }
        fn get_sprint(&self, _id: Uuid) -> KanbanResult<Option<Sprint>> {
            unimplemented!()
        }
        fn list_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
            unimplemented!()
        }
        fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
            unimplemented!()
        }
        fn upsert_sprint(&self, _sprint: Sprint) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_sprint(&self, _id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn delete_sprints_by_board(&self, _board_id: Uuid) -> KanbanResult<()> {
            unimplemented!()
        }
        fn get_graph(&self) -> KanbanResult<DependencyGraph> {
            unimplemented!()
        }
        fn set_graph(&self, _graph: DependencyGraph) -> KanbanResult<()> {
            unimplemented!()
        }
    }

    impl CommandStore for StubBackend {
        fn append_batch(&self, _batch: &CommandBatch) -> KanbanResult<u64> {
            unimplemented!()
        }
        fn batch_count(&self) -> KanbanResult<u64> {
            self.batch_count_calls
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            if self.batch_count_fails {
                Err(KanbanError::Internal("stub batch_count boom".into()))
            } else {
                Ok(0)
            }
        }
        fn load_batches(&self, _offset: u64, _limit: u64) -> KanbanResult<Vec<CommandBatch>> {
            unimplemented!()
        }
    }

    impl KanbanBackend for StubBackend {
        fn as_data_store(&self) -> &dyn DataStore {
            self
        }
        fn with_transaction(&self, _f: TransactionFn<'_>) -> KanbanResult<()> {
            unimplemented!()
        }
    }

    #[test]
    fn test_backend_without_local_persistence_returns_none() {
        let backend = StubBackend::default();
        let backend: &dyn KanbanBackend = &backend;
        assert!(backend.local_persistence().is_none());
    }

    #[test]
    fn test_default_compatibility_notice_is_none() {
        let backend = StubBackend::default();
        let backend: &dyn KanbanBackend = &backend;
        assert!(backend.compatibility_notice().is_none());
    }

    #[test]
    fn test_kanban_backend_as_any_defaults_to_none() {
        let backend = StubBackend::default();
        let backend: &dyn KanbanBackend = &backend;
        assert!(backend.as_any().is_none());
    }

    #[test]
    fn test_mark_dirty_is_callable_on_a_backend_that_does_not_override_it() {
        let backend = StubBackend::default();
        let backend: &dyn KanbanBackend = &backend;
        backend.mark_dirty();
    }

    #[tokio::test]
    async fn test_default_probe_delegates_to_batch_count() {
        let backend = StubBackend::default();
        let b: &dyn KanbanBackend = &backend;

        let result = b.probe().await;

        assert!(
            result.is_ok(),
            "expected probe() to succeed, got: {result:?}"
        );
        assert_eq!(
            backend
                .batch_count_calls
                .load(std::sync::atomic::Ordering::Relaxed),
            1,
            "expected the default probe to call batch_count exactly once"
        );
    }

    #[tokio::test]
    async fn test_default_probe_propagates_a_batch_count_error() {
        let backend = StubBackend {
            batch_count_fails: true,
            ..Default::default()
        };
        let b: &dyn KanbanBackend = &backend;

        let result = b.probe().await;

        match result {
            Err(e) => assert!(
                e.to_string().contains("stub batch_count boom"),
                "expected the batch_count error to propagate, got: {e}"
            ),
            Ok(_) => panic!("expected probe() to propagate the batch_count failure"),
        }
    }
}