freenet_test_network/
network.rs

1use crate::{docker::DockerNatBackend, peer::TestPeer, Error, Result};
2use chrono::Utc;
3use freenet_stdlib::{
4    client_api::{
5        ClientRequest, ConnectedPeerInfo, HostResponse, NodeDiagnosticsConfig, NodeQuery,
6        QueryResponse, SystemMetrics, WebApi,
7    },
8    prelude::ContractKey,
9};
10use regex::Regex;
11use serde::{Deserialize, Serialize};
12use serde_json::json;
13use std::{
14    collections::{HashMap, HashSet},
15    fs,
16    path::{Path, PathBuf},
17    sync::LazyLock,
18    time::Duration,
19};
20
21/// Detailed connectivity status for a single peer
22#[derive(Debug, Clone)]
23pub struct PeerConnectivityStatus {
24    pub peer_id: String,
25    pub connections: Option<usize>,
26    pub error: Option<String>,
27}
28
29/// Detailed connectivity check result
30#[derive(Debug)]
31pub struct ConnectivityStatus {
32    pub total_peers: usize,
33    pub connected_peers: usize,
34    pub ratio: f64,
35    pub peer_status: Vec<PeerConnectivityStatus>,
36}
37
38/// A test network consisting of gateways and peer nodes
39pub struct TestNetwork {
40    pub(crate) gateways: Vec<TestPeer>,
41    pub(crate) peers: Vec<TestPeer>,
42    pub(crate) min_connectivity: f64,
43    pub(crate) run_root: PathBuf,
44    /// Docker backend for NAT simulation (if used)
45    pub(crate) docker_backend: Option<DockerNatBackend>,
46}
47
48impl TestNetwork {
49    /// Create a new network builder
50    pub fn builder() -> crate::builder::NetworkBuilder {
51        crate::builder::NetworkBuilder::new()
52    }
53
54    /// Get a gateway peer by index
55    pub fn gateway(&self, index: usize) -> &TestPeer {
56        &self.gateways[index]
57    }
58
59    /// Get a non-gateway peer by index
60    pub fn peer(&self, index: usize) -> &TestPeer {
61        &self.peers[index]
62    }
63
64    /// Get all gateway WebSocket URLs
65    pub fn gateway_ws_urls(&self) -> Vec<String> {
66        self.gateways.iter().map(|p| p.ws_url()).collect()
67    }
68
69    /// Get all peer WebSocket URLs
70    pub fn peer_ws_urls(&self) -> Vec<String> {
71        self.peers.iter().map(|p| p.ws_url()).collect()
72    }
73
74    /// Wait until the network is ready for use
75    ///
76    /// This checks that peers have formed connections and the network
77    /// is sufficiently connected for testing.
78    pub async fn wait_until_ready(&self) -> Result<()> {
79        self.wait_until_ready_with_timeout(Duration::from_secs(30))
80            .await
81    }
82
83    /// Wait until the network is ready with a custom timeout
84    pub async fn wait_until_ready_with_timeout(&self, timeout: Duration) -> Result<()> {
85        let start = std::time::Instant::now();
86        let mut last_progress_log = std::time::Instant::now();
87        let progress_interval = Duration::from_secs(10);
88
89        tracing::info!(
90            "Waiting for network connectivity (timeout: {}s, required: {}%)",
91            timeout.as_secs(),
92            (self.min_connectivity * 100.0) as u8
93        );
94
95        loop {
96            if start.elapsed() > timeout {
97                // Log final detailed status on failure
98                let status = self.check_connectivity_detailed().await;
99                let details = Self::format_connectivity_status(&status);
100                tracing::error!(
101                    "Connectivity timeout: {}/{} peers connected ({:.1}%) - {}",
102                    status.connected_peers,
103                    status.total_peers,
104                    status.ratio * 100.0,
105                    details
106                );
107                return Err(Error::ConnectivityFailed(format!(
108                    "Network did not reach {}% connectivity within {}s",
109                    (self.min_connectivity * 100.0) as u8,
110                    timeout.as_secs()
111                )));
112            }
113
114            // Check connectivity with detailed status
115            let status = self.check_connectivity_detailed().await;
116
117            if status.ratio >= self.min_connectivity {
118                tracing::info!("Network ready: {:.1}% connectivity", status.ratio * 100.0);
119                return Ok(());
120            }
121
122            // Log progress periodically (every 10 seconds)
123            if last_progress_log.elapsed() >= progress_interval {
124                let elapsed = start.elapsed().as_secs();
125                let details = Self::format_connectivity_status(&status);
126                tracing::info!(
127                    "[{}s] Connectivity: {}/{} ({:.0}%) - {}",
128                    elapsed,
129                    status.connected_peers,
130                    status.total_peers,
131                    status.ratio * 100.0,
132                    details
133                );
134                last_progress_log = std::time::Instant::now();
135            } else {
136                tracing::debug!(
137                    "Network connectivity: {}/{} ({:.1}%)",
138                    status.connected_peers,
139                    status.total_peers,
140                    status.ratio * 100.0
141                );
142            }
143
144            tokio::time::sleep(Duration::from_millis(500)).await;
145        }
146    }
147
148    /// Check current network connectivity with detailed status
149    pub async fn check_connectivity_detailed(&self) -> ConnectivityStatus {
150        let all_peers: Vec<_> = self.gateways.iter().chain(self.peers.iter()).collect();
151        let total = all_peers.len();
152
153        if total == 0 {
154            return ConnectivityStatus {
155                total_peers: 0,
156                connected_peers: 0,
157                ratio: 1.0,
158                peer_status: vec![],
159            };
160        }
161
162        let mut connected_count = 0;
163        let mut peer_status = Vec::with_capacity(total);
164
165        for peer in &all_peers {
166            match self.query_peer_connections(peer).await {
167                Ok(0) => {
168                    peer_status.push(PeerConnectivityStatus {
169                        peer_id: peer.id().to_string(),
170                        connections: Some(0),
171                        error: None,
172                    });
173                }
174                Ok(connections) => {
175                    connected_count += 1;
176                    peer_status.push(PeerConnectivityStatus {
177                        peer_id: peer.id().to_string(),
178                        connections: Some(connections),
179                        error: None,
180                    });
181                }
182                Err(e) => {
183                    peer_status.push(PeerConnectivityStatus {
184                        peer_id: peer.id().to_string(),
185                        connections: None,
186                        error: Some(e.to_string()),
187                    });
188                }
189            }
190        }
191
192        let ratio = connected_count as f64 / total as f64;
193        ConnectivityStatus {
194            total_peers: total,
195            connected_peers: connected_count,
196            ratio,
197            peer_status,
198        }
199    }
200
201    /// Check current network connectivity ratio (0.0 to 1.0)
202    async fn check_connectivity(&self) -> Result<f64> {
203        let status = self.check_connectivity_detailed().await;
204        Ok(status.ratio)
205    }
206
207    /// Format connectivity status for logging
208    fn format_connectivity_status(status: &ConnectivityStatus) -> String {
209        let mut parts: Vec<String> = status
210            .peer_status
211            .iter()
212            .map(|p| match (&p.connections, &p.error) {
213                (Some(c), _) => format!("{}:{}", p.peer_id, c),
214                (None, Some(_)) => format!("{}:err", p.peer_id),
215                (None, None) => format!("{}:?", p.peer_id),
216            })
217            .collect();
218        parts.sort();
219        parts.join(", ")
220    }
221
222    /// Query a single peer for its connection count
223    async fn query_peer_connections(&self, peer: &TestPeer) -> Result<usize> {
224        use tokio_tungstenite::connect_async;
225
226        let url = format!("{}?encodingProtocol=native", peer.ws_url());
227        let (ws_stream, _) =
228            tokio::time::timeout(std::time::Duration::from_secs(5), connect_async(&url))
229                .await
230                .map_err(|_| Error::ConnectivityFailed(format!("Timeout connecting to {}", url)))?
231                .map_err(|e| {
232                    Error::ConnectivityFailed(format!("Failed to connect to {}: {}", url, e))
233                })?;
234
235        let mut client = WebApi::start(ws_stream);
236
237        client
238            .send(ClientRequest::NodeQueries(NodeQuery::ConnectedPeers))
239            .await
240            .map_err(|e| Error::ConnectivityFailed(format!("Failed to send query: {}", e)))?;
241
242        let response = tokio::time::timeout(std::time::Duration::from_secs(5), client.recv())
243            .await
244            .map_err(|_| Error::ConnectivityFailed("Timeout waiting for response".into()))?;
245
246        let result = match response {
247            Ok(HostResponse::QueryResponse(QueryResponse::ConnectedPeers { peers })) => {
248                Ok(peers.len())
249            }
250            Ok(other) => Err(Error::ConnectivityFailed(format!(
251                "Unexpected response: {:?}",
252                other
253            ))),
254            Err(e) => Err(Error::ConnectivityFailed(format!("Query failed: {}", e))),
255        };
256
257        client.disconnect("connectivity probe").await;
258
259        result
260    }
261
262    /// Get the current network topology
263    pub async fn topology(&self) -> Result<NetworkTopology> {
264        // TODO: Query peers for their connections and build topology
265        Ok(NetworkTopology {
266            peers: vec![],
267            connections: vec![],
268        })
269    }
270
271    /// Export network information in JSON format for visualization tools
272    pub fn export_for_viz(&self) -> String {
273        let peers: Vec<_> = self
274            .gateways
275            .iter()
276            .chain(self.peers.iter())
277            .map(|p| {
278                serde_json::json!({
279                    "id": p.id(),
280                    "is_gateway": p.is_gateway(),
281                    "ws_port": p.ws_port,
282                    "network_port": p.network_port,
283                })
284            })
285            .collect();
286
287        serde_json::to_string_pretty(&serde_json::json!({
288            "peers": peers
289        }))
290        .unwrap_or_default()
291    }
292
293    /// Collect diagnostics from every peer, returning a snapshot that can be serialized to JSON
294    /// for offline analysis.
295    pub async fn collect_diagnostics(&self) -> Result<NetworkDiagnosticsSnapshot> {
296        let mut peers = Vec::with_capacity(self.gateways.len() + self.peers.len());
297        for peer in self.gateways.iter().chain(self.peers.iter()) {
298            peers.push(self.query_peer_diagnostics(peer).await);
299        }
300        peers.sort_by(|a, b| a.peer_id.cmp(&b.peer_id));
301        Ok(NetworkDiagnosticsSnapshot {
302            collected_at: Utc::now(),
303            peers,
304        })
305    }
306
307    async fn query_peer_diagnostics(&self, peer: &TestPeer) -> PeerDiagnosticsSnapshot {
308        use tokio_tungstenite::connect_async;
309
310        let mut snapshot = PeerDiagnosticsSnapshot::new(peer);
311        let url = format!("{}?encodingProtocol=native", peer.ws_url());
312        match tokio::time::timeout(std::time::Duration::from_secs(10), connect_async(&url)).await {
313            Ok(Ok((ws_stream, _))) => {
314                let mut client = WebApi::start(ws_stream);
315                let config = NodeDiagnosticsConfig {
316                    include_node_info: true,
317                    include_network_info: true,
318                    include_subscriptions: false,
319                    contract_keys: vec![],
320                    include_system_metrics: true,
321                    include_detailed_peer_info: true,
322                    include_subscriber_peer_ids: false,
323                };
324                if let Err(err) = client
325                    .send(ClientRequest::NodeQueries(NodeQuery::NodeDiagnostics {
326                        config,
327                    }))
328                    .await
329                {
330                    snapshot.error = Some(format!("failed to send diagnostics request: {err}"));
331                    return snapshot;
332                }
333                match tokio::time::timeout(std::time::Duration::from_secs(10), client.recv()).await
334                {
335                    Ok(Ok(HostResponse::QueryResponse(QueryResponse::NodeDiagnostics(
336                        response,
337                    )))) => {
338                        let node_info = response.node_info;
339                        let network_info = response.network_info;
340                        snapshot.peer_id = node_info
341                            .as_ref()
342                            .map(|info| info.peer_id.clone())
343                            .unwrap_or_else(|| peer.id().to_string());
344                        snapshot.is_gateway = node_info
345                            .as_ref()
346                            .map(|info| info.is_gateway)
347                            .unwrap_or_else(|| peer.is_gateway());
348                        snapshot.location =
349                            node_info.as_ref().and_then(|info| info.location.clone());
350                        snapshot.listening_address = node_info
351                            .as_ref()
352                            .and_then(|info| info.listening_address.clone());
353                        if let Some(info) = network_info {
354                            snapshot.active_connections = Some(info.active_connections);
355                            snapshot.connected_peer_ids = info
356                                .connected_peers
357                                .into_iter()
358                                .map(|(peer_id, _)| peer_id)
359                                .collect();
360                        }
361                        snapshot.connected_peers_detailed = response.connected_peers_detailed;
362                        snapshot.system_metrics = response.system_metrics;
363                    }
364                    Ok(Ok(other)) => {
365                        snapshot.error =
366                            Some(format!("unexpected diagnostics response: {:?}", other));
367                    }
368                    Ok(Err(err)) => {
369                        snapshot.error = Some(format!("diagnostics channel error: {err}"));
370                    }
371                    Err(_) => {
372                        snapshot.error = Some("timeout waiting for diagnostics response".into());
373                    }
374                }
375            }
376            Ok(Err(err)) => {
377                snapshot.error = Some(format!("failed to connect websocket: {err}"));
378            }
379            Err(_) => {
380                snapshot.error = Some("timeout establishing diagnostics websocket".into());
381            }
382        }
383        snapshot
384    }
385
386    /// Collect per-peer ring data (locations + adjacency) for visualization/debugging.
387    pub async fn ring_snapshot(&self) -> Result<Vec<RingPeerSnapshot>> {
388        self.collect_ring_snapshot(None).await
389    }
390
391    async fn collect_ring_snapshot(
392        &self,
393        contract_key: Option<&ContractKey>,
394    ) -> Result<Vec<RingPeerSnapshot>> {
395        let mut snapshots = Vec::with_capacity(self.gateways.len() + self.peers.len());
396        for peer in self.gateways.iter().chain(self.peers.iter()) {
397            snapshots.push(query_ring_snapshot(peer, contract_key).await?);
398        }
399        snapshots.sort_by(|a, b| a.id.cmp(&b.id));
400        Ok(snapshots)
401    }
402
403    /// Generate an interactive HTML ring visualization for the current network.
404    pub async fn write_ring_visualization<P: AsRef<Path>>(&self, output_path: P) -> Result<()> {
405        self.write_ring_visualization_internal(output_path, None)
406            .await
407    }
408
409    /// Generate an interactive HTML ring visualization for a specific contract.
410    pub async fn write_ring_visualization_for_contract<P: AsRef<Path>>(
411        &self,
412        output_path: P,
413        contract_id: &str,
414    ) -> Result<()> {
415        let contract_id_owned = contract_id.to_string();
416        let contract_key = ContractKey::from_id(contract_id_owned.clone()).map_err(|err| {
417            Error::Other(anyhow::anyhow!(
418                "invalid contract key {}: {}",
419                contract_id,
420                err
421            ))
422        })?;
423        self.write_ring_visualization_internal(
424            output_path,
425            Some((&contract_key, contract_id_owned.as_str())),
426        )
427        .await
428    }
429
430    async fn write_ring_visualization_internal<P: AsRef<Path>>(
431        &self,
432        output_path: P,
433        contract: Option<(&ContractKey, &str)>,
434    ) -> Result<()> {
435        let (snapshots, contract_viz) = if let Some((contract_key, contract_id)) = contract {
436            let snapshots = self.collect_ring_snapshot(Some(contract_key)).await?;
437            let caching_peers = snapshots
438                .iter()
439                .filter(|peer| {
440                    peer.contract
441                        .as_ref()
442                        .map(|state| state.stores_contract)
443                        .unwrap_or(false)
444                })
445                .map(|peer| peer.id.clone())
446                .collect::<Vec<_>>();
447            let contract_location = contract_location_from_key(contract_key);
448            let flow = self.collect_contract_flow(contract_id, &snapshots)?;
449            let viz = ContractVizData {
450                key: contract_id.to_string(),
451                location: contract_location,
452                caching_peers,
453                put: OperationPath {
454                    edges: flow.put_edges,
455                    completion_peer: flow.put_completion_peer,
456                },
457                update: OperationPath {
458                    edges: flow.update_edges,
459                    completion_peer: flow.update_completion_peer,
460                },
461                errors: flow.errors,
462            };
463            (snapshots, Some(viz))
464        } else {
465            (self.collect_ring_snapshot(None).await?, None)
466        };
467
468        let metrics = compute_ring_metrics(&snapshots);
469        let payload = json!({
470            "generated_at": Utc::now().to_rfc3339(),
471            "run_root": self.run_root.display().to_string(),
472            "nodes": snapshots,
473            "metrics": metrics,
474            "contract": contract_viz,
475        });
476        let data_json = serde_json::to_string(&payload).map_err(|e| Error::Other(e.into()))?;
477        let html = render_ring_template(&data_json);
478        let out_path = output_path.as_ref();
479        if let Some(parent) = out_path.parent() {
480            if !parent.exists() {
481                fs::create_dir_all(parent)?;
482            }
483        }
484        fs::write(out_path, html)?;
485        tracing::info!(path = %out_path.display(), "Wrote ring visualization");
486        Ok(())
487    }
488
489    fn collect_contract_flow(
490        &self,
491        contract_id: &str,
492        peers: &[RingPeerSnapshot],
493    ) -> Result<ContractFlowData> {
494        let mut data = ContractFlowData::default();
495        let logs = self.read_logs()?;
496        for entry in logs {
497            if !entry.message.contains(contract_id) {
498                continue;
499            }
500            if let Some(caps) = PUT_REQUEST_RE.captures(&entry.message) {
501                if &caps["key"] != contract_id {
502                    continue;
503                }
504                data.put_edges.push(ContractOperationEdge {
505                    from: caps["from"].to_string(),
506                    to: caps["to"].to_string(),
507                    timestamp: entry.timestamp.map(|ts| ts.to_rfc3339()),
508                    log_level: entry.level.clone(),
509                    log_source: Some(entry.peer_id.clone()),
510                    message: entry.message.clone(),
511                });
512                continue;
513            }
514            if let Some(caps) = PUT_COMPLETION_RE.captures(&entry.message) {
515                if &caps["key"] != contract_id {
516                    continue;
517                }
518                data.put_completion_peer = Some(caps["peer"].to_string());
519                continue;
520            }
521            if let Some(caps) = UPDATE_PROPAGATION_RE.captures(&entry.message) {
522                if &caps["contract"] != contract_id {
523                    continue;
524                }
525                let from = caps["from"].to_string();
526                let ts = entry.timestamp.map(|ts| ts.to_rfc3339());
527                let level = entry.level.clone();
528                let source = Some(entry.peer_id.clone());
529                let targets = caps["targets"].trim();
530                if !targets.is_empty() {
531                    for prefix in targets.split(',').filter(|s| !s.is_empty()) {
532                        if let Some(resolved) = resolve_peer_id(prefix, peers) {
533                            data.update_edges.push(ContractOperationEdge {
534                                from: from.clone(),
535                                to: resolved,
536                                timestamp: ts.clone(),
537                                log_level: level.clone(),
538                                log_source: source.clone(),
539                                message: entry.message.clone(),
540                            });
541                        }
542                    }
543                }
544                continue;
545            }
546            if let Some(caps) = UPDATE_NO_TARGETS_RE.captures(&entry.message) {
547                if &caps["contract"] != contract_id {
548                    continue;
549                }
550                data.errors.push(entry.message.clone());
551                continue;
552            }
553            if entry.message.contains("update will not propagate") {
554                data.errors.push(entry.message.clone());
555            }
556        }
557        Ok(data)
558    }
559
560    /// Dump logs from all peers, optionally filtered by a pattern
561    ///
562    /// If `filter` is Some, only logs containing the pattern (case-insensitive) are printed.
563    /// Logs are printed in chronological order with peer ID prefix.
564    ///
565    /// This is useful for debugging test failures - call it before assertions or in error handlers.
566    pub fn dump_logs(&self, filter: Option<&str>) {
567        match self.read_logs() {
568            Ok(mut entries) => {
569                // Sort by timestamp
570                entries.sort_by(|a, b| match (&a.timestamp, &b.timestamp) {
571                    (Some(ta), Some(tb)) => ta.cmp(tb),
572                    (Some(_), None) => std::cmp::Ordering::Less,
573                    (None, Some(_)) => std::cmp::Ordering::Greater,
574                    (None, None) => std::cmp::Ordering::Equal,
575                });
576
577                let filter_lower = filter.map(|f| f.to_lowercase());
578                let mut count = 0;
579
580                println!("--- Peer Logs {} ---",
581                    filter.map(|f| format!("(filtered: '{}')", f)).unwrap_or_default());
582
583                for entry in &entries {
584                    let matches = filter_lower
585                        .as_ref()
586                        .map(|f| entry.message.to_lowercase().contains(f))
587                        .unwrap_or(true);
588
589                    if matches {
590                        let ts = entry.timestamp_raw.as_deref().unwrap_or("?");
591                        let level = entry.level.as_deref().unwrap_or("?");
592                        println!("[{}] {} [{}] {}", entry.peer_id, ts, level, entry.message);
593                        count += 1;
594                    }
595                }
596
597                println!("--- End Peer Logs ({} entries) ---", count);
598            }
599            Err(e) => {
600                println!("--- Failed to read logs: {} ---", e);
601            }
602        }
603    }
604
605    /// Dump logs related to connection establishment and NAT traversal
606    ///
607    /// Filters for: hole punch, NAT, connect, acceptor, joiner, handshake
608    pub fn dump_connection_logs(&self) {
609        match self.read_logs() {
610            Ok(mut entries) => {
611                entries.sort_by(|a, b| match (&a.timestamp, &b.timestamp) {
612                    (Some(ta), Some(tb)) => ta.cmp(tb),
613                    (Some(_), None) => std::cmp::Ordering::Less,
614                    (None, Some(_)) => std::cmp::Ordering::Greater,
615                    (None, None) => std::cmp::Ordering::Equal,
616                });
617
618                let keywords = [
619                    "hole", "punch", "nat", "traverse", "acceptor", "joiner",
620                    "handshake", "outbound", "inbound", "connect:", "connection",
621                ];
622
623                println!("--- Connection/NAT Logs ---");
624                let mut count = 0;
625
626                for entry in &entries {
627                    let msg_lower = entry.message.to_lowercase();
628                    let matches = keywords.iter().any(|kw| msg_lower.contains(kw));
629
630                    if matches {
631                        let ts = entry.timestamp_raw.as_deref().unwrap_or("?");
632                        let level = entry.level.as_deref().unwrap_or("?");
633                        println!("[{}] {} [{}] {}", entry.peer_id, ts, level, entry.message);
634                        count += 1;
635                    }
636                }
637
638                println!("--- End Connection/NAT Logs ({} entries) ---", count);
639            }
640            Err(e) => {
641                println!("--- Failed to read logs: {} ---", e);
642            }
643        }
644    }
645}
646
647impl TestNetwork {
648    pub(crate) fn new(
649        gateways: Vec<TestPeer>,
650        peers: Vec<TestPeer>,
651        min_connectivity: f64,
652        run_root: PathBuf,
653    ) -> Self {
654        Self {
655            gateways,
656            peers,
657            min_connectivity,
658            run_root,
659            docker_backend: None,
660        }
661    }
662
663    pub(crate) fn new_with_docker(
664        gateways: Vec<TestPeer>,
665        peers: Vec<TestPeer>,
666        min_connectivity: f64,
667        run_root: PathBuf,
668        docker_backend: Option<DockerNatBackend>,
669    ) -> Self {
670        Self {
671            gateways,
672            peers,
673            min_connectivity,
674            run_root,
675            docker_backend,
676        }
677    }
678
679    /// Directory containing all peer state/logs for this test network run.
680    pub fn run_root(&self) -> &std::path::Path {
681        &self.run_root
682    }
683}
684
685/// Snapshot describing diagnostics collected across the network at a moment in time.
686#[derive(Debug, Clone, Serialize, Deserialize)]
687pub struct NetworkDiagnosticsSnapshot {
688    pub collected_at: chrono::DateTime<Utc>,
689    pub peers: Vec<PeerDiagnosticsSnapshot>,
690}
691
692/// Diagnostic information for a single peer.
693#[derive(Debug, Clone, Serialize, Deserialize)]
694pub struct PeerDiagnosticsSnapshot {
695    pub peer_id: String,
696    pub is_gateway: bool,
697    pub ws_url: String,
698    pub location: Option<String>,
699    pub listening_address: Option<String>,
700    pub connected_peer_ids: Vec<String>,
701    pub connected_peers_detailed: Vec<ConnectedPeerInfo>,
702    pub active_connections: Option<usize>,
703    pub system_metrics: Option<SystemMetrics>,
704    pub error: Option<String>,
705}
706
707impl PeerDiagnosticsSnapshot {
708    fn new(peer: &TestPeer) -> Self {
709        Self {
710            peer_id: peer.id().to_string(),
711            is_gateway: peer.is_gateway(),
712            ws_url: peer.ws_url(),
713            location: None,
714            listening_address: None,
715            connected_peer_ids: Vec::new(),
716            connected_peers_detailed: Vec::new(),
717            active_connections: None,
718            system_metrics: None,
719            error: None,
720        }
721    }
722}
723
724/// Snapshot describing a peer's ring metadata and adjacency.
725#[derive(Debug, Clone, Serialize)]
726pub struct RingPeerSnapshot {
727    pub id: String,
728    pub is_gateway: bool,
729    pub ws_port: u16,
730    pub network_port: u16,
731    pub network_address: String,
732    #[serde(skip_serializing_if = "Option::is_none")]
733    pub location: Option<f64>,
734    pub connections: Vec<String>,
735    #[serde(skip_serializing_if = "Option::is_none")]
736    pub contract: Option<PeerContractStatus>,
737}
738
739/// Convert a diagnostics snapshot into the ring snapshot format used by the visualization.
740pub fn ring_nodes_from_diagnostics(snapshot: &NetworkDiagnosticsSnapshot) -> Vec<RingPeerSnapshot> {
741    snapshot
742        .peers
743        .iter()
744        .map(|peer| {
745            let location = peer
746                .location
747                .as_deref()
748                .and_then(|loc| loc.parse::<f64>().ok());
749            let (network_address, network_port) =
750                parse_listening_address(peer.listening_address.as_ref(), &peer.ws_url);
751            let ws_port = parse_ws_port(&peer.ws_url);
752            let mut connections = peer.connected_peer_ids.clone();
753            connections.retain(|id| id != &peer.peer_id);
754            connections.sort();
755            connections.dedup();
756
757            RingPeerSnapshot {
758                id: peer.peer_id.clone(),
759                is_gateway: peer.is_gateway,
760                ws_port,
761                network_port,
762                network_address,
763                location,
764                connections,
765                contract: None,
766            }
767        })
768        .collect()
769}
770
771/// Render a ring visualization from a saved diagnostics snapshot (e.g. a large soak run).
772pub fn write_ring_visualization_from_diagnostics<P: AsRef<Path>, Q: AsRef<Path>>(
773    snapshot: &NetworkDiagnosticsSnapshot,
774    run_root: P,
775    output_path: Q,
776) -> Result<()> {
777    let nodes = ring_nodes_from_diagnostics(snapshot);
778    let metrics = compute_ring_metrics(&nodes);
779    let payload = json!({
780        "generated_at": snapshot.collected_at.to_rfc3339(),
781        "run_root": run_root.as_ref().display().to_string(),
782        "nodes": nodes,
783        "metrics": metrics,
784    });
785    let data_json = serde_json::to_string(&payload).map_err(|e| Error::Other(e.into()))?;
786    let html = render_ring_template(&data_json);
787    let out_path = output_path.as_ref();
788    if let Some(parent) = out_path.parent() {
789        if !parent.exists() {
790            fs::create_dir_all(parent)?;
791        }
792    }
793    fs::write(out_path, html)?;
794    tracing::info!(path = %out_path.display(), "Wrote ring visualization from diagnostics");
795    Ok(())
796}
797
798/// Contract-specific status for a peer when a contract key is provided.
799#[derive(Debug, Clone, Serialize)]
800pub struct PeerContractStatus {
801    pub stores_contract: bool,
802    pub subscribed_locally: bool,
803    pub subscriber_peer_ids: Vec<String>,
804    pub subscriber_count: usize,
805}
806
807#[derive(Debug, Clone, Serialize)]
808pub struct ContractVizData {
809    pub key: String,
810    pub location: f64,
811    pub caching_peers: Vec<String>,
812    pub put: OperationPath,
813    pub update: OperationPath,
814    pub errors: Vec<String>,
815}
816
817#[derive(Debug, Clone, Serialize)]
818pub struct OperationPath {
819    pub edges: Vec<ContractOperationEdge>,
820    #[serde(skip_serializing_if = "Option::is_none")]
821    pub completion_peer: Option<String>,
822}
823
824#[derive(Debug, Clone, Serialize)]
825pub struct ContractOperationEdge {
826    pub from: String,
827    pub to: String,
828    #[serde(skip_serializing_if = "Option::is_none")]
829    pub timestamp: Option<String>,
830    #[serde(skip_serializing_if = "Option::is_none")]
831    pub log_level: Option<String>,
832    #[serde(skip_serializing_if = "Option::is_none")]
833    pub log_source: Option<String>,
834    pub message: String,
835}
836
837/// Aggregated metrics that help reason about small-world properties.
838#[derive(Debug, Clone, Serialize)]
839pub struct RingVizMetrics {
840    pub node_count: usize,
841    pub gateway_count: usize,
842    pub edge_count: usize,
843    pub average_degree: f64,
844    #[serde(skip_serializing_if = "Option::is_none")]
845    pub average_ring_distance: Option<f64>,
846    #[serde(skip_serializing_if = "Option::is_none")]
847    pub min_ring_distance: Option<f64>,
848    #[serde(skip_serializing_if = "Option::is_none")]
849    pub max_ring_distance: Option<f64>,
850    #[serde(skip_serializing_if = "Option::is_none")]
851    pub pct_edges_under_5pct: Option<f64>,
852    #[serde(skip_serializing_if = "Option::is_none")]
853    pub pct_edges_under_10pct: Option<f64>,
854    #[serde(skip_serializing_if = "Option::is_none")]
855    pub short_over_long_ratio: Option<f64>,
856    #[serde(skip_serializing_if = "Vec::is_empty")]
857    pub distance_histogram: Vec<RingDistanceBucket>,
858}
859
860#[derive(Debug, Clone, Serialize)]
861pub struct RingDistanceBucket {
862    pub upper_bound: f64,
863    pub count: usize,
864}
865
866/// Network topology information
867#[derive(Debug, Clone, Serialize, Deserialize)]
868pub struct NetworkTopology {
869    pub peers: Vec<PeerInfo>,
870    pub connections: Vec<Connection>,
871}
872
873/// Information about a peer in the network
874#[derive(Debug, Clone, Serialize, Deserialize)]
875pub struct PeerInfo {
876    pub id: String,
877    pub is_gateway: bool,
878    pub ws_port: u16,
879}
880
881/// A connection between two peers
882#[derive(Debug, Clone, Serialize, Deserialize)]
883pub struct Connection {
884    pub from: String,
885    pub to: String,
886}
887
888#[derive(Default)]
889struct ContractFlowData {
890    put_edges: Vec<ContractOperationEdge>,
891    put_completion_peer: Option<String>,
892    update_edges: Vec<ContractOperationEdge>,
893    update_completion_peer: Option<String>,
894    errors: Vec<String>,
895}
896
897async fn query_ring_snapshot(
898    peer: &TestPeer,
899    contract_key: Option<&ContractKey>,
900) -> Result<RingPeerSnapshot> {
901    use tokio_tungstenite::connect_async;
902
903    let url = format!("{}?encodingProtocol=native", peer.ws_url());
904    let (ws_stream, _) = tokio::time::timeout(Duration::from_secs(5), connect_async(&url))
905        .await
906        .map_err(|_| Error::ConnectivityFailed(format!("Timeout connecting to {}", peer.id())))?
907        .map_err(|e| {
908            Error::ConnectivityFailed(format!("Failed to connect to {}: {}", peer.id(), e))
909        })?;
910
911    let mut client = WebApi::start(ws_stream);
912    let diag_config = if let Some(key) = contract_key {
913        NodeDiagnosticsConfig {
914            include_node_info: true,
915            include_network_info: true,
916            include_subscriptions: true,
917            contract_keys: vec![key.clone()],
918            include_system_metrics: false,
919            include_detailed_peer_info: true,
920            include_subscriber_peer_ids: true,
921        }
922    } else {
923        NodeDiagnosticsConfig::basic_status()
924    };
925
926    client
927        .send(ClientRequest::NodeQueries(NodeQuery::NodeDiagnostics {
928            config: diag_config,
929        }))
930        .await
931        .map_err(|e| {
932            Error::ConnectivityFailed(format!(
933                "Failed to send diagnostics to {}: {}",
934                peer.id(),
935                e
936            ))
937        })?;
938
939    let response = tokio::time::timeout(Duration::from_secs(5), client.recv())
940        .await
941        .map_err(|_| {
942            Error::ConnectivityFailed(format!(
943                "Timeout waiting for diagnostics response from {}",
944                peer.id()
945            ))
946        })?;
947
948    let diag = match response {
949        Ok(HostResponse::QueryResponse(QueryResponse::NodeDiagnostics(diag))) => diag,
950        Ok(other) => {
951            client.disconnect("ring snapshot error").await;
952            return Err(Error::ConnectivityFailed(format!(
953                "Unexpected diagnostics response from {}: {:?}",
954                peer.id(),
955                other
956            )));
957        }
958        Err(e) => {
959            client.disconnect("ring snapshot error").await;
960            return Err(Error::ConnectivityFailed(format!(
961                "Diagnostics query failed for {}: {}",
962                peer.id(),
963                e
964            )));
965        }
966    };
967
968    let node_info = diag.node_info.ok_or_else(|| {
969        Error::ConnectivityFailed(format!("{} did not return node_info", peer.id()))
970    })?;
971
972    let location = node_info
973        .location
974        .as_deref()
975        .and_then(|value| value.parse::<f64>().ok());
976
977    let mut connections: Vec<String> = diag
978        .connected_peers_detailed
979        .into_iter()
980        .map(|info| info.peer_id)
981        .collect();
982
983    if connections.is_empty() {
984        if let Some(network_info) = diag.network_info {
985            connections = network_info
986                .connected_peers
987                .into_iter()
988                .map(|(peer_id, _)| peer_id)
989                .collect();
990        }
991    }
992
993    connections.retain(|conn| conn != &node_info.peer_id);
994    connections.sort();
995    connections.dedup();
996
997    let contract_status = contract_key.and_then(|key| {
998        let (stores_contract, subscriber_count, subscriber_peer_ids) =
999            if let Some(state) = diag.contract_states.get(key) {
1000                (
1001                    true,
1002                    state.subscribers as usize,
1003                    state.subscriber_peer_ids.clone(),
1004                )
1005            } else {
1006                (false, 0, Vec::new())
1007            };
1008        let subscribed_locally = diag
1009            .subscriptions
1010            .iter()
1011            .any(|sub| &sub.contract_key == key);
1012        if stores_contract || subscribed_locally {
1013            Some(PeerContractStatus {
1014                stores_contract,
1015                subscribed_locally,
1016                subscriber_peer_ids,
1017                subscriber_count,
1018            })
1019        } else {
1020            None
1021        }
1022    });
1023
1024    client.disconnect("ring snapshot complete").await;
1025
1026    Ok(RingPeerSnapshot {
1027        id: node_info.peer_id,
1028        is_gateway: node_info.is_gateway,
1029        ws_port: peer.ws_port,
1030        network_port: peer.network_port,
1031        network_address: peer.network_address.clone(),
1032        location,
1033        connections,
1034        contract: contract_status,
1035    })
1036}
1037
1038fn compute_ring_metrics(nodes: &[RingPeerSnapshot]) -> RingVizMetrics {
1039    let node_count = nodes.len();
1040    let gateway_count = nodes.iter().filter(|peer| peer.is_gateway).count();
1041    let mut total_degree = 0usize;
1042    let mut unique_edges: HashSet<(String, String)> = HashSet::new();
1043
1044    for node in nodes {
1045        total_degree += node.connections.len();
1046        for neighbor in &node.connections {
1047            if neighbor == &node.id {
1048                continue;
1049            }
1050            let edge = if node.id < *neighbor {
1051                (node.id.clone(), neighbor.clone())
1052            } else {
1053                (neighbor.clone(), node.id.clone())
1054            };
1055            unique_edges.insert(edge);
1056        }
1057    }
1058
1059    let average_degree = if node_count == 0 {
1060        0.0
1061    } else {
1062        total_degree as f64 / node_count as f64
1063    };
1064
1065    let mut location_lookup = HashMap::new();
1066    for node in nodes {
1067        if let Some(loc) = node.location {
1068            location_lookup.insert(node.id.clone(), loc);
1069        }
1070    }
1071
1072    let mut distances = Vec::new();
1073    for (a, b) in &unique_edges {
1074        if let (Some(loc_a), Some(loc_b)) = (location_lookup.get(a), location_lookup.get(b)) {
1075            let mut distance = (loc_a - loc_b).abs();
1076            if distance > 0.5 {
1077                distance = 1.0 - distance;
1078            }
1079            distances.push(distance);
1080        }
1081    }
1082
1083    let average_ring_distance = if distances.is_empty() {
1084        None
1085    } else {
1086        Some(distances.iter().sum::<f64>() / distances.len() as f64)
1087    };
1088    let min_ring_distance = distances.iter().cloned().reduce(f64::min);
1089    let max_ring_distance = distances.iter().cloned().reduce(f64::max);
1090    let pct_edges_under_5pct = calculate_percentage(&distances, 0.05);
1091    let pct_edges_under_10pct = calculate_percentage(&distances, 0.10);
1092
1093    let short_edges = distances.iter().filter(|d| **d <= 0.10).count();
1094    let long_edges = distances
1095        .iter()
1096        .filter(|d| **d > 0.10 && **d <= 0.50)
1097        .count();
1098    let short_over_long_ratio = if short_edges == 0 || long_edges == 0 {
1099        None
1100    } else {
1101        Some(short_edges as f64 / long_edges as f64)
1102    };
1103
1104    let mut distance_histogram = Vec::new();
1105    let bucket_bounds: Vec<f64> = (1..=5).map(|i| i as f64 * 0.10).collect(); // 0.1 buckets up to 0.5
1106    let mut cumulative = 0usize;
1107    for bound in bucket_bounds {
1108        let up_to_bound = distances.iter().filter(|d| **d <= bound).count();
1109        let count = up_to_bound.saturating_sub(cumulative);
1110        cumulative = up_to_bound;
1111        distance_histogram.push(RingDistanceBucket {
1112            upper_bound: bound,
1113            count,
1114        });
1115    }
1116
1117    RingVizMetrics {
1118        node_count,
1119        gateway_count,
1120        edge_count: unique_edges.len(),
1121        average_degree,
1122        average_ring_distance,
1123        min_ring_distance,
1124        max_ring_distance,
1125        pct_edges_under_5pct,
1126        pct_edges_under_10pct,
1127        short_over_long_ratio,
1128        distance_histogram,
1129    }
1130}
1131
1132fn calculate_percentage(distances: &[f64], threshold: f64) -> Option<f64> {
1133    if distances.is_empty() {
1134        return None;
1135    }
1136    let matching = distances.iter().filter(|value| **value < threshold).count();
1137    Some((matching as f64 / distances.len() as f64) * 100.0)
1138}
1139
1140fn parse_ws_port(ws_url: &str) -> u16 {
1141    ws_url
1142        .split("://")
1143        .nth(1)
1144        .and_then(|rest| rest.split('/').next())
1145        .and_then(|host_port| host_port.split(':').nth(1))
1146        .and_then(|port| port.parse().ok())
1147        .unwrap_or(0)
1148}
1149
1150fn parse_listening_address(addr: Option<&String>, ws_url: &str) -> (String, u16) {
1151    if let Some(addr) = addr {
1152        let mut parts = addr.split(':');
1153        let host = parts.next().unwrap_or("").to_string();
1154        let port = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
1155        (host, port)
1156    } else {
1157        let host = ws_url
1158            .split("://")
1159            .nth(1)
1160            .and_then(|rest| rest.split('/').next())
1161            .and_then(|host_port| host_port.split(':').next())
1162            .unwrap_or_default()
1163            .to_string();
1164        (host, 0)
1165    }
1166}
1167
1168fn resolve_peer_id(prefix: &str, peers: &[RingPeerSnapshot]) -> Option<String> {
1169    let needle = prefix.trim().trim_matches(|c| c == '"' || c == '\'');
1170    peers
1171        .iter()
1172        .find(|peer| peer.id.starts_with(needle))
1173        .map(|peer| peer.id.clone())
1174}
1175
1176fn contract_location_from_key(key: &ContractKey) -> f64 {
1177    let mut value = 0.0;
1178    let mut divisor = 256.0;
1179    for byte in key.as_bytes() {
1180        value += f64::from(*byte) / divisor;
1181        divisor *= 256.0;
1182    }
1183    value.fract()
1184}
1185
1186static PUT_REQUEST_RE: LazyLock<Regex> = LazyLock::new(|| {
1187    Regex::new(r"Requesting put for contract (?P<key>\S+) from (?P<from>\S+) to (?P<to>\S+)")
1188        .expect("valid regex")
1189});
1190static PUT_COMPLETION_RE: LazyLock<Regex> = LazyLock::new(|| {
1191    Regex::new(r"Peer completed contract value put,.*key: (?P<key>\S+),.*this_peer: (?P<peer>\S+)")
1192        .expect("valid regex")
1193});
1194static UPDATE_PROPAGATION_RE: LazyLock<Regex> = LazyLock::new(|| {
1195    Regex::new(
1196        r"UPDATE_PROPAGATION: contract=(?P<contract>\S+) from=(?P<from>\S+) targets=(?P<targets>[^ ]*)\s+count=",
1197    )
1198    .expect("valid regex")
1199});
1200static UPDATE_NO_TARGETS_RE: LazyLock<Regex> = LazyLock::new(|| {
1201    Regex::new(r"UPDATE_PROPAGATION: contract=(?P<contract>\S+) from=(?P<from>\S+) NO_TARGETS")
1202        .expect("valid regex")
1203});
1204
1205const HTML_TEMPLATE: &str = r###"<!DOCTYPE html>
1206<html lang="en">
1207<head>
1208  <meta charset="UTF-8" />
1209  <title>Freenet Ring Topology</title>
1210  <style>
1211    :root {
1212      color-scheme: dark;
1213      font-family: "Inter", "Helvetica Neue", Arial, sans-serif;
1214    }
1215    body {
1216      background: #020617;
1217      color: #e2e8f0;
1218      margin: 0;
1219      padding: 32px;
1220      display: flex;
1221      justify-content: center;
1222      min-height: 100vh;
1223    }
1224    #container {
1225      max-width: 1000px;
1226      width: 100%;
1227      background: #0f172a;
1228      border-radius: 18px;
1229      padding: 28px 32px 40px;
1230      box-shadow: 0 40px 120px rgba(2, 6, 23, 0.85);
1231    }
1232    h1 {
1233      margin: 0 0 8px;
1234      font-size: 26px;
1235      letter-spacing: 0.4px;
1236      color: #f8fafc;
1237    }
1238    #meta {
1239      margin: 0 0 20px;
1240      color: #94a3b8;
1241      font-size: 14px;
1242    }
1243    canvas {
1244      width: 100%;
1245      max-width: 900px;
1246      height: auto;
1247      background: radial-gradient(circle, #020617 0%, #0f172a 70%, #020617 100%);
1248      border-radius: 16px;
1249      border: 1px solid rgba(148, 163, 184, 0.1);
1250      display: block;
1251      margin: 0 auto 24px;
1252    }
1253    #metrics {
1254      display: grid;
1255      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
1256      gap: 12px;
1257      margin-bottom: 20px;
1258      font-size: 14px;
1259    }
1260    #metrics div {
1261      background: #1e293b;
1262      padding: 12px 14px;
1263      border-radius: 12px;
1264      border: 1px solid rgba(148, 163, 184, 0.15);
1265    }
1266    .legend {
1267      display: flex;
1268      flex-wrap: wrap;
1269      gap: 18px;
1270      margin-bottom: 24px;
1271      font-size: 14px;
1272      color: #cbd5f5;
1273    }
1274    .legend span {
1275      display: flex;
1276      align-items: center;
1277      gap: 6px;
1278    }
1279    .legend .line {
1280      width: 30px;
1281      height: 6px;
1282      border-radius: 3px;
1283      display: inline-block;
1284    }
1285    .legend .put-line {
1286      background: #22c55e;
1287    }
1288    .legend .update-line {
1289      background: #f59e0b;
1290    }
1291    .legend .contract-dot {
1292      background: #a855f7;
1293      box-shadow: 0 0 6px rgba(168, 85, 247, 0.7);
1294    }
1295    .legend .cached-dot {
1296      background: #38bdf8;
1297    }
1298    .legend .peer-dot {
1299      background: #64748b;
1300    }
1301    .legend .gateway-dot {
1302      background: #f97316;
1303    }
1304    .dot {
1305      width: 14px;
1306      height: 14px;
1307      border-radius: 50%;
1308      display: inline-block;
1309    }
1310    #contract-info {
1311      background: rgba(15, 23, 42, 0.7);
1312      border-radius: 12px;
1313      border: 1px solid rgba(148, 163, 184, 0.15);
1314      padding: 14px;
1315      margin-bottom: 20px;
1316      font-size: 13px;
1317      color: #cbd5f5;
1318    }
1319    #contract-info h2 {
1320      margin: 0 0 8px;
1321      font-size: 16px;
1322      color: #f8fafc;
1323    }
1324    #contract-info .op-block {
1325      margin-top: 10px;
1326    }
1327    #contract-info ol {
1328      padding-left: 20px;
1329      margin: 6px 0;
1330    }
1331    #contract-info .errors {
1332      margin-top: 10px;
1333      color: #f97316;
1334    }
1335    #peer-list {
1336      border-top: 1px solid rgba(148, 163, 184, 0.15);
1337      padding-top: 18px;
1338      display: grid;
1339      grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
1340      gap: 14px;
1341      font-size: 13px;
1342    }
1343    .peer {
1344      background: rgba(15, 23, 42, 0.75);
1345      padding: 12px 14px;
1346      border-radius: 12px;
1347      border: 1px solid rgba(148, 163, 184, 0.2);
1348    }
1349    .peer strong {
1350      display: block;
1351      font-size: 13px;
1352      color: #f1f5f9;
1353      margin-bottom: 6px;
1354      word-break: break-all;
1355    }
1356    .peer span {
1357      display: block;
1358      color: #94a3b8;
1359    }
1360    .chart-card {
1361      background: rgba(15, 23, 42, 0.75);
1362      padding: 12px 14px;
1363      border-radius: 12px;
1364      border: 1px solid rgba(148, 163, 184, 0.2);
1365      margin-top: 12px;
1366    }
1367    .chart-card h3 {
1368      margin: 0 0 8px;
1369      font-size: 15px;
1370      color: #e2e8f0;
1371    }
1372  </style>
1373  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
1374</head>
1375<body>
1376  <div id="container">
1377    <h1>Freenet Ring Topology</h1>
1378    <p id="meta"></p>
1379    <canvas id="ring" width="900" height="900"></canvas>
1380    <div id="metrics"></div>
1381    <div class="chart-card" style="height: 280px;">
1382      <h3>Ring distance distribution</h3>
1383      <canvas id="histogram-chart" style="height: 220px;"></canvas>
1384    </div>
1385    <div class="legend">
1386      <span><span class="dot peer-dot"></span>Peer</span>
1387      <span><span class="dot gateway-dot"></span>Gateway</span>
1388      <span><span class="dot cached-dot"></span>Cached peer</span>
1389      <span><span class="dot contract-dot"></span>Contract</span>
1390      <span><span class="line put-line"></span>PUT path</span>
1391      <span><span class="line update-line"></span>UPDATE path</span>
1392      <span><span class="dot" style="background:#475569"></span>Connection</span>
1393    </div>
1394    <div id="contract-info"></div>
1395    <div id="peer-list"></div>
1396  </div>
1397  <script>
1398    const vizData = __DATA__;
1399    const contractData = vizData.contract ?? null;
1400    const metaEl = document.getElementById("meta");
1401    metaEl.textContent = vizData.nodes.length
1402      ? `Captured ${vizData.nodes.length} nodes · ${vizData.metrics.edge_count} edges · Generated ${vizData.generated_at} · Run root: ${vizData.run_root}`
1403      : "No peers reported diagnostics data.";
1404
1405    const metricsEl = document.getElementById("metrics");
1406    const fmtNumber = (value, digits = 2) => (typeof value === "number" ? value.toFixed(digits) : "n/a");
1407    const fmtPercent = (value, digits = 1) => (typeof value === "number" ? `${value.toFixed(digits)}%` : "n/a");
1408
1409    metricsEl.innerHTML = `
1410      <div><strong>Total nodes</strong><br/>${vizData.metrics.node_count} (gateways: ${vizData.metrics.gateway_count})</div>
1411      <div><strong>Edges</strong><br/>${vizData.metrics.edge_count}</div>
1412      <div><strong>Average degree</strong><br/>${fmtNumber(vizData.metrics.average_degree)}</div>
1413      <div><strong>Average ring distance</strong><br/>${fmtNumber(vizData.metrics.average_ring_distance, 3)}</div>
1414      <div><strong>Min / Max ring distance</strong><br/>${fmtNumber(vizData.metrics.min_ring_distance, 3)} / ${fmtNumber(vizData.metrics.max_ring_distance, 3)}</div>
1415      <div><strong>Edges &lt;5% / &lt;10%</strong><br/>${fmtPercent(vizData.metrics.pct_edges_under_5pct)} / ${fmtPercent(vizData.metrics.pct_edges_under_10pct)}</div>
1416      <div><strong>Short/long edge ratio (≤0.1 / 0.1–0.5)</strong><br/>${fmtNumber(vizData.metrics.short_over_long_ratio, 2)}</div>
1417    `;
1418
1419    const histogram = vizData.metrics.distance_histogram ?? [];
1420    const labels = histogram.map((b, idx) => {
1421      const lower = idx === 0 ? 0 : histogram[idx - 1].upper_bound;
1422      return `${lower.toFixed(1)}–${b.upper_bound.toFixed(1)}`;
1423    });
1424    const counts = histogram.map((b) => b.count);
1425
1426    if (histogram.length && window.Chart) {
1427      const ctx = document.getElementById("histogram-chart").getContext("2d");
1428      new Chart(ctx, {
1429        data: {
1430          labels,
1431          datasets: [
1432            {
1433              type: "bar",
1434              label: "Edges per bucket",
1435              data: counts,
1436              backgroundColor: "rgba(56, 189, 248, 0.75)",
1437              borderColor: "#38bdf8",
1438              borderWidth: 1,
1439            },
1440          ],
1441        },
1442        options: {
1443          responsive: true,
1444          maintainAspectRatio: false,
1445          animation: false,
1446          interaction: { mode: "index", intersect: false },
1447          plugins: {
1448            legend: { position: "bottom" },
1449            tooltip: {
1450              callbacks: {
1451                label: (ctx) => {
1452                  const label = ctx.dataset.label || "";
1453                  const value = ctx.parsed.y;
1454                  return ctx.dataset.type === "line"
1455                    ? `${label}: ${value.toFixed(1)}%`
1456                    : `${label}: ${value}`;
1457                },
1458              },
1459            },
1460          },
1461          scales: {
1462            x: { title: { display: true, text: "Ring distance (fraction of circumference)" } },
1463            y: {
1464              beginAtZero: true,
1465              title: { display: true, text: "Edge count" },
1466              grid: { color: "rgba(148,163,184,0.15)" },
1467            },
1468          },
1469        },
1470      });
1471    }
1472
1473    const peersEl = document.getElementById("peer-list");
1474    peersEl.innerHTML = vizData.nodes
1475      .map((node) => {
1476        const role = node.is_gateway ? "Gateway" : "Peer";
1477        const loc = typeof node.location === "number" ? node.location.toFixed(6) : "unknown";
1478        return `<div class="peer">
1479          <strong>${node.id}</strong>
1480          <span>${role}</span>
1481          <span>Location: ${loc}</span>
1482          <span>Degree: ${node.connections.length}</span>
1483        </div>`;
1484      })
1485      .join("");
1486
1487    const contractInfoEl = document.getElementById("contract-info");
1488    const canvas = document.getElementById("ring");
1489    const ctx = canvas.getContext("2d");
1490    const width = canvas.width;
1491    const height = canvas.height;
1492    const center = { x: width / 2, y: height / 2 };
1493    const radius = Math.min(width, height) * 0.37;
1494    const cachingPeers = new Set(contractData?.caching_peers ?? []);
1495    const putEdges = contractData?.put?.edges ?? [];
1496    const updateEdges = contractData?.update?.edges ?? [];
1497    const contractLocation = typeof (contractData?.location) === "number" ? contractData.location : null;
1498
1499    function shortId(id) {
1500      return id.slice(-6);
1501    }
1502
1503    function angleFromLocation(location) {
1504      return (location % 1) * Math.PI * 2;
1505    }
1506
1507    function polarToCartesian(angle, r = radius) {
1508      const theta = angle - Math.PI / 2;
1509      return {
1510        x: center.x + r * Math.cos(theta),
1511        y: center.y + r * Math.sin(theta),
1512      };
1513    }
1514
1515    const nodes = vizData.nodes.map((node, idx) => {
1516      const angle = typeof node.location === "number"
1517        ? angleFromLocation(node.location)
1518        : (idx / vizData.nodes.length) * Math.PI * 2;
1519      const coords = polarToCartesian(angle);
1520      return {
1521        ...node,
1522        angle,
1523        x: coords.x,
1524        y: coords.y,
1525      };
1526    });
1527    const nodeMap = new Map(nodes.map((node) => [node.id, node]));
1528
1529    function drawRingBase() {
1530      ctx.save();
1531      ctx.strokeStyle = "#475569";
1532      ctx.lineWidth = 2;
1533      ctx.beginPath();
1534      ctx.arc(center.x, center.y, radius, 0, Math.PI * 2);
1535      ctx.stroke();
1536      ctx.setLineDash([4, 8]);
1537      ctx.strokeStyle = "rgba(148,163,184,0.3)";
1538      [0, 0.25, 0.5, 0.75].forEach((loc) => {
1539        const angle = angleFromLocation(loc);
1540        const inner = polarToCartesian(angle, radius * 0.9);
1541        const outer = polarToCartesian(angle, radius * 1.02);
1542        ctx.beginPath();
1543        ctx.moveTo(inner.x, inner.y);
1544        ctx.lineTo(outer.x, outer.y);
1545        ctx.stroke();
1546        ctx.fillStyle = "#94a3b8";
1547        ctx.font = "11px 'Fira Code', monospace";
1548        ctx.textAlign = "center";
1549        ctx.fillText(loc.toFixed(2), outer.x, outer.y - 6);
1550      });
1551      ctx.restore();
1552    }
1553
1554    function drawConnections() {
1555      ctx.save();
1556      ctx.strokeStyle = "rgba(148, 163, 184, 0.35)";
1557      ctx.lineWidth = 1.2;
1558      const drawn = new Set();
1559      nodes.forEach((node) => {
1560        node.connections.forEach((neighborId) => {
1561          const neighbor = nodeMap.get(neighborId);
1562          if (!neighbor) return;
1563          const key = node.id < neighborId ? `${node.id}|${neighborId}` : `${neighborId}|${node.id}`;
1564          if (drawn.has(key)) return;
1565          drawn.add(key);
1566          ctx.beginPath();
1567          ctx.moveTo(node.x, node.y);
1568          ctx.lineTo(neighbor.x, neighbor.y);
1569          ctx.stroke();
1570        });
1571      });
1572      ctx.restore();
1573    }
1574
1575    function drawContractMarker() {
1576      if (typeof contractLocation !== "number") return;
1577      const pos = polarToCartesian(angleFromLocation(contractLocation));
1578      ctx.save();
1579      ctx.fillStyle = "#a855f7";
1580      ctx.beginPath();
1581      ctx.arc(pos.x, pos.y, 9, 0, Math.PI * 2);
1582      ctx.fill();
1583      ctx.lineWidth = 2;
1584      ctx.strokeStyle = "#f3e8ff";
1585      ctx.stroke();
1586      ctx.fillStyle = "#f3e8ff";
1587      ctx.font = "10px 'Fira Code', monospace";
1588      ctx.textAlign = "center";
1589      ctx.fillText("contract", pos.x, pos.y - 16);
1590      ctx.restore();
1591    }
1592
1593    function drawPeers() {
1594      nodes.forEach((node) => {
1595        const baseColor = node.is_gateway ? "#f97316" : "#64748b";
1596        const fill = cachingPeers.has(node.id) ? "#38bdf8" : baseColor;
1597        ctx.save();
1598        ctx.beginPath();
1599        ctx.fillStyle = fill;
1600        ctx.arc(node.x, node.y, 6.5, 0, Math.PI * 2);
1601        ctx.fill();
1602        ctx.lineWidth = 1.6;
1603        ctx.strokeStyle = "#0f172a";
1604        ctx.stroke();
1605        ctx.fillStyle = "#f8fafc";
1606        ctx.font = "12px 'Fira Code', monospace";
1607        ctx.textAlign = "center";
1608        ctx.fillText(shortId(node.id), node.x, node.y - 14);
1609        const locText = typeof node.location === "number" ? node.location.toFixed(3) : "n/a";
1610        ctx.fillStyle = "#94a3b8";
1611        ctx.font = "10px 'Fira Code', monospace";
1612        ctx.fillText(locText, node.x, node.y + 20);
1613        ctx.restore();
1614      });
1615    }
1616
1617    function drawOperationEdges(edges, color, dashed = false) {
1618      if (!edges.length) return;
1619      ctx.save();
1620      ctx.strokeStyle = color;
1621      ctx.lineWidth = 3;
1622      if (dashed) ctx.setLineDash([10, 8]);
1623      edges.forEach((edge, idx) => {
1624        const from = nodeMap.get(edge.from);
1625        const to = nodeMap.get(edge.to);
1626        if (!from || !to) return;
1627        ctx.beginPath();
1628        ctx.moveTo(from.x, from.y);
1629        ctx.lineTo(to.x, to.y);
1630        ctx.stroke();
1631        drawArrowhead(from, to, color);
1632        const midX = (from.x + to.x) / 2;
1633        const midY = (from.y + to.y) / 2;
1634        ctx.fillStyle = color;
1635        ctx.font = "11px 'Fira Code', monospace";
1636        ctx.fillText(`#${idx + 1}`, midX, midY - 4);
1637      });
1638      ctx.restore();
1639    }
1640
1641    function drawArrowhead(from, to, color) {
1642      const angle = Math.atan2(to.y - from.y, to.x - from.x);
1643      const length = 12;
1644      const spread = Math.PI / 6;
1645      ctx.save();
1646      ctx.fillStyle = color;
1647      ctx.beginPath();
1648      ctx.moveTo(to.x, to.y);
1649      ctx.lineTo(
1650        to.x - length * Math.cos(angle - spread),
1651        to.y - length * Math.sin(angle - spread)
1652      );
1653      ctx.lineTo(
1654        to.x - length * Math.cos(angle + spread),
1655        to.y - length * Math.sin(angle + spread)
1656      );
1657      ctx.closePath();
1658      ctx.fill();
1659      ctx.restore();
1660    }
1661
1662    function renderOperationList(title, edges) {
1663      if (!edges.length) {
1664        return `<div class="op-block"><strong>${title}:</strong> none recorded</div>`;
1665      }
1666      const items = edges
1667        .map((edge, idx) => {
1668          const ts = edge.timestamp
1669            ? new Date(edge.timestamp).toLocaleTimeString()
1670            : "no-ts";
1671          return `<li>#${idx + 1}: ${shortId(edge.from)} → ${shortId(edge.to)} (${ts})</li>`;
1672        })
1673        .join("");
1674      return `<div class="op-block"><strong>${title}:</strong><ol>${items}</ol></div>`;
1675    }
1676
1677    function renderContractInfo(data) {
1678      if (!data) {
1679        contractInfoEl.textContent = "No contract-specific data collected for this snapshot.";
1680        return;
1681      }
1682      const errors = data.errors?.length
1683        ? `<div class="errors"><strong>Notable events:</strong><ul>${data.errors
1684            .map((msg) => `<li>${msg}</li>`)
1685            .join("")}</ul></div>`
1686        : "";
1687      const putSummary = renderOperationList("PUT path", data.put.edges);
1688      const updateSummary = renderOperationList("UPDATE path", data.update.edges);
1689      contractInfoEl.innerHTML = `
1690        <h2>Contract ${data.key}</h2>
1691        <div><strong>Cached peers:</strong> ${data.caching_peers.length}</div>
1692        <div><strong>PUT completion:</strong> ${
1693          data.put.completion_peer ?? "pending"
1694        }</div>
1695        <div><strong>UPDATE completion:</strong> ${
1696          data.update.completion_peer ?? "pending"
1697        }</div>
1698        ${putSummary}
1699        ${updateSummary}
1700        ${errors}
1701      `;
1702    }
1703
1704    renderContractInfo(contractData);
1705
1706    if (nodes.length) {
1707      drawRingBase();
1708      drawConnections();
1709      drawContractMarker();
1710      drawOperationEdges(putEdges, "#22c55e", false);
1711      drawOperationEdges(updateEdges, "#f59e0b", true);
1712      drawPeers();
1713    } else {
1714      ctx.fillStyle = "#94a3b8";
1715      ctx.font = "16px Inter, sans-serif";
1716      ctx.fillText("No diagnostics available to render ring.", center.x - 140, center.y);
1717    }
1718  </script>
1719</body>
1720</html>
1721"###;
1722
1723fn render_ring_template(data_json: &str) -> String {
1724    HTML_TEMPLATE.replace("__DATA__", data_json)
1725}
1726
1727#[cfg(test)]
1728mod tests {
1729    use super::{compute_ring_metrics, RingPeerSnapshot};
1730
1731    #[test]
1732    fn ring_metrics_basic() {
1733        let nodes = vec![
1734            RingPeerSnapshot {
1735                id: "a".into(),
1736                is_gateway: false,
1737                ws_port: 0,
1738                network_port: 0,
1739                network_address: "127.1.0.1".into(),
1740                location: Some(0.1),
1741                connections: vec!["b".into(), "c".into()],
1742                contract: None,
1743            },
1744            RingPeerSnapshot {
1745                id: "b".into(),
1746                is_gateway: false,
1747                ws_port: 0,
1748                network_port: 0,
1749                network_address: "127.2.0.1".into(),
1750                location: Some(0.2),
1751                connections: vec!["a".into()],
1752                contract: None,
1753            },
1754            RingPeerSnapshot {
1755                id: "c".into(),
1756                is_gateway: true,
1757                ws_port: 0,
1758                network_port: 0,
1759                network_address: "127.3.0.1".into(),
1760                location: Some(0.8),
1761                connections: vec!["a".into()],
1762                contract: None,
1763            },
1764        ];
1765
1766        let metrics = compute_ring_metrics(&nodes);
1767        assert_eq!(metrics.node_count, 3);
1768        assert_eq!(metrics.gateway_count, 1);
1769        assert_eq!(metrics.edge_count, 2);
1770        assert!((metrics.average_degree - (4.0 / 3.0)).abs() < f64::EPSILON);
1771        assert!(metrics.average_ring_distance.is_some());
1772    }
1773}