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
561impl TestNetwork {
562    pub(crate) fn new(
563        gateways: Vec<TestPeer>,
564        peers: Vec<TestPeer>,
565        min_connectivity: f64,
566        run_root: PathBuf,
567    ) -> Self {
568        Self {
569            gateways,
570            peers,
571            min_connectivity,
572            run_root,
573            docker_backend: None,
574        }
575    }
576
577    pub(crate) fn new_with_docker(
578        gateways: Vec<TestPeer>,
579        peers: Vec<TestPeer>,
580        min_connectivity: f64,
581        run_root: PathBuf,
582        docker_backend: Option<DockerNatBackend>,
583    ) -> Self {
584        Self {
585            gateways,
586            peers,
587            min_connectivity,
588            run_root,
589            docker_backend,
590        }
591    }
592
593    /// Directory containing all peer state/logs for this test network run.
594    pub fn run_root(&self) -> &std::path::Path {
595        &self.run_root
596    }
597}
598
599/// Snapshot describing diagnostics collected across the network at a moment in time.
600#[derive(Debug, Clone, Serialize, Deserialize)]
601pub struct NetworkDiagnosticsSnapshot {
602    pub collected_at: chrono::DateTime<Utc>,
603    pub peers: Vec<PeerDiagnosticsSnapshot>,
604}
605
606/// Diagnostic information for a single peer.
607#[derive(Debug, Clone, Serialize, Deserialize)]
608pub struct PeerDiagnosticsSnapshot {
609    pub peer_id: String,
610    pub is_gateway: bool,
611    pub ws_url: String,
612    pub location: Option<String>,
613    pub listening_address: Option<String>,
614    pub connected_peer_ids: Vec<String>,
615    pub connected_peers_detailed: Vec<ConnectedPeerInfo>,
616    pub active_connections: Option<usize>,
617    pub system_metrics: Option<SystemMetrics>,
618    pub error: Option<String>,
619}
620
621impl PeerDiagnosticsSnapshot {
622    fn new(peer: &TestPeer) -> Self {
623        Self {
624            peer_id: peer.id().to_string(),
625            is_gateway: peer.is_gateway(),
626            ws_url: peer.ws_url(),
627            location: None,
628            listening_address: None,
629            connected_peer_ids: Vec::new(),
630            connected_peers_detailed: Vec::new(),
631            active_connections: None,
632            system_metrics: None,
633            error: None,
634        }
635    }
636}
637
638/// Snapshot describing a peer's ring metadata and adjacency.
639#[derive(Debug, Clone, Serialize)]
640pub struct RingPeerSnapshot {
641    pub id: String,
642    pub is_gateway: bool,
643    pub ws_port: u16,
644    pub network_port: u16,
645    pub network_address: String,
646    #[serde(skip_serializing_if = "Option::is_none")]
647    pub location: Option<f64>,
648    pub connections: Vec<String>,
649    #[serde(skip_serializing_if = "Option::is_none")]
650    pub contract: Option<PeerContractStatus>,
651}
652
653/// Convert a diagnostics snapshot into the ring snapshot format used by the visualization.
654pub fn ring_nodes_from_diagnostics(snapshot: &NetworkDiagnosticsSnapshot) -> Vec<RingPeerSnapshot> {
655    snapshot
656        .peers
657        .iter()
658        .map(|peer| {
659            let location = peer
660                .location
661                .as_deref()
662                .and_then(|loc| loc.parse::<f64>().ok());
663            let (network_address, network_port) =
664                parse_listening_address(peer.listening_address.as_ref(), &peer.ws_url);
665            let ws_port = parse_ws_port(&peer.ws_url);
666            let mut connections = peer.connected_peer_ids.clone();
667            connections.retain(|id| id != &peer.peer_id);
668            connections.sort();
669            connections.dedup();
670
671            RingPeerSnapshot {
672                id: peer.peer_id.clone(),
673                is_gateway: peer.is_gateway,
674                ws_port,
675                network_port,
676                network_address,
677                location,
678                connections,
679                contract: None,
680            }
681        })
682        .collect()
683}
684
685/// Render a ring visualization from a saved diagnostics snapshot (e.g. a large soak run).
686pub fn write_ring_visualization_from_diagnostics<P: AsRef<Path>, Q: AsRef<Path>>(
687    snapshot: &NetworkDiagnosticsSnapshot,
688    run_root: P,
689    output_path: Q,
690) -> Result<()> {
691    let nodes = ring_nodes_from_diagnostics(snapshot);
692    let metrics = compute_ring_metrics(&nodes);
693    let payload = json!({
694        "generated_at": snapshot.collected_at.to_rfc3339(),
695        "run_root": run_root.as_ref().display().to_string(),
696        "nodes": nodes,
697        "metrics": metrics,
698    });
699    let data_json = serde_json::to_string(&payload).map_err(|e| Error::Other(e.into()))?;
700    let html = render_ring_template(&data_json);
701    let out_path = output_path.as_ref();
702    if let Some(parent) = out_path.parent() {
703        if !parent.exists() {
704            fs::create_dir_all(parent)?;
705        }
706    }
707    fs::write(out_path, html)?;
708    tracing::info!(path = %out_path.display(), "Wrote ring visualization from diagnostics");
709    Ok(())
710}
711
712/// Contract-specific status for a peer when a contract key is provided.
713#[derive(Debug, Clone, Serialize)]
714pub struct PeerContractStatus {
715    pub stores_contract: bool,
716    pub subscribed_locally: bool,
717    pub subscriber_peer_ids: Vec<String>,
718    pub subscriber_count: usize,
719}
720
721#[derive(Debug, Clone, Serialize)]
722pub struct ContractVizData {
723    pub key: String,
724    pub location: f64,
725    pub caching_peers: Vec<String>,
726    pub put: OperationPath,
727    pub update: OperationPath,
728    pub errors: Vec<String>,
729}
730
731#[derive(Debug, Clone, Serialize)]
732pub struct OperationPath {
733    pub edges: Vec<ContractOperationEdge>,
734    #[serde(skip_serializing_if = "Option::is_none")]
735    pub completion_peer: Option<String>,
736}
737
738#[derive(Debug, Clone, Serialize)]
739pub struct ContractOperationEdge {
740    pub from: String,
741    pub to: String,
742    #[serde(skip_serializing_if = "Option::is_none")]
743    pub timestamp: Option<String>,
744    #[serde(skip_serializing_if = "Option::is_none")]
745    pub log_level: Option<String>,
746    #[serde(skip_serializing_if = "Option::is_none")]
747    pub log_source: Option<String>,
748    pub message: String,
749}
750
751/// Aggregated metrics that help reason about small-world properties.
752#[derive(Debug, Clone, Serialize)]
753pub struct RingVizMetrics {
754    pub node_count: usize,
755    pub gateway_count: usize,
756    pub edge_count: usize,
757    pub average_degree: f64,
758    #[serde(skip_serializing_if = "Option::is_none")]
759    pub average_ring_distance: Option<f64>,
760    #[serde(skip_serializing_if = "Option::is_none")]
761    pub min_ring_distance: Option<f64>,
762    #[serde(skip_serializing_if = "Option::is_none")]
763    pub max_ring_distance: Option<f64>,
764    #[serde(skip_serializing_if = "Option::is_none")]
765    pub pct_edges_under_5pct: Option<f64>,
766    #[serde(skip_serializing_if = "Option::is_none")]
767    pub pct_edges_under_10pct: Option<f64>,
768    #[serde(skip_serializing_if = "Option::is_none")]
769    pub short_over_long_ratio: Option<f64>,
770    #[serde(skip_serializing_if = "Vec::is_empty")]
771    pub distance_histogram: Vec<RingDistanceBucket>,
772}
773
774#[derive(Debug, Clone, Serialize)]
775pub struct RingDistanceBucket {
776    pub upper_bound: f64,
777    pub count: usize,
778}
779
780/// Network topology information
781#[derive(Debug, Clone, Serialize, Deserialize)]
782pub struct NetworkTopology {
783    pub peers: Vec<PeerInfo>,
784    pub connections: Vec<Connection>,
785}
786
787/// Information about a peer in the network
788#[derive(Debug, Clone, Serialize, Deserialize)]
789pub struct PeerInfo {
790    pub id: String,
791    pub is_gateway: bool,
792    pub ws_port: u16,
793}
794
795/// A connection between two peers
796#[derive(Debug, Clone, Serialize, Deserialize)]
797pub struct Connection {
798    pub from: String,
799    pub to: String,
800}
801
802#[derive(Default)]
803struct ContractFlowData {
804    put_edges: Vec<ContractOperationEdge>,
805    put_completion_peer: Option<String>,
806    update_edges: Vec<ContractOperationEdge>,
807    update_completion_peer: Option<String>,
808    errors: Vec<String>,
809}
810
811async fn query_ring_snapshot(
812    peer: &TestPeer,
813    contract_key: Option<&ContractKey>,
814) -> Result<RingPeerSnapshot> {
815    use tokio_tungstenite::connect_async;
816
817    let url = format!("{}?encodingProtocol=native", peer.ws_url());
818    let (ws_stream, _) = tokio::time::timeout(Duration::from_secs(5), connect_async(&url))
819        .await
820        .map_err(|_| Error::ConnectivityFailed(format!("Timeout connecting to {}", peer.id())))?
821        .map_err(|e| {
822            Error::ConnectivityFailed(format!("Failed to connect to {}: {}", peer.id(), e))
823        })?;
824
825    let mut client = WebApi::start(ws_stream);
826    let diag_config = if let Some(key) = contract_key {
827        NodeDiagnosticsConfig {
828            include_node_info: true,
829            include_network_info: true,
830            include_subscriptions: true,
831            contract_keys: vec![key.clone()],
832            include_system_metrics: false,
833            include_detailed_peer_info: true,
834            include_subscriber_peer_ids: true,
835        }
836    } else {
837        NodeDiagnosticsConfig::basic_status()
838    };
839
840    client
841        .send(ClientRequest::NodeQueries(NodeQuery::NodeDiagnostics {
842            config: diag_config,
843        }))
844        .await
845        .map_err(|e| {
846            Error::ConnectivityFailed(format!(
847                "Failed to send diagnostics to {}: {}",
848                peer.id(),
849                e
850            ))
851        })?;
852
853    let response = tokio::time::timeout(Duration::from_secs(5), client.recv())
854        .await
855        .map_err(|_| {
856            Error::ConnectivityFailed(format!(
857                "Timeout waiting for diagnostics response from {}",
858                peer.id()
859            ))
860        })?;
861
862    let diag = match response {
863        Ok(HostResponse::QueryResponse(QueryResponse::NodeDiagnostics(diag))) => diag,
864        Ok(other) => {
865            client.disconnect("ring snapshot error").await;
866            return Err(Error::ConnectivityFailed(format!(
867                "Unexpected diagnostics response from {}: {:?}",
868                peer.id(),
869                other
870            )));
871        }
872        Err(e) => {
873            client.disconnect("ring snapshot error").await;
874            return Err(Error::ConnectivityFailed(format!(
875                "Diagnostics query failed for {}: {}",
876                peer.id(),
877                e
878            )));
879        }
880    };
881
882    let node_info = diag.node_info.ok_or_else(|| {
883        Error::ConnectivityFailed(format!("{} did not return node_info", peer.id()))
884    })?;
885
886    let location = node_info
887        .location
888        .as_deref()
889        .and_then(|value| value.parse::<f64>().ok());
890
891    let mut connections: Vec<String> = diag
892        .connected_peers_detailed
893        .into_iter()
894        .map(|info| info.peer_id)
895        .collect();
896
897    if connections.is_empty() {
898        if let Some(network_info) = diag.network_info {
899            connections = network_info
900                .connected_peers
901                .into_iter()
902                .map(|(peer_id, _)| peer_id)
903                .collect();
904        }
905    }
906
907    connections.retain(|conn| conn != &node_info.peer_id);
908    connections.sort();
909    connections.dedup();
910
911    let contract_status = contract_key.and_then(|key| {
912        let (stores_contract, subscriber_count, subscriber_peer_ids) =
913            if let Some(state) = diag.contract_states.get(key) {
914                (
915                    true,
916                    state.subscribers as usize,
917                    state.subscriber_peer_ids.clone(),
918                )
919            } else {
920                (false, 0, Vec::new())
921            };
922        let subscribed_locally = diag
923            .subscriptions
924            .iter()
925            .any(|sub| &sub.contract_key == key);
926        if stores_contract || subscribed_locally {
927            Some(PeerContractStatus {
928                stores_contract,
929                subscribed_locally,
930                subscriber_peer_ids,
931                subscriber_count,
932            })
933        } else {
934            None
935        }
936    });
937
938    client.disconnect("ring snapshot complete").await;
939
940    Ok(RingPeerSnapshot {
941        id: node_info.peer_id,
942        is_gateway: node_info.is_gateway,
943        ws_port: peer.ws_port,
944        network_port: peer.network_port,
945        network_address: peer.network_address.clone(),
946        location,
947        connections,
948        contract: contract_status,
949    })
950}
951
952fn compute_ring_metrics(nodes: &[RingPeerSnapshot]) -> RingVizMetrics {
953    let node_count = nodes.len();
954    let gateway_count = nodes.iter().filter(|peer| peer.is_gateway).count();
955    let mut total_degree = 0usize;
956    let mut unique_edges: HashSet<(String, String)> = HashSet::new();
957
958    for node in nodes {
959        total_degree += node.connections.len();
960        for neighbor in &node.connections {
961            if neighbor == &node.id {
962                continue;
963            }
964            let edge = if node.id < *neighbor {
965                (node.id.clone(), neighbor.clone())
966            } else {
967                (neighbor.clone(), node.id.clone())
968            };
969            unique_edges.insert(edge);
970        }
971    }
972
973    let average_degree = if node_count == 0 {
974        0.0
975    } else {
976        total_degree as f64 / node_count as f64
977    };
978
979    let mut location_lookup = HashMap::new();
980    for node in nodes {
981        if let Some(loc) = node.location {
982            location_lookup.insert(node.id.clone(), loc);
983        }
984    }
985
986    let mut distances = Vec::new();
987    for (a, b) in &unique_edges {
988        if let (Some(loc_a), Some(loc_b)) = (location_lookup.get(a), location_lookup.get(b)) {
989            let mut distance = (loc_a - loc_b).abs();
990            if distance > 0.5 {
991                distance = 1.0 - distance;
992            }
993            distances.push(distance);
994        }
995    }
996
997    let average_ring_distance = if distances.is_empty() {
998        None
999    } else {
1000        Some(distances.iter().sum::<f64>() / distances.len() as f64)
1001    };
1002    let min_ring_distance = distances.iter().cloned().reduce(f64::min);
1003    let max_ring_distance = distances.iter().cloned().reduce(f64::max);
1004    let pct_edges_under_5pct = calculate_percentage(&distances, 0.05);
1005    let pct_edges_under_10pct = calculate_percentage(&distances, 0.10);
1006
1007    let short_edges = distances.iter().filter(|d| **d <= 0.10).count();
1008    let long_edges = distances
1009        .iter()
1010        .filter(|d| **d > 0.10 && **d <= 0.50)
1011        .count();
1012    let short_over_long_ratio = if short_edges == 0 || long_edges == 0 {
1013        None
1014    } else {
1015        Some(short_edges as f64 / long_edges as f64)
1016    };
1017
1018    let mut distance_histogram = Vec::new();
1019    let bucket_bounds: Vec<f64> = (1..=5).map(|i| i as f64 * 0.10).collect(); // 0.1 buckets up to 0.5
1020    let mut cumulative = 0usize;
1021    for bound in bucket_bounds {
1022        let up_to_bound = distances.iter().filter(|d| **d <= bound).count();
1023        let count = up_to_bound.saturating_sub(cumulative);
1024        cumulative = up_to_bound;
1025        distance_histogram.push(RingDistanceBucket {
1026            upper_bound: bound,
1027            count,
1028        });
1029    }
1030
1031    RingVizMetrics {
1032        node_count,
1033        gateway_count,
1034        edge_count: unique_edges.len(),
1035        average_degree,
1036        average_ring_distance,
1037        min_ring_distance,
1038        max_ring_distance,
1039        pct_edges_under_5pct,
1040        pct_edges_under_10pct,
1041        short_over_long_ratio,
1042        distance_histogram,
1043    }
1044}
1045
1046fn calculate_percentage(distances: &[f64], threshold: f64) -> Option<f64> {
1047    if distances.is_empty() {
1048        return None;
1049    }
1050    let matching = distances.iter().filter(|value| **value < threshold).count();
1051    Some((matching as f64 / distances.len() as f64) * 100.0)
1052}
1053
1054fn parse_ws_port(ws_url: &str) -> u16 {
1055    ws_url
1056        .split("://")
1057        .nth(1)
1058        .and_then(|rest| rest.split('/').next())
1059        .and_then(|host_port| host_port.split(':').nth(1))
1060        .and_then(|port| port.parse().ok())
1061        .unwrap_or(0)
1062}
1063
1064fn parse_listening_address(addr: Option<&String>, ws_url: &str) -> (String, u16) {
1065    if let Some(addr) = addr {
1066        let mut parts = addr.split(':');
1067        let host = parts.next().unwrap_or("").to_string();
1068        let port = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
1069        (host, port)
1070    } else {
1071        let host = ws_url
1072            .split("://")
1073            .nth(1)
1074            .and_then(|rest| rest.split('/').next())
1075            .and_then(|host_port| host_port.split(':').next())
1076            .unwrap_or_default()
1077            .to_string();
1078        (host, 0)
1079    }
1080}
1081
1082fn resolve_peer_id(prefix: &str, peers: &[RingPeerSnapshot]) -> Option<String> {
1083    let needle = prefix.trim().trim_matches(|c| c == '"' || c == '\'');
1084    peers
1085        .iter()
1086        .find(|peer| peer.id.starts_with(needle))
1087        .map(|peer| peer.id.clone())
1088}
1089
1090fn contract_location_from_key(key: &ContractKey) -> f64 {
1091    let mut value = 0.0;
1092    let mut divisor = 256.0;
1093    for byte in key.as_bytes() {
1094        value += f64::from(*byte) / divisor;
1095        divisor *= 256.0;
1096    }
1097    value.fract()
1098}
1099
1100static PUT_REQUEST_RE: LazyLock<Regex> = LazyLock::new(|| {
1101    Regex::new(r"Requesting put for contract (?P<key>\S+) from (?P<from>\S+) to (?P<to>\S+)")
1102        .expect("valid regex")
1103});
1104static PUT_COMPLETION_RE: LazyLock<Regex> = LazyLock::new(|| {
1105    Regex::new(r"Peer completed contract value put,.*key: (?P<key>\S+),.*this_peer: (?P<peer>\S+)")
1106        .expect("valid regex")
1107});
1108static UPDATE_PROPAGATION_RE: LazyLock<Regex> = LazyLock::new(|| {
1109    Regex::new(
1110        r"UPDATE_PROPAGATION: contract=(?P<contract>\S+) from=(?P<from>\S+) targets=(?P<targets>[^ ]*)\s+count=",
1111    )
1112    .expect("valid regex")
1113});
1114static UPDATE_NO_TARGETS_RE: LazyLock<Regex> = LazyLock::new(|| {
1115    Regex::new(r"UPDATE_PROPAGATION: contract=(?P<contract>\S+) from=(?P<from>\S+) NO_TARGETS")
1116        .expect("valid regex")
1117});
1118
1119const HTML_TEMPLATE: &str = r###"<!DOCTYPE html>
1120<html lang="en">
1121<head>
1122  <meta charset="UTF-8" />
1123  <title>Freenet Ring Topology</title>
1124  <style>
1125    :root {
1126      color-scheme: dark;
1127      font-family: "Inter", "Helvetica Neue", Arial, sans-serif;
1128    }
1129    body {
1130      background: #020617;
1131      color: #e2e8f0;
1132      margin: 0;
1133      padding: 32px;
1134      display: flex;
1135      justify-content: center;
1136      min-height: 100vh;
1137    }
1138    #container {
1139      max-width: 1000px;
1140      width: 100%;
1141      background: #0f172a;
1142      border-radius: 18px;
1143      padding: 28px 32px 40px;
1144      box-shadow: 0 40px 120px rgba(2, 6, 23, 0.85);
1145    }
1146    h1 {
1147      margin: 0 0 8px;
1148      font-size: 26px;
1149      letter-spacing: 0.4px;
1150      color: #f8fafc;
1151    }
1152    #meta {
1153      margin: 0 0 20px;
1154      color: #94a3b8;
1155      font-size: 14px;
1156    }
1157    canvas {
1158      width: 100%;
1159      max-width: 900px;
1160      height: auto;
1161      background: radial-gradient(circle, #020617 0%, #0f172a 70%, #020617 100%);
1162      border-radius: 16px;
1163      border: 1px solid rgba(148, 163, 184, 0.1);
1164      display: block;
1165      margin: 0 auto 24px;
1166    }
1167    #metrics {
1168      display: grid;
1169      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
1170      gap: 12px;
1171      margin-bottom: 20px;
1172      font-size: 14px;
1173    }
1174    #metrics div {
1175      background: #1e293b;
1176      padding: 12px 14px;
1177      border-radius: 12px;
1178      border: 1px solid rgba(148, 163, 184, 0.15);
1179    }
1180    .legend {
1181      display: flex;
1182      flex-wrap: wrap;
1183      gap: 18px;
1184      margin-bottom: 24px;
1185      font-size: 14px;
1186      color: #cbd5f5;
1187    }
1188    .legend span {
1189      display: flex;
1190      align-items: center;
1191      gap: 6px;
1192    }
1193    .legend .line {
1194      width: 30px;
1195      height: 6px;
1196      border-radius: 3px;
1197      display: inline-block;
1198    }
1199    .legend .put-line {
1200      background: #22c55e;
1201    }
1202    .legend .update-line {
1203      background: #f59e0b;
1204    }
1205    .legend .contract-dot {
1206      background: #a855f7;
1207      box-shadow: 0 0 6px rgba(168, 85, 247, 0.7);
1208    }
1209    .legend .cached-dot {
1210      background: #38bdf8;
1211    }
1212    .legend .peer-dot {
1213      background: #64748b;
1214    }
1215    .legend .gateway-dot {
1216      background: #f97316;
1217    }
1218    .dot {
1219      width: 14px;
1220      height: 14px;
1221      border-radius: 50%;
1222      display: inline-block;
1223    }
1224    #contract-info {
1225      background: rgba(15, 23, 42, 0.7);
1226      border-radius: 12px;
1227      border: 1px solid rgba(148, 163, 184, 0.15);
1228      padding: 14px;
1229      margin-bottom: 20px;
1230      font-size: 13px;
1231      color: #cbd5f5;
1232    }
1233    #contract-info h2 {
1234      margin: 0 0 8px;
1235      font-size: 16px;
1236      color: #f8fafc;
1237    }
1238    #contract-info .op-block {
1239      margin-top: 10px;
1240    }
1241    #contract-info ol {
1242      padding-left: 20px;
1243      margin: 6px 0;
1244    }
1245    #contract-info .errors {
1246      margin-top: 10px;
1247      color: #f97316;
1248    }
1249    #peer-list {
1250      border-top: 1px solid rgba(148, 163, 184, 0.15);
1251      padding-top: 18px;
1252      display: grid;
1253      grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
1254      gap: 14px;
1255      font-size: 13px;
1256    }
1257    .peer {
1258      background: rgba(15, 23, 42, 0.75);
1259      padding: 12px 14px;
1260      border-radius: 12px;
1261      border: 1px solid rgba(148, 163, 184, 0.2);
1262    }
1263    .peer strong {
1264      display: block;
1265      font-size: 13px;
1266      color: #f1f5f9;
1267      margin-bottom: 6px;
1268      word-break: break-all;
1269    }
1270    .peer span {
1271      display: block;
1272      color: #94a3b8;
1273    }
1274    .chart-card {
1275      background: rgba(15, 23, 42, 0.75);
1276      padding: 12px 14px;
1277      border-radius: 12px;
1278      border: 1px solid rgba(148, 163, 184, 0.2);
1279      margin-top: 12px;
1280    }
1281    .chart-card h3 {
1282      margin: 0 0 8px;
1283      font-size: 15px;
1284      color: #e2e8f0;
1285    }
1286  </style>
1287  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
1288</head>
1289<body>
1290  <div id="container">
1291    <h1>Freenet Ring Topology</h1>
1292    <p id="meta"></p>
1293    <canvas id="ring" width="900" height="900"></canvas>
1294    <div id="metrics"></div>
1295    <div class="chart-card" style="height: 280px;">
1296      <h3>Ring distance distribution</h3>
1297      <canvas id="histogram-chart" style="height: 220px;"></canvas>
1298    </div>
1299    <div class="legend">
1300      <span><span class="dot peer-dot"></span>Peer</span>
1301      <span><span class="dot gateway-dot"></span>Gateway</span>
1302      <span><span class="dot cached-dot"></span>Cached peer</span>
1303      <span><span class="dot contract-dot"></span>Contract</span>
1304      <span><span class="line put-line"></span>PUT path</span>
1305      <span><span class="line update-line"></span>UPDATE path</span>
1306      <span><span class="dot" style="background:#475569"></span>Connection</span>
1307    </div>
1308    <div id="contract-info"></div>
1309    <div id="peer-list"></div>
1310  </div>
1311  <script>
1312    const vizData = __DATA__;
1313    const contractData = vizData.contract ?? null;
1314    const metaEl = document.getElementById("meta");
1315    metaEl.textContent = vizData.nodes.length
1316      ? `Captured ${vizData.nodes.length} nodes · ${vizData.metrics.edge_count} edges · Generated ${vizData.generated_at} · Run root: ${vizData.run_root}`
1317      : "No peers reported diagnostics data.";
1318
1319    const metricsEl = document.getElementById("metrics");
1320    const fmtNumber = (value, digits = 2) => (typeof value === "number" ? value.toFixed(digits) : "n/a");
1321    const fmtPercent = (value, digits = 1) => (typeof value === "number" ? `${value.toFixed(digits)}%` : "n/a");
1322
1323    metricsEl.innerHTML = `
1324      <div><strong>Total nodes</strong><br/>${vizData.metrics.node_count} (gateways: ${vizData.metrics.gateway_count})</div>
1325      <div><strong>Edges</strong><br/>${vizData.metrics.edge_count}</div>
1326      <div><strong>Average degree</strong><br/>${fmtNumber(vizData.metrics.average_degree)}</div>
1327      <div><strong>Average ring distance</strong><br/>${fmtNumber(vizData.metrics.average_ring_distance, 3)}</div>
1328      <div><strong>Min / Max ring distance</strong><br/>${fmtNumber(vizData.metrics.min_ring_distance, 3)} / ${fmtNumber(vizData.metrics.max_ring_distance, 3)}</div>
1329      <div><strong>Edges &lt;5% / &lt;10%</strong><br/>${fmtPercent(vizData.metrics.pct_edges_under_5pct)} / ${fmtPercent(vizData.metrics.pct_edges_under_10pct)}</div>
1330      <div><strong>Short/long edge ratio (≤0.1 / 0.1–0.5)</strong><br/>${fmtNumber(vizData.metrics.short_over_long_ratio, 2)}</div>
1331    `;
1332
1333    const histogram = vizData.metrics.distance_histogram ?? [];
1334    const labels = histogram.map((b, idx) => {
1335      const lower = idx === 0 ? 0 : histogram[idx - 1].upper_bound;
1336      return `${lower.toFixed(1)}–${b.upper_bound.toFixed(1)}`;
1337    });
1338    const counts = histogram.map((b) => b.count);
1339
1340    if (histogram.length && window.Chart) {
1341      const ctx = document.getElementById("histogram-chart").getContext("2d");
1342      new Chart(ctx, {
1343        data: {
1344          labels,
1345          datasets: [
1346            {
1347              type: "bar",
1348              label: "Edges per bucket",
1349              data: counts,
1350              backgroundColor: "rgba(56, 189, 248, 0.75)",
1351              borderColor: "#38bdf8",
1352              borderWidth: 1,
1353            },
1354          ],
1355        },
1356        options: {
1357          responsive: true,
1358          maintainAspectRatio: false,
1359          animation: false,
1360          interaction: { mode: "index", intersect: false },
1361          plugins: {
1362            legend: { position: "bottom" },
1363            tooltip: {
1364              callbacks: {
1365                label: (ctx) => {
1366                  const label = ctx.dataset.label || "";
1367                  const value = ctx.parsed.y;
1368                  return ctx.dataset.type === "line"
1369                    ? `${label}: ${value.toFixed(1)}%`
1370                    : `${label}: ${value}`;
1371                },
1372              },
1373            },
1374          },
1375          scales: {
1376            x: { title: { display: true, text: "Ring distance (fraction of circumference)" } },
1377            y: {
1378              beginAtZero: true,
1379              title: { display: true, text: "Edge count" },
1380              grid: { color: "rgba(148,163,184,0.15)" },
1381            },
1382          },
1383        },
1384      });
1385    }
1386
1387    const peersEl = document.getElementById("peer-list");
1388    peersEl.innerHTML = vizData.nodes
1389      .map((node) => {
1390        const role = node.is_gateway ? "Gateway" : "Peer";
1391        const loc = typeof node.location === "number" ? node.location.toFixed(6) : "unknown";
1392        return `<div class="peer">
1393          <strong>${node.id}</strong>
1394          <span>${role}</span>
1395          <span>Location: ${loc}</span>
1396          <span>Degree: ${node.connections.length}</span>
1397        </div>`;
1398      })
1399      .join("");
1400
1401    const contractInfoEl = document.getElementById("contract-info");
1402    const canvas = document.getElementById("ring");
1403    const ctx = canvas.getContext("2d");
1404    const width = canvas.width;
1405    const height = canvas.height;
1406    const center = { x: width / 2, y: height / 2 };
1407    const radius = Math.min(width, height) * 0.37;
1408    const cachingPeers = new Set(contractData?.caching_peers ?? []);
1409    const putEdges = contractData?.put?.edges ?? [];
1410    const updateEdges = contractData?.update?.edges ?? [];
1411    const contractLocation = typeof (contractData?.location) === "number" ? contractData.location : null;
1412
1413    function shortId(id) {
1414      return id.slice(-6);
1415    }
1416
1417    function angleFromLocation(location) {
1418      return (location % 1) * Math.PI * 2;
1419    }
1420
1421    function polarToCartesian(angle, r = radius) {
1422      const theta = angle - Math.PI / 2;
1423      return {
1424        x: center.x + r * Math.cos(theta),
1425        y: center.y + r * Math.sin(theta),
1426      };
1427    }
1428
1429    const nodes = vizData.nodes.map((node, idx) => {
1430      const angle = typeof node.location === "number"
1431        ? angleFromLocation(node.location)
1432        : (idx / vizData.nodes.length) * Math.PI * 2;
1433      const coords = polarToCartesian(angle);
1434      return {
1435        ...node,
1436        angle,
1437        x: coords.x,
1438        y: coords.y,
1439      };
1440    });
1441    const nodeMap = new Map(nodes.map((node) => [node.id, node]));
1442
1443    function drawRingBase() {
1444      ctx.save();
1445      ctx.strokeStyle = "#475569";
1446      ctx.lineWidth = 2;
1447      ctx.beginPath();
1448      ctx.arc(center.x, center.y, radius, 0, Math.PI * 2);
1449      ctx.stroke();
1450      ctx.setLineDash([4, 8]);
1451      ctx.strokeStyle = "rgba(148,163,184,0.3)";
1452      [0, 0.25, 0.5, 0.75].forEach((loc) => {
1453        const angle = angleFromLocation(loc);
1454        const inner = polarToCartesian(angle, radius * 0.9);
1455        const outer = polarToCartesian(angle, radius * 1.02);
1456        ctx.beginPath();
1457        ctx.moveTo(inner.x, inner.y);
1458        ctx.lineTo(outer.x, outer.y);
1459        ctx.stroke();
1460        ctx.fillStyle = "#94a3b8";
1461        ctx.font = "11px 'Fira Code', monospace";
1462        ctx.textAlign = "center";
1463        ctx.fillText(loc.toFixed(2), outer.x, outer.y - 6);
1464      });
1465      ctx.restore();
1466    }
1467
1468    function drawConnections() {
1469      ctx.save();
1470      ctx.strokeStyle = "rgba(148, 163, 184, 0.35)";
1471      ctx.lineWidth = 1.2;
1472      const drawn = new Set();
1473      nodes.forEach((node) => {
1474        node.connections.forEach((neighborId) => {
1475          const neighbor = nodeMap.get(neighborId);
1476          if (!neighbor) return;
1477          const key = node.id < neighborId ? `${node.id}|${neighborId}` : `${neighborId}|${node.id}`;
1478          if (drawn.has(key)) return;
1479          drawn.add(key);
1480          ctx.beginPath();
1481          ctx.moveTo(node.x, node.y);
1482          ctx.lineTo(neighbor.x, neighbor.y);
1483          ctx.stroke();
1484        });
1485      });
1486      ctx.restore();
1487    }
1488
1489    function drawContractMarker() {
1490      if (typeof contractLocation !== "number") return;
1491      const pos = polarToCartesian(angleFromLocation(contractLocation));
1492      ctx.save();
1493      ctx.fillStyle = "#a855f7";
1494      ctx.beginPath();
1495      ctx.arc(pos.x, pos.y, 9, 0, Math.PI * 2);
1496      ctx.fill();
1497      ctx.lineWidth = 2;
1498      ctx.strokeStyle = "#f3e8ff";
1499      ctx.stroke();
1500      ctx.fillStyle = "#f3e8ff";
1501      ctx.font = "10px 'Fira Code', monospace";
1502      ctx.textAlign = "center";
1503      ctx.fillText("contract", pos.x, pos.y - 16);
1504      ctx.restore();
1505    }
1506
1507    function drawPeers() {
1508      nodes.forEach((node) => {
1509        const baseColor = node.is_gateway ? "#f97316" : "#64748b";
1510        const fill = cachingPeers.has(node.id) ? "#38bdf8" : baseColor;
1511        ctx.save();
1512        ctx.beginPath();
1513        ctx.fillStyle = fill;
1514        ctx.arc(node.x, node.y, 6.5, 0, Math.PI * 2);
1515        ctx.fill();
1516        ctx.lineWidth = 1.6;
1517        ctx.strokeStyle = "#0f172a";
1518        ctx.stroke();
1519        ctx.fillStyle = "#f8fafc";
1520        ctx.font = "12px 'Fira Code', monospace";
1521        ctx.textAlign = "center";
1522        ctx.fillText(shortId(node.id), node.x, node.y - 14);
1523        const locText = typeof node.location === "number" ? node.location.toFixed(3) : "n/a";
1524        ctx.fillStyle = "#94a3b8";
1525        ctx.font = "10px 'Fira Code', monospace";
1526        ctx.fillText(locText, node.x, node.y + 20);
1527        ctx.restore();
1528      });
1529    }
1530
1531    function drawOperationEdges(edges, color, dashed = false) {
1532      if (!edges.length) return;
1533      ctx.save();
1534      ctx.strokeStyle = color;
1535      ctx.lineWidth = 3;
1536      if (dashed) ctx.setLineDash([10, 8]);
1537      edges.forEach((edge, idx) => {
1538        const from = nodeMap.get(edge.from);
1539        const to = nodeMap.get(edge.to);
1540        if (!from || !to) return;
1541        ctx.beginPath();
1542        ctx.moveTo(from.x, from.y);
1543        ctx.lineTo(to.x, to.y);
1544        ctx.stroke();
1545        drawArrowhead(from, to, color);
1546        const midX = (from.x + to.x) / 2;
1547        const midY = (from.y + to.y) / 2;
1548        ctx.fillStyle = color;
1549        ctx.font = "11px 'Fira Code', monospace";
1550        ctx.fillText(`#${idx + 1}`, midX, midY - 4);
1551      });
1552      ctx.restore();
1553    }
1554
1555    function drawArrowhead(from, to, color) {
1556      const angle = Math.atan2(to.y - from.y, to.x - from.x);
1557      const length = 12;
1558      const spread = Math.PI / 6;
1559      ctx.save();
1560      ctx.fillStyle = color;
1561      ctx.beginPath();
1562      ctx.moveTo(to.x, to.y);
1563      ctx.lineTo(
1564        to.x - length * Math.cos(angle - spread),
1565        to.y - length * Math.sin(angle - spread)
1566      );
1567      ctx.lineTo(
1568        to.x - length * Math.cos(angle + spread),
1569        to.y - length * Math.sin(angle + spread)
1570      );
1571      ctx.closePath();
1572      ctx.fill();
1573      ctx.restore();
1574    }
1575
1576    function renderOperationList(title, edges) {
1577      if (!edges.length) {
1578        return `<div class="op-block"><strong>${title}:</strong> none recorded</div>`;
1579      }
1580      const items = edges
1581        .map((edge, idx) => {
1582          const ts = edge.timestamp
1583            ? new Date(edge.timestamp).toLocaleTimeString()
1584            : "no-ts";
1585          return `<li>#${idx + 1}: ${shortId(edge.from)} → ${shortId(edge.to)} (${ts})</li>`;
1586        })
1587        .join("");
1588      return `<div class="op-block"><strong>${title}:</strong><ol>${items}</ol></div>`;
1589    }
1590
1591    function renderContractInfo(data) {
1592      if (!data) {
1593        contractInfoEl.textContent = "No contract-specific data collected for this snapshot.";
1594        return;
1595      }
1596      const errors = data.errors?.length
1597        ? `<div class="errors"><strong>Notable events:</strong><ul>${data.errors
1598            .map((msg) => `<li>${msg}</li>`)
1599            .join("")}</ul></div>`
1600        : "";
1601      const putSummary = renderOperationList("PUT path", data.put.edges);
1602      const updateSummary = renderOperationList("UPDATE path", data.update.edges);
1603      contractInfoEl.innerHTML = `
1604        <h2>Contract ${data.key}</h2>
1605        <div><strong>Cached peers:</strong> ${data.caching_peers.length}</div>
1606        <div><strong>PUT completion:</strong> ${
1607          data.put.completion_peer ?? "pending"
1608        }</div>
1609        <div><strong>UPDATE completion:</strong> ${
1610          data.update.completion_peer ?? "pending"
1611        }</div>
1612        ${putSummary}
1613        ${updateSummary}
1614        ${errors}
1615      `;
1616    }
1617
1618    renderContractInfo(contractData);
1619
1620    if (nodes.length) {
1621      drawRingBase();
1622      drawConnections();
1623      drawContractMarker();
1624      drawOperationEdges(putEdges, "#22c55e", false);
1625      drawOperationEdges(updateEdges, "#f59e0b", true);
1626      drawPeers();
1627    } else {
1628      ctx.fillStyle = "#94a3b8";
1629      ctx.font = "16px Inter, sans-serif";
1630      ctx.fillText("No diagnostics available to render ring.", center.x - 140, center.y);
1631    }
1632  </script>
1633</body>
1634</html>
1635"###;
1636
1637fn render_ring_template(data_json: &str) -> String {
1638    HTML_TEMPLATE.replace("__DATA__", data_json)
1639}
1640
1641#[cfg(test)]
1642mod tests {
1643    use super::{compute_ring_metrics, RingPeerSnapshot};
1644
1645    #[test]
1646    fn ring_metrics_basic() {
1647        let nodes = vec![
1648            RingPeerSnapshot {
1649                id: "a".into(),
1650                is_gateway: false,
1651                ws_port: 0,
1652                network_port: 0,
1653                network_address: "127.1.0.1".into(),
1654                location: Some(0.1),
1655                connections: vec!["b".into(), "c".into()],
1656                contract: None,
1657            },
1658            RingPeerSnapshot {
1659                id: "b".into(),
1660                is_gateway: false,
1661                ws_port: 0,
1662                network_port: 0,
1663                network_address: "127.2.0.1".into(),
1664                location: Some(0.2),
1665                connections: vec!["a".into()],
1666                contract: None,
1667            },
1668            RingPeerSnapshot {
1669                id: "c".into(),
1670                is_gateway: true,
1671                ws_port: 0,
1672                network_port: 0,
1673                network_address: "127.3.0.1".into(),
1674                location: Some(0.8),
1675                connections: vec!["a".into()],
1676                contract: None,
1677            },
1678        ];
1679
1680        let metrics = compute_ring_metrics(&nodes);
1681        assert_eq!(metrics.node_count, 3);
1682        assert_eq!(metrics.gateway_count, 1);
1683        assert_eq!(metrics.edge_count, 2);
1684        assert!((metrics.average_degree - (4.0 / 3.0)).abs() < f64::EPSILON);
1685        assert!(metrics.average_ring_distance.is_some());
1686    }
1687}