• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef COMPONENTS_METRICS_STRUCTURED_EVENT_VALIDATOR_H_
6 #define COMPONENTS_METRICS_STRUCTURED_EVENT_VALIDATOR_H_
7 
8 #include <cstdint>
9 #include <optional>
10 #include <string>
11 #include <string_view>
12 #include <unordered_map>
13 
14 #include "components/metrics/structured/enums.h"
15 #include "components/metrics/structured/event.h"
16 
17 namespace metrics::structured {
18 
19 // Interface to be implemented by codegen for every event to validate
20 // messages received by the structured metric service.
21 class EventValidator {
22  public:
23   // Metadata about a registered metric.
24   struct MetricMetadata {
25     Event::MetricType metric_type;
26     uint64_t metric_name_hash;
27   };
28 
29   // Should not be copied or moved.
30   EventValidator(const EventValidator&) = delete;
31   EventValidator& operator=(const EventValidator& other) = delete;
32 
33   virtual ~EventValidator();
34 
35   // Returns the event validator if |metric_name| is a valid metric for this
36   // event. This method is virtual because a static constexpr map will be
37   // defined within each event validator implementation.
38   std::optional<MetricMetadata> GetMetricMetadata(
39       const std::string& metric_name) const;
40 
41   std::optional<std::string_view> GetMetricName(
42       uint64_t metric_name_hash) const;
43 
44   uint64_t event_hash() const;
45   bool can_force_record() const;
46 
47  protected:
48   // Should not be constructed directly.
49   explicit EventValidator(uint64_t event_hash, bool force_record);
50 
51   std::unordered_map<std::string_view, EventValidator::MetricMetadata>
52       metric_metadata_;
53 
54   std::unordered_map<uint64_t, std::string_view> metrics_name_map_;
55 
56  private:
57   uint64_t event_hash_;
58   // Flag for whether an event can be recorded, not uploaded, before a user has
59   // been able to opt-in.
60   bool force_record_;
61 };
62 
63 }  // namespace metrics::structured
64 
65 #endif  // COMPONENTS_METRICS_STRUCTURED_EVENT_VALIDATOR_H_
66