kanban-core 0.5.1

Core traits, errors, and result types for the kanban project management tool
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

use super::algorithms;
use super::edge::{Edge, EdgeDirection};

/// Generic graph structure that can hold any edge type E
///
/// Stores edges as an edge list for efficient serialization.
/// Provides adjacency list views for graph algorithms.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Graph<E> {
    edges: Vec<Edge<E>>,
}

impl<E> Default for Graph<E> {
    fn default() -> Self {
        Self { edges: Vec::new() }
    }
}

impl<E> Graph<E> {
    /// Create a new empty graph
    pub fn new() -> Self {
        Self { edges: Vec::new() }
    }

    /// Add an edge to the graph
    ///
    /// Note: Cycle checking must be done by caller if needed
    /// (see `would_create_cycle` method)
    pub fn add_edge(&mut self, edge: Edge<E>) {
        self.edges.push(edge);
    }

    /// Remove an edge between two nodes
    ///
    /// Returns true if an edge was removed, false if no matching edge found
    pub fn remove_edge(&mut self, source: Uuid, target: Uuid) -> bool
    where
        E: Clone,
    {
        let initial_len = self.edges.len();
        self.edges.retain(|e| !e.connects(source, target));
        self.edges.len() < initial_len
    }

    /// Remove all edges involving a node (for deletion cascades)
    pub fn remove_node(&mut self, node_id: Uuid) {
        self.edges.retain(|e| !e.involves(node_id));
    }

    /// Archive all edges involving a node (for archive cascades)
    pub fn archive_node(&mut self, node_id: Uuid) {
        for edge in &mut self.edges {
            if edge.involves(node_id) {
                edge.archive();
            }
        }
    }

    /// Unarchive all edges involving a node (for unarchive cascades)
    pub fn unarchive_node(&mut self, node_id: Uuid) {
        for edge in &mut self.edges {
            if edge.involves(node_id) {
                edge.unarchive();
            }
        }
    }

    /// Get all outgoing edges from a node (where node is source)
    pub fn outgoing(&self, node_id: Uuid) -> Vec<&Edge<E>> {
        self.edges.iter().filter(|e| e.source == node_id).collect()
    }

    /// Get all incoming edges to a node (where node is target)
    pub fn incoming(&self, node_id: Uuid) -> Vec<&Edge<E>> {
        self.edges.iter().filter(|e| e.target == node_id).collect()
    }

    /// Get all active outgoing edges from a node
    pub fn outgoing_active(&self, node_id: Uuid) -> Vec<&Edge<E>> {
        self.edges
            .iter()
            .filter(|e| e.source == node_id && e.is_active())
            .collect()
    }

    /// Get all active incoming edges to a node
    pub fn incoming_active(&self, node_id: Uuid) -> Vec<&Edge<E>> {
        self.edges
            .iter()
            .filter(|e| e.target == node_id && e.is_active())
            .collect()
    }

    /// Get all neighbor node IDs (connected nodes, handling bidirectional edges)
    pub fn neighbors(&self, node_id: Uuid) -> Vec<Uuid>
    where
        E: Clone,
    {
        let mut neighbors = Vec::new();

        for edge in &self.edges {
            if edge.source == node_id {
                neighbors.push(edge.target);
            } else if edge.target == node_id {
                match edge.direction {
                    EdgeDirection::Bidirectional => neighbors.push(edge.source),
                    EdgeDirection::Directed => {}
                }
            }
        }

        neighbors
    }

    /// Get all active neighbor node IDs
    pub fn neighbors_active(&self, node_id: Uuid) -> Vec<Uuid>
    where
        E: Clone,
    {
        let mut neighbors = Vec::new();

        for edge in self.edges.iter().filter(|e| e.is_active()) {
            if edge.source == node_id {
                neighbors.push(edge.target);
            } else if edge.target == node_id {
                match edge.direction {
                    EdgeDirection::Bidirectional => neighbors.push(edge.source),
                    EdgeDirection::Directed => {}
                }
            }
        }

        neighbors
    }

    /// Build an adjacency list view of the graph (for algorithms)
    /// Only includes active edges
    pub fn adjacency_list(&self) -> HashMap<Uuid, Vec<Uuid>>
    where
        E: Clone,
    {
        let mut adj_list: HashMap<Uuid, Vec<Uuid>> = HashMap::new();

        for edge in self.edges.iter().filter(|e| e.is_active()) {
            adj_list.entry(edge.source).or_default().push(edge.target);

            if edge.direction == EdgeDirection::Bidirectional {
                adj_list.entry(edge.target).or_default().push(edge.source);
            }
        }

        adj_list
    }

    /// Get all edges (for serialization/inspection)
    pub fn edges(&self) -> &[Edge<E>] {
        &self.edges
    }

    /// Get all active edges
    pub fn active_edges(&self) -> Vec<&Edge<E>> {
        self.edges.iter().filter(|e| e.is_active()).collect()
    }

    /// Check if an edge exists between two nodes
    pub fn has_edge(&self, source: Uuid, target: Uuid) -> bool
    where
        E: Clone,
    {
        self.edges.iter().any(|e| e.connects(source, target))
    }

