homestar_runtime/runner/
nodeinfo.rs

1//! Node information.
2
3use libp2p::{Multiaddr, PeerId};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::{collections::HashMap, fmt};
7use tabled::Tabled;
8
9/// Node information.
10#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
11#[schemars(rename = "node_info")]
12pub struct NodeInfo {
13    /// Static node information available at startup.
14    #[serde(rename = "static")]
15    pub(crate) stat: StaticNodeInfo,
16    /// Dynamic node information available through events
17    /// at runtime.
18    pub(crate) dynamic: DynamicNodeInfo,
19}
20
21impl NodeInfo {
22    /// Create an instance of [NodeInfo].
23    pub(crate) fn new(stat: StaticNodeInfo, dynamic: DynamicNodeInfo) -> Self {
24        Self { stat, dynamic }
25    }
26}
27
28/// Static node information available at startup.
29#[derive(Debug, Clone, Serialize, Deserialize, Tabled, JsonSchema)]
30#[schemars(rename = "static")]
31pub(crate) struct StaticNodeInfo {
32    /// The [PeerId] of a node.
33    #[schemars(with = "String", description = "The peer ID of the node")]
34    pub(crate) peer_id: PeerId,
35}
36
37impl fmt::Display for StaticNodeInfo {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "peer_id: {}", self.peer_id)
40    }
41}
42
43impl StaticNodeInfo {
44    /// Create an instance of [StaticNodeInfo].
45    pub(crate) fn new(peer_id: PeerId) -> Self {
46        Self { peer_id }
47    }
48
49    /// Get a reference to the [PeerId] of a node.
50    #[allow(dead_code)]
51    pub(crate) fn peer_id(&self) -> &PeerId {
52        &self.peer_id
53    }
54}
55
56/// Dynamic node information available through events
57/// at runtime.
58#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
59#[schemars(rename = "dynamic")]
60pub(crate) struct DynamicNodeInfo {
61    /// Listeners for the node.
62    #[schemars(with = "Vec<String>", description = "Listen addresses for the node")]
63    pub(crate) listeners: Vec<Multiaddr>,
64    /// Connections for the node.
65    #[schemars(
66        with = "HashMap<String, String>",
67        description = "Peers and their addresses that are connected to the node"
68    )]
69    pub(crate) connections: HashMap<PeerId, Multiaddr>,
70}
71
72impl fmt::Display for DynamicNodeInfo {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(
75            f,
76            "listeners: {:?}, connections: {:?}",
77            self.listeners, self.connections
78        )
79    }
80}
81
82impl DynamicNodeInfo {
83    /// Create an instance of [DynamicNodeInfo].
84    pub(crate) fn new(listeners: Vec<Multiaddr>, connections: HashMap<PeerId, Multiaddr>) -> Self {
85        Self {
86            listeners,
87            connections,
88        }
89    }
90}