erpc_analysis/db_trait.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 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 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
use async_trait::async_trait;
use std::collections::HashMap;
use thiserror::Error;
use crate::models::metrics::{GraphMetrics, NodeMetrics};
use crate::models::partitions::ComponentAnalysisResult;
/// Represents errors that can occur during analysis operations, including
/// database interactions.
#[derive(Error, Debug)]
pub enum AnalysisError {
/// An error originating from the underlying database driver (neo4rs).
#[error("Database Driver Error: {0}")]
DriverError(#[from] neo4rs::Error),
/// Failed to establish an initial connection to the database.
#[error("Failed to connect to database: {0}")]
ConnectionFailed(String),
/// An error occurred while attempting to drop an existing
/// GDS graph projection.
#[error(
"Failed to drop graph projection '{projection_name}': {source_error}"
)]
ProjectionDropFailed {
projection_name: String,
source_error: String,
},
/// An error occurred during the creation of a GDS graph projection.
#[error(
"Failed to create graph projection '{projection_name}': {source_error}"
)]
ProjectionCreationFailed {
projection_name: String,
source_error: String,
},
/// A generic error for database query execution failures not covered by
/// other specific variants.
#[error("Database query execution failed: {0}")]
QueryFailed(String),
/// Indicates that a requested GDS graph projection was not found.
#[error("GDS graph projection '{0}' not found.")]
ProjectionNotFound(String),
/// Indicates that a GDS graph projection already exists when it
/// was not expected.
#[error("GDS graph projection '{0}' already exists.")]
ProjectionAlreadyExists(String),
/// An error occurred during the execution of a graph algorithm.
#[error("Graph algorithm execution failed: {0}")]
AlgorithmError(String),
/// For configuration-related errors during analysis setup.
#[error("Analysis configuration error: {0}")]
ConfigurationError(String),
/// For I/O errors that might occur (e.g., reading a script file
/// for a query).
#[error("I/O error: {0}")]
IoError(#[from] std::io::Error),
/// For any other general error encountered during analysis.
#[error("An unexpected analysis error occurred: {0}")]
Generic(String),
}
/// Parameters for creating a GDS graph projection.
#[derive(Debug, Clone)]
pub struct GraphProjectionParams {
pub projection_name: String,
pub node_label: String,
pub relationship_types: HashMap<String, String>,
pub relationship_properties_to_project: Option<Vec<String>>,
}
/// Trait defining the interface for database operations required by
/// the eRPC analysis engine.
#[async_trait]
pub trait AnalysisDatabase: Send + Sync {
/// Creates or recreates a GDS graph projection.
/// If a projection with the same name exists, it should ideally be dropped
/// and recreated.
async fn create_graph_projection(
&self,
params: &GraphProjectionParams,
) -> Result<(), AnalysisError>;
/// Deletes an existing GDS graph projection if it exists.
/// Should succeed even if the projection does not exist (making
/// it idempotent).
async fn delete_graph_projection(
&self,
projection_name: &str,
) -> Result<(), AnalysisError>;
/// Checks if a GDS graph projection with the given name exists.
async fn check_graph_projection_exists(
&self,
projection_name: &str,
) -> Result<bool, AnalysisError>;
/// Calculates node-level degree metrics for all nodes in a
/// given GDS projection.
/// Returns a vector of NodeMetrics containing in-degree,
/// out-degree, and total degree for each node in the graph.
async fn calculate_node_degrees(
&self,
projection_name: &str,
) -> Result<Vec<NodeMetrics>, AnalysisError>;
/// Calculates comprehensive graph metrics for a given GDS projection
/// including basic counts, degree distribution, and degree statistics.
async fn calculate_graph_metrics(
&self,
projection_name: &str,
) -> Result<GraphMetrics, AnalysisError>;
/// Calculates weakly connected components using Neo4j GDS WCC algorithm.
/// Returns analysis results containing components, sizes, and statistics.
async fn calculate_weakly_connected_components(
&self,
projection_name: &str,
) -> Result<ComponentAnalysisResult, AnalysisError>;
/// Calculates strongly connected components using Neo4j GDS SCC algorithm.
/// Returns analysis results containing components, sizes, and statistics.
async fn calculate_strongly_connected_components(
&self,
projection_name: &str,
) -> Result<ComponentAnalysisResult, AnalysisError>;
}
/// Mock database implementation for testing purposes
pub mod mock {
use super::*;
use std::collections::HashMap;
use std::sync::RwLock;
use crate::models::partitions::ConnectedComponent;
/// Simple in-memory mock database for testing
#[derive(Debug)]
pub struct MockDatabase {
pub projections: RwLock<HashMap<String, MockProjection>>,
pub should_fail_on: Option<String>, // Operation that should fail
pub call_count: RwLock<HashMap<String, usize>>, // Track method calls
}
#[derive(Debug, Clone)]
pub struct MockProjection {
pub name: String,
pub node_count: i64,
pub relationship_count: i64,
pub nodes: Vec<NodeMetrics>,
}
impl Default for MockDatabase {
fn default() -> Self {
Self {
projections: RwLock::new(HashMap::new()),
should_fail_on: None,
call_count: RwLock::new(HashMap::new()),
}
}
}
impl MockDatabase {
pub fn new() -> Self {
Self::default()
}
/// Add a test projection with predefined data
pub fn with_projection(
self,
name: &str,
nodes: Vec<NodeMetrics>,
) -> Self {
let node_count = nodes.len() as i64;
let relationship_count =
nodes.iter().map(|n| n.total_degree).sum::<i64>();
self.projections.write().unwrap().insert(
name.to_string(),
MockProjection {
name: name.to_string(),
node_count,
relationship_count,
nodes,
},
);
self
}
/// Configure the mock to fail on a specific operation
pub fn fail_on(mut self, operation: &str) -> Self {
self.should_fail_on = Some(operation.to_string());
self
}
/// Get the number of times a method was called
pub fn get_call_count(&self, method: &str) -> usize {
self.call_count
.read()
.unwrap()
.get(method)
.copied()
.unwrap_or(0)
}
fn increment_call_count(&self, method: &str) {
*self
.call_count
.write()
.unwrap()
.entry(method.to_string())
.or_insert(0) += 1;
}
fn should_fail(&self, operation: &str) -> bool {
self.should_fail_on
.as_ref()
.is_some_and(|fail_op| fail_op == operation)
}
}
#[async_trait]
impl AnalysisDatabase for MockDatabase {
async fn create_graph_projection(
&self,
params: &GraphProjectionParams,
) -> Result<(), AnalysisError> {
self.increment_call_count("create_graph_projection");
if self.should_fail("create_graph_projection") {
return Err(AnalysisError::ProjectionCreationFailed {
projection_name: params.projection_name.clone(),
source_error: "Mock failure".to_string(),
});
}
// Mock successful creation
self.projections.write().unwrap().insert(
params.projection_name.clone(),
MockProjection {
name: params.projection_name.clone(),
node_count: 0,
relationship_count: 0,
nodes: vec![],
},
);
Ok(())
}
async fn delete_graph_projection(
&self,
projection_name: &str,
) -> Result<(), AnalysisError> {
self.increment_call_count("delete_graph_projection");
if self.should_fail("delete_graph_projection") {
return Err(AnalysisError::ProjectionDropFailed {
projection_name: projection_name.to_string(),
source_error: "Mock failure".to_string(),
});
}
// Always succeed (idempotent)
self.projections.write().unwrap().remove(projection_name);
Ok(())
}
async fn check_graph_projection_exists(
&self,
projection_name: &str,
) -> Result<bool, AnalysisError> {
self.increment_call_count("check_graph_projection_exists");
if self.should_fail("check_graph_projection_exists") {
return Err(AnalysisError::QueryFailed(
"Mock failure".to_string(),
));
}
Ok(self
.projections
.read()
.unwrap()
.contains_key(projection_name))
}
async fn calculate_node_degrees(
&self,
projection_name: &str,
) -> Result<Vec<NodeMetrics>, AnalysisError> {
self.increment_call_count("calculate_node_degrees");
if self.should_fail("calculate_node_degrees") {
return Err(AnalysisError::QueryFailed(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => Ok(projection.nodes.clone()),
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_graph_metrics(
&self,
projection_name: &str,
) -> Result<GraphMetrics, AnalysisError> {
self.increment_call_count("calculate_graph_metrics");
if self.should_fail("calculate_graph_metrics") {
return Err(AnalysisError::QueryFailed(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
let mut degree_distribution = HashMap::new();
let mut total_degree_sum = 0i64;
let mut max_degree = 0i64;
let mut min_degree = i64::MAX;
for node in &projection.nodes {
let degree = node.total_degree;
*degree_distribution.entry(degree).or_insert(0) += 1;
total_degree_sum += degree;
max_degree = max_degree.max(degree);
min_degree = min_degree.min(degree);
}
if min_degree == i64::MAX {
min_degree = 0;
}
let average_degree = if !projection.nodes.is_empty() {
total_degree_sum as f64 / projection.nodes.len() as f64
} else {
0.0
};
Ok(GraphMetrics {
node_count: Some(projection.node_count),
relationship_count: Some(
projection.relationship_count,
),
degree_distribution: Some(degree_distribution),
average_degree: Some(average_degree),
max_degree: Some(max_degree),
min_degree: Some(min_degree),
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_weakly_connected_components(
&self,
projection_name: &str,
) -> Result<ComponentAnalysisResult, AnalysisError> {
self.increment_call_count("calculate_weakly_connected_components");
if self.should_fail("calculate_weakly_connected_components") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
// Mock WCC analysis: create realistic mock components
let mut components = Vec::new();
if !projection.nodes.is_empty() {
// For mock purposes, create varied component structures
if projection.nodes.len() > 2 {
// First component with first half of nodes
let mid = projection.nodes.len() / 2;
let first_component_fingerprints: Vec<String> =
projection.nodes[0..mid]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
components.push(ConnectedComponent {
component_id: 0,
relay_fingerprints:
first_component_fingerprints.clone(),
size: first_component_fingerprints.len(),
});
// Second component with remaining nodes
let second_component_fingerprints: Vec<String> =
projection.nodes[mid..]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
components.push(ConnectedComponent {
component_id: 1,
relay_fingerprints:
second_component_fingerprints.clone(),
size: second_component_fingerprints.len(),
});
} else {
// Single component with all nodes
let all_fingerprints: Vec<String> = projection
.nodes
.iter()
.map(|n| n.fingerprint.clone())
.collect();
components.push(ConnectedComponent {
component_id: 0,
relay_fingerprints: all_fingerprints.clone(),
size: all_fingerprints.len(),
});
}
}
// Sort components by size (largest first)
components.sort_by(|a, b| b.size.cmp(&a.size));
// Calculate statistics
let total_components = components.len();
let largest_component_size =
components.first().map(|c| c.size).unwrap_or(0);
let smallest_component_size =
components.last().map(|c| c.size).unwrap_or(0);
// Calculate size distribution
let mut component_size_distribution = HashMap::new();
for component in &components {
*component_size_distribution
.entry(component.size)
.or_insert(0) += 1;
}
// Calculate isolation ratio
let total_nodes = projection.nodes.len();
let isolation_ratio = if total_nodes > 0 {
(largest_component_size as f64 / total_nodes as f64)
* 100.0
} else {
0.0
};
Ok(ComponentAnalysisResult {
components,
total_components: Some(total_components),
largest_component_size: Some(largest_component_size),
smallest_component_size: Some(smallest_component_size),
component_size_distribution: Some(
component_size_distribution,
),
isolation_ratio: Some(isolation_ratio),
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_strongly_connected_components(
&self,
projection_name: &str,
) -> Result<ComponentAnalysisResult, AnalysisError> {
self.increment_call_count(
"calculate_strongly_connected_components",
);
if self.should_fail("calculate_strongly_connected_components") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
// Mock SCC analysis: create realistic mock components
let mut components = Vec::new();
if !projection.nodes.is_empty() {
// For mock purposes, create varied component structures
if projection.nodes.len() > 2 {
// First component with first half of nodes
let mid = projection.nodes.len() / 2;
let first_component_fingerprints: Vec<String> =
projection.nodes[0..mid]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
components.push(ConnectedComponent {
component_id: 0,
relay_fingerprints:
first_component_fingerprints.clone(),
size: first_component_fingerprints.len(),
});
// Second component with remaining nodes
let second_component_fingerprints: Vec<String> =
projection.nodes[mid..]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
components.push(ConnectedComponent {
component_id: 1,
relay_fingerprints:
second_component_fingerprints.clone(),
size: second_component_fingerprints.len(),
});
} else {
// Single component with all nodes
let all_fingerprints: Vec<String> = projection
.nodes
.iter()
.map(|n| n.fingerprint.clone())
.collect();
components.push(ConnectedComponent {
component_id: 0,
relay_fingerprints: all_fingerprints.clone(),
size: all_fingerprints.len(),
});
}
}
// Sort components by size (largest first)
components.sort_by(|a, b| b.size.cmp(&a.size));
// Calculate statistics
let total_components = components.len();
let largest_component_size =
components.first().map(|c| c.size).unwrap_or(0);
let smallest_component_size =
components.last().map(|c| c.size).unwrap_or(0);
// Calculate size distribution correctly
let mut component_size_distribution = HashMap::new();
for component in &components {
*component_size_distribution
.entry(component.size)
.or_insert(0) += 1;
}
// Calculate isolation ratio
let total_nodes = projection.nodes.len();
let isolation_ratio = if total_nodes > 0 {
(largest_component_size as f64 / total_nodes as f64)
* 100.0
} else {
0.0
};
Ok(ComponentAnalysisResult {
components,
total_components: Some(total_components),
largest_component_size: Some(largest_component_size),
smallest_component_size: Some(smallest_component_size),
component_size_distribution: Some(
component_size_distribution,
),
isolation_ratio: Some(isolation_ratio),
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
}
}
#[cfg(test)]
mod tests {
use super::mock::MockDatabase;
use super::*;
#[tokio::test]
async fn test_mock_database_basic_operations() {
let db = MockDatabase::new();
// Test projection doesn't exist initially
let exists = db.check_graph_projection_exists("test").await.unwrap();
assert!(!exists);
// Create projection
let params = GraphProjectionParams {
projection_name: "test".to_string(),
node_label: "Relay".to_string(),
relationship_types: HashMap::new(),
relationship_properties_to_project: None,
};
db.create_graph_projection(¶ms).await.unwrap();
// Check it exists now
let exists = db.check_graph_projection_exists("test").await.unwrap();
assert!(exists);
// Delete projection
db.delete_graph_projection("test").await.unwrap();
// Check it doesn't exist anymore
let exists = db.check_graph_projection_exists("test").await.unwrap();
assert!(!exists);
}
#[tokio::test]
async fn test_mock_with_test_data() {
let nodes = vec![
NodeMetrics {
fingerprint: "RELAY001".to_string(),
in_degree: 3,
out_degree: 2,
total_degree: 5,
},
NodeMetrics {
fingerprint: "RELAY002".to_string(),
in_degree: 1,
out_degree: 4,
total_degree: 5,
},
];
let db = MockDatabase::new().with_projection("test_proj", nodes);
let result = db.calculate_node_degrees("test_proj").await.unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result[0].fingerprint, "RELAY001");
assert_eq!(result[0].total_degree, 5);
}
#[tokio::test]
async fn test_mock_wcc_edge_cases() {
let db = MockDatabase::new();
// Test projection not found
let result = db
.calculate_weakly_connected_components("nonexistent")
.await;
assert!(result.is_err());
// Test with only 2 nodes (should create single component)
let nodes = vec![
NodeMetrics {
fingerprint: "RELAY001".to_string(),
in_degree: 1,
out_degree: 1,
total_degree: 2,
},
NodeMetrics {
fingerprint: "RELAY002".to_string(),
in_degree: 1,
out_degree: 1,
total_degree: 2,
},
];
let db_with_data =
MockDatabase::new().with_projection("single_component", nodes);
let result = db_with_data
.calculate_weakly_connected_components("single_component")
.await
.unwrap();
// Should have 1 component with both nodes
assert_eq!(result.total_components.unwrap(), 1);
assert_eq!(result.components.len(), 1);
assert_eq!(result.components[0].size, 2);
assert_eq!(result.isolation_ratio.unwrap(), 100.0);
}
#[tokio::test]
async fn test_mock_scc_edge_cases_and_failures() {
let db = MockDatabase::new();
// Test projection not found
let result = db
.calculate_strongly_connected_components("nonexistent")
.await;
assert!(result.is_err());
// Test with only 2 nodes (should create single component)
let nodes = vec![
NodeMetrics {
fingerprint: "SCC_SINGLE_001".to_string(),
in_degree: 1,
out_degree: 1,
total_degree: 2,
},
NodeMetrics {
fingerprint: "SCC_SINGLE_002".to_string(),
in_degree: 1,
out_degree: 1,
total_degree: 2,
},
];
let db_single =
MockDatabase::new().with_projection("single_scc", nodes);
let result = db_single
.calculate_strongly_connected_components("single_scc")
.await
.unwrap();
// Should have only 1 component
assert_eq!(result.total_components.unwrap(), 1);
assert_eq!(result.components.len(), 1);
assert_eq!(result.components[0].size, 2);
assert_eq!(result.isolation_ratio.unwrap(), 100.0);
// Test failure scenario
let fail_nodes = vec![NodeMetrics {
fingerprint: "FAIL_RELAY001".to_string(),
in_degree: 1,
out_degree: 1,
total_degree: 2,
}];
let db_fail = MockDatabase::new()
.with_projection("fail_test", fail_nodes)
.fail_on("calculate_strongly_connected_components");
let fail_result = db_fail
.calculate_strongly_connected_components("fail_test")
.await;
assert!(fail_result.is_err());
assert_eq!(
db_fail.get_call_count("calculate_strongly_connected_components"),
1
);
}
}