Module glean.metrics

This module contains all of the metric types.

Expand source code
# 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 http://mozilla.org/MPL/2.0/.


"""
This module contains all of the metric types.
"""

# Re-export utilities
from .._uniffi import CommonMetricData
from .._uniffi import LabeledMetricData
from .._uniffi import Lifetime
from .._uniffi import MemoryUnit
from .._uniffi import TimerId
from .._uniffi import TimeUnit
from .._uniffi import RecordedExperiment

# Re-export some metrics directly
from .._uniffi import BooleanMetric as BooleanMetricType
from .._uniffi import CounterMetric as CounterMetricType
from .._uniffi import MemoryDistributionMetric as MemoryDistributionMetricType
from .._uniffi import QuantityMetric as QuantityMetricType
from .._uniffi import StringListMetric as StringListMetricType

# Export wrapper implementations for metric types
from .datetime import DatetimeMetricType
from .event import EventMetricType, EventExtras, RecordedEvent
from .object import ObjectMetricType, ObjectSerialize
from .labeled import (
    LabeledBooleanMetricType,
    LabeledCounterMetricType,
    LabeledStringMetricType,
)
from .ping import PingType
from .string import StringMetricType
from .timespan import TimespanMetricType
from .timing_distribution import TimingDistributionMetricType
from .url import UrlMetricType
from .uuid import UuidMetricType


__all__ = [
    "BooleanMetricType",
    "CommonMetricData",
    "CounterMetricType",
    "DatetimeMetricType",
    "EventExtras",
    "EventMetricType",
    "LabeledBooleanMetricType",
    "LabeledCounterMetricType",
    "LabeledMetricData",
    "LabeledStringMetricType",
    "Lifetime",
    "MemoryDistributionMetricType",
    "MemoryUnit",
    "ObjectMetricType",
    "ObjectSerialize",
    "PingType",
    "QuantityMetricType",
    "RecordedEvent",
    "RecordedExperiment",
    "StringListMetricType",
    "StringMetricType",
    "TimeUnit",
    "TimerId",
    "TimespanMetricType",
    "TimingDistributionMetricType",
    "UrlMetricType",
    "UuidMetricType",
]

Sub-modules

glean.metrics.datetime
glean.metrics.event
glean.metrics.labeled
glean.metrics.object
glean.metrics.ping
glean.metrics.string
glean.metrics.timespan
glean.metrics.timing_distribution
glean.metrics.url
glean.metrics.uuid

Classes

class BooleanMetricType (meta: "'CommonMetricData'")
Expand source code
class BooleanMetric:
    _pointer: ctypes.c_void_p
    def __init__(self, meta: "CommonMetricData"):
        _UniffiConverterTypeCommonMetricData.check_lower(meta)
        
        self._pointer = _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_constructor_booleanmetric_new,
        _UniffiConverterTypeCommonMetricData.lower(meta))

    def __del__(self):
        # In case of partial initialization of instances.
        pointer = getattr(self, "_pointer", None)
        if pointer is not None:
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_free_booleanmetric, pointer)

    def _uniffi_clone_pointer(self):
        return _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_clone_booleanmetric, self._pointer)

    # Used by alternative constructors or any methods which return this type.
    @classmethod
    def _make_instance_(cls, pointer):
        # Lightly yucky way to bypass the usual __init__ logic
        # and just create a new instance with the required pointer.
        inst = cls.__new__(cls)
        inst._pointer = pointer
        return inst


    def set(self, value: "bool") -> None:
        _UniffiConverterBool.check_lower(value)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_booleanmetric_set,self._uniffi_clone_pointer(),
        _UniffiConverterBool.lower(value))






    def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
        _UniffiConverterTypeErrorType.check_lower(error)
        
        return _UniffiConverterInt32.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_booleanmetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
        _UniffiConverterTypeErrorType.lower(error))
        )





    def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[bool]":
        if ping_name is _DEFAULT:
            ping_name = None
        _UniffiConverterOptionalString.check_lower(ping_name)
        
        return _UniffiConverterOptionalBool.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_booleanmetric_test_get_value,self._uniffi_clone_pointer(),
        _UniffiConverterOptionalString.lower(ping_name))
        )

Methods

def set(self, value: "'bool'") ‑> None
Expand source code
def set(self, value: "bool") -> None:
    _UniffiConverterBool.check_lower(value)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_booleanmetric_set,self._uniffi_clone_pointer(),
    _UniffiConverterBool.lower(value))
def test_get_num_recorded_errors(self, error: "'ErrorType'") ‑> int
Expand source code
def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
    _UniffiConverterTypeErrorType.check_lower(error)
    
    return _UniffiConverterInt32.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_booleanmetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
    _UniffiConverterTypeErrorType.lower(error))
    )
def test_get_value(self, ping_name: "'typing.Union[glean.metrics.object, typing.Optional[str]]'" = <object object>) ‑> Optional[bool]
Expand source code
def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[bool]":
    if ping_name is _DEFAULT:
        ping_name = None
    _UniffiConverterOptionalString.check_lower(ping_name)
    
    return _UniffiConverterOptionalBool.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_booleanmetric_test_get_value,self._uniffi_clone_pointer(),
    _UniffiConverterOptionalString.lower(ping_name))
    )
class CommonMetricData (*, category: "'str'", name: "'str'", send_in_pings: "'typing.List[str]'", lifetime: "'Lifetime'", disabled: "'bool'", dynamic_label: "'typing.Optional[str]'" = <object object>)
Expand source code
class CommonMetricData:
    category: "str"
    name: "str"
    send_in_pings: "typing.List[str]"
    lifetime: "Lifetime"
    disabled: "bool"
    dynamic_label: "typing.Optional[str]"
    def __init__(self, *, category: "str", name: "str", send_in_pings: "typing.List[str]", lifetime: "Lifetime", disabled: "bool", dynamic_label: "typing.Optional[str]" = _DEFAULT):
        self.category = category
        self.name = name
        self.send_in_pings = send_in_pings
        self.lifetime = lifetime
        self.disabled = disabled
        if dynamic_label is _DEFAULT:
            self.dynamic_label = None
        else:
            self.dynamic_label = dynamic_label

    def __str__(self):
        return "CommonMetricData(category={}, name={}, send_in_pings={}, lifetime={}, disabled={}, dynamic_label={})".format(self.category, self.name, self.send_in_pings, self.lifetime, self.disabled, self.dynamic_label)

    def __eq__(self, other):
        if self.category != other.category:
            return False
        if self.name != other.name:
            return False
        if self.send_in_pings != other.send_in_pings:
            return False
        if self.lifetime != other.lifetime:
            return False
        if self.disabled != other.disabled:
            return False
        if self.dynamic_label != other.dynamic_label:
            return False
        return True

Class variables

var category : str
var disabled : bool
var dynamic_label : Optional[str]
var lifetime : glean._uniffi.glean.Lifetime
var name : str
var send_in_pings : List[str]
class CounterMetricType (meta: "'CommonMetricData'")
Expand source code
class CounterMetric:
    _pointer: ctypes.c_void_p
    def __init__(self, meta: "CommonMetricData"):
        _UniffiConverterTypeCommonMetricData.check_lower(meta)
        
        self._pointer = _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_constructor_countermetric_new,
        _UniffiConverterTypeCommonMetricData.lower(meta))

    def __del__(self):
        # In case of partial initialization of instances.
        pointer = getattr(self, "_pointer", None)
        if pointer is not None:
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_free_countermetric, pointer)

    def _uniffi_clone_pointer(self):
        return _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_clone_countermetric, self._pointer)

    # Used by alternative constructors or any methods which return this type.
    @classmethod
    def _make_instance_(cls, pointer):
        # Lightly yucky way to bypass the usual __init__ logic
        # and just create a new instance with the required pointer.
        inst = cls.__new__(cls)
        inst._pointer = pointer
        return inst


    def add(self, amount: "typing.Union[object, int]" = _DEFAULT) -> None:
        if amount is _DEFAULT:
            amount = 1
        _UniffiConverterInt32.check_lower(amount)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_countermetric_add,self._uniffi_clone_pointer(),
        _UniffiConverterInt32.lower(amount))






    def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
        _UniffiConverterTypeErrorType.check_lower(error)
        
        return _UniffiConverterInt32.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_countermetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
        _UniffiConverterTypeErrorType.lower(error))
        )





    def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[int]":
        if ping_name is _DEFAULT:
            ping_name = None
        _UniffiConverterOptionalString.check_lower(ping_name)
        
        return _UniffiConverterOptionalInt32.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_countermetric_test_get_value,self._uniffi_clone_pointer(),
        _UniffiConverterOptionalString.lower(ping_name))
        )

