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 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
use async_trait::async_trait;
use std::collections::HashMap;
use thiserror::Error;
use crate::models::metrics::{
CentralityAnalysisResult, GraphMetrics, NodeMetrics, PathAnalysisResult,
PathResult,
};
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>;
/// Calculates communities using Neo4j GDS Louvain algorithm.
/// Returns analysis results containing communities, sizes, and statistics.
async fn calculate_louvain_communities(
&self,
projection_name: &str,
params: &crate::config::LouvainConfig,
) -> Result<ComponentAnalysisResult, AnalysisError>;
/// Calculates communities using Neo4j GDS Label Propagation algorithm.
/// Returns analysis results containing communities, sizes, and statistics.
async fn calculate_label_propagation_communities(
&self,
projection_name: &str,
params: &crate::config::LabelPropagationConfig,
) -> Result<ComponentAnalysisResult, AnalysisError>;
/// Calculates modularity score for a given community assignment.
/// Higher modularity indicates better community structure.
async fn calculate_modularity(
&self,
projection_name: &str,
community_property: &str,
) -> Result<f64, AnalysisError>;
/// Classifies connected components by geographic location (country).
/// Groups relays by country and analyzes their distribution across
/// components.
async fn classify_components_by_geography(
&self,
components: &[crate::models::partitions::ConnectedComponent],
) -> Result<
crate::models::partitions::PartitionClassificationResult,
AnalysisError,
>;
/// Classifies connected components by ASN.
/// Groups relays by ASN and analyzes their distribution across components.
async fn classify_components_by_asn(
&self,
components: &[crate::models::partitions::ConnectedComponent],
) -> Result<
crate::models::partitions::PartitionClassificationResult,
AnalysisError,
>;
/// Classifies connected components by relay family relationships.
/// Groups relays by family membership and analyzes their distribution
/// across components.
async fn classify_components_by_family(
&self,
components: &[crate::models::partitions::ConnectedComponent],
) -> Result<
crate::models::partitions::PartitionClassificationResult,
AnalysisError,
>;
/// Calculates betweenness centrality for nodes in a GDS projection.
/// Uses Neo4j GDS betweenness centrality algorithm to identify nodes
/// that act as bridges between other nodes.
async fn calculate_betweenness_centrality(
&self,
projection_name: &str,
sampling_size: Option<usize>,
sampling_seed: Option<u64>,
) -> Result<CentralityAnalysisResult, AnalysisError>;
/// Calculates closeness centrality for nodes in a GDS projection.
/// Uses Neo4j GDS closeness centrality algorithm to identify nodes
/// that are close to all other nodes in the network.
async fn calculate_closeness_centrality(
&self,
projection_name: &str,
use_wasserman_faust: Option<bool>,
) -> Result<CentralityAnalysisResult, AnalysisError>;
/// Calculates both betweenness and closeness centrality
async fn calculate_combined_centrality(
&self,
projection_name: &str,
betweenness_sampling_size: Option<usize>,
betweenness_sampling_seed: Option<u64>,
use_wasserman_faust: Option<bool>,
) -> Result<CentralityAnalysisResult, AnalysisError>;
/// Analyzes shortest paths between nodes from different communities.
/// Uses Neo4j GDS shortest path algorithms to understand
/// inter-community connectivity.
async fn analyze_paths_between_communities(
&self,
projection_name: &str,
source_nodes: &[String],
target_nodes: &[String],
) -> Result<PathAnalysisResult, AnalysisError>;
}
/// Mock database implementation for testing purposes
pub mod mock {
use super::*;
use std::collections::HashMap;
use std::sync::RwLock;
use crate::models::metrics::{CentralityDistribution, CentralityMetrics};
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)
}
// Helper function to deterministically assign countries based on relay
// fingerprint
fn get_mock_country_for_relay(relay: &str) -> String {
let hash = relay.bytes().map(|b| b as u32).sum::<u32>();
match hash % 4 {
0 => "US".to_string(),
1 => "DE".to_string(),
2 => "FR".to_string(),
_ => "NL".to_string(),
}
}
// Helper function to deterministically assign ASNs based on relay
// fingerprint
fn get_mock_asn_for_relay(relay: &str) -> String {
let hash = relay.bytes().map(|b| b as u32).sum::<u32>();
match hash % 3 {
0 => "13335".to_string(), // Cloudflare
1 => "210558".to_string(), // Tor-related ASN
_ => "64512".to_string(), // Private ASN
}
}
// Helper function to deterministically assign families based on relay
// fingerprint
fn get_mock_family_for_relay(relay: &str) -> Option<String> {
let hash = relay.bytes().map(|b| b as u32).sum::<u32>();
match hash % 5 {
0 => Some("family_torproject_main".to_string()),
1 => Some("family_hackingteam".to_string()),
2 => Some("family_small_fragmented".to_string()),
3 => Some("family_test_small".to_string()),
_ => None,
}
}
/// Calculates classification metrics for partition analysis groups
fn calculate_classification_metrics(
groups: &[crate::models::partitions::ClassificationGroup],
components: &[crate::models::partitions::ConnectedComponent],
) -> crate::models::partitions::ClassificationMetrics {
// Calculate basic metrics
let total_relays: usize =
components.iter().map(|c| c.relay_fingerprints.len()).sum();
let total_classified: usize =
groups.iter().map(|g| g.relay_fingerprints.len()).sum();
let coverage = if total_relays > 0 {
(total_classified as f64 / total_relays as f64) * 100.0
} else {
0.0
};
let groups_with_partitions = groups
.iter()
.filter(|g| g.component_mapping.len() > 1)
.count();
let largest_group_size = groups
.iter()
.map(|g| g.relay_fingerprints.len())
.max()
.unwrap_or(0);
let average_group_size = if !groups.is_empty() {
total_classified as f64 / groups.len() as f64
} else {
0.0
};
// Calculate diversity score (Shannon entropy-like metric)
let diversity_score = if !groups.is_empty() && total_classified > 0
{
let total_relays_f64 = total_classified as f64;
let entropy = groups
.iter()
.map(|g| {
g.relay_fingerprints.len() as f64 / total_relays_f64
})
.filter(|&p| p > 0.0)
.map(|p| -p * p.ln())
.sum::<f64>();
entropy / (groups.len() as f64).ln()
} else {
0.0
};
// Calculate partition correlation
let partition_correlation = if !groups.is_empty() {
groups.iter().map(|g| g.isolation_score).sum::<f64>()
/ groups.len() as f64
/ 100.0
} else {
0.0
};
crate::models::partitions::ClassificationMetrics {
total_groups: groups.len(),
groups_with_partitions,
classification_coverage: coverage,
largest_group_size,
average_group_size,
diversity_score,
partition_correlation,
}
}
}
#[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),
// WCC analysis doesn't calculate modularity
modularity: None,
})
}
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),
// SCC analysis doesn't calculate modularity
modularity: None,
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_louvain_communities(
&self,
projection_name: &str,
_params: &crate::config::LouvainConfig,
) -> Result<ComponentAnalysisResult, AnalysisError> {
self.increment_call_count("calculate_louvain_communities");
if self.should_fail("calculate_louvain_communities") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
let mut communities = Vec::new();
if !projection.nodes.is_empty() {
// For mock purposes, create varied community
// structures
if projection.nodes.len() > 2 {
// First community with first half of nodes
let mid = projection.nodes.len() / 2;
let first_community_fingerprints: Vec<String> =
projection.nodes[0..mid]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 0,
relay_fingerprints:
first_community_fingerprints.clone(),
size: first_community_fingerprints.len(),
});
// Second community with remaining nodes
let second_community_fingerprints: Vec<String> =
projection.nodes[mid..]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 1,
relay_fingerprints:
second_community_fingerprints.clone(),
size: second_community_fingerprints.len(),
});
} else {
// Single community with all nodes
let all_fingerprints: Vec<String> = projection
.nodes
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 0,
relay_fingerprints: all_fingerprints.clone(),
size: all_fingerprints.len(),
});
}
}
// Sort communities by size (largest first)
communities.sort_by(|a, b| b.size.cmp(&a.size));
// Calculate statistics
let total_communities = communities.len();
let largest_community_size =
communities.first().map(|c| c.size).unwrap_or(0);
let smallest_community_size =
communities.last().map(|c| c.size).unwrap_or(0);
// Calculate size distribution
let mut community_size_distribution = HashMap::new();
for community in &communities {
*community_size_distribution
.entry(community.size)
.or_insert(0) += 1;
}
// Calculate isolation ratio
let total_nodes = projection.nodes.len();
let isolation_ratio = if total_nodes > 0 {
(largest_community_size as f64 / total_nodes as f64)
* 100.0
} else {
0.0
};
Ok(ComponentAnalysisResult {
components: communities,
total_components: Some(total_communities),
largest_component_size: Some(largest_community_size),
smallest_component_size: Some(smallest_community_size),
component_size_distribution: Some(
community_size_distribution,
),
isolation_ratio: Some(isolation_ratio),
// Mock modularity score for Louvain comm. detection
modularity: Some(0.42),
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_label_propagation_communities(
&self,
projection_name: &str,
_params: &crate::config::LabelPropagationConfig,
) -> Result<ComponentAnalysisResult, AnalysisError> {
self.increment_call_count(
"calculate_label_propagation_communities",
);
if self.should_fail("calculate_label_propagation_communities") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
let mut communities = Vec::new();
if !projection.nodes.is_empty() {
// For mock purposes, create varied community
// structures
// Label Propagation tends to create more communities
// than Louvain
if projection.nodes.len() > 3 {
let third = projection.nodes.len() / 3;
// First community
let first_community_fingerprints: Vec<String> =
projection.nodes[0..third]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 0,
relay_fingerprints:
first_community_fingerprints.clone(),
size: first_community_fingerprints.len(),
});
// Second community
let second_community_fingerprints: Vec<String> =
projection.nodes[third..2 * third]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 1,
relay_fingerprints:
second_community_fingerprints.clone(),
size: second_community_fingerprints.len(),
});
// Third community with remaining nodes
let third_community_fingerprints: Vec<String> =
projection.nodes[2 * third..]
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 2,
relay_fingerprints:
third_community_fingerprints.clone(),
size: third_community_fingerprints.len(),
});
} else {
// Single community with all nodes for small graphs
let all_fingerprints: Vec<String> = projection
.nodes
.iter()
.map(|n| n.fingerprint.clone())
.collect();
communities.push(ConnectedComponent {
component_id: 0,
relay_fingerprints: all_fingerprints.clone(),
size: all_fingerprints.len(),
});
}
}
// Sort communities by size (largest first)
communities.sort_by(|a, b| b.size.cmp(&a.size));
// Calculate statistics
let total_communities = communities.len();
let largest_community_size =
communities.first().map(|c| c.size).unwrap_or(0);
let smallest_community_size =
communities.last().map(|c| c.size).unwrap_or(0);
// Calculate size distribution
let mut community_size_distribution = HashMap::new();
for community in &communities {
*community_size_distribution
.entry(community.size)
.or_insert(0) += 1;
}
// Calculate isolation ratio
let total_nodes = projection.nodes.len();
let isolation_ratio = if total_nodes > 0 {
(largest_community_size as f64 / total_nodes as f64)
* 100.0
} else {
0.0
};
Ok(ComponentAnalysisResult {
components: communities,
total_components: Some(total_communities),
largest_component_size: Some(largest_community_size),
smallest_component_size: Some(smallest_community_size),
component_size_distribution: Some(
community_size_distribution,
),
isolation_ratio: Some(isolation_ratio),
// Mock modularity score for LPA community detection
modularity: Some(0.42),
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_modularity(
&self,
projection_name: &str,
_community_property: &str,
) -> Result<f64, AnalysisError> {
self.increment_call_count("calculate_modularity");
if self.should_fail("calculate_modularity") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(_) => {
Ok(0.42) // Mock modularity score
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn classify_components_by_geography(
&self,
components: &[crate::models::partitions::ConnectedComponent],
) -> Result<
crate::models::partitions::PartitionClassificationResult,
AnalysisError,
> {
self.increment_call_count("classify_components_by_geography");
if self.should_fail("classify_components_by_geography") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
use crate::models::partitions::{
ClassificationGroup, ClassificationMetrics,
ClassificationType, PartitionClassificationResult,
};
use std::collections::HashMap;
let mut groups: Vec<ClassificationGroup> = Vec::new();
let unclassified_relays = Vec::new();
if components.is_empty() {
return Ok(PartitionClassificationResult {
classification_type: ClassificationType::Geographic,
groups,
metrics: ClassificationMetrics {
total_groups: 0,
groups_with_partitions: 0,
classification_coverage: 0.0,
largest_group_size: 0,
average_group_size: 0.0,
diversity_score: 0.0,
partition_correlation: 0.0,
},
unclassified_relays,
});
}
// Create deterministic geographic assignment based on relay
// fingerprint
let mut country_relays: HashMap<String, Vec<String>> =
HashMap::new();
let mut relay_to_component: HashMap<String, i64> = HashMap::new();
// Build relay-to-component mapping from input
for component in components {
for relay in &component.relay_fingerprints {
relay_to_component
.insert(relay.clone(), component.component_id);
}
}
// Assign countries based on relay fingerprint hash
for component in components {
for relay in &component.relay_fingerprints {
let country = Self::get_mock_country_for_relay(relay);
country_relays
.entry(country)
.or_default()
.push(relay.clone());
}
}
// Create classification groups for each country
for (country, relays) in country_relays {
if relays.is_empty() {
continue;
}
let mut component_mapping: HashMap<i64, usize> =
HashMap::new();
// Count relays per component for this country
for relay in &relays {
if let Some(&component_id) = relay_to_component.get(relay)
{
*component_mapping.entry(component_id).or_insert(0) +=
1;
}
}
// Calculate isolation score (% of relays NOT in largest
// component)
let largest_component_size =
component_mapping.values().max().copied().unwrap_or(0);
let total_relays_in_country = relays.len();
let fragmented_relays =
total_relays_in_country - largest_component_size;
let isolation_score = if total_relays_in_country > 0 {
(fragmented_relays as f64 / total_relays_in_country as f64)
* 100.0
} else {
0.0
};
groups.push(ClassificationGroup {
identifier: country,
relay_fingerprints: relays,
component_mapping,
isolation_score,
});
}
// Calculate metrics
let metrics =
Self::calculate_classification_metrics(&groups, components);
Ok(PartitionClassificationResult {
classification_type: ClassificationType::Geographic,
groups,
metrics,
unclassified_relays,
})
}
async fn classify_components_by_asn(
&self,
components: &[crate::models::partitions::ConnectedComponent],
) -> Result<
crate::models::partitions::PartitionClassificationResult,
AnalysisError,
> {
self.increment_call_count("classify_components_by_asn");
if self.should_fail("classify_components_by_asn") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
use crate::models::partitions::{
ClassificationGroup, ClassificationMetrics,
ClassificationType, PartitionClassificationResult,
};
use std::collections::HashMap;
let mut groups: Vec<ClassificationGroup> = Vec::new();
let unclassified_relays = Vec::new();
if components.is_empty() {
return Ok(PartitionClassificationResult {
classification_type: ClassificationType::ASN,
groups,
metrics: ClassificationMetrics {
total_groups: 0,
groups_with_partitions: 0,
classification_coverage: 0.0,
largest_group_size: 0,
average_group_size: 0.0,
diversity_score: 0.0,
partition_correlation: 0.0,
},
unclassified_relays,
});
}
// Create deterministic ASN assignment based on relay fingerprint
let mut asn_relays: HashMap<String, Vec<String>> = HashMap::new();
let mut relay_to_component: HashMap<String, i64> = HashMap::new();
// Build relay-to-component mapping from input
for component in components {
for relay in &component.relay_fingerprints {
relay_to_component
.insert(relay.clone(), component.component_id);
}
}
// Assign ASNs based on relay fingerprint hash
for component in components {
for relay in &component.relay_fingerprints {
let asn = Self::get_mock_asn_for_relay(relay);
asn_relays.entry(asn).or_default().push(relay.clone());
}
}
// Create classification groups for each ASN
for (asn, relays) in asn_relays {
if relays.is_empty() {
continue;
}
let mut component_mapping: HashMap<i64, usize> =
HashMap::new();
// Count relays per component for this ASN
for relay in &relays {
if let Some(&component_id) = relay_to_component.get(relay)
{
*component_mapping.entry(component_id).or_insert(0) +=
1;
}
}
// Calculate isolation score
let largest_component_size =
component_mapping.values().max().copied().unwrap_or(0);
let total_relays_in_asn = relays.len();
let fragmented_relays =
total_relays_in_asn - largest_component_size;
let isolation_score = if total_relays_in_asn > 0 {
(fragmented_relays as f64 / total_relays_in_asn as f64)
* 100.0
} else {
0.0
};
groups.push(ClassificationGroup {
identifier: asn,
relay_fingerprints: relays,
component_mapping,
isolation_score,
});
}
// Calculate metrics
let metrics =
Self::calculate_classification_metrics(&groups, components);
Ok(PartitionClassificationResult {
classification_type: ClassificationType::ASN,
groups,
metrics,
unclassified_relays,
})
}
async fn classify_components_by_family(
&self,
components: &[crate::models::partitions::ConnectedComponent],
) -> Result<
crate::models::partitions::PartitionClassificationResult,
AnalysisError,
> {
self.increment_call_count("classify_components_by_family");
if self.should_fail("classify_components_by_family") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
use crate::models::partitions::{
ClassificationGroup, ClassificationMetrics,
ClassificationType, PartitionClassificationResult,
};
use std::collections::HashMap;
let mut groups: Vec<ClassificationGroup> = Vec::new();
let mut unclassified_relays = Vec::new();
if components.is_empty() {
return Ok(PartitionClassificationResult {
classification_type: ClassificationType::Family,
groups,
metrics: ClassificationMetrics {
total_groups: 0,
groups_with_partitions: 0,
classification_coverage: 0.0,
largest_group_size: 0,
average_group_size: 0.0,
diversity_score: 0.0,
partition_correlation: 0.0,
},
unclassified_relays,
});
}
// Create deterministic family assignment based on relay
// fingerprint
let mut family_relays: HashMap<String, Vec<String>> =
HashMap::new();
let mut relay_to_component: HashMap<String, i64> = HashMap::new();
// Build relay-to-component mapping from input
for component in components {
for relay in &component.relay_fingerprints {
relay_to_component
.insert(relay.clone(), component.component_id);
}
}
// Assign families based on relay fingerprint hash
// Some relays are in families, others are unclassified
for component in components {
for relay in &component.relay_fingerprints {
if let Some(family) =
Self::get_mock_family_for_relay(relay)
{
family_relays
.entry(family)
.or_default()
.push(relay.clone());
} else {
unclassified_relays.push(relay.clone());
}
}
}
// Create classification groups for each family
for (family, relays) in family_relays {
if relays.is_empty() {
continue;
}
let mut component_mapping: HashMap<i64, usize> =
HashMap::new();
// Count relays per component for this family
for relay in &relays {
if let Some(&component_id) = relay_to_component.get(relay)
{
*component_mapping.entry(component_id).or_insert(0) +=
1;
}
}
// Calculate isolation score
let largest_component_size =
component_mapping.values().max().copied().unwrap_or(0);
let total_relays_in_family = relays.len();
let fragmented_relays =
total_relays_in_family - largest_component_size;
let isolation_score = if total_relays_in_family > 0 {
(fragmented_relays as f64 / total_relays_in_family as f64)
* 100.0
} else {
0.0
};
groups.push(ClassificationGroup {
identifier: family,
relay_fingerprints: relays,
component_mapping,
isolation_score,
});
}
// Calculate metrics
let metrics =
Self::calculate_classification_metrics(&groups, components);
Ok(PartitionClassificationResult {
classification_type: ClassificationType::Family,
groups,
metrics,
unclassified_relays,
})
}
async fn calculate_betweenness_centrality(
&self,
projection_name: &str,
sampling_size: Option<usize>,
sampling_seed: Option<u64>,
) -> Result<CentralityAnalysisResult, AnalysisError> {
self.increment_call_count("calculate_betweenness_centrality");
if self.should_fail("calculate_betweenness_centrality") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
let mut centrality_metrics = Vec::new();
if projection.nodes.is_empty() {
return Ok(CentralityAnalysisResult {
centrality_metrics: vec![],
total_nodes_analyzed: Some(0),
betweenness_distribution: None,
closeness_distribution: None,
});
}
// Respect sampling parameters
let nodes_to_analyze =
if let Some(sample_size) = sampling_size {
let sample_size =
sample_size.min(projection.nodes.len());
// Use seed for deterministic sampling
let mut nodes = projection.nodes.clone();
if let Some(seed) = sampling_seed {
nodes.sort_by(|a, b| {
let hash_a = a
.fingerprint
.bytes()
.map(|b| b as u32)
.sum::<u32>()
.wrapping_add(seed as u32);
let hash_b = b
.fingerprint
.bytes()
.map(|b| b as u32)
.sum::<u32>()
.wrapping_add(seed as u32);
hash_a.cmp(&hash_b)
});
}
nodes.into_iter().take(sample_size).collect()
} else {
projection.nodes.clone()
};
// Create mock centrality metrics for analyzed nodes
for node in &nodes_to_analyze {
let mut hash = node
.fingerprint
.bytes()
.map(|b| b as u32)
.sum::<u32>();
if let Some(seed) = sampling_seed {
hash = hash.wrapping_add(seed as u32);
}
let betweenness_score = (hash % 100) as f64 / 100.0;
centrality_metrics.push(CentralityMetrics {
fingerprint: node.fingerprint.clone(),
betweenness_centrality: Some(betweenness_score),
closeness_centrality: None,
});
}
// Calculate mock distribution
let scores: Vec<f64> = centrality_metrics
.iter()
.filter_map(|m| m.betweenness_centrality)
.collect();
let distribution = if !scores.is_empty() {
let min = scores
.iter()
.copied()
.fold(f64::INFINITY, f64::min);
let max = scores
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max);
let mean =
scores.iter().sum::<f64>() / scores.len() as f64;
// Sort scores for percentile calculation
let mut sorted_scores = scores.clone();
sorted_scores
.sort_by(|a, b| a.partial_cmp(b).unwrap());
let len = sorted_scores.len();
let get_percentile = |p: f64| -> f64 {
let index =
((len as f64 - 1.0) * p).round() as usize;
sorted_scores[index.min(len - 1)]
};
Some(CentralityDistribution {
min,
max,
mean,
p50: get_percentile(0.50),
p75: get_percentile(0.75),
p90: get_percentile(0.90),
p95: get_percentile(0.95),
p99: get_percentile(0.99),
p999: get_percentile(0.999),
})
} else {
None
};
Ok(CentralityAnalysisResult {
centrality_metrics,
total_nodes_analyzed: Some(nodes_to_analyze.len()),
betweenness_distribution: distribution,
closeness_distribution: None,
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_closeness_centrality(
&self,
projection_name: &str,
use_wasserman_faust: Option<bool>,
) -> Result<CentralityAnalysisResult, AnalysisError> {
self.increment_call_count("calculate_closeness_centrality");
if self.should_fail("calculate_closeness_centrality") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
match self.projections.read().unwrap().get(projection_name) {
Some(projection) => {
let mut centrality_metrics = Vec::new();
if projection.nodes.is_empty() {
return Ok(CentralityAnalysisResult {
centrality_metrics: vec![],
total_nodes_analyzed: Some(0),
betweenness_distribution: None,
closeness_distribution: None,
});
}
// Create mock centrality metrics for each node
for node in &projection.nodes {
let hash = node
.fingerprint
.bytes()
.map(|b| b as u32)
.sum::<u32>();
// Adjust scoring based on Wasserman-Faust parameter
let closeness_score =
if use_wasserman_faust.unwrap_or(false) {
(hash % 90 + 10) as f64 / 100.0 // 0.1 to 1.0
} else {
// Standard normalization
(hash % 80 + 20) as f64 / 100.0 // 0.2 to 1.0
};
centrality_metrics.push(CentralityMetrics {
fingerprint: node.fingerprint.clone(),
betweenness_centrality: None,
closeness_centrality: Some(closeness_score),
});
}
// Calculate mock distribution
let scores: Vec<f64> = centrality_metrics
.iter()
.filter_map(|m| m.closeness_centrality)
.collect();
let distribution = if !scores.is_empty() {
let min = scores
.iter()
.copied()
.fold(f64::INFINITY, f64::min);
let max = scores
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max);
let mean =
scores.iter().sum::<f64>() / scores.len() as f64;
// Sort scores for percentile calculation
let mut sorted_scores = scores.clone();
sorted_scores
.sort_by(|a, b| a.partial_cmp(b).unwrap());
let len = sorted_scores.len();
let get_percentile = |p: f64| -> f64 {
let index =
((len as f64 - 1.0) * p).round() as usize;
sorted_scores[index.min(len - 1)]
};
Some(CentralityDistribution {
min,
max,
mean,
p50: get_percentile(0.50),
p75: get_percentile(0.75),
p90: get_percentile(0.90),
p95: get_percentile(0.95),
p99: get_percentile(0.99),
p999: get_percentile(0.999),
})
} else {
None
};
Ok(CentralityAnalysisResult {
centrality_metrics,
total_nodes_analyzed: Some(projection.nodes.len()),
betweenness_distribution: None,
closeness_distribution: distribution,
})
}
None => Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
)),
}
}
async fn calculate_combined_centrality(
&self,
projection_name: &str,
betweenness_sampling_size: Option<usize>,
betweenness_sampling_seed: Option<u64>,
use_wasserman_faust: Option<bool>,
) -> Result<CentralityAnalysisResult, AnalysisError> {
self.increment_call_count("calculate_combined_centrality");
if self.should_fail("calculate_combined_centrality") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
// Call individual centrality methods and merge results
let betweenness_result = self
.calculate_betweenness_centrality(
projection_name,
betweenness_sampling_size,
betweenness_sampling_seed,
)
.await?;
let closeness_result = self
.calculate_closeness_centrality(
projection_name,
use_wasserman_faust,
)
.await?;
let mut combined_metrics = std::collections::HashMap::new();
// Add betweenness centrality metrics
for metric in betweenness_result.centrality_metrics {
combined_metrics.insert(metric.fingerprint.clone(), metric);
}
// Add closeness centrality metrics
for metric in closeness_result.centrality_metrics {
if let Some(existing) =
combined_metrics.get_mut(&metric.fingerprint)
{
existing.closeness_centrality =
metric.closeness_centrality;
} else {
combined_metrics
.insert(metric.fingerprint.clone(), metric);
}
}
let centrality_metrics: Vec<CentralityMetrics> =
combined_metrics.into_values().collect();
Ok(CentralityAnalysisResult {
centrality_metrics,
total_nodes_analyzed: betweenness_result.total_nodes_analyzed,
betweenness_distribution: betweenness_result
.betweenness_distribution,
closeness_distribution: closeness_result
.closeness_distribution,
})
}
async fn analyze_paths_between_communities(
&self,
projection_name: &str,
source_nodes: &[String],
target_nodes: &[String],
) -> Result<PathAnalysisResult, AnalysisError> {
self.increment_call_count("analyze_paths_between_communities");
if self.should_fail("analyze_paths_between_communities") {
return Err(AnalysisError::AlgorithmError(
"Mock failure".to_string(),
));
}
if !self.check_graph_projection_exists(projection_name).await? {
return Err(AnalysisError::ProjectionNotFound(
projection_name.to_string(),
));
}
let mut path_results = Vec::new();
for source in source_nodes {
for target in target_nodes {
if source != target {
// Mock high connectivity: 100% connected, length based on fingerprints
let path_length =
((source.len() + target.len()) % 10) + 4;
path_results.push(PathResult {
source_fingerprint: source.clone(),
target_fingerprint: target.clone(),
path_exists: true,
path_length: Some(path_length),
path_cost: Some(path_length as f64 - 1.0),
intermediate_nodes: Some(vec![]),
});
}
}
}
let connected_pairs =
path_results.iter().filter(|p| p.path_exists).count();
let total_pairs = path_results.len();
let average_path_length = if connected_pairs > 0 {
Some(
path_results
.iter()
.filter(|p| p.path_exists)
.map(|p| p.path_length.unwrap_or(0) as f64)
.sum::<f64>()
/ connected_pairs as f64,
)
} else {
None
};
let max_path_length = path_results
.iter()
.map(|p| p.path_length.unwrap_or(0))
.max();
let min_path_length = path_results
.iter()
.filter(|p| p.path_exists)
.map(|p| p.path_length.unwrap_or(0))
.min();
Ok(PathAnalysisResult {
path_results,
total_paths_analyzed: Some(total_pairs),
connected_community_pairs: Some(connected_pairs),
disconnected_community_pairs: Some(
total_pairs - connected_pairs,
),
average_path_length,
max_path_length,
min_path_length,
})
}
}
}
#[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
);
}
#[tokio::test]
async fn test_mock_path_analysis_with_self_loops() {
let db = MockDatabase::new().with_projection("test_proj", vec![]);
// Test with overlapping source and target nodes
let source_nodes = vec!["RELAY_A".to_string(), "RELAY_B".to_string()];
let target_nodes = vec!["RELAY_A".to_string(), "RELAY_C".to_string()]; // overlaps
let result = db
.analyze_paths_between_communities(
"test_proj",
&source_nodes,
&target_nodes,
)
.await
.expect("Path analysis should succeed");
// Total pairs should exclude self-loops: 2×2 - 1 overlap = 3
assert_eq!(result.total_paths_analyzed, Some(3));
assert_eq!(result.connected_community_pairs, Some(3));
assert_eq!(result.path_results.len(), 3);
// Verify no self-loops in results
for path in &result.path_results {
assert_ne!(path.source_fingerprint, path.target_fingerprint);
}
}
#[tokio::test]
async fn test_combined_centrality_functionality() {
let nodes = vec![
NodeMetrics {
fingerprint: "RELAY_A".to_string(),
in_degree: 5,
out_degree: 3,
total_degree: 8,
},
NodeMetrics {
fingerprint: "RELAY_B".to_string(),
in_degree: 2,
out_degree: 4,
total_degree: 6,
},
];
let db = MockDatabase::new().with_projection("test_combined", nodes);
let result = db
.calculate_combined_centrality(
"test_combined",
Some(1000),
Some(42),
Some(true),
)
.await
.expect("Combined centrality should succeed");
// Should have combined metrics for both nodes
assert_eq!(result.centrality_metrics.len(), 2);
assert!(result.total_nodes_analyzed.is_some());
assert!(result.betweenness_distribution.is_some());
assert!(result.closeness_distribution.is_some());
// Verify both centrality types are present
for metric in &result.centrality_metrics {
assert!(metric.betweenness_centrality.is_some());
assert!(metric.closeness_centrality.is_some());
}
}
#[tokio::test]
async fn test_centrality_with_sampling() {
let nodes = vec![
NodeMetrics {
fingerprint: "RELAY_A".to_string(),
in_degree: 5,
out_degree: 3,
total_degree: 8,
},
NodeMetrics {
fingerprint: "RELAY_B".to_string(),
in_degree: 2,
out_degree: 4,
total_degree: 6,
},
NodeMetrics {
fingerprint: "RELAY_C".to_string(),
in_degree: 1,
out_degree: 2,
total_degree: 3,
},
];
let db = MockDatabase::new().with_projection("test_sampling", nodes);
// Test with sampling
let result = db
.calculate_betweenness_centrality(
"test_sampling",
Some(2), // Sample only 2 nodes
Some(42),
)
.await
.expect("Betweenness centrality should succeed");
// Should only analyze 2 nodes due to sampling
assert_eq!(result.total_nodes_analyzed, Some(2));
assert_eq!(result.centrality_metrics.len(), 2);
// Test without sampling
let result_full = db
.calculate_betweenness_centrality("test_sampling", None, None)
.await
.expect("Betweenness centrality should succeed");
// Should analyze all 3 nodes
assert_eq!(result_full.total_nodes_analyzed, Some(3));
assert_eq!(result_full.centrality_metrics.len(), 3);
}
#[tokio::test]
async fn test_wasserman_faust_parameter() {
let nodes = vec![NodeMetrics {
fingerprint: "RELAY_A".to_string(),
in_degree: 5,
out_degree: 3,
total_degree: 8,
}];
let db = MockDatabase::new().with_projection("test_wf", nodes);
// Test with Wasserman-Faust
let result_wf = db
.calculate_closeness_centrality("test_wf", Some(true))
.await
.expect("Closeness centrality should succeed");
// Test without Wasserman-Faust
let result_normal = db
.calculate_closeness_centrality("test_wf", Some(false))
.await
.expect("Closeness centrality should succeed");
// Results should be different due to different scoring ranges
let wf_score = result_wf.centrality_metrics[0]
.closeness_centrality
.unwrap();
let normal_score = result_normal.centrality_metrics[0]
.closeness_centrality
.unwrap();
// Both should be valid but potentially different
assert!((0.0..=1.0).contains(&wf_score));
assert!((0.0..=1.0).contains(&normal_score));
}
#[tokio::test]
async fn test_projection_not_found_errors() {
let db = MockDatabase::new();
// Test centrality operations with non-existent projection
let result = db
.calculate_betweenness_centrality("non_existent", None, None)
.await;
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
AnalysisError::ProjectionNotFound(_)
));
let result = db
.calculate_closeness_centrality("non_existent", None)
.await;
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
AnalysisError::ProjectionNotFound(_)
));
let result = db
.analyze_paths_between_communities(
"non_existent",
&["A".to_string()],
&["B".to_string()],
)
.await;
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
AnalysisError::ProjectionNotFound(_)
));
}
}