erpc_analysis/algorithms/
components.rs

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
// Connected components algorithms (WCC, SCC)

use log::info;
use std::sync::Arc;

use crate::db_trait::{AnalysisDatabase, AnalysisError};
use crate::models::partitions::ComponentAnalysisResult;

/// Analyzer for connected components in the Tor network graph
pub struct ComponentAnalyzer {
    db_client: Arc<dyn AnalysisDatabase>,
}

impl ComponentAnalyzer {
    /// Create a new ComponentAnalyzer with the given database client
    pub fn new(db_client: Arc<dyn AnalysisDatabase>) -> Self {
        Self { db_client }
    }

    /// Analyze weakly connected components for a given projection
    pub async fn analyze_weakly_connected_components(
        &self,
        projection_name: &str,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!("=== Starting Weakly Connected Components Analysis ===");

        let result = self
            .db_client
            .calculate_weakly_connected_components(projection_name)
            .await?;

        info!("=== WCC Analysis Complete ===");

        info!(
            "Network has {} weakly connected components",
            result.components.len()
        );

        Ok(result)
    }

    /// Analyze strongly connected components for a given projection
    pub async fn analyze_strongly_connected_components(
        &self,
        projection_name: &str,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!("=== Starting Strongly Connected Components Analysis ===");

        let result = self
            .db_client
            .calculate_strongly_connected_components(projection_name)
            .await?;

        info!("=== SCC Analysis Complete ===");

        info!(
            "Network has {} strongly connected components",
            result.components.len()
        );

        Ok(result)
    }