Methods

def add(self, amount: "'typing.Union[glean.metrics.object, int]'" = <object object>) ‑> None
Expand source code
def add(self, amount: "typing.Union[object, int]" = _DEFAULT) -> None:
    if amount is _DEFAULT:
        amount = 1
    _UniffiConverterInt32.check_lower(amount)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_countermetric_add,self._uniffi_clone_pointer(),
    _UniffiConverterInt32.lower(amount))
def test_get_num_recorded_errors(self, error: "'ErrorType'") ‑> int
Expand source code
def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
    _UniffiConverterTypeErrorType.check_lower(error)
    
    return _UniffiConverterInt32.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_countermetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
    _UniffiConverterTypeErrorType.lower(error))
    )
def test_get_value(self, ping_name: "'typing.Union[glean.metrics.object, typing.Optional[str]]'" = <object object>) ‑> Optional[int]
Expand source code
def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[int]":
    if ping_name is _DEFAULT:
        ping_name = None
    _UniffiConverterOptionalString.check_lower(ping_name)
    
    return _UniffiConverterOptionalInt32.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_countermetric_test_get_value,self._uniffi_clone_pointer(),
    _UniffiConverterOptionalString.lower(ping_name))
    )
class DatetimeMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData, time_unit: glean._uniffi.glean.TimeUnit)

This implements the developer facing API for recording datetime metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The datetime API only exposes the DatetimeMetricType.set() method.

Expand source code
class DatetimeMetricType:
    """
    This implements the developer facing API for recording datetime metrics.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The datetime API only exposes the `DatetimeMetricType.set` method.
    """

    def __init__(self, common_metric_data: CommonMetricData, time_unit: TimeUnit):
        self._inner = DatetimeMetric(common_metric_data, time_unit)

    def set(self, value: Optional[datetime.datetime] = None) -> None:
        """
        Set a datetime value, truncating it to the metric's resolution.

        Args:
            value (datetime.datetime): (default: now) The `datetime.datetime`
                value to set. If not provided, will record the current time.
        """
        if value is None:
            # now at UTC -> astimezone gives us a time with the local timezone.
            value = datetime.datetime.now(datetime.timezone.utc).astimezone()

        tzinfo = value.tzinfo
        if tzinfo is not None:
            utcoff = tzinfo.utcoffset(value)
            if utcoff is not None:
                offset = utcoff.seconds
            else:
                offset = 0
        else:
            offset = 0

        dt = Datetime(
            year=value.year,
            month=value.month,
            day=value.day,
            hour=value.hour,
            minute=value.minute,
            second=value.second,
            nanosecond=value.microsecond * 1000,
            offset_seconds=offset,
        )

        self._inner.set(dt)

    def test_get_value_as_str(self, ping_name: Optional[str] = None) -> Optional[str]:
        """
        Returns the stored value for testing purposes only, as an ISO8601 string.

        Args:
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            value (str): value of the stored metric.
        """
        dt = self.test_get_value(ping_name)
        if not dt:
            return None

        return dt.isoformat()

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[datetime.datetime]:
        """
        Returns the stored value for testing purposes only.

        Args:
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            value (datetime.datetime): value of the stored metric.
        """
        value = self._inner.test_get_value(ping_name)
        if not value:
            return None

        tz = tzoffset(value.offset_seconds)
        dt = datetime.datetime(
            year=value.year,
            month=value.month,
            day=value.day,
            hour=value.hour,
            minute=value.minute,
            second=value.second,
            microsecond=round(value.nanosecond / 1000),
            tzinfo=tz,
        )
        return dt

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def set(self, value: Optional[datetime.datetime] = None) ‑> None

Set a datetime value, truncating it to the metric's resolution.

Args

value : datetime.datetime
(default: now) The datetime.datetime value to set. If not provided, will record the current time.
Expand source code
def set(self, value: Optional[datetime.datetime] = None) -> None:
    """
    Set a datetime value, truncating it to the metric's resolution.

    Args:
        value (datetime.datetime): (default: now) The `datetime.datetime`
            value to set. If not provided, will record the current time.
    """
    if value is None:
        # now at UTC -> astimezone gives us a time with the local timezone.
        value = datetime.datetime.now(datetime.timezone.utc).astimezone()

    tzinfo = value.tzinfo
    if tzinfo is not None:
        utcoff = tzinfo.utcoffset(value)
        if utcoff is not None:
            offset = utcoff.seconds
        else:
            offset = 0
    else:
        offset = 0

    dt = Datetime(
        year=value.year,
        month=value.month,
        day=value.day,
        hour=value.hour,
        minute=value.minute,
        second=value.second,
        nanosecond=value.microsecond * 1000,
        offset_seconds=offset,
    )

    self._inner.set(dt)
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int
Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[datetime.datetime]

Returns the stored value for testing purposes only.

Args

ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

value (datetime.datetime): value of the stored metric.

Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[datetime.datetime]:
    """
    Returns the stored value for testing purposes only.

    Args:
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        value (datetime.datetime): value of the stored metric.
    """
    value = self._inner.test_get_value(ping_name)
    if not value:
        return None

    tz = tzoffset(value.offset_seconds)
    dt = datetime.datetime(
        year=value.year,
        month=value.month,
        day=value.day,
        hour=value.hour,
        minute=value.minute,
        second=value.second,
        microsecond=round(value.nanosecond / 1000),
        tzinfo=tz,
    )
    return dt
def test_get_value_as_str(self, ping_name: Optional[str] = None) ‑> Optional[str]

Returns the stored value for testing purposes only, as an ISO8601 string.

Args

ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

value (str): value of the stored metric.

Expand source code
def test_get_value_as_str(self, ping_name: Optional[str] = None) -> Optional[str]:
    """
    Returns the stored value for testing purposes only, as an ISO8601 string.

    Args:
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        value (str): value of the stored metric.
    """
    dt = self.test_get_value(ping_name)
    if not dt:
        return None

    return dt.isoformat()
class EventExtras

A class that can be converted into key-value pairs of event extras. This will be automatically implemented for event properties of an [EventMetricType].

Expand source code
class EventExtras:
    """
    A class that can be converted into key-value pairs of event extras.
    This will be automatically implemented for event properties of an [EventMetricType].
    """

    def to_ffi_extra(self) -> Dict[str, str]:
        """
        Convert the event extras into a key-value dict:
        """
        return {}

Methods

def to_ffi_extra(self) ‑> Dict[str, str]

Convert the event extras into a key-value dict:

Expand source code
def to_ffi_extra(self) -> Dict[str, str]:
    """
    Convert the event extras into a key-value dict:
    """
    return {}
class EventMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData, allowed_extra_keys: List[str])

This implements the developer facing API for recording events.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The event API only exposes the EventMetricType.record() method, which takes care of validating the input data and making sure that limits are enforced.

Expand source code
class EventMetricType:
    """
    This implements the developer facing API for recording events.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The event API only exposes the `EventMetricType.record` method, which
    takes care of validating the input data and making sure that limits are
    enforced.
    """

    def __init__(
        self,
        common_metric_data: CommonMetricData,
        allowed_extra_keys: List[str],
    ):
        self._inner = EventMetric(common_metric_data, allowed_extra_keys)

    def record(self, extra: Optional[EventExtras] = None) -> None:
        """
        Record an event by using the information provided by the instance of
        this class.

        Args:
            extra: optional. The extra keys and values for this event.
                   The maximum length for values is 100.
        """

        if isinstance(extra, EventExtras):
            inner_extra = extra.to_ffi_extra()
        else:
            inner_extra = {}

        self._inner.record(inner_extra)

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[List[RecordedEvent]]:
        """
        Returns the stored value for testing purposes only.

        Args:
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            value (list of RecordedEventData): value of the stored events.
        """
        # Translate NO extras into an empty dictionary,
        # to simplify handling.
        recordings = self._inner.test_get_value(ping_name)
        if recordings:
            for recording in recordings:
                if recording.extra is None:
                    recording.extra = {}

        return recordings

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        """
        Returns the number of errors recorded for the given metric.

        Args:
            error_type (ErrorType): The type of error recorded.
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            num_errors (int): The number of errors recorded for the metric for
                the given error type.
        """
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def record(self, extra: Optional[EventExtras] = None) ‑> None

