Skip to content

Commit 88b2cc2

Browse files
committed
refactor: [torrust#1403] move labeled metrics to primitives pkg
1 parent 4b5fd1b commit 88b2cc2

File tree

7 files changed

+116
-103
lines changed

7 files changed

+116
-103
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
//! API resources for the [`stats`](crate::v1::context::stats)
22
//! API context.
3-
use bittorrent_http_tracker_core::statistics::metrics::LabeledMetric;
43
use serde::{Deserialize, Serialize};
54
use torrust_rest_tracker_api_core::statistics::services::{TrackerLabeledMetrics, TrackerMetrics};
5+
use torrust_tracker_primitives::metrics::LabeledMetrics;
66

77
/// It contains all the statistics generated by the tracker.
88
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
@@ -118,10 +118,10 @@ impl From<TrackerMetrics> for Stats {
118118
}
119119

120120
/// It contains all the statistics generated by the tracker.
121-
#[derive(Serialize, Debug, PartialEq, Eq)]
121+
#[derive(Serialize, Debug, PartialEq)]
122122
pub struct LabeledStats {
123123
// Extendable metrics
124-
labeled_metrics: Vec<LabeledMetric>,
124+
labeled_metrics: LabeledMetrics,
125125
}
126126

127127
impl From<TrackerLabeledMetrics> for LabeledStats {
Lines changed: 3 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::collections::BTreeMap;
22

33
use serde::Serialize;
4+
use torrust_tracker_primitives::metrics::LabeledMetrics;
45

56
/// Metrics collected by the tracker.
67
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
@@ -17,107 +18,11 @@ pub struct Metrics {
1718
/// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers.
1819
pub tcp6_scrapes_handled: u64,
1920

20-
pub labeled_metrics: Vec<LabeledMetric>,
21+
pub labeled_metrics: LabeledMetrics,
2122
}
2223

2324
impl Metrics {
2425
pub fn increase_counter(&mut self, metric_name: &str, metric_labels: &BTreeMap<String, String>) {
25-
let mut found = false;
26-
27-
for labeled_metric in &mut self.labeled_metrics {
28-
// todo:
29-
// - Check that the metric has the counter type.
30-
31-
if labeled_metric.metric.name == metric_name && labeled_metric.labels == *metric_labels {
32-
labeled_metric.metric.value += 1;
33-
found = true;
34-
break;
35-
}
36-
}
37-
38-
if !found {
39-
self.labeled_metrics.push(LabeledMetric {
40-
metric: Metric {
41-
name: metric_name.to_string(),
42-
kind: "counter".to_string(),
43-
value: 1,
44-
},
45-
labels: metric_labels.clone(),
46-
});
47-
}
48-
}
49-
}
50-
51-
#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize)]
52-
pub struct LabeledMetric {
53-
pub metric: Metric,
54-
pub labels: BTreeMap<String, String>,
55-
}
56-
57-
#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize)]
58-
pub struct Metric {
59-
pub name: String,
60-
pub kind: String,
61-
pub value: u64, // todo: change to f64. See https://prometheus.io/docs/concepts/data_model/#samples
62-
}
63-
64-
#[cfg(test)]
65-
mod tests {
66-
use std::collections::BTreeMap;
67-
68-
use super::LabeledMetric;
69-
use crate::statistics::metrics::{Metric, Metrics};
70-
71-
#[allow(clippy::no_effect_replace)]
72-
#[test]
73-
fn metrics_should_be_serializable_to_json() {
74-
let metrics = Metrics {
75-
tcp4_announces_handled: 1,
76-
tcp4_scrapes_handled: 2,
77-
tcp6_announces_handled: 3,
78-
tcp6_scrapes_handled: 4,
79-
labeled_metrics: vec![LabeledMetric {
80-
metric: Metric {
81-
name: "announce_requests_received_total".to_string(),
82-
kind: "counter".to_string(),
83-
value: 325,
84-
},
85-
labels: BTreeMap::from([
86-
("ip_version".to_string(), "ipv4".to_string()),
87-
("protocol".to_string(), "udp".to_string()),
88-
("url".to_string(), "udp://127.0.0.1:6969".to_string()),
89-
]),
90-
}],
91-
};
92-
93-
let json = serde_json::to_string(&metrics).unwrap();
94-
95-
assert_eq!(
96-
formatjson::format_json(&json).unwrap(),
97-
formatjson::format_json(
98-
r#"
99-
{
100-
"tcp4_announces_handled":1,
101-
"tcp4_scrapes_handled":2,
102-
"tcp6_announces_handled":3,
103-
"tcp6_scrapes_handled":4,
104-
"labeled_metrics": [
105-
{
106-
"metric": {
107-
"name": "announce_requests_received_total",
108-
"kind": "counter",
109-
"value": 325
110-
},
111-
"labels": {
112-
"ip_version":"ipv4",
113-
"protocol":"udp",
114-
"url":"udp://127.0.0.1:6969"
115-
}
116-
}
117-
]
118-
}"#
119-
)
120-
.unwrap()
121-
);
26+
self.labeled_metrics.increase_counter(metric_name, metric_labels);
12227
}
12328
}

packages/primitives/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ binascii = "0"
2020
bittorrent-primitives = "0.1.0"
2121
derive_more = { version = "2", features = ["constructor"] }
2222
serde = { version = "1", features = ["derive"] }
23+
serde_json = "1.0.140"
2324
tdyne-peer-id = "1"
2425
tdyne-peer-id-registry = "0"
2526
thiserror = "2"
@@ -28,4 +29,5 @@ url = "2.5.4"
2829
zerocopy = "0.7"
2930

3031
[dev-dependencies]
32+
formatjson = "0.3.1"
3133
rstest = "0.25.0"

packages/primitives/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
//! by the tracker server crate, but also by other crates in the Torrust
66
//! ecosystem.
77
pub mod core;
8+
pub mod metrics;
89
pub mod pagination;
910
pub mod peer;
1011
pub mod service_binding;

packages/primitives/src/metrics.rs

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
use std::collections::BTreeMap;
2+
3+
use serde::Serialize;
4+
5+
/// Metrics collected by the tracker.
6+
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
7+
pub struct LabeledMetrics {
8+
pub metrics: Vec<LabeledMetric>,
9+
}
10+
11+
impl LabeledMetrics {
12+
pub fn increase_counter(&mut self, metric_name: &str, metric_labels: &BTreeMap<String, String>) {
13+
let mut found = false;
14+
15+
for labeled_metric in &mut self.metrics {
16+
// todo:
17+
// - Check that the metric has the counter type.
18+
19+
if labeled_metric.metric.name == metric_name && labeled_metric.labels == *metric_labels {
20+
labeled_metric.metric.value += 1;
21+
found = true;
22+
break;
23+
}
24+
}
25+
26+
if !found {
27+
self.metrics.push(LabeledMetric {
28+
metric: Metric {
29+
name: metric_name.to_string(),
30+
kind: "counter".to_string(),
31+
value: 1,
32+
},
33+
labels: metric_labels.clone(),
34+
});
35+
}
36+
}
37+
}
38+
39+
#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize)]
40+
pub struct LabeledMetric {
41+
pub metric: Metric,
42+
pub labels: BTreeMap<String, String>,
43+
}
44+
45+
#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize)]
46+
pub struct Metric {
47+
pub name: String,
48+
pub kind: String,
49+
pub value: u64, // todo: change to f64. See https://prometheus.io/docs/concepts/data_model/#samples
50+
}
51+
52+
#[cfg(test)]
53+
mod tests {
54+
use std::collections::BTreeMap;
55+
56+
use super::LabeledMetric;
57+
use crate::metrics::{LabeledMetrics, Metric};
58+
59+
#[allow(clippy::no_effect_replace)]
60+
#[test]
61+
fn metrics_should_be_serializable_to_json() {
62+
let metrics = LabeledMetrics {
63+
metrics: vec![LabeledMetric {
64+
metric: Metric {
65+
name: "announce_requests_received_total".to_string(),
66+
kind: "counter".to_string(),
67+
value: 325,
68+
},
69+
labels: BTreeMap::from([
70+
("ip_version".to_string(), "ipv4".to_string()),
71+
("protocol".to_string(), "udp".to_string()),
72+
("url".to_string(), "udp://127.0.0.1:6969".to_string()),
73+
]),
74+
}],
75+
};
76+
77+
let json = serde_json::to_string(&metrics).unwrap();
78+
79+
assert_eq!(
80+
formatjson::format_json(&json).unwrap(),
81+
formatjson::format_json(
82+
r#"
83+
{
84+
"metrics": [
85+
{
86+
"metric": {
87+
"name": "announce_requests_received_total",
88+
"kind": "counter",
89+
"value": 325
90+
},
91+
"labels": {
92+
"ip_version":"ipv4",
93+
"protocol":"udp",
94+
"url":"udp://127.0.0.1:6969"
95+
}
96+
}
97+
]
98+
}"#
99+
)
100+
.unwrap()
101+
);
102+
}
103+
}

packages/rest-tracker-api-core/src/statistics/services.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use std::sync::Arc;
22

3-
use bittorrent_http_tracker_core::statistics::metrics::LabeledMetric;
43
use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
54
use bittorrent_udp_tracker_core::services::banning::BanService;
65
use bittorrent_udp_tracker_core::{self};
76
use tokio::sync::RwLock;
7+
use torrust_tracker_primitives::metrics::LabeledMetrics;
88
use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata;
99
use torrust_udp_tracker_server::statistics as udp_server_statistics;
1010

@@ -81,7 +81,7 @@ pub async fn get_metrics(
8181
#[derive(Debug, PartialEq)]
8282
pub struct TrackerLabeledMetrics {
8383
// Extendable metrics
84-
pub labeled_metrics: Vec<LabeledMetric>,
84+
pub labeled_metrics: LabeledMetrics,
8585
}
8686

8787
/// It returns all the [`TrackerLabeledMetrics`]

0 commit comments

Comments
 (0)