xref: /aosp_15_r20/external/cronet/components/metrics/structured/event_validator.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 
12 #include "components/metrics/structured/enums.h"
13 #include "components/metrics/structured/event.h"
14 
15 namespace metrics::structured {
16 
17 // Interface to be implemented by codegen for every event to validate
18 // messages received by the structured metric service.
19 class EventValidator {
20  public:
21   // Metadata about a registered metric.
22   struct MetricMetadata {
23     Event::MetricType metric_type;
24     uint64_t metric_name_hash;
25   };
26 
27   // Should not be copied or moved.
28   EventValidator(const EventValidator&) = delete;
29   EventValidator& operator=(const EventValidator& other) = delete;
30 
31   virtual ~EventValidator();
32 
33   // Returns the event validator if |metric_name| is a valid metric for this
34   // event. This method is virtual because a static constexpr map will be
35   // defined within each event validator implementation.
36   std::optional<MetricMetadata> GetMetricMetadata(
37       const std::string& metric_name) const;
38 
39   std::optional<base::StringPiece> GetMetricName(
40       uint64_t metric_name_hash) const;
41 
42   uint64_t event_hash() const;
43   bool can_force_record() const;
44 
45  protected:
46   // Should not be constructed directly.
47   explicit EventValidator(uint64_t event_hash, bool force_record);
48 
49   std::unordered_map<base::StringPiece, EventValidator::MetricMetadata>
50       metric_metadata_;
51 
52   std::unordered_map<uint64_t, base::StringPiece> metrics_name_map_;
53 
54  private:
55   uint64_t event_hash_;
56   // Flag for whether an event can be recorded, not uploaded, before a user has
57   // been able to opt-in.
58   bool force_record_;
59 };
60 
61 }  // namespace metrics::structured
62 
63 #endif  // COMPONENTS_METRICS_STRUCTURED_EVENT_VALIDATOR_H_
64