Record an event by using the information provided by the instance of this class.

Args

extra
optional. The extra keys and values for this event. The maximum length for values is 100.
Expand source code
def record(self, extra: Optional[EventExtras] = None) -> None:
    """
    Record an event by using the information provided by the instance of
    this class.

    Args:
        extra: optional. The extra keys and values for this event.
               The maximum length for values is 100.
    """

    if isinstance(extra, EventExtras):
        inner_extra = extra.to_ffi_extra()
    else:
        inner_extra = {}

    self._inner.record(inner_extra)
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int

Returns the number of errors recorded for the given metric.

Args

error_type : ErrorType
The type of error recorded.
ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

num_errors (int): The number of errors recorded for the metric for the given error type.

Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    """
    Returns the number of errors recorded for the given metric.

    Args:
        error_type (ErrorType): The type of error recorded.
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        num_errors (int): The number of errors recorded for the metric for
            the given error type.
    """
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[List[glean._uniffi.glean.RecordedEvent]]

Returns the stored value for testing purposes only.

Args

ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

value (list of RecordedEventData): value of the stored events.

Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[List[RecordedEvent]]:
    """
    Returns the stored value for testing purposes only.

    Args:
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        value (list of RecordedEventData): value of the stored events.
    """
    # Translate NO extras into an empty dictionary,
    # to simplify handling.
    recordings = self._inner.test_get_value(ping_name)
    if recordings:
        for recording in recordings:
            if recording.extra is None:
                recording.extra = {}

    return recordings
class LabeledBooleanMetricType (labeled_metric_data: glean._uniffi.glean.LabeledMetricData, labels: Optional[Set[str]] = None)

This implements the developer-facing API for labeled metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

Unlike most metric types, LabeledMetricType does not have its own corresponding storage, but records metrics for the underlying metric type T in the storage for that type. The only difference is that labeled metrics are stored with the special key $category.$name/$label. The collect method knows how to pull these special values back out of the individual metric storage and rearrange them correctly in the ping.

Expand source code
class LabeledBooleanMetricType(LabeledMetricBase):
    _ctor = LabeledBoolean

Ancestors

  • glean.metrics.labeled.LabeledMetricBase
class LabeledCounterMetricType (labeled_metric_data: glean._uniffi.glean.LabeledMetricData, labels: Optional[Set[str]] = None)

This implements the developer-facing API for labeled metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

Unlike most metric types, LabeledMetricType does not have its own corresponding storage, but records metrics for the underlying metric type T in the storage for that type. The only difference is that labeled metrics are stored with the special key $category.$name/$label. The collect method knows how to pull these special values back out of the individual metric storage and rearrange them correctly in the ping.

Expand source code
class LabeledCounterMetricType(LabeledMetricBase):
    _ctor = LabeledCounter

Ancestors

  • glean.metrics.labeled.LabeledMetricBase
class LabeledMetricData
Expand source code
class LabeledMetricData:
    def __init__(self):
        raise RuntimeError("LabeledMetricData cannot be instantiated directly")

    # Each enum variant is a nested class of the enum itself.
    class COMMON:
        cmd: "CommonMetricData"

        def __init__(self,cmd: "CommonMetricData"):
            self.cmd = cmd

        def __str__(self):
            return "LabeledMetricData.COMMON(cmd={})".format(self.cmd)

        def __eq__(self, other):
            if not other.is_common():
                return False
            if self.cmd != other.cmd:
                return False
            return True
    
    class CUSTOM_DISTRIBUTION:
        cmd: "CommonMetricData"
        range_min: "int"
        range_max: "int"
        bucket_count: "int"
        histogram_type: "HistogramType"

        def __init__(self,cmd: "CommonMetricData", range_min: "int", range_max: "int", bucket_count: "int", histogram_type: "HistogramType"):
            self.cmd = cmd
            self.range_min = range_min
            self.range_max = range_max
            self.bucket_count = bucket_count
            self.histogram_type = histogram_type

        def __str__(self):
            return "LabeledMetricData.CUSTOM_DISTRIBUTION(cmd={}, range_min={}, range_max={}, bucket_count={}, histogram_type={})".format(self.cmd, self.range_min, self.range_max, self.bucket_count, self.histogram_type)

        def __eq__(self, other):
            if not other.is_custom_distribution():
                return False
            if self.cmd != other.cmd:
                return False
            if self.range_min != other.range_min:
                return False
            if self.range_max != other.range_max:
                return False
            if self.bucket_count != other.bucket_count:
                return False
            if self.histogram_type != other.histogram_type:
                return False
            return True
    
    class MEMORY_DISTRIBUTION:
        cmd: "CommonMetricData"
        unit: "MemoryUnit"

        def __init__(self,cmd: "CommonMetricData", unit: "MemoryUnit"):
            self.cmd = cmd
            self.unit = unit

        def __str__(self):
            return "LabeledMetricData.MEMORY_DISTRIBUTION(cmd={}, unit={})".format(self.cmd, self.unit)

        def __eq__(self, other):
            if not other.is_memory_distribution():
                return False
            if self.cmd != other.cmd:
                return False
            if self.unit != other.unit:
                return False
            return True
    
    class TIMING_DISTRIBUTION:
        cmd: "CommonMetricData"
        unit: "TimeUnit"

        def __init__(self,cmd: "CommonMetricData", unit: "TimeUnit"):
            self.cmd = cmd
            self.unit = unit

        def __str__(self):
            return "LabeledMetricData.TIMING_DISTRIBUTION(cmd={}, unit={})".format(self.cmd, self.unit)

        def __eq__(self, other):
            if not other.is_timing_distribution():
                return False
            if self.cmd != other.cmd:
                return False
            if self.unit != other.unit:
                return False
            return True
    
    

    # For each variant, we have an `is_NAME` method for easily checking
    # whether an instance is that variant.
    def is_common(self) -> bool:
        return isinstance(self, LabeledMetricData.COMMON)
    def is_custom_distribution(self) -> bool:
        return isinstance(self, LabeledMetricData.CUSTOM_DISTRIBUTION)
    def is_memory_distribution(self) -> bool:
        return isinstance(self, LabeledMetricData.MEMORY_DISTRIBUTION)
    def is_timing_distribution(self) -> bool:
        return isinstance(self, LabeledMetricData.TIMING_DISTRIBUTION)

Subclasses

  • glean._uniffi.glean.LabeledMetricData.COMMON
  • glean._uniffi.glean.LabeledMetricData.CUSTOM_DISTRIBUTION
  • glean._uniffi.glean.LabeledMetricData.MEMORY_DISTRIBUTION
  • glean._uniffi.glean.LabeledMetricData.TIMING_DISTRIBUTION

Class variables

var COMMON
var CUSTOM_DISTRIBUTION
var MEMORY_DISTRIBUTION
var TIMING_DISTRIBUTION

Methods

def is_common(self) ‑> bool
Expand source code
def is_common(self) -> bool:
    return isinstance(self, LabeledMetricData.COMMON)
def is_custom_distribution(self) ‑> bool
Expand source code
def is_custom_distribution(self) -> bool:
    return isinstance(self, LabeledMetricData.CUSTOM_DISTRIBUTION)
def is_memory_distribution(self) ‑> bool
Expand source code
def is_memory_distribution(self) -> bool:
    return isinstance(self, LabeledMetricData.MEMORY_DISTRIBUTION)
def is_timing_distribution(self) ‑> bool
Expand source code
def is_timing_distribution(self) -> bool:
    return isinstance(self, LabeledMetricData.TIMING_DISTRIBUTION)
class LabeledStringMetricType (labeled_metric_data: glean._uniffi.glean.LabeledMetricData, labels: Optional[Set[str]] = None)

