nym_statistics_common/clients/
connection.rs

1// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use super::ClientStatsEvents;
5
6use nym_credentials_interface::TicketType;
7use serde::{Deserialize, Serialize};
8
9#[derive(Default, Debug, Clone, Serialize, Deserialize)]
10pub(crate) struct ConnectionStats {
11    //tickets
12    mixnet_entry_spent: u32,
13    vpn_entry_spent: u32,
14    mixnet_exit_spent: u32,
15    vpn_exit_spent: u32,
16
17    //country_connection
18    wg_exit_country_code: String,
19    mix_exit_country_code: String,
20}
21
22/// Event space for Nym API statistics tracking
23#[derive(Debug)]
24pub enum ConnectionStatsEvent {
25    /// ecash ticket was spend
26    TicketSpent {
27        typ: TicketType,
28        amount: u32,
29    },
30    WgCountry(String),
31    MixCountry(String),
32}
33impl From<ConnectionStatsEvent> for ClientStatsEvents {
34    fn from(event: ConnectionStatsEvent) -> ClientStatsEvents {
35        ClientStatsEvents::Connection(event)
36    }
37}
38
39/// Nym API statistics tracking object
40#[derive(Default)]
41pub struct ConnectionStatsControl {
42    // Keep track of packet statistics over time
43    stats: ConnectionStats,
44}
45
46impl ConnectionStatsControl {
47    pub(crate) fn handle_event(&mut self, event: ConnectionStatsEvent) {
48        match event {
49            ConnectionStatsEvent::TicketSpent { typ, amount } => match typ {
50                TicketType::V1MixnetEntry => self.stats.mixnet_entry_spent += amount,
51                TicketType::V1MixnetExit => self.stats.mixnet_exit_spent += amount,
52                TicketType::V1WireguardEntry => self.stats.vpn_entry_spent += amount,
53                TicketType::V1WireguardExit => self.stats.vpn_exit_spent += amount,
54            },
55            ConnectionStatsEvent::WgCountry(cc) => {
56                self.stats.wg_exit_country_code = cc;
57            }
58            ConnectionStatsEvent::MixCountry(cc) => {
59                self.stats.mix_exit_country_code = cc;
60            }
61        }
62    }
63
64    pub(crate) fn report(&self) -> ConnectionStats {
65        self.stats.clone()
66    }
67}