libp2p_metrics/
dcutr.rs

1// Copyright 2021 Protocol Labs.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use prometheus_client::{
22    encoding::{EncodeLabelSet, EncodeLabelValue},
23    metrics::{counter::Counter, family::Family},
24    registry::Registry,
25};
26
27pub(crate) struct Metrics {
28    events: Family<EventLabels, Counter>,
29}
30
31impl Metrics {
32    pub(crate) fn new(registry: &mut Registry) -> Self {
33        let sub_registry = registry.sub_registry_with_prefix("dcutr");
34
35        let events = Family::default();
36        sub_registry.register(
37            "events",
38            "Events emitted by the relay NetworkBehaviour",
39            events.clone(),
40        );
41
42        Self { events }
43    }
44}
45
46#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
47struct EventLabels {
48    event: EventType,
49}
50
51#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelValue)]
52enum EventType {
53    DirectConnectionUpgradeSucceeded,
54    DirectConnectionUpgradeFailed,
55}
56
57impl From<&libp2p_dcutr::Event> for EventType {
58    fn from(event: &libp2p_dcutr::Event) -> Self {
59        match event {
60            libp2p_dcutr::Event {
61                remote_peer_id: _,
62                result: Ok(_),
63            } => EventType::DirectConnectionUpgradeSucceeded,
64            libp2p_dcutr::Event {
65                remote_peer_id: _,
66                result: Err(_),
67            } => EventType::DirectConnectionUpgradeFailed,
68        }
69    }
70}
71
72impl super::Recorder<libp2p_dcutr::Event> for Metrics {
73    fn record(&self, event: &libp2p_dcutr::Event) {
74        self.events
75            .get_or_create(&EventLabels {
76                event: event.into(),
77            })
78            .inc();
79    }
80}