~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/services/metrics/models.py -rw-r--r-- 1.1 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
byceps.services.metrics.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from dataclasses import dataclass, field
from typing import List


@dataclass(frozen=True)
class Label:
    name: str
    value: str

    def serialize(self) -> str:
        escaped_value = _escape_label_value(self.value)
        return f'{self.name}="{escaped_value}"'


def _escape_label_value(value: str) -> str:
    def escape(char):
        if char == '\\':
            return r'\\'
        elif char == '"':
            return r'\"'
        elif char == '\n':
            return r'\n'
        else:
            return char

    return ''.join(map(escape, value))


@dataclass(frozen=True)
class Metric:
    name: str
    value: float
    labels: List[Label] = field(default_factory=dict)

    def serialize(self) -> str:
        labels_str = ''
        if self.labels:
            labels_str = (
                '{'
                + ', '.join(label.serialize() for label in self.labels)
                + '}'
            )

        return f'{self.name}{labels_str} {self.value}'