erpc_analysis/
tasks.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
446
447
448
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::Result;
use log::{error, info, warn};

use crate::algorithms::ComponentAnalyzer;
use crate::args::Args;
use crate::db_trait::{
    AnalysisDatabase, AnalysisError, GraphProjectionParams,
};
use crate::models::metrics::{GraphMetrics, NodeMetrics};

/// Handles task execution based on CLI arguments
pub struct TaskHandler {
    db_client: Arc<dyn AnalysisDatabase>,
    args: Args,
}

impl TaskHandler {
    pub fn new(db_client: Arc<dyn AnalysisDatabase>, args: Args) -> Self {
        Self { db_client, args }
    }

    /// Execute the specified task or run default analysis
    pub async fn execute(&self) -> Result<(), Box<dyn std::error::Error>> {
        match &self.args.task {
            Some(task) => self.execute_specific_task(task).await,
            None => self.execute_default_analysis().await,
        }
    }

    async fn execute_specific_task(
        &self,
        task: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        match task {
            "projection-create" => self.handle_projection_create().await,
            "projection-delete" => self.handle_projection_delete().await,
            "projection-exists" => self.handle_projection_exists().await,
            "metrics-basic" => self.handle_metrics_basic().await,
            "metrics-degrees" => self.handle_metrics_degrees().await,
            "metrics-distribution" => self.handle_metrics_distribution().await,
            "components-analysis" => self.handle_components_analysis().await,
            "info-database" => self.handle_info_database().await,
            "help" => self.handle_help().await,
            _ => {
                error!("Unknown task: {}", task);
                println!("{}", Args::task_help());
                std::process::exit(1);
            }
        }
    }

    /// Execute the default analysis workflow
    async fn execute_default_analysis(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running default analysis workflow...");

        let proj_params = self.create_default_projection_params();

        info!(
            "Creating/updating GDS graph projection: '{}' with node \
             label: '{}'",
            proj_params.projection_name, proj_params.node_label
        );

        self.db_client
            .create_graph_projection(&proj_params)
            .await
            .map_err(|e: AnalysisError| {
                error!(
                    "Failed to create GDS graph projection '{}': {:?}",
                    proj_params.projection_name, e
                );
                Box::new(e) as Box<dyn std::error::Error>
            })?;

        info!(
            "Successfully created/updated GDS graph projection: '{}'",
            proj_params.projection_name
        );

        self.calculate_and_display_metrics(&proj_params.projection_name)
            .await?;

        self.handle_components_analysis().await?;

        Ok(())
    }

    async fn handle_projection_create(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let proj_params = self.create_projection_params("tor_erpc_projection");

        if !self.args.force
            && self
                .db_client
                .check_graph_projection_exists(&proj_params.projection_name)
                .await?
        {
            println!(
                "Projection '{}' already exists. Use --force to recreate.",
                proj_params.projection_name
            );
            return Ok(());
        }

        info!(
            "Creating graph projection: '{}'",
            proj_params.projection_name
        );
        self.db_client.create_graph_projection(&proj_params).await?;
        println!(
            "✅ Successfully created projection: '{}'",
            proj_params.projection_name
        );

        Ok(())
    }

    async fn handle_projection_delete(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Deleting graph projection: tor_erpc_projection");
        self.db_client
            .delete_graph_projection("tor_erpc_projection")
            .await?;
        println!("✅ Successfully deleted projection: tor_erpc_projection");

        Ok(())
    }

    async fn handle_projection_exists(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let exists = self
            .db_client
            .check_graph_projection_exists("tor_erpc_projection")
            .await?;

        if exists {
            println!("✅ Projection: tor_erpc_projection exists");
        } else {
            println!("❌ Projection: tor_erpc_projection does not exist");
        }

        Ok(())
    }

    async fn handle_metrics_basic(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Calculating basic metrics for projection: tor_erpc_projection");
        let metrics = self
            .db_client
            .calculate_graph_metrics("tor_erpc_projection")
            .await
            .map_err(|e| {
                error!("Failed to calculate graph metrics: {:?}", e);
                e
            })?;
        info!("Successfully calculated metrics, displaying results...");
        self.display_basic_metrics(&metrics)?;
        Ok(())
    }

    async fn handle_metrics_degrees(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let node_degrees = self
            .db_client
            .calculate_node_degrees("tor_erpc_projection")
            .await
            .map_err(|e| {
                error!("Failed to calculate node degrees: {:?}", e);
                e
            })?;
        self.display_degree_metrics(&node_degrees)?;
        Ok(())
    }

    async fn handle_metrics_distribution(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let metrics = self
            .db_client
            .calculate_graph_metrics("tor_erpc_projection")
            .await
            .map_err(|e| {
                error!(
                    "Failed to calculate graph metrics for distribution: {:?}",
                    e
                );
                e
            })?;
        self.display_degree_distribution(&metrics)?;
        Ok(())
    }

    async fn handle_info_database(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Test actual database connectivity
        let connection_status = match self
            .db_client
            .check_graph_projection_exists("test_connection")
            .await
        {
            Ok(_) => "Connected",
            Err(_) => "Connection Failed",
        };

        println!("Database Information:");
        println!("  Type: Neo4j");
        println!("  Status: {}", connection_status);
        Ok(())
    }

    async fn handle_help(&self) -> Result<(), Box<dyn std::error::Error>> {
        println!("{}", Args::task_help());
        Ok(())
    }

