File: structured_metrics_debug_provider.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (202 lines) | stat: -rw-r--r-- 6,676 bytes parent folder | download | duplicates (3)
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
195
196
197
198
199
200
201
202
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/metrics/debug/structured/structured_metrics_debug_provider.h"

#include <optional>
#include <string_view>
#include <utility>

#include "base/i18n/number_formatting.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "components/metrics/structured/event_validator.h"
#include "components/metrics/structured/project_validator.h"
#include "components/metrics/structured/proto/event_storage.pb.h"
#include "components/metrics/structured/recorder.h"
#include "components/metrics/structured/structured_metrics_service.h"
#include "components/metrics/structured/structured_metrics_validator.h"
#include "third_party/metrics_proto/structured_data.pb.h"

namespace metrics::structured {
namespace {

struct EventInfo {
  std::string_view project_name;
  std::string_view event_name;
  raw_ptr<const EventValidator> event_validator;

  // Normalizes the name into an easier to read format as defined in the
  // structured.xml.
  std::string NormalizeProjectName() const;
  std::string NormalizeEventName() const;
};

std::string Normalize(std::string_view value) {
  std::string result;
  base::ReplaceChars(value, "_", ".", &result);
  return result;
}

std::string EventInfo::NormalizeProjectName() const {
  return Normalize(project_name);
}

std::string EventInfo::NormalizeEventName() const {
  return Normalize(event_name);
}

// Retrieves information about an event that is needed for rendering.
std::optional<EventInfo> GetEventInfo(const StructuredEventProto& proto) {
  validator::Validators* validators = validator::Validators::Get();
  auto project_name = validators->GetProjectName(proto.project_name_hash());
  if (!project_name.has_value()) {
    return std::nullopt;
  }

  // This will not fail.
  const auto* project_validator =
      validators->GetProjectValidator(*project_name);
  CHECK(project_validator);

  const auto event_name =
      project_validator->GetEventName(proto.event_name_hash());
  if (!event_name.has_value()) {
    return std::nullopt;
  }

  // This will not fail.
  const auto* event_validator =
      project_validator->GetEventValidator(*event_name);
  CHECK(event_validator);

  return EventInfo{.project_name = *project_name,
                   .event_name = *event_name,
                   .event_validator = event_validator};
}

// Creates a dictionary that represents a key-value pair.
base::Value::Dict CreateKeyValue(std::string_view key, base::Value value) {
  base::Value::Dict result;
  result.Set("key", key);
  result.Set("value", std::move(value));
  return result;
}

std::optional<base::Value> MetricToValue(
    const StructuredEventProto::Metric& metric) {
  using Metric = StructuredEventProto::Metric;
  switch (metric.value_case()) {
    case Metric::kValueHmac:
      return base::Value(base::NumberToString(metric.value_hmac()));
    case Metric::kValueInt64:
      return base::Value(base::NumberToString(metric.value_int64()));
    case Metric::kValueString:
      return base::Value(metric.value_string());
    case Metric::kValueDouble:
      return base::Value(metric.value_double());
    case Metric::kValueRepeatedInt64: {
      base::Value::List list;
      for (int value : metric.value_repeated_int64().values()) {
        list.Append(value);
      }
      return base::Value(std::move(list));
    }
    case Metric::VALUE_NOT_SET:
      return std::nullopt;
  }
}

// Creates a list of metrics represented by a key-value pair from the metrics of
// an event.
base::Value::List CreateMetricsList(const google::protobuf::RepeatedPtrField<
                                        StructuredEventProto::Metric>& metrics,
                                    const EventValidator* event_validator) {
  base::Value::List result;
  for (const auto& metric : metrics) {
    std::string metric_name =
        event_validator
            ? std::string(event_validator->GetMetricName(metric.name_hash())
                              .value_or("unknown"))
            : base::NumberToString(metric.name_hash());
    auto value = MetricToValue(metric);
    if (!value.has_value()) {
      continue;
    }
    result.Append(CreateKeyValue(metric_name, std::move(*value)));
  }
  return result;
}

// Creates an event metadata dictionary from an event.
base::Value::Dict CreateEventMetadataDict(
    const StructuredEventProto::EventSequenceMetadata& sequence_metadata) {
  base::Value::Dict metadata;
  metadata.Set("systemUptimeMs",
               base::FormatNumber(sequence_metadata.system_uptime()));
  metadata.Set("id", base::NumberToString(sequence_metadata.event_unique_id()));
  metadata.Set("resetCounter",
               base::NumberToString(sequence_metadata.reset_counter()));
  return metadata;
}

// Creates a dictionary from an event.
base::Value::Dict CreateEventDict(const StructuredEventProto& proto) {
  base::Value::Dict result;

  auto event_info = GetEventInfo(proto);
  const EventValidator* event_validator = nullptr;

  if (event_info.has_value()) {
    event_validator = event_info->event_validator;
    result.Set("project", event_info->NormalizeProjectName());
    result.Set("event", event_info->NormalizeEventName());
  } else {
    result.Set("project", base::NumberToString(proto.project_name_hash()));
    result.Set("event", base::NumberToString(proto.event_name_hash()));
  }

  result.Set("metrics", CreateMetricsList(proto.metrics(), event_validator));

  if (proto.event_type() == StructuredEventProto::SEQUENCE) {
    result.Set("type", "sequence");
    result.Set("sequenceMetadata",
               CreateEventMetadataDict(proto.event_sequence_metadata()));
  } else {
    result.Set("type", "metric");
  }

  return result;
}

}  // namespace

StructuredMetricsDebugProvider::StructuredMetricsDebugProvider(
    StructuredMetricsService* service)
    : service_(service) {
  CHECK(service);
  LoadRecordedEvents();
  service_->recorder()->AddEventsObserver(this);
}

StructuredMetricsDebugProvider::~StructuredMetricsDebugProvider() {
  service_->recorder()->RemoveEventsObserver(this);
}

void StructuredMetricsDebugProvider::OnEventRecorded(
    const StructuredEventProto& event) {
  events_.Append(CreateEventDict(event));
}

void StructuredMetricsDebugProvider::LoadRecordedEvents() {
  EventsProto proto;
  service_->recorder()->event_storage()->CopyEvents(&proto);
  for (const auto& event : proto.events()) {
    events_.Append(CreateEventDict(event));
  }
}

}  // namespace metrics::structured