    /// Display detailed component analysis results
    pub fn display_weak_connectivity_analysis(
        &self,
        result: &ComponentAnalysisResult,
        config: &crate::config::AnalysisSettings,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Weakly Connected Components Analysis:");
        info!("Total Components: {}", result.total_components.unwrap_or(0));
        info!(
            "Largest Component Size: {}",
            result.largest_component_size.unwrap_or(0)
        );
        info!(
            "Smallest Component Size: {}",
            result.smallest_component_size.unwrap_or(0)
        );

        let isolation_ratio = result.isolation_ratio.unwrap_or(0.0);
        info!("Isolation Ratio: {:.2}%", isolation_ratio);

        // Check against threshold
        if isolation_ratio < config.isolation_ratio_threshold {
            info!(
                "⚠️  Network fragmentation detected: Isolation ratio \
                 {:.2}% is below threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        } else {
            info!(
                "✅ Network connectivity is healthy: Isolation ratio \
                 {:.2}% is above threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        }

        if config.calculate_distribution {
            if let Some(distribution) = &result.component_size_distribution {
                info!("Component Size Distribution:");
                let mut sizes: Vec<_> = distribution.iter().collect();
                sizes.sort_by(|a, b| b.0.cmp(a.0)); // Sort by size descending

                for (size, count) in
                    sizes.iter().take(config.max_display_components.min(5))
                {
                    info!("{} component(s) with {} relays each", count, size);
                }
            }
        }

        // Show top components by size
        if result.components.len() > 1 {
            info!(
                "Top {} Largest Components:",
                config.max_display_components.min(result.components.len())
            );
            for (i, component) in result
                .components
                .iter()
                .take(config.max_display_components)
                .enumerate()
            {
                info!(
                    "{}. Component {}: {} relays",
                    i + 1,
                    component.component_id,
                    component.size
                );
            }
        }

        Ok(())
    }

    /// Display detailed strong connectivity analysis results
    pub fn display_strong_connectivity_analysis(
        &self,
        result: &ComponentAnalysisResult,
        config: &crate::config::AnalysisSettings,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Strong Connectivity Analysis:");
        info!("Total Components: {}", result.total_components.unwrap_or(0));
        info!(
            "Largest Component Size: {}",
            result.largest_component_size.unwrap_or(0)
        );
        info!(
            "Smallest Component Size: {}",
            result.smallest_component_size.unwrap_or(0)
        );

        let isolation_ratio = result.isolation_ratio.unwrap_or(0.0);
        info!("Isolation Ratio: {:.2}%", isolation_ratio);

        // Check against threshold
        if isolation_ratio < config.isolation_ratio_threshold {
            info!(
                "⚠️  Network fragmentation detected: Isolation ratio \
                 {:.2}% is below threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        } else {
            info!(
                "✅ Network connectivity is healthy: Isolation ratio \
                 {:.2}% is above threshold {:.1}%",
                isolation_ratio, config.isolation_ratio_threshold
            );
        }

        if config.calculate_distribution {
            if let Some(distribution) = &result.component_size_distribution {
                info!("Component Size Distribution:");
                let mut sizes: Vec<_> = distribution.iter().collect();
                sizes.sort_by(|a, b| b.0.cmp(a.0)); // Sort by size descending

                for (size, count) in
                    sizes.iter().take(config.max_display_components.min(5))
                {
                    info!("{} component(s) with {} relays each", count, size);
                }
            }
        }

        // Show top components by size
        if result.components.len() > 1 {
            info!(
                "Top {} Largest Components:",
                config.max_display_components.min(result.components.len())
            );
            for (i, component) in result
                .components
                .iter()
                .take(config.max_display_components)
                .enumerate()
            {
                info!(
                    "{}. Component {}: {} relays",
                    i + 1,
                    component.component_id,
                    component.size
                );
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db_trait::mock::MockDatabase;
    use crate::models::metrics::NodeMetrics;

    /// Test WCC algorithm correctness with known graph topology
    #[tokio::test]
    async fn test_wcc_algorithm_correctness() {
        // Create a graph with 6 nodes (> 2, so MockDatabase creates
        // 2 components)
        let nodes = vec![
            NodeMetrics {
                fingerprint: "RELAY_A".to_string(),
                in_degree: 0,
                out_degree: 1,
                total_degree: 1,
            },
            NodeMetrics {
                fingerprint: "RELAY_B".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_C".to_string(),
                in_degree: 1,
                out_degree: 0,
                total_degree: 1,
            },
            NodeMetrics {
                fingerprint: "RELAY_D".to_string(),
                in_degree: 0,
                out_degree: 1,
                total_degree: 1,
            },
            NodeMetrics {
                fingerprint: "RELAY_E".to_string(),
                in_degree: 1,
                out_degree: 0,
                total_degree: 1,
            },
            NodeMetrics {
                fingerprint: "RELAY_F".to_string(),
                in_degree: 0,
                out_degree: 0,
                total_degree: 0,
            },
        ];

        let db =
            Arc::new(MockDatabase::new().with_projection("test_wcc", nodes));

        let analyzer = ComponentAnalyzer::new(db);
        let result = analyzer
            .analyze_weakly_connected_components("test_wcc")
            .await
            .expect("WCC analysis should succeed");

        // MockDatabase creates 2 components when > 2 nodes (6 nodes here)
        assert_eq!(result.total_components, Some(2));
        assert_eq!(result.components.len(), 2); // actual components = 2

        // Verify basic structure
        assert!(result.largest_component_size.is_some());
        assert!(result.smallest_component_size.is_some());
        assert!(result.isolation_ratio.is_some());

        // Check that all fingerprints are accounted for
        let total_fingerprints: usize =
            result.components.iter().map(|c| c.size).sum();
        assert_eq!(total_fingerprints, 6);
    }

    /// Test SCC algorithm correctness with directed graph
    #[tokio::test]
    async fn test_scc_algorithm_correctness() {
        // Create a directed graph with 4 nodes (> 2, so MockDatabase
        // creates 2 components)
        let nodes = vec![
            NodeMetrics {
                fingerprint: "RELAY_A".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_B".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_C".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
            NodeMetrics {
                fingerprint: "RELAY_D".to_string(),
                in_degree: 1,
                out_degree: 1,
                total_degree: 2,
            },
        ];

        let db =
            Arc::new(MockDatabase::new().with_projection("test_scc", nodes));

        let analyzer = ComponentAnalyzer::new(db);
        let result = analyzer
            .analyze_strongly_connected_components("test_scc")
            .await
            .expect("SCC analysis should succeed");

        // MockDatabase creates 2 components when > 2 nodes
        assert_eq!(result.total_components, Some(2));
        assert_eq!(result.components.len(), 2);

        // Verify basic structure
        assert!(result.largest_component_size.is_some());
        assert!(result.smallest_component_size.is_some());
        assert!(result.isolation_ratio.is_some());

        // Check that all fingerprints are accounted for
        let total_fingerprints: usize =
            result.components.iter().map(|c| c.size).sum();
        assert_eq!(total_fingerprints, 4);
    }

    /// Test handling of small graphs and error cases
    #[tokio::test]
    async fn test_small_graphs_and_errors() {
        let db = Arc::new(MockDatabase::new());
        let analyzer = ComponentAnalyzer::new(db.clone());

        // Test error handling for non-existent projections
        let wcc_result = analyzer
            .analyze_weakly_connected_components("nonexistent")
            .await;
        assert!(
            wcc_result.is_err(),
            "Should fail for non-existent projection"
        );

        let scc_result = analyzer
            .analyze_strongly_connected_components("nonexistent")
            .await;
        assert!(
            scc_result.is_err(),
            "Should fail for non-existent projection"
        );

        // Test handling of isolated nodes (2 nodes = single component)
        let isolated_nodes = vec![
            NodeMetrics {
                fingerprint: "ISOLATED_1".to_string(),
                in_degree: 0,
                out_degree: 0,
                total_degree: 0,
            },
            NodeMetrics {
                fingerprint: "ISOLATED_2".to_string(),
                in_degree: 0,
                out_degree: 0,
                total_degree: 0,
            },
        ];

        let db_isolated = Arc::new(
            MockDatabase::new()
                .with_projection("isolated_test", isolated_nodes),
        );

        let analyzer_isolated = ComponentAnalyzer::new(db_isolated);
        let result = analyzer_isolated
            .analyze_weakly_connected_components("isolated_test")
            .await
            .expect("Isolated nodes analysis should succeed");

        // MockDatabase creates 1 component for <= 2 nodes
        assert_eq!(result.total_components, Some(1));
        assert_eq!(result.components.len(), 1);
        assert_eq!(result.largest_component_size, Some(2));
        assert_eq!(result.isolation_ratio.unwrap(), 100.0);
    }

    /// Test edge cases: single node graph and failure handling
    #[tokio::test]
    async fn test_component_analysis_edge_cases() {
        // Test single node graph
        let single_node = vec![NodeMetrics {
            fingerprint: "SINGLE_NODE".to_string(),
            in_degree: 0,
            out_degree: 0,
            total_degree: 0,
        }];

        let db_single = Arc::new(
            MockDatabase::new().with_projection("single_node", single_node),
        );

        let analyzer_single = ComponentAnalyzer::new(db_single);
        let result = analyzer_single
            .analyze_weakly_connected_components("single_node")
            .await
            .expect("Single node analysis should succeed");

        assert_eq!(result.total_components, Some(1));
        assert_eq!(result.largest_component_size, Some(1));
        assert_eq!(result.smallest_component_size, Some(1));
        assert!((result.isolation_ratio.unwrap() - 100.0).abs() < 0.01);

        // Test SCC failure handling
        let fail_nodes = vec![NodeMetrics {
            fingerprint: "FAIL_RELAY".to_string(),
            in_degree: 1,
            out_degree: 1,
            total_degree: 2,
        }];

        let db_fail = Arc::new(
            MockDatabase::new()
                .with_projection("fail_test", fail_nodes)
                .fail_on("calculate_strongly_connected_components"),
        );

        let analyzer_fail = ComponentAnalyzer::new(db_fail);
        let result = analyzer_fail
            .analyze_strongly_connected_components("fail_test")
            .await;

        assert!(result.is_err(), "Should fail when database operation fails");
    }
}