xref: /aosp_15_r20/external/cronet/components/metrics/structured/external_metrics.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_EXTERNAL_METRICS_H_
6 #define COMPONENTS_METRICS_STRUCTURED_EXTERNAL_METRICS_H_
7 
8 #include "base/containers/flat_set.h"
9 #include "base/files/file_path.h"
10 #include "base/functional/callback.h"
11 #include "base/memory/scoped_refptr.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/task/sequenced_task_runner.h"
14 #include "base/time/time.h"
15 
16 namespace metrics::structured {
17 
18 class EventsProto;
19 class ExternalMetricsTest;
20 
21 // ExternalMetrics reads structured metrics saved by Chrome OS and uploads them
22 // to the UMA server on its behalf. This is structured metrics' equivalent of
23 // `ash::ExternalMetrics`.
24 //
25 // Chrome periodically reads a directory of protos and adds their content into
26 // the StructuredMetricProvider's regular metrics upload. After reading each
27 // file, it is deleted. Chrome and ChromeOS use flock to prevent concurrent
28 // read/writes.
29 class ExternalMetrics {
30  public:
31   using MetricsCollectedCallback =
32       base::RepeatingCallback<void(const EventsProto&)>;
33 
34   ExternalMetrics(const base::FilePath& events_directory,
35                   const base::TimeDelta& collection_interval,
36                   MetricsCollectedCallback callback);
37   ~ExternalMetrics();
38   ExternalMetrics(const ExternalMetrics&) = delete;
39   ExternalMetrics& operator=(const ExternalMetrics&) = delete;
40 
41   // Adds a project to the disallowed list for testing.
42   void AddDisallowedProjectForTest(uint64_t project_name_hash);
43 
44   void EnableRecording();
45   void DisableRecording();
46 
47  private:
48   friend class ExternalMetricsTest;
49 
50   void ScheduleCollector();
51   void CollectEventsAndReschedule();
52   void CollectEvents();
53 
54   // Builds a cache of disallow projects from the Finch controlled variable.
55   void CacheDisallowedProjectsSet();
56 
57   bool recording_enabled_ = false;
58 
59   const base::FilePath events_directory_;
60   const base::TimeDelta collection_interval_;
61   MetricsCollectedCallback callback_;
62 
63   // A set of projects that are not allowed to be recorded. This is a cache of
64   // GetDisabledProjects().
65   base::flat_set<uint64_t> disallowed_projects_;
66 
67   scoped_refptr<base::SequencedTaskRunner> task_runner_;
68   base::WeakPtrFactory<ExternalMetrics> weak_factory_{this};
69 };
70 
71 }  // namespace metrics::structured
72 
73 #endif  // COMPONENTS_METRICS_STRUCTURED_EXTERNAL_METRICS_H_
74