injectable-rs-graph 0.1.0

Compile-time dependency graph validation for the injectable-rs DI framework
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
//! The dependency graph — a collection of nodes with validation.

use crate::{GraphNode, ValidationError};

/// A dependency graph of all injectable types in the application.
///
/// The graph is constructed from metadata generated by the proc macros
/// and is validated once at container build time. After validation,
/// the graph is not used during runtime resolution — providers resolve
/// dependencies through static dispatch.
///
/// # Construction
///
/// The graph is typically built automatically by the container builder:
///
/// ```rust,ignore
/// let graph = DependencyGraph::new(vec![
///     GraphNode::new("UserService", &["Database", "Cache"]),
///     GraphNode::leaf("Database"),
///     GraphNode::leaf("Cache"),
/// ]);
/// graph.validate()?;
/// ```
#[derive(Debug, Clone)]
pub struct DependencyGraph {
    nodes: Vec<GraphNode>,
}

impl DependencyGraph {
    /// Create a new empty dependency graph.
    pub fn empty() -> Self {
        Self { nodes: Vec::new() }
    }

    /// Create a new dependency graph from a list of nodes.
    pub fn new(nodes: Vec<GraphNode>) -> Self {
        Self { nodes }
    }

    /// Add a node to the graph.
    pub fn add_node(&mut self, node: GraphNode) {
        self.nodes.push(node);
    }

    /// Get all nodes in the graph.
    pub fn nodes(&self) -> &[GraphNode] {
        &self.nodes
    }

    /// Get the number of nodes in the graph.
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Returns `true` if the graph contains no nodes.
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Find a node by name.
    pub fn find_node(&self, name: &str) -> Option<&GraphNode> {
        self.nodes.iter().find(|n| n.name == name)
    }

    /// Validate the entire dependency graph.
    ///
    /// Checks for:
    /// - Circular dependencies (via DFS)
    /// - Missing dependencies (references to types not in the graph)
    /// - Duplicate node definitions
    /// - Scope mismatches (wider-scope types depending on narrower-scope types)
    ///
    /// Returns a list of validation errors. An empty list means the graph is valid.
    pub fn validate(&self) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        // Check for duplicate nodes
        self.check_duplicates(&mut errors);

        // Check for missing dependencies
        self.check_missing(&mut errors);

        // Check for circular dependencies
        self.check_cycles(&mut errors);

        // Check for scope mismatches
        self.check_scope_mismatches(&mut errors);

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    fn check_duplicates(&self, errors: &mut Vec<ValidationError>) {
        let mut seen = std::collections::HashSet::new();
        for node in &self.nodes {
            if !seen.insert(node.name) {
                errors.push(ValidationError::DuplicateNode {
                    name: node.name.to_string(),
                });
            }
        }
    }

    fn check_missing(&self, errors: &mut Vec<ValidationError>) {
        let names: std::collections::HashSet<&str> = self.nodes.iter().map(|n| n.name).collect();

        for node in &self.nodes {
            for dep in node.dependencies {
                if !names.contains(dep) {
                    // Skip path-qualified names (containing `::` or `<`): these are
                    // external types provided via DynProvider and are not in the graph.
                    if dep.contains("::") || dep.contains('<') {
                        continue;
                    }
                    errors.push(ValidationError::MissingDependency {
                        source: node.name.to_string(),
                        missing: dep.to_string(),
                    });
                }
            }
        }
    }

    fn check_cycles(&self, errors: &mut Vec<ValidationError>) {
        let mut visited = std::collections::HashSet::new();
        let mut in_stack = std::collections::HashSet::new();
        let mut path = Vec::new();

        for node in &self.nodes {
            if !visited.contains(node.name) {
                self.dfs(node.name, &mut visited, &mut in_stack, &mut path, errors);
            }
        }
    }