    /// Handle comprehensive component analysis task
    async fn handle_components_analysis(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Create separate projection for partition detection (success-only)
        info!(
            "Creating partition detection projection (SUCCESS edges only)..."
        );

        let partition_params = self.create_partition_detection_params(
            "tor_erpc_connectivity_analysis",
        );

        self.db_client
            .create_graph_projection(&partition_params)
            .await
            .map_err(|e| {
                error!(
                    "Failed to create partition detection projection: {:?}",
                    e
                );
                e
            })?;

        info!("Running weak connectivity analysis using WCC algorithm...");
        self.run_wcc_analysis(&partition_params.projection_name)
            .await?;

        info!("Running strong connectivity analysis using SCC algorithm...");
        self.run_scc_analysis(&partition_params.projection_name)
            .await?;

        Ok(())
    }

    async fn run_wcc_analysis(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let analyzer = ComponentAnalyzer::new(Arc::clone(&self.db_client));

        let result = analyzer
            .analyze_weakly_connected_components(projection_name)
            .await?;

        analyzer.display_weak_connectivity_analysis(&result)?;

        Ok(())
    }

    async fn run_scc_analysis(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let analyzer = ComponentAnalyzer::new(Arc::clone(&self.db_client));

        let result = analyzer
            .analyze_strongly_connected_components(projection_name)
            .await?;

        analyzer.display_strong_connectivity_analysis(&result)?;

        Ok(())
    }

    /// Create default projection parameters (includes both success & failure)
    /// This maintains all relationship data for analysis
    fn create_default_projection_params(&self) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            .insert("CIRCUIT_SUCCESS".to_string(), "NATURAL".to_string());
        rel_types_map
            .insert("CIRCUIT_FAILURE".to_string(), "NATURAL".to_string());

        GraphProjectionParams {
            projection_name: "tor_erpc_projection".to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            // Properties are not used for current analysis
            relationship_properties_to_project: None,
        }
    }

    /// Create projection parameters with custom name (includes both success
    /// and failure)
    fn create_projection_params(&self, name: &str) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            .insert("CIRCUIT_SUCCESS".to_string(), "NATURAL".to_string());
        rel_types_map
            .insert("CIRCUIT_FAILURE".to_string(), "NATURAL".to_string());

        GraphProjectionParams {
            projection_name: name.to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            // Properties are not used for current analysis
            relationship_properties_to_project: None,
        }
    }

    /// Create projection for partition detection (success-only)
    /// Excludes CIRCUIT_FAILURE to detect actual connectivity partitions
    fn create_partition_detection_params(
        &self,
        name: &str,
    ) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            // CIRCUIT_FAILURE intentionally excluded for partition detection
            .insert("CIRCUIT_SUCCESS".to_string(), "NATURAL".to_string());

        GraphProjectionParams {
            projection_name: name.to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            relationship_properties_to_project: None,
        }
    }

    /// Calculate and display metrics
    async fn calculate_and_display_metrics(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("=== Starting Graph Metrics Calculation ===");

        let graph_metrics = self
            .db_client
            .calculate_graph_metrics(projection_name)
            .await
            .map_err(|e: AnalysisError| {
                error!("Failed to calculate graph metrics: {:?}", e);
                Box::new(e) as Box<dyn std::error::Error>
            })?;

        self.display_basic_metrics(&graph_metrics)?;
        self.display_degree_distribution(&graph_metrics)?;

        let node_degrees = self
            .db_client
            .calculate_node_degrees(projection_name)
            .await
            .map_err(|e: AnalysisError| {
                error!("Failed to calculate node degrees: {:?}", e);
                Box::new(e) as Box<dyn std::error::Error>
            })?;

        self.display_degree_metrics(&node_degrees)?;

        info!("=== Graph Metrics Calculation Complete ===");
        Ok(())
    }

    fn display_basic_metrics(
        &self,
        metrics: &GraphMetrics,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Basic Graph Metrics:");
        info!("  Nodes: {}", metrics.node_count.unwrap_or(0));
        info!(
            "  Relationships: {}",
            metrics.relationship_count.unwrap_or(0)
        );
        info!(
            "  Average degree: {:.2}",
            metrics.average_degree.unwrap_or(0.0)
        );
        info!("  Maximum degree: {}", metrics.max_degree.unwrap_or(0));
        info!("  Minimum degree: {}", metrics.min_degree.unwrap_or(0));
        Ok(())
    }

    fn display_degree_metrics(
        &self,
        node_degrees: &[NodeMetrics],
    ) -> Result<(), Box<dyn std::error::Error>> {
        let mut sorted_degrees = node_degrees.to_vec();
        sorted_degrees.sort_by(|a, b| b.total_degree.cmp(&a.total_degree));

        info!("Top 10 Most Connected Relays:");
        for (i, node) in sorted_degrees.iter().take(10).enumerate() {
            info!(
                "  {}. {} - Total: {}, In: {}, Out: {}",
                i + 1,
                &node.fingerprint,
                node.total_degree,
                node.in_degree,
                node.out_degree
            );
        }
        Ok(())
    }

    fn display_degree_distribution(
        &self,
        metrics: &GraphMetrics,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(degree_dist) = &metrics.degree_distribution {
            info!(
                "Degree Distribution ({} unique values):",
                degree_dist.len()
            );
            let mut dist_vec: Vec<(i64, i64)> =
                degree_dist.iter().map(|(&k, &v)| (k, v)).collect();
            dist_vec.sort_by(|a, b| b.1.cmp(&a.1)); // Sort by count descending

            info!("  Top 5 Most Common Degrees:");
            for (i, (degree, count)) in dist_vec.iter().take(5).enumerate() {
                info!(
                    "    {}. {} relays have degree {}",
                    i + 1,
                    count,
                    degree
                );
            }
        } else {
            warn!("No degree distribution data available");
        }
        Ok(())
    }
}