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