summaryrefslogtreecommitdiffstats
path: root/third_party/python/glean_parser/glean_parser/templates/python_server.jinja2
blob: 689fab21090aa7092855a411d2e49523d41db122 (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
{# The final Go code is autogenerated, but this template is not. Please file bugs! #}
"""
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/.

AUTOGENERATED BY glean_parser v{{ parser_version }}. DO NOT EDIT. DO NOT COMMIT.
"""

from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from uuid import uuid4
import json

GLEAN_EVENT_MOZLOG_TYPE = "glean-server-event"


{% for ping, metrics_by_type in pings.items() %}
class {{ ping|camelize }}ServerEventLogger:
    def __init__(
        self, application_id: str, app_display_version: str, channel: str
    ) -> None:
        """
        Create {{ ping|camelize }}ServerEventLogger instance.

        :param str application_id: The application ID.
        :param str app_display_version: The application display version.
        :param str channel: The channel.
        """
        self._application_id = application_id
        self._app_display_version = app_display_version
        self._channel = channel

    def _record(
        self,
        user_agent: str,
        ip_address: str,
        {% for metric_type, metrics in metrics_by_type.items() %}
        {% if metric_type != 'event' %}
        {% for metric in metrics %}
        {{ metric.category }}_{{ metric.name }}: {{ metric.type|py_metric_type }},
        {% endfor %}
        {% endif %}
        {% endfor %}
        event: dict[str, Any]
    ) -> None:
        now = datetime.now(timezone.utc)
        timestamp = now.isoformat()
        event["timestamp"] = int(1000.0 * now.timestamp())  # Milliseconds since epoch
        event_payload = {
            "metrics": {
                {% for metric_type, metrics in metrics_by_type.items() %}
                {% if metric_type != 'event' %}
                "{{ metric_type }}": {
                    {% for metric in metrics %}
                    "{{ metric.category }}.{{ metric.name }}": {{ metric.category }}_{{ metric.name }},
                    {% endfor %}
                },
                {% endif %}
                {% endfor %}
            },
            "events": [event],
            "ping_info": {
                # seq is required in the Glean schema, however is not useful in server context
                "seq": 0,
                "start_time": timestamp,
                "end_time": timestamp,
            },
            # `Unknown` fields below are required in the Glean schema, however they are
            # not useful in server context
            "client_info": {
                "telemetry_sdk_build": "glean_parser v{{ parser_version }}",
                "first_run_date": "Unknown",
                "os": "Unknown",
                "os_version": "Unknown",
                "architecture": "Unknown",
                "app_build": "Unknown",
                "app_display_version": self._app_display_version,
                "app_channel": self._channel,
            },
        }
        event_payload_serialized = json.dumps(event_payload)

        # This is the message structure that Decoder expects:
        # https://github.com/mozilla/gcp-ingestion/pull/2400
        ping = {
            "document_namespace": self._application_id,
            "document_type": "{{ ping }}",
            "document_version": "1",
            "document_id": str(uuid4()),
            "user_agent": user_agent,
            "ip_address": ip_address,
            "payload": event_payload_serialized,
        }


        self.emit_record(now, ping)

    def emit_record(self, now: datetime, ping:dict[str, Any]) -> None:
        """Log the ping to STDOUT.
        Applications might want to override this method to use their own logging.
        If doing so, make sure to log the ping as JSON, and to include the
        `Type: GLEAN_EVENT_MOZLOG_TYPE`."""
        ping_envelope = {
            "Timestamp": now.isoformat(),
            "Logger": "glean",
            "Type": GLEAN_EVENT_MOZLOG_TYPE,
            "Fields": ping,
        }
        ping_envelope_serialized = json.dumps(ping_envelope)

        print(ping_envelope_serialized)

    {% for event in metrics_by_type["event"] %}
    def {{ event|record_event_function_name }}(
        self,
        user_agent: str,
        ip_address: str,
        {% for metric_type, metrics in metrics_by_type.items() %}
        {% if metric_type != 'event' %}
        {% for metric in metrics %}
        {{ metric.category }}_{{ metric.name }}: {{ metric.type|py_metric_type }},
        {% endfor %}
        {% endif %}
        {% endfor %}
        {% for extra, metadata in event.extra_keys.items() %}
        {{ extra }}: {{ metadata.type|py_metric_type }},
        {% endfor %}
    ) -> None:
        """
        Record and submit a {{ event.category }}_{{ event.name }} event:
        {{ event.description|clean_string }}
        Event is logged to STDOUT via `print`.

        :param str user_agent: The user agent.
        :param str ip_address: The IP address. Will be used to decode Geo information
            and scrubbed at ingestion.
        {% for metric_type, metrics in metrics_by_type.items() %}
        {% if metric_type != 'event' %}
        {% for metric in metrics %}
        :param {{ metric.type|py_metric_type }} {{ metric.category }}_{{ metric.name }}: {{ metric.description|clean_string }}
        {% endfor %}
        {% endif %}
        {% endfor %}
        {% if event.extra_keys %}
        {% for extra, metadata in event.extra_keys.items() %}
        :param {{ metadata.type|py_metric_type }} {{ extra }}: {{ metadata.description|clean_string }}
        {% endfor %}
        {% endif %}
        """
        event = {
            "category": "{{ event.category }}",
            "name": "{{ event.name }}",
            {% if event.extra_keys %}
            "extra": {
                {% for extra, metadata in event.extra_keys.items() %}
                "{{ extra }}": str({{ extra }}){% if 'bool' == metadata.type|py_metric_type %}.lower(){% endif %},
                {% endfor %}
            },
            {% endif %}
        }
        self._record(
            user_agent,
            ip_address,
            {% for metric_type, metrics in metrics_by_type.items() %}
            {% if metric_type != 'event' %}
            {% for metric in metrics %}
            {{ metric.category }}_{{ metric.name }},
            {% endfor %}
            {% endif %}
            {% endfor %}
            event
        )
    {% endfor %}
{% endfor %}

{% for ping in pings %}
def {{ ping|factory_method }}(
    application_id: str,
    app_display_version: str,
    channel: str,
) -> {{ ping|camelize }}ServerEventLogger:
    """
    Factory function that creates an instance of Glean Server Event Logger to record
    `{{ ping }}` ping events.
    :param str application_id: The application ID.
    :param str app_display_version: The application display version.
    :param str channel: The channel.
    :return: An instance of {{ ping|camelize }}ServerEventLogger.
    :rtype: {{ ping|camelize }}ServerEventLogger
    """
    return {{ ping|camelize }}ServerEventLogger(application_id, app_display_version, channel)
{% endfor %}