    /// Check if adding an edge would create a cycle
    /// Only checks active edges
    pub fn would_create_cycle(&self, source: Uuid, target: Uuid) -> bool
    where
        E: Clone,
    {
        let adj_list = self.adjacency_list();
        algorithms::would_create_cycle(&adj_list, source, target)
    }

    /// Check if the graph contains any cycles
    /// Only checks active edges
    pub fn has_cycle(&self) -> bool
    where
        E: Clone,
    {
        let adj_list = self.adjacency_list();
        algorithms::has_cycle(&adj_list)
    }

    /// Get all nodes reachable from a given node
    /// Only considers active edges
    pub fn reachable_from(&self, start: Uuid) -> std::collections::HashSet<Uuid>
    where
        E: Clone,
    {
        let adj_list = self.adjacency_list();
        algorithms::reachable_from(&adj_list, start)
    }

    /// Get the count of edges (total, including archived)
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// Get the count of active edges
    pub fn active_edge_count(&self) -> usize {
        self.edges.iter().filter(|e| e.is_active()).count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::edge::EdgeDirection;

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    enum TestEdgeType {
        TypeA,
        TypeB,
    }

    #[test]
    fn test_graph_creation() {
        let graph: Graph<TestEdgeType> = Graph::new();
        assert_eq!(graph.edge_count(), 0);
    }

    #[test]
    fn test_add_edge() {
        let mut graph = Graph::new();
        let source = Uuid::new_v4();
        let target = Uuid::new_v4();
        let edge = Edge::new(source, target, TestEdgeType::TypeA, EdgeDirection::Directed);

        graph.add_edge(edge);
        assert_eq!(graph.edge_count(), 1);
        assert!(graph.has_edge(source, target));
    }

    #[test]
    fn test_remove_edge() {
        let mut graph = Graph::new();
        let source = Uuid::new_v4();
        let target = Uuid::new_v4();
        let edge = Edge::new(source, target, TestEdgeType::TypeA, EdgeDirection::Directed);

        graph.add_edge(edge);
        assert!(graph.remove_edge(source, target));
        assert_eq!(graph.edge_count(), 0);
        assert!(!graph.has_edge(source, target));
    }

    #[test]
    fn test_remove_node() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();
        let node_c = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_b,
            node_c,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_c,
            node_a,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));

        assert_eq!(graph.edge_count(), 3);

        graph.remove_node(node_b);
        assert_eq!(graph.edge_count(), 1);
        assert!(graph.has_edge(node_c, node_a));
        assert!(!graph.has_edge(node_a, node_b));
        assert!(!graph.has_edge(node_b, node_c));
    }

    #[test]
    fn test_archive_node() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();
        let node_c = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_b,
            node_c,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));

        assert_eq!(graph.active_edge_count(), 2);

        graph.archive_node(node_b);
        assert_eq!(graph.edge_count(), 2);
        assert_eq!(graph.active_edge_count(), 0);
    }

    #[test]
    fn test_unarchive_node() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.archive_node(node_a);
        assert_eq!(graph.active_edge_count(), 0);

        graph.unarchive_node(node_a);
        assert_eq!(graph.active_edge_count(), 1);
    }

    #[test]
    fn test_outgoing_incoming() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();
        let node_c = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_a,
            node_c,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_c,
            node_a,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));

        assert_eq!(graph.outgoing(node_a).len(), 2);
        assert_eq!(graph.incoming(node_a).len(), 1);
        assert_eq!(graph.outgoing(node_b).len(), 0);
        assert_eq!(graph.incoming(node_b).len(), 1);
    }

    #[test]
    fn test_neighbors_directed() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();
        let node_c = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_a,
            node_c,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));

        let neighbors = graph.neighbors(node_a);
        assert_eq!(neighbors.len(), 2);
        assert!(neighbors.contains(&node_b));
        assert!(neighbors.contains(&node_c));

        assert_eq!(graph.neighbors(node_b).len(), 0);
    }

    #[test]
    fn test_neighbors_bidirectional() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Bidirectional,
        ));

        let neighbors_a = graph.neighbors(node_a);
        let neighbors_b = graph.neighbors(node_b);

        assert_eq!(neighbors_a.len(), 1);
        assert_eq!(neighbors_b.len(), 1);
        assert!(neighbors_a.contains(&node_b));
        assert!(neighbors_b.contains(&node_a));
    }

    #[test]
    fn test_would_create_cycle() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();
        let node_c = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_b,
            node_c,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));

        // c -> a would create cycle: a -> b -> c -> a
        assert!(graph.would_create_cycle(node_c, node_a));

        // c -> b would also create cycle: b -> c -> b
        assert!(graph.would_create_cycle(node_c, node_b));
    }

    #[test]
    fn test_adjacency_list() {
        let mut graph = Graph::new();
        let node_a = Uuid::new_v4();
        let node_b = Uuid::new_v4();
        let node_c = Uuid::new_v4();

        graph.add_edge(Edge::new(
            node_a,
            node_b,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));
        graph.add_edge(Edge::new(
            node_b,
            node_c,
            TestEdgeType::TypeA,
            EdgeDirection::Directed,
        ));

        let adj_list = graph.adjacency_list();
        assert_eq!(adj_list.len(), 2);
        assert_eq!(adj_list.get(&node_a).unwrap().len(), 1);
        assert_eq!(adj_list.get(&node_b).unwrap().len(), 1);
    }
}