This implements the developer-facing API for labeled metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

Unlike most metric types, LabeledMetricType does not have its own corresponding storage, but records metrics for the underlying metric type T in the storage for that type. The only difference is that labeled metrics are stored with the special key $category.$name/$label. The collect method knows how to pull these special values back out of the individual metric storage and rearrange them correctly in the ping.

Expand source code
class LabeledStringMetricType(LabeledMetricBase):
    _ctor = LabeledString

Ancestors

  • glean.metrics.labeled.LabeledMetricBase
class Lifetime (value, names=None, *, module=None, qualname=None, type=None, start=1)

An enumeration.

Expand source code
class Lifetime(enum.Enum):
    PING = 0
    
    APPLICATION = 1
    
    USER = 2

Ancestors

  • enum.Enum

Class variables

var APPLICATION
var PING
var USER
class MemoryDistributionMetricType (meta: "'CommonMetricData'", memory_unit: "'MemoryUnit'")
Expand source code
class MemoryDistributionMetric:
    _pointer: ctypes.c_void_p
    def __init__(self, meta: "CommonMetricData",memory_unit: "MemoryUnit"):
        _UniffiConverterTypeCommonMetricData.check_lower(meta)
        
        _UniffiConverterTypeMemoryUnit.check_lower(memory_unit)
        
        self._pointer = _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_constructor_memorydistributionmetric_new,
        _UniffiConverterTypeCommonMetricData.lower(meta),
        _UniffiConverterTypeMemoryUnit.lower(memory_unit))

    def __del__(self):
        # In case of partial initialization of instances.
        pointer = getattr(self, "_pointer", None)
        if pointer is not None:
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_free_memorydistributionmetric, pointer)

    def _uniffi_clone_pointer(self):
        return _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_clone_memorydistributionmetric, self._pointer)

    # Used by alternative constructors or any methods which return this type.
    @classmethod
    def _make_instance_(cls, pointer):
        # Lightly yucky way to bypass the usual __init__ logic
        # and just create a new instance with the required pointer.
        inst = cls.__new__(cls)
        inst._pointer = pointer
        return inst


    def accumulate(self, sample: "int") -> None:
        _UniffiConverterInt64.check_lower(sample)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_accumulate,self._uniffi_clone_pointer(),
        _UniffiConverterInt64.lower(sample))






    def accumulate_samples(self, samples: "typing.List[int]") -> None:
        _UniffiConverterSequenceInt64.check_lower(samples)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_accumulate_samples,self._uniffi_clone_pointer(),
        _UniffiConverterSequenceInt64.lower(samples))






    def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
        _UniffiConverterTypeErrorType.check_lower(error)
        
        return _UniffiConverterInt32.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
        _UniffiConverterTypeErrorType.lower(error))
        )





    def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[DistributionData]":
        if ping_name is _DEFAULT:
            ping_name = None
        _UniffiConverterOptionalString.check_lower(ping_name)
        
        return _UniffiConverterOptionalTypeDistributionData.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_test_get_value,self._uniffi_clone_pointer(),
        _UniffiConverterOptionalString.lower(ping_name))
        )

Methods

def accumulate(self, sample: "'int'") ‑> None
Expand source code
def accumulate(self, sample: "int") -> None:
    _UniffiConverterInt64.check_lower(sample)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_accumulate,self._uniffi_clone_pointer(),
    _UniffiConverterInt64.lower(sample))
def accumulate_samples(self, samples: "'typing.List[int]'") ‑> None
Expand source code
def accumulate_samples(self, samples: "typing.List[int]") -> None:
    _UniffiConverterSequenceInt64.check_lower(samples)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_accumulate_samples,self._uniffi_clone_pointer(),
    _UniffiConverterSequenceInt64.lower(samples))
def test_get_num_recorded_errors(self, error: "'ErrorType'") ‑> int
Expand source code
def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
    _UniffiConverterTypeErrorType.check_lower(error)
    
    return _UniffiConverterInt32.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
    _UniffiConverterTypeErrorType.lower(error))
    )
def test_get_value(self, ping_name: "'typing.Union[glean.metrics.object, typing.Optional[str]]'" = <object object>) ‑> Optional[glean._uniffi.glean.DistributionData]
Expand source code
def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[DistributionData]":
    if ping_name is _DEFAULT:
        ping_name = None
    _UniffiConverterOptionalString.check_lower(ping_name)
    
    return _UniffiConverterOptionalTypeDistributionData.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_memorydistributionmetric_test_get_value,self._uniffi_clone_pointer(),
    _UniffiConverterOptionalString.lower(ping_name))
    )
class MemoryUnit (value, names=None, *, module=None, qualname=None, type=None, start=1)

An enumeration.

Expand source code
class MemoryUnit(enum.Enum):
    BYTE = 0
    
    KILOBYTE = 1
    
    MEGABYTE = 2
    
    GIGABYTE = 3

Ancestors

  • enum.Enum

Class variables

var BYTE
var GIGABYTE
var KILOBYTE
var MEGABYTE
class ObjectMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData, ty: Any)

This implements the developer facing API for recording events.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The event API only exposes the ObjectMetricType.set() method, which takes care of validating the input data and making sure that limits are enforced.

Expand source code
class ObjectMetricType(Generic[T]):
    """
    This implements the developer facing API for recording events.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The event API only exposes the `ObjectMetricType.set` method, which
    takes care of validating the input data and making sure that limits are
    enforced.
    """

    def __init__(
        self,
        common_metric_data: CommonMetricData,
        ty: Any,
    ):
        self._inner = ObjectMetric(common_metric_data)
        self._objty = ty

    def set(self, obj: T) -> None:
        """
        Set the object.
        Args:
            extra: optional. The extra keys and values for this event.
                   The maximum length for values is 100.
        """

        if isinstance(obj, self._objty):
            inner_obj = obj.into_serialized_object()
            self._inner.set_string(inner_obj)
        else:
            self._inner.record_schema_error()

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[dict]:
        """
        Returns the stored value for testing purposes only.

        Args:
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            value (list of RecordedEventData): value of the stored events.
        """
        data = self._inner.test_get_value(ping_name)
        if data:
            return json.loads(data)

        return None

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        """
        Returns the number of errors recorded for the given metric.

        Args:
            error_type (ErrorType): The type of error recorded.
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            num_errors (int): The number of errors recorded for the metric for
                the given error type.
        """
        return self._inner.test_get_num_recorded_errors(error_type)

Ancestors

  • typing.Generic

Methods

def set(self, obj: ~T) ‑> None

Set the object.

Args

extra
optional. The extra keys and values for this event. The maximum length for values is 100.
Expand source code
def set(self, obj: T) -> None:
    """
    Set the object.
    Args:
        extra: optional. The extra keys and values for this event.
               The maximum length for values is 100.
    """

    if isinstance(obj, self._objty):
        inner_obj = obj.into_serialized_object()
        self._inner.set_string(inner_obj)
    else:
        self._inner.record_schema_error()
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int

Returns the number of errors recorded for the given metric.

Args

error_type : ErrorType
The type of error recorded.
ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

num_errors (int): The number of errors recorded for the metric for the given error type.

Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    """
    Returns the number of errors recorded for the given metric.

    Args:
        error_type (ErrorType): The type of error recorded.
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        num_errors (int): The number of errors recorded for the metric for
            the given error type.
    """
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[dict]

Returns the stored value for testing purposes only.

Args

ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

value (list of RecordedEventData): value of the stored events.

Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[dict]:
    """
    Returns the stored value for testing purposes only.

    Args:
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        value (list of RecordedEventData): value of the stored events.
    """
    data = self._inner.test_get_value(ping_name)
    if data:
        return json.loads(data)

    return None
class ObjectSerialize

A class that can be converted into key-value pairs of event extras. This will be automatically implemented for event properties of an [ObjectMetricType].

Expand source code
class ObjectSerialize:
    """
    A class that can be converted into key-value pairs of event extras.
    This will be automatically implemented for event properties of an [ObjectMetricType].
    """

    def into_serialized_object(self) -> str:
        """
        Convert the event extras into a key-value dict:
        """
        return json.dumps(self, cls=EncodeObject)

