1 // Copyright 2016 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.
5 #ifndef COMPONENTS_METRICS_DATA_USE_TRACKER_H_
6 #define COMPONENTS_METRICS_DATA_USE_TRACKER_H_
10 #include "base/functional/callback.h"
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/raw_ptr.h"
13 #include "base/sequence_checker.h"
14 #include "base/time/time.h"
15 #include "components/prefs/pref_registry_simple.h"
16 #include "components/prefs/pref_service.h"
20 // Records the data use of user traffic and UMA traffic in user prefs. Taking
21 // into account those prefs it can verify whether certain UMA log upload is
23 class DataUseTracker {
25 explicit DataUseTracker(PrefService* local_state);
27 DataUseTracker(const DataUseTracker&) = delete;
28 DataUseTracker& operator=(const DataUseTracker&) = delete;
30 virtual ~DataUseTracker();
32 // Returns an instance of |DataUseTracker| with provided |local_state| if
33 // users data use should be tracked and null pointer otherwise.
34 static std::unique_ptr<DataUseTracker> Create(PrefService* local_state);
36 // Registers data use prefs using provided |registry|.
37 static void RegisterPrefs(PrefRegistrySimple* registry);
39 // Updates data usage tracking prefs with the specified values.
40 static void UpdateMetricsUsagePrefs(int message_size,
42 bool is_metrics_service_usage,
43 PrefService* local_state);
45 // Returns whether a log with provided |log_bytes| can be uploaded according
46 // to data use ratio and UMA quota provided by variations.
47 bool ShouldUploadLogOnCellular(int log_bytes);
50 FRIEND_TEST_ALL_PREFIXES(DataUseTrackerTest, CheckUpdateUsagePref);
51 FRIEND_TEST_ALL_PREFIXES(DataUseTrackerTest, CheckRemoveExpiredEntries);
52 FRIEND_TEST_ALL_PREFIXES(DataUseTrackerTest, CheckComputeTotalDataUse);
53 FRIEND_TEST_ALL_PREFIXES(DataUseTrackerTest, CheckCanUploadUMALog);
55 // Updates data usage tracking prefs with the specified values.
56 void UpdateMetricsUsagePrefsInternal(int message_size,
58 bool is_metrics_service_usage);
60 // Updates provided |pref_name| for a current date with the given message
62 void UpdateUsagePref(const std::string& pref_name, int message_size);
64 // Removes entries from the all data use prefs.
65 void RemoveExpiredEntries();
67 // Removes entries from the given |pref_name| if they are more than 7 days
69 void RemoveExpiredEntriesForPref(const std::string& pref_name);
71 // Computes data usage according to all the entries in the given dictionary
73 int ComputeTotalDataUse(const std::string& pref_name);
75 // Returns the current date for measurement.
76 virtual base::Time GetCurrentMeasurementDate() const;
78 // Returns the current date as a string with a proper formatting.
79 virtual std::string GetCurrentMeasurementDateAsString() const;
81 raw_ptr<PrefService> local_state_;
83 SEQUENCE_CHECKER(sequence_checker_);
86 } // namespace metrics
87 #endif // COMPONENTS_METRICS_DATA_USE_TRACKER_H_