    fn dfs<'a>(
        &self,
        current: &'a str,
        visited: &mut std::collections::HashSet<&'a str>,
        in_stack: &mut std::collections::HashSet<&'a str>,
        path: &mut Vec<&'a str>,
        errors: &mut Vec<ValidationError>,
    ) {
        visited.insert(current);
        in_stack.insert(current);
        path.push(current);

        if let Some(node) = self.find_node(current) {
            for dep in node.dependencies {
                if !visited.contains(dep) {
                    self.dfs(dep, visited, in_stack, path, errors);
                } else if in_stack.contains(dep) {
                    // Found a cycle — record the cycle path
                    let cycle_start = path.iter().position(|n| *n == *dep).unwrap_or(0);
                    // Panic Safety: cycle_start comes from position() which returns an index < path.len(),
                    // or 0 as fallback; either way cycle_start <= path.len().
                    let cycle: Vec<String> = path
                        .get(cycle_start..)
                        .unwrap_or(&[])
                        .iter()
                        .map(|s| s.to_string())
                        .chain(std::iter::once(dep.to_string()))
                        .collect();

                    errors.push(ValidationError::CircularDependency { chain: cycle });
                }
            }
        }

        path.pop();
        in_stack.remove(current);
    }

    /// Check for scope mismatches.
    ///
    /// A scope mismatch occurs when a wider-scope type (e.g., singleton)
    /// depends on a narrower-scope type (e.g., transient). This is
    /// problematic because the narrower-scope instance would be captured
    /// by the wider-scope instance for its entire lifetime, violating
    /// the narrower scope's semantics.
    ///
    /// # Scope Ordering
    ///
    /// From widest to narrowest:
    /// - `singleton` (widest — lives for the entire application lifetime)
    /// - `transient` (narrowest — new instance per resolution)
    ///
    /// # Valid Combinations
    ///
    /// - singleton → singleton: OK
    /// - transient → singleton: OK (transient gets a shared singleton)
    /// - transient → transient: OK (each gets a fresh instance)
    /// - singleton → transient: ERROR (singleton captures a single transient forever)
    fn check_scope_mismatches(&self, errors: &mut Vec<ValidationError>) {
        for node in &self.nodes {
            for dep_name in node.dependencies {
                if let Some(dep) = self.find_node(dep_name) {
                    if is_wider_scope(node.scope, dep.scope) {
                        errors.push(ValidationError::ScopeMismatch {
                            source: node.name.to_string(),
                            source_scope: node.scope.to_string(),
                            dependency: dep_name.to_string(),
                            dependency_scope: dep.scope.to_string(),
                        });
                    }
                }
            }
        }
    }

    /// Compute the topological order of the dependency graph.
    ///
    /// Returns nodes in construction order (dependencies before dependents).
    /// Returns an error if the graph contains cycles.
    pub fn topological_order(&self) -> Result<Vec<&str>, Vec<ValidationError>> {
        self.validate()?;

        let mut result = Vec::new();
        let mut visited = std::collections::HashSet::new();
        let mut temp_marked = std::collections::HashSet::new();

        for node in &self.nodes {
            if !visited.contains(node.name) {
                self.topo_visit(node.name, &mut visited, &mut temp_marked, &mut result);
            }
        }

        Ok(result)
    }

    fn topo_visit<'a>(
        &self,
        current: &'a str,
        visited: &mut std::collections::HashSet<&'a str>,
        temp_marked: &mut std::collections::HashSet<&'a str>,
        result: &mut Vec<&'a str>,
    ) {
        if visited.contains(current) {
            return;
        }
        if temp_marked.contains(current) {
            return; // Cycle — already validated above
        }

        temp_marked.insert(current);

        if let Some(node) = self.find_node(current) {
            for dep in node.dependencies {
                self.topo_visit(dep, visited, temp_marked, result);
            }
        }

        temp_marked.remove(current);
        visited.insert(current);
        result.push(current);
    }

    /// Compute the destruction order (reverse topological).
    ///
    /// Dependencies are destroyed after their dependents.
    pub fn destruction_order(&self) -> Result<Vec<&str>, Vec<ValidationError>> {
        let mut order = self.topological_order()?;
        order.reverse();
        Ok(order)
    }
}