Methods

def into_serialized_object(self) ‑> str

Convert the event extras into a key-value dict:

Expand source code
def into_serialized_object(self) -> str:
    """
    Convert the event extras into a key-value dict:
    """
    return json.dumps(self, cls=EncodeObject)
class PingType (name: str, include_client_id: bool, send_if_empty: bool, precise_timestamps: bool, include_info_sections: bool, schedules_pings: List[str], reason_codes: List[str], enabled: bool = True, follows_collection_enabled: bool = True)

This implements the developer facing API for custom pings.

The Ping API only exposes the PingType.submit() method, which schedules a ping for eventual uploading.

Expand source code
class PingType:
    def __init__(
        self,
        name: str,
        include_client_id: bool,
        send_if_empty: bool,
        precise_timestamps: bool,
        include_info_sections: bool,
        schedules_pings: List[str],
        reason_codes: List[str],
        enabled: bool = True,
        follows_collection_enabled: bool = True,
    ):
        """
        This implements the developer facing API for custom pings.

        The Ping API only exposes the `PingType.submit` method, which schedules a
        ping for eventual uploading.
        """
        self._reason_codes = reason_codes
        self._inner = GleanPingType(
            name,
            include_client_id,
            send_if_empty,
            precise_timestamps,
            include_info_sections,
            enabled,
            schedules_pings,
            reason_codes,
            follows_collection_enabled,
        )
        self._test_callback = None  # type: Optional[Callable[[Optional[str]], None]]

    def test_before_next_submit(self, cb: Callable[[Optional[str]], None]):
        """
        **Test-only API**

        Attach a callback to be called right before a new ping is submitted.
        The provided function is called exactly once before submitting a ping.

        Note: The callback will be called on any call to submit.
        A ping might not be sent afterwards, e.g. if the ping is otherwise empty (and
        `send_if_empty` is `False`).
        """
        self._test_callback = cb

    def submit(self, reason: Optional[int] = None) -> None:
        """
        Collect and submit the ping for eventual uploading.

        If the ping currently contains no content, it will not be sent.

        Args:
            reason (enum, optional): The reason the ping was submitted.
        """
        reason_string: Optional[str] = None
        if reason is not None:
            reason_string = self._reason_codes[reason]
        else:
            reason_string = None

        if self._test_callback is not None:
            self._test_callback(reason_string)
            self._test_callback = None

        self._inner.submit(reason_string)

    def set_enabled(self, enabled: bool) -> None:
        """
        Enable or disable a ping.

        Disabling a ping causes all data for that ping to be removed from storage
        and all pending pings of that type to be deleted.
        """
        self._inner.set_enabled(enabled)

Methods

def set_enabled(self, enabled: bool) ‑> None

Enable or disable a ping.

Disabling a ping causes all data for that ping to be removed from storage and all pending pings of that type to be deleted.

Expand source code
def set_enabled(self, enabled: bool) -> None:
    """
    Enable or disable a ping.

    Disabling a ping causes all data for that ping to be removed from storage
    and all pending pings of that type to be deleted.
    """
    self._inner.set_enabled(enabled)
def submit(self, reason: Optional[int] = None) ‑> None

Collect and submit the ping for eventual uploading.

If the ping currently contains no content, it will not be sent.

Args

reason : enum, optional
The reason the ping was submitted.
Expand source code
def submit(self, reason: Optional[int] = None) -> None:
    """
    Collect and submit the ping for eventual uploading.

    If the ping currently contains no content, it will not be sent.

    Args:
        reason (enum, optional): The reason the ping was submitted.
    """
    reason_string: Optional[str] = None
    if reason is not None:
        reason_string = self._reason_codes[reason]
    else:
        reason_string = None

    if self._test_callback is not None:
        self._test_callback(reason_string)
        self._test_callback = None

    self._inner.submit(reason_string)
def test_before_next_submit(self, cb: Callable[[Optional[str]], None])

Test-only API

Attach a callback to be called right before a new ping is submitted. The provided function is called exactly once before submitting a ping.

Note: The callback will be called on any call to submit. A ping might not be sent afterwards, e.g. if the ping is otherwise empty (and send_if_empty is False).

Expand source code
def test_before_next_submit(self, cb: Callable[[Optional[str]], None]):
    """
    **Test-only API**

    Attach a callback to be called right before a new ping is submitted.
    The provided function is called exactly once before submitting a ping.

    Note: The callback will be called on any call to submit.
    A ping might not be sent afterwards, e.g. if the ping is otherwise empty (and
    `send_if_empty` is `False`).
    """
    self._test_callback = cb
class QuantityMetricType (meta: "'CommonMetricData'")
Expand source code
class QuantityMetric:
    _pointer: ctypes.c_void_p
    def __init__(self, meta: "CommonMetricData"):
        _UniffiConverterTypeCommonMetricData.check_lower(meta)
        
        self._pointer = _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_constructor_quantitymetric_new,
        _UniffiConverterTypeCommonMetricData.lower(meta))

    def __del__(self):
        # In case of partial initialization of instances.
        pointer = getattr(self, "_pointer", None)
        if pointer is not None:
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_free_quantitymetric, pointer)

    def _uniffi_clone_pointer(self):
        return _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_clone_quantitymetric, self._pointer)

    # Used by alternative constructors or any methods which return this type.
    @classmethod
    def _make_instance_(cls, pointer):
        # Lightly yucky way to bypass the usual __init__ logic
        # and just create a new instance with the required pointer.
        inst = cls.__new__(cls)
        inst._pointer = pointer
        return inst


    def set(self, value: "int") -> None:
        _UniffiConverterInt64.check_lower(value)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_quantitymetric_set,self._uniffi_clone_pointer(),
        _UniffiConverterInt64.lower(value))






    def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
        _UniffiConverterTypeErrorType.check_lower(error)
        
        return _UniffiConverterInt32.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_quantitymetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
        _UniffiConverterTypeErrorType.lower(error))
        )





    def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[int]":
        if ping_name is _DEFAULT:
            ping_name = None
        _UniffiConverterOptionalString.check_lower(ping_name)
        
        return _UniffiConverterOptionalInt64.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_quantitymetric_test_get_value,self._uniffi_clone_pointer(),
        _UniffiConverterOptionalString.lower(ping_name))
        )

Methods

def set(self, value: "'int'") ‑> None
Expand source code
def set(self, value: "int") -> None:
    _UniffiConverterInt64.check_lower(value)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_quantitymetric_set,self._uniffi_clone_pointer(),
    _UniffiConverterInt64.lower(value))
def test_get_num_recorded_errors(self, error: "'ErrorType'") ‑> int
Expand source code
def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
    _UniffiConverterTypeErrorType.check_lower(error)
    
    return _UniffiConverterInt32.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_quantitymetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
    _UniffiConverterTypeErrorType.lower(error))
    )
def test_get_value(self, ping_name: "'typing.Union[glean.metrics.object, typing.Optional[str]]'" = <object object>) ‑> Optional[int]
Expand source code
def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[int]":
    if ping_name is _DEFAULT:
        ping_name = None
    _UniffiConverterOptionalString.check_lower(ping_name)
    
    return _UniffiConverterOptionalInt64.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_quantitymetric_test_get_value,self._uniffi_clone_pointer(),
    _UniffiConverterOptionalString.lower(ping_name))
    )
class RecordedEvent (*, timestamp: "'int'", category: "'str'", name: "'str'", extra: "'typing.Optional[dict[str, str]]'")
Expand source code
class RecordedEvent:
    timestamp: "int"
    category: "str"
    name: "str"
    extra: "typing.Optional[dict[str, str]]"
    def __init__(self, *, timestamp: "int", category: "str", name: "str", extra: "typing.Optional[dict[str, str]]"):
        self.timestamp = timestamp
        self.category = category
        self.name = name
        self.extra = extra

    def __str__(self):
        return "RecordedEvent(timestamp={}, category={}, name={}, extra={})".format(self.timestamp, self.category, self.name, self.extra)

    def __eq__(self, other):
        if self.timestamp != other.timestamp:
            return False
        if self.category != other.category:
            return False
        if self.name != other.name:
            return False
        if self.extra != other.extra:
            return False
        return True

