1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use std::{
    collections::HashMap,
    io::{Error, ErrorKind},
    str::FromStr,
};

use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_with::serde_as;

/// Represents AvalancheGo health status.
/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/api/health#APIHealthReply
#[derive(Debug, Deserialize, Eq, PartialEq, Clone)]
pub struct Health {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checks: Option<HashMap<String, CheckResult>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub healthy: Option<bool>,
}

/// Represents AvalancheGo health status.
/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/api/health#Result
#[serde_as]
#[derive(Debug, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CheckResult {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde_as(as = "crate::formatting::serde::rfc_3339::DateTimeUtc")]
    pub timestamp: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contiguous_failures: Option<i64>,
    #[serde_as(as = "Option<crate::formatting::serde::rfc_3339::DateTimeUtc>")]
    #[serde(default)]
    pub time_of_first_failure: Option<DateTime<Utc>>,
}

/// ref. https://doc.rust-lang.org/std/str/trait.FromStr.html
impl FromStr for Health {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s).map_err(|e| {
            Error::new(
                ErrorKind::Other,
                format!("failed serde_json::from_str '{}'", e),
            )
        })
    }
}

/// RUST_LOG=debug cargo test --package avalanche-types --lib -- jsonrpc::health::test_parse --exact --show-output
#[test]
fn test_parse() {
    use log::info;
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    let data = "

{
    \"checks\": {
        \"C\": {
            \"message\": {
                \"consensus\": {
                    \"longestRunningBlock\": \"0s\",
                    \"outstandingBlocks\": 0
                },
                \"vm\": null
            },
            \"timestamp\": \"2022-02-16T08:15:01.766696642Z\",
            \"duration\": 5861
        },
        \"P\": {
            \"message\": {
                \"consensus\": {
                    \"longestRunningBlock\": \"0s\",
                    \"outstandingBlocks\": 0
                },
                \"vm\": {
                    \"percentConnected\": 1
                }
            },
            \"timestamp\": \"2022-02-16T08:15:01.766695342Z\",
            \"duration\": 19790
        },
        \"X\": {
            \"message\": {
                \"consensus\": {
                    \"outstandingVertices\": 0,
                    \"snowstorm\": {
                        \"outstandingTransactions\": 0
                    }
                },
                \"vm\": null
            },
            \"timestamp\": \"2022-02-16T08:15:01.766712432Z\",
            \"duration\": 8731
        },
        \"bootstrapped\": {
            \"message\": [],
            \"timestamp\": \"2022-02-16T08:15:01.766704522Z\",
            \"duration\": 8120
        },
        \"network\": {
            \"message\": {
                \"connectedPeers\": 4,
                \"sendFailRate\": 0.016543146704195332,
                \"timeSinceLastMsgReceived\": \"1.766701162s\",
                \"timeSinceLastMsgSent\": \"3.766701162s\"
            },
            \"timestamp\": \"2022-02-16T08:15:01.766702722Z\",
            \"duration\": 5600
        },
        \"router\": {
            \"message\": {
                \"longestRunningRequest\": \"0s\",
                \"outstandingRequests\": 0
            },
            \"timestamp\": \"2022-02-16T08:15:01.766689781Z\",
            \"duration\": 11210
        }
    },
    \"healthy\": true
}

";

    let parsed = Health::from_str(data).unwrap();
    info!("parsed: {:?}", parsed);
    assert!(parsed.healthy.unwrap());
}