/// Determine if `source_scope` is wider than `dep_scope`.
///
/// Returns `true` when a scope mismatch would occur — i.e., when a
/// wider-scope type depends on a narrower-scope type.
///
/// # Scope Width Ordering
///
/// - `singleton` is the widest scope
/// - `transient` is narrower than `singleton`
///
/// Any unrecognized scope is treated as equivalent to `singleton` (no mismatch).
fn is_wider_scope(source_scope: &str, dep_scope: &str) -> bool {
    match (source_scope, dep_scope) {
        // singleton depending on transient is the canonical mismatch
        ("singleton", "transient") => true,
        // All other combinations are valid
        _ => false,
    }
}

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

    #[test]
    fn test_is_wider_scope() {
        assert!(is_wider_scope("singleton", "transient"));
        assert!(!is_wider_scope("singleton", "singleton"));
        assert!(!is_wider_scope("transient", "singleton"));
        assert!(!is_wider_scope("transient", "transient"));
        assert!(!is_wider_scope("request", "transient"));
        assert!(!is_wider_scope("singleton", "request"));
    }

    #[test]
    fn empty_graph_is_valid() {
        let g = DependencyGraph::empty();
        assert!(g.is_empty());
        assert_eq!(g.len(), 0);
        assert!(g.validate().is_ok());
    }

    #[test]
    fn valid_linear_graph() {
        let g = DependencyGraph::new(vec![
            GraphNode::leaf("Database"),
            GraphNode::new("UserService", &["Database"]),
        ]);
        assert!(g.validate().is_ok());
    }

    #[test]
    fn circular_dependency_detected() {
        let g = DependencyGraph::new(vec![
            GraphNode::new("A", &["B"]),
            GraphNode::new("B", &["A"]),
        ]);
        let errs = g.validate().unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::CircularDependency { .. }))
        );
    }

    #[test]
    fn three_node_cycle_detected() {
        let g = DependencyGraph::new(vec![
            GraphNode::new("A", &["B"]),
            GraphNode::new("B", &["C"]),
            GraphNode::new("C", &["A"]),
        ]);
        let errs = g.validate().unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::CircularDependency { .. }))
        );
    }

    #[test]
    fn missing_dependency_detected() {
        let g = DependencyGraph::new(vec![GraphNode::new("UserService", &["MissingDep"])]);
        let errs = g.validate().unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::MissingDependency { .. }))
        );
    }

    #[test]
    fn duplicate_node_detected() {
        let g = DependencyGraph::new(vec![
            GraphNode::leaf("Database"),
            GraphNode::leaf("Database"),
        ]);
        let errs = g.validate().unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::DuplicateNode { .. }))
        );
    }

    #[test]
    fn scope_mismatch_detected() {
        let g = DependencyGraph::new(vec![
            GraphNode::leaf("Transient").then_with_scope("transient"),
            GraphNode::with_scope("Singleton", &["Transient"], "singleton"),
        ]);
        let errs = g.validate().unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::ScopeMismatch { .. }))
        );
    }

    #[test]
    fn topological_order_valid_graph() {
        let g = DependencyGraph::new(vec![
            GraphNode::leaf("Database"),
            GraphNode::new("UserService", &["Database"]),
        ]);
        let order = g.topological_order().unwrap();
        let db_pos = order.iter().position(|n| *n == "Database").unwrap();
        let svc_pos = order.iter().position(|n| *n == "UserService").unwrap();
        assert!(db_pos < svc_pos);
    }

    #[test]
    fn destruction_order_is_reverse_topo() {
        let g = DependencyGraph::new(vec![
            GraphNode::leaf("Database"),
            GraphNode::new("UserService", &["Database"]),
        ]);
        let topo = g.topological_order().unwrap();
        let destruct = g.destruction_order().unwrap();
        assert_eq!(topo, destruct.iter().rev().cloned().collect::<Vec<_>>());
    }

    #[test]
    fn find_node_existing() {
        let g = DependencyGraph::new(vec![GraphNode::leaf("Database")]);
        assert!(g.find_node("Database").is_some());
        assert!(g.find_node("Missing").is_none());
    }

    #[test]
    fn add_node_increases_len() {
        let mut g = DependencyGraph::empty();
        g.add_node(GraphNode::leaf("Foo"));
        assert_eq!(g.len(), 1);
        assert!(!g.is_empty());
    }

    #[test]
    fn path_qualified_dep_not_missing() {
        // Dependencies with '::' are external types, not graph nodes
        let g = DependencyGraph::new(vec![GraphNode::new("MyService", &["sqlx::SqlitePool"])]);
        assert!(g.validate().is_ok());
    }
}

// Helper for tests: create a node with a scope override via builder pattern
#[allow(dead_code)]
trait NodeScopeExt {
    fn then_with_scope(self, scope: &'static str) -> GraphNode;
}

impl NodeScopeExt for GraphNode {
    fn then_with_scope(self, scope: &'static str) -> GraphNode {
        GraphNode::with_scope(self.name, self.dependencies, scope)
    }
}