Class variables

var category : str
var extra : Optional[dict[str, str]]
var name : str
var timestamp : int
class RecordedExperiment (*, branch: "'str'", extra: "'typing.Optional[dict[str, str]]'")
Expand source code
class RecordedExperiment:
    branch: "str"
    extra: "typing.Optional[dict[str, str]]"
    def __init__(self, *, branch: "str", extra: "typing.Optional[dict[str, str]]"):
        self.branch = branch
        self.extra = extra

    def __str__(self):
        return "RecordedExperiment(branch={}, extra={})".format(self.branch, self.extra)

    def __eq__(self, other):
        if self.branch != other.branch:
            return False
        if self.extra != other.extra:
            return False
        return True

Class variables

var branch : str
var extra : Optional[dict[str, str]]
class StringListMetricType (meta: "'CommonMetricData'")
Expand source code
class StringListMetric:
    _pointer: ctypes.c_void_p
    def __init__(self, meta: "CommonMetricData"):
        _UniffiConverterTypeCommonMetricData.check_lower(meta)
        
        self._pointer = _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_constructor_stringlistmetric_new,
        _UniffiConverterTypeCommonMetricData.lower(meta))

    def __del__(self):
        # In case of partial initialization of instances.
        pointer = getattr(self, "_pointer", None)
        if pointer is not None:
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_free_stringlistmetric, pointer)

    def _uniffi_clone_pointer(self):
        return _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_clone_stringlistmetric, self._pointer)

    # Used by alternative constructors or any methods which return this type.
    @classmethod
    def _make_instance_(cls, pointer):
        # Lightly yucky way to bypass the usual __init__ logic
        # and just create a new instance with the required pointer.
        inst = cls.__new__(cls)
        inst._pointer = pointer
        return inst


    def add(self, value: "str") -> None:
        _UniffiConverterString.check_lower(value)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_add,self._uniffi_clone_pointer(),
        _UniffiConverterString.lower(value))






    def set(self, value: "typing.List[str]") -> None:
        _UniffiConverterSequenceString.check_lower(value)
        
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_set,self._uniffi_clone_pointer(),
        _UniffiConverterSequenceString.lower(value))






    def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
        _UniffiConverterTypeErrorType.check_lower(error)
        
        return _UniffiConverterInt32.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
        _UniffiConverterTypeErrorType.lower(error))
        )





    def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[typing.List[str]]":
        if ping_name is _DEFAULT:
            ping_name = None
        _UniffiConverterOptionalString.check_lower(ping_name)
        
        return _UniffiConverterOptionalSequenceString.lift(
            _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_test_get_value,self._uniffi_clone_pointer(),
        _UniffiConverterOptionalString.lower(ping_name))
        )

Methods

def add(self, value: "'str'") ‑> None
Expand source code
def add(self, value: "str") -> None:
    _UniffiConverterString.check_lower(value)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_add,self._uniffi_clone_pointer(),
    _UniffiConverterString.lower(value))
def set(self, value: "'typing.List[str]'") ‑> None
Expand source code
def set(self, value: "typing.List[str]") -> None:
    _UniffiConverterSequenceString.check_lower(value)
    
    _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_set,self._uniffi_clone_pointer(),
    _UniffiConverterSequenceString.lower(value))
def test_get_num_recorded_errors(self, error: "'ErrorType'") ‑> int
Expand source code
def test_get_num_recorded_errors(self, error: "ErrorType") -> "int":
    _UniffiConverterTypeErrorType.check_lower(error)
    
    return _UniffiConverterInt32.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_test_get_num_recorded_errors,self._uniffi_clone_pointer(),
    _UniffiConverterTypeErrorType.lower(error))
    )
def test_get_value(self, ping_name: "'typing.Union[glean.metrics.object, typing.Optional[str]]'" = <object object>) ‑> Optional[List[str]]
Expand source code
def test_get_value(self, ping_name: "typing.Union[object, typing.Optional[str]]" = _DEFAULT) -> "typing.Optional[typing.List[str]]":
    if ping_name is _DEFAULT:
        ping_name = None
    _UniffiConverterOptionalString.check_lower(ping_name)
    
    return _UniffiConverterOptionalSequenceString.lift(
        _uniffi_rust_call(_UniffiLib.uniffi_glean_core_fn_method_stringlistmetric_test_get_value,self._uniffi_clone_pointer(),
    _UniffiConverterOptionalString.lower(ping_name))
    )
class StringMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData)

This implements the developer facing API for recording string metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The string API only exposes the StringMetricType.set() method, which takes care of validating the input data and making sure that limits are enforced.

Expand source code
class StringMetricType:
    """
    This implements the developer facing API for recording string metrics.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The string API only exposes the `StringMetricType.set` method, which
    takes care of validating the input data and making sure that limits are
    enforced.
    """

    def __init__(self, common_metric_data: CommonMetricData):
        self._inner = StringMetric(common_metric_data)

    def set(self, value: str) -> None:
        """
        Set a string value.

        Args:
            value (str): This is a user-defined string value. If the length of
                the string exceeds the maximum length, it will be truncated.
        """
        if value is None:
            return

        self._inner.set(value)

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[str]:
        return self._inner.test_get_value(ping_name)

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def set(self, value: str) ‑> None

Set a string value.

Args

value : str
This is a user-defined string value. If the length of the string exceeds the maximum length, it will be truncated.
Expand source code
def set(self, value: str) -> None:
    """
    Set a string value.

    Args:
        value (str): This is a user-defined string value. If the length of
            the string exceeds the maximum length, it will be truncated.
    """
    if value is None:
        return

    self._inner.set(value)
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int
Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[str]
Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[str]:
    return self._inner.test_get_value(ping_name)
class TimeUnit (value, names=None, *, module=None, qualname=None, type=None, start=1)

An enumeration.

Expand source code
class TimeUnit(enum.Enum):
    NANOSECOND = 0
    
    MICROSECOND = 1
    
    MILLISECOND = 2
    
    SECOND = 3
    
    MINUTE = 4
    
    HOUR = 5
    
    DAY = 6

Ancestors

  • enum.Enum

Class variables

var DAY
var HOUR
var MICROSECOND
var MILLISECOND
var MINUTE
var NANOSECOND
var SECOND
class TimerId (*, id: "'int'")
Expand source code
class TimerId:
    id: "int"
    def __init__(self, *, id: "int"):
        self.id = id

    def __str__(self):
        return "TimerId(id={})".format(self.id)

    def __eq__(self, other):
        if self.id != other.id:
            return False
        return True

Class variables

var id : int
class TimespanMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData, time_unit: glean._uniffi.glean.TimeUnit)

This implements the developer facing API for recording timespan metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The timespan API exposes the TimespanMetricType.start(), TimespanMetricType.stop() and TimespanMetricType.cancel() methods.

Expand source code
class TimespanMetricType:
    """
    This implements the developer facing API for recording timespan metrics.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The timespan API exposes the `TimespanMetricType.start`,
    `TimespanMetricType.stop` and `TimespanMetricType.cancel` methods.
    """

    def __init__(
        self,
        common_metric_data: CommonMetricData,
        time_unit: TimeUnit,
    ):
        self._inner = TimespanMetric(common_metric_data, time_unit)

    def start(self) -> None:
        """
        Start tracking time for the provided metric.

        This records an error if it’s already tracking time (i.e. `start` was
        already called with no corresponding `stop`): in that case the original
        start time will be preserved.
        """
        self._inner.start()

    def stop(self) -> None:
        """
        Stop tracking time for the provided metric.

        Sets the metric to the elapsed time, but does not overwrite an already
        existing value.
        This will record an error if no `start` was called or there is an already
        existing value.
        """
        self._inner.stop()

    def cancel(self) -> None:
        """
        Abort a previous `start` call. No error is recorded if no `start` was called.
        """
        self._inner.cancel()

    class _TimespanContextManager:
        """
        A context manager for recording timings. Used by the `measure` method.
        """

        def __init__(self, timespan: "TimespanMetricType"):
            self._timespan = timespan

        def __enter__(self) -> None:
            self._timespan.start()

        def __exit__(self, type, value, tb) -> None:
            if tb is None:
                self._timespan.stop()
            else:
                self._timespan.cancel()

    def measure(self) -> "_TimespanContextManager":
        """
        Provides a context manager for measuring the time it takes to execute
        snippets of code in a `with` statement.

        If the contents of the `with` statement raise an exception, the timing
        is not recorded.

        Usage:
            with metrics.perf.timer.measure():
                # ... do something that takes time ...
        """
        return self._TimespanContextManager(self)

    def set_raw_nanos(self, elapsed_nanos: int) -> None:
        """
        Explicitly set the timespan value, in nanoseconds.

        This API should only be used if your library or application requires recording
        times in a way that can not make use of [start]/[stop]/[cancel].

        [setRawNanos] does not overwrite a running timer or an already existing value.

        Args:
            elapsed_nanos (int): The elapsed time to record, in nanoseconds.
        """
        self._inner.set_raw_nanos(elapsed_nanos)

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[int]:
        """
        Returns the stored value for testing purposes only.

        Args:
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            value (bool): value of the stored metric.
        """
        return self._inner.test_get_value(ping_name)

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        """
        Returns the number of errors recorded for the given metric.

        Args:
            error_type (ErrorType): The type of error recorded.
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            num_errors (int): The number of errors recorded for the metric for
                the given error type.
        """
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def cancel(self) ‑> None

