Quellcodebibliothek Statistik Leitseite products/sources/formale Sprachen/C/Firefox/toolkit/components/glean/api/src/private/   (Browser von der Mozilla Stiftung Version 136.0.1©)  Datei vom 10.2.2025 mit Größe 6 kB image not shown  

Quelle  rate.rs   Sprache: unbekannt

 
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use inherent::inherent;

use super::CommonMetricData;

use glean::traits::Rate;

use crate::ipc::{need_ipc, with_ipc_payload};
use crate::private::MetricId;

/// Developer-facing API for recording rate metrics.
///
/// Instances of this class type are automatically generated by the parsers
/// at build time, allowing developers to record values that were previously
/// registered in the metrics.yaml file.
#[derive(Clone)]
pub enum RateMetric {
    Parent {
        /// The metric's ID. Used for testing and profiler markers. Rate
        /// metrics canot be labeled, so we only store a MetricId. If this
        /// changes, this should be changed to a MetricGetter to distinguish
        /// between metrics and sub-metrics.
        id: MetricId,
        inner: glean::private::RateMetric,
    },
    Child(RateMetricIpc),
}
#[derive(Clone, Debug)]
pub struct RateMetricIpc(MetricId);

impl RateMetric {
    /// The public constructor used by automatically generated metrics.
    pub fn new(id: MetricId, meta: CommonMetricData) -> Self {
        if need_ipc() {
            RateMetric::Child(RateMetricIpc(id))
        } else {
            let inner = glean::private::RateMetric::new(meta);
            RateMetric::Parent { id, inner }
        }
    }

    #[cfg(test)]
    pub(crate) fn metric_id(&self) -> MetricId {
        match self {
            RateMetric::Parent { id, .. } => *id,
            RateMetric::Child(c) => c.0,
        }
    }

    #[cfg(test)]
    pub(crate) fn child_metric(&self) -> Self {
        match self {
            RateMetric::Parent { id, .. } => RateMetric::Child(RateMetricIpc(*id)),
            RateMetric::Child(_) => panic!("Can't get a child metric from a child metric"),
        }
    }
}

#[inherent]
impl Rate for RateMetric {
    pub fn add_to_numerator(&self, amount: i32) {
        #[allow(unused)]
        let id = match self {
            RateMetric::Parent { id, inner } => {
                inner.add_to_numerator(amount);
                *id
            }
            RateMetric::Child(c) => {
                with_ipc_payload(move |payload| {
                    if let Some(r) = payload.rates.get_mut(&c.0) {
                        r.0 += amount;
                    } else {
                        payload.rates.insert(c.0, (amount, 0));
                    }
                });
                c.0
            }
        };

        #[cfg(feature = "with_gecko")]
        if gecko_profiler::can_accept_markers() {
            gecko_profiler::add_marker(
                "Rate::addToNumerator",
                super::profiler_utils::TelemetryProfilerCategory,
                Default::default(),
                super::profiler_utils::IntLikeMetricMarker::new(id.into(), None, amount),
            );
        }
    }

    pub fn add_to_denominator(&self, amount: i32) {
        #[allow(unused)]
        let id = match self {
            RateMetric::Parent { id, inner } => {
                inner.add_to_denominator(amount);
                *id
            }
            RateMetric::Child(c) => {
                with_ipc_payload(move |payload| {
                    if let Some(r) = payload.rates.get_mut(&c.0) {
                        r.1 += amount;
                    } else {
                        payload.rates.insert(c.0, (0, amount));
                    }
                });
                c.0
            }
        };

        #[cfg(feature = "with_gecko")]
        if gecko_profiler::can_accept_markers() {
            gecko_profiler::add_marker(
                "Rate::addToDenominator",
                super::profiler_utils::TelemetryProfilerCategory,
                Default::default(),
                super::profiler_utils::IntLikeMetricMarker::new(id.into(), None, amount),
            );
        }
    }

    pub fn test_get_value<'a, S: Into<Option<&'a str>>>(
        &self,
        ping_name: S,
    ) -> Option<glean::Rate> {
        let ping_name = ping_name.into().map(|s| s.to_string());
        match self {
            RateMetric::Parent { inner, .. } => inner.test_get_value(ping_name),
            RateMetric::Child(c) => {
                panic!("Cannot get test value for {:?} in non-parent process!", c.0);
            }
        }
    }

    pub fn test_get_num_recorded_errors(&self, error: glean::ErrorType) -> i32 {
        match self {
            RateMetric::Parent { inner, .. } => inner.test_get_num_recorded_errors(error),
            RateMetric::Child(c) => {
                panic!(
                    "Cannot get the number of recorded errors for {:?} in non-parent process!",
                    c.0
                );
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{common_test::*, ipc, metrics};
    use glean::Rate;

    #[test]
    fn sets_rate_value_parent() {
        let _lock = lock_test();

        let metric = &metrics::test_only_ipc::irate;
        metric.add_to_numerator(1);
        metric.add_to_denominator(100);

        assert_eq!(
            Rate {
                numerator: 1,
                denominator: 100
            },
            metric.test_get_value("test-ping").unwrap()
        );
    }

    #[test]
    fn sets_rate_value_child() {
        let _lock = lock_test();

        let parent_metric = &metrics::test_only_ipc::irate;
        parent_metric.add_to_numerator(3);
        parent_metric.add_to_denominator(9);

        {
            // scope for need_ipc RAII
            let child_metric = parent_metric.child_metric();
            let _raii = ipc::test_set_need_ipc(true);
            let metric_id = child_metric.metric_id();

            child_metric.add_to_numerator(42);
            child_metric.add_to_denominator(24);

            ipc::with_ipc_payload(move |payload| {
                assert_eq!(
                    (42, 24),
                    *payload.rates.get(&metric_id).unwrap(),
                    "Stored the correct value in the ipc payload"
                );
            });
        }

        assert!(
            false == ipc::need_ipc(),
            "RAII dropped, should not need ipc any more"
        );
        assert!(ipc::replay_from_buf(&ipc::take_buf().unwrap()).is_ok());

        assert_eq!(
            Rate {
                numerator: 45,
                denominator: 33
            },
            parent_metric.test_get_value("test-ping").unwrap(),
            "Values from the 'processes' should be summed"
        );
    }
}

[ Dauer der Verarbeitung: 0.24 Sekunden  (vorverarbeitet)  ]