Abort a previous start call. No error is recorded if no start was called.

Expand source code
def cancel(self) -> None:
    """
    Abort a previous `start` call. No error is recorded if no `start` was called.
    """
    self._inner.cancel()
def measure(self) ‑> _TimespanContextManager

Provides a context manager for measuring the time it takes to execute snippets of code in a with statement.

If the contents of the with statement raise an exception, the timing is not recorded.

Usage

with metrics.perf.timer.measure(): # … do something that takes time …

Expand source code
def measure(self) -> "_TimespanContextManager":
    """
    Provides a context manager for measuring the time it takes to execute
    snippets of code in a `with` statement.

    If the contents of the `with` statement raise an exception, the timing
    is not recorded.

    Usage:
        with metrics.perf.timer.measure():
            # ... do something that takes time ...
    """
    return self._TimespanContextManager(self)
def set_raw_nanos(self, elapsed_nanos: int) ‑> None

Explicitly set the timespan value, in nanoseconds.

This API should only be used if your library or application requires recording times in a way that can not make use of [start]/[stop]/[cancel].

[setRawNanos] does not overwrite a running timer or an already existing value.

Args

elapsed_nanos : int
The elapsed time to record, in nanoseconds.
Expand source code
def set_raw_nanos(self, elapsed_nanos: int) -> None:
    """
    Explicitly set the timespan value, in nanoseconds.

    This API should only be used if your library or application requires recording
    times in a way that can not make use of [start]/[stop]/[cancel].

    [setRawNanos] does not overwrite a running timer or an already existing value.

    Args:
        elapsed_nanos (int): The elapsed time to record, in nanoseconds.
    """
    self._inner.set_raw_nanos(elapsed_nanos)
def start(self) ‑> None

Start tracking time for the provided metric.

This records an error if it’s already tracking time (i.e. start was already called with no corresponding stop): in that case the original start time will be preserved.

Expand source code
def start(self) -> None:
    """
    Start tracking time for the provided metric.

    This records an error if it’s already tracking time (i.e. `start` was
    already called with no corresponding `stop`): in that case the original
    start time will be preserved.
    """
    self._inner.start()
def stop(self) ‑> None

Stop tracking time for the provided metric.

Sets the metric to the elapsed time, but does not overwrite an already existing value. This will record an error if no start was called or there is an already existing value.

Expand source code
def stop(self) -> None:
    """
    Stop tracking time for the provided metric.

    Sets the metric to the elapsed time, but does not overwrite an already
    existing value.
    This will record an error if no `start` was called or there is an already
    existing value.
    """
    self._inner.stop()
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int

Returns the number of errors recorded for the given metric.

Args

error_type : ErrorType
The type of error recorded.
ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

num_errors (int): The number of errors recorded for the metric for the given error type.

Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    """
    Returns the number of errors recorded for the given metric.

    Args:
        error_type (ErrorType): The type of error recorded.
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        num_errors (int): The number of errors recorded for the metric for
            the given error type.
    """
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[int]

Returns the stored value for testing purposes only.

Args

ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

value (bool): value of the stored metric.

Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[int]:
    """
    Returns the stored value for testing purposes only.

    Args:
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        value (bool): value of the stored metric.
    """
    return self._inner.test_get_value(ping_name)
class TimingDistributionMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData, time_unit: glean._uniffi.glean.TimeUnit)

This implements the developer facing API for recording timing distribution metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

Expand source code
class TimingDistributionMetricType:
    """
    This implements the developer facing API for recording timing distribution
    metrics.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.
    """

    def __init__(
        self,
        common_metric_data: CommonMetricData,
        time_unit: TimeUnit,
    ):
        self._inner = TimingDistributionMetric(common_metric_data, time_unit)

    def start(self) -> TimerId:
        """
        Start tracking time for the provided metric.
        Multiple timers can run simultaneously.

        Returns:
            timer_id: The object to associate with this timing.
        """
        return self._inner.start()

    def stop_and_accumulate(self, timer_id: TimerId) -> None:
        """
        Stop tracking time for the provided metric and associated timer id. Add a
        count to the corresponding bucket in the timing distribution.
        This will record an error if no `start` was called.

        Args:
            timer_id: The timer id associated with this timing. This allows for
                concurrent timing of events associated with different ids to
                the same timespan metric.
        """
        self._inner.stop_and_accumulate(timer_id)

    def cancel(self, timer_id: TimerId) -> None:
        """
        Abort a previous `start` call. No error is recorded if no `start` was called.

        Args:
            timer_id: The timer id associated with this timing. This allows for
                concurrent timing of events associated with different ids to
                the same timing distribution metric.
        """
        self._inner.cancel(timer_id)

    def accumulate_samples(self, samples: list) -> None:
        """
        Accumulates the provided samples in the metric.

        Args:
            samples: The list holding the samples to be recorded by the metric.
        """
        self._inner.accumulate_samples(samples)

    def accumulate_single_sample(self, sample: int) -> None:
        """
        Accumulates a single sample and appends it to the metric.

        Args:
            sample: The single sample to be recorded by the metric.
        """
        self._inner.accumulate_single_sample(sample)

    class _TimingDistributionContextManager:
        """
        A context manager for recording timings. Used by the `measure` method.
        """

        def __init__(self, timing_distribution: "TimingDistributionMetricType"):
            self._timing_distribution = timing_distribution

        def __enter__(self) -> None:
            self._timer_id = self._timing_distribution.start()

        def __exit__(self, type, value, tb) -> None:
            if tb is None:
                self._timing_distribution.stop_and_accumulate(self._timer_id)
            else:
                self._timing_distribution.cancel(self._timer_id)

    def measure(self) -> "_TimingDistributionContextManager":
        """
        Provides a context manager for measuring the time it takes to execute
        snippets of code in a `with` statement.

        If the contents of the `with` statement raise an exception, the timing
        is not recorded.

        Usage:
            with metrics.perf.timer.measure():
                # ... do something that takes time ...
        """
        return self._TimingDistributionContextManager(self)

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[DistributionData]:
        """
        Returns the stored value for testing purposes only.

        Args:
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            value (DistriubutionData): value of the stored metric.
        """
        return self._inner.test_get_value(ping_name)

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        """
        Returns the number of errors recorded for the given metric.

        Args:
            error_type (ErrorType): The type of error recorded.
            ping_name (str): (default: first value in send_in_pings) The name
                of the ping to retrieve the metric for.

        Returns:
            num_errors (int): The number of errors recorded for the metric for
                the given error type.
        """
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def accumulate_samples(self, samples: list) ‑> None

Accumulates the provided samples in the metric.

Args

samples
The list holding the samples to be recorded by the metric.
Expand source code
def accumulate_samples(self, samples: list) -> None:
    """
    Accumulates the provided samples in the metric.

    Args:
        samples: The list holding the samples to be recorded by the metric.
    """
    self._inner.accumulate_samples(samples)
def accumulate_single_sample(self, sample: int) ‑> None

Accumulates a single sample and appends it to the metric.

Args

sample
The single sample to be recorded by the metric.
Expand source code
def accumulate_single_sample(self, sample: int) -> None:
    """
    Accumulates a single sample and appends it to the metric.

    Args:
        sample: The single sample to be recorded by the metric.
    """
    self._inner.accumulate_single_sample(sample)
def cancel(self, timer_id: glean._uniffi.glean.TimerId) ‑> None

Abort a previous start call. No error is recorded if no start was called.

Args

timer_id
The timer id associated with this timing. This allows for concurrent timing of events associated with different ids to the same timing distribution metric.
Expand source code
def cancel(self, timer_id: TimerId) -> None:
    """
    Abort a previous `start` call. No error is recorded if no `start` was called.

    Args:
        timer_id: The timer id associated with this timing. This allows for
            concurrent timing of events associated with different ids to
            the same timing distribution metric.
    """
    self._inner.cancel(timer_id)
def measure(self) ‑> _TimingDistributionContextManager

Provides a context manager for measuring the time it takes to execute snippets of code in a with statement.

If the contents of the with statement raise an exception, the timing is not recorded.

Usage

with metrics.perf.timer.measure(): # … do something that takes time …

Expand source code
def measure(self) -> "_TimingDistributionContextManager":
    """
    Provides a context manager for measuring the time it takes to execute
    snippets of code in a `with` statement.

    If the contents of the `with` statement raise an exception, the timing
    is not recorded.

    Usage:
        with metrics.perf.timer.measure():
            # ... do something that takes time ...
    """
    return self._TimingDistributionContextManager(self)
def start(self) ‑> glean._uniffi.glean.TimerId

Start tracking time for the provided metric. Multiple timers can run simultaneously.

Returns

timer_id
The object to associate with this timing.
Expand source code
def start(self) -> TimerId:
    """
    Start tracking time for the provided metric.
    Multiple timers can run simultaneously.

    Returns:
        timer_id: The object to associate with this timing.
    """
    return self._inner.start()
def stop_and_accumulate(self, timer_id: glean._uniffi.glean.TimerId) ‑> None

Stop tracking time for the provided metric and associated timer id. Add a count to the corresponding bucket in the timing distribution. This will record an error if no start was called.

Args

timer_id
The timer id associated with this timing. This allows for concurrent timing of events associated with different ids to the same timespan metric.
Expand source code
def stop_and_accumulate(self, timer_id: TimerId) -> None:
    """
    Stop tracking time for the provided metric and associated timer id. Add a
    count to the corresponding bucket in the timing distribution.
    This will record an error if no `start` was called.

    Args:
        timer_id: The timer id associated with this timing. This allows for
            concurrent timing of events associated with different ids to
            the same timespan metric.
    """
    self._inner.stop_and_accumulate(timer_id)
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int

Returns the number of errors recorded for the given metric.

Args

error_type : ErrorType
The type of error recorded.
ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

num_errors (int): The number of errors recorded for the metric for the given error type.

Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    """
    Returns the number of errors recorded for the given metric.

    Args:
        error_type (ErrorType): The type of error recorded.
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        num_errors (int): The number of errors recorded for the metric for
            the given error type.
    """
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[glean._uniffi.glean.DistributionData]

Returns the stored value for testing purposes only.

Args

ping_name : str
(default: first value in send_in_pings) The name of the ping to retrieve the metric for.

Returns

value (DistriubutionData): value of the stored metric.

Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[DistributionData]:
    """
    Returns the stored value for testing purposes only.

    Args:
        ping_name (str): (default: first value in send_in_pings) The name
            of the ping to retrieve the metric for.

    Returns:
        value (DistriubutionData): value of the stored metric.
    """
    return self._inner.test_get_value(ping_name)
class UrlMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData)

This implements the developer facing API for recording URL metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The url API only exposes the UrlMetricType.set() method, which takes care of validating the input data and making sure that limits are enforced. See https://mozilla.github.io/glean/book/reference/metrics/url.html#limits

Expand source code
class UrlMetricType:
    """
    This implements the developer facing API for recording URL metrics.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The url API only exposes the `UrlMetricType.set` method, which
    takes care of validating the input data and making sure that limits are
    enforced.
    See https://mozilla.github.io/glean/book/reference/metrics/url.html#limits
    """

    def __init__(self, common_metric_data: CommonMetricData):
        self._inner = UrlMetric(common_metric_data)

    def set(self, value: str) -> None:
        """
        Set a URL value.

        Args:
            value (str): This is a user-defined URL value. If the length of
                the URL exceeds the maximum length, it will not be recorded.
        """
        if value is None:
            return

        self._inner.set(value)

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[str]:
        return self._inner.test_get_value(ping_name)

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def set(self, value: str) ‑> None

Set a URL value.

Args

value : str
This is a user-defined URL value. If the length of the URL exceeds the maximum length, it will not be recorded.
Expand source code
def set(self, value: str) -> None:
    """
    Set a URL value.

    Args:
        value (str): This is a user-defined URL value. If the length of
            the URL exceeds the maximum length, it will not be recorded.
    """
    if value is None:
        return

    self._inner.set(value)
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int
Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[str]
Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[str]:
    return self._inner.test_get_value(ping_name)
class UuidMetricType (common_metric_data: glean._uniffi.glean.CommonMetricData)

This implements the developer facing API for recording UUID metrics.

Instances of this class type are automatically generated by load_metrics(), allowing developers to record values that were previously registered in the metrics.yaml file.

The UUID API exposes the UuidMetricType.generate_and_set() and UuidMetricType.set() methods.

Expand source code
class UuidMetricType:
    """
    This implements the developer facing API for recording UUID metrics.

    Instances of this class type are automatically generated by
    `glean.load_metrics`, allowing developers to record values that were
    previously registered in the metrics.yaml file.

    The UUID API exposes the `UuidMetricType.generate_and_set` and
    `UuidMetricType.set` methods.
    """

    def __init__(self, common_metric_data: CommonMetricData):
        self._inner = UuidMetric(common_metric_data)

    def generate_and_set(self) -> Optional[uuid.UUID]:
        """
        Generate a new UUID value and set it in the metric store.
        """
        id = self._inner.generate_and_set()
        return uuid.UUID("urn:uuid:" + id)

    def set(self, value: Union[uuid.UUID, str]) -> None:
        """
        Explicitly set an existing UUID value.

        Args:
            value (uuid.UUID): A valid UUID to set the metric to.
        """
        self._inner.set(str(value))

    def test_get_value(self, ping_name: Optional[str] = None) -> Optional[uuid.UUID]:
        id = self._inner.test_get_value()
        if id:
            return uuid.UUID("urn:uuid:" + id)
        else:
            return None

    def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
        return self._inner.test_get_num_recorded_errors(error_type)

Methods

def generate_and_set(self) ‑> Optional[uuid.UUID]

Generate a new UUID value and set it in the metric store.

Expand source code
def generate_and_set(self) -> Optional[uuid.UUID]:
    """
    Generate a new UUID value and set it in the metric store.
    """
    id = self._inner.generate_and_set()
    return uuid.UUID("urn:uuid:" + id)
def set(self, value: Union[uuid.UUID, str]) ‑> None

Explicitly set an existing UUID value.

Args

value : uuid.UUID
A valid UUID to set the metric to.
Expand source code
def set(self, value: Union[uuid.UUID, str]) -> None:
    """
    Explicitly set an existing UUID value.

    Args:
        value (uuid.UUID): A valid UUID to set the metric to.
    """
    self._inner.set(str(value))
def test_get_num_recorded_errors(self, error_type: glean._uniffi.glean.ErrorType) ‑> int
Expand source code
def test_get_num_recorded_errors(self, error_type: ErrorType) -> int:
    return self._inner.test_get_num_recorded_errors(error_type)
def test_get_value(self, ping_name: Optional[str] = None) ‑> Optional[uuid.UUID]
Expand source code
def test_get_value(self, ping_name: Optional[str] = None) -> Optional[uuid.UUID]:
    id = self._inner.test_get_value()
    if id:
        return uuid.UUID("urn:uuid:" + id)
    else:
        return None