xref: /aosp_15_r20/external/cronet/components/metrics/structured/key_data_prefs_delegate.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2024 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_KEY_DATA_PREFS_DELEGATE_H_
6 #define COMPONENTS_METRICS_STRUCTURED_KEY_DATA_PREFS_DELEGATE_H_
7 
8 #include <cstdint>
9 #include <string>
10 #include <string_view>
11 
12 #include "base/gtest_prod_util.h"
13 #include "base/memory/raw_ptr.h"
14 #include "base/sequence_checker.h"
15 #include "base/time/time.h"
16 #include "components/metrics/structured/lib/key_data.h"
17 #include "components/prefs/pref_service.h"
18 
19 namespace metrics::structured {
20 
21 class KeyDataPrefsDelegateTest;
22 FORWARD_DECLARE_TEST(KeyDataPrefsDelegateTest, Purge);
23 
24 // Storages Structured Metrics key data in the devices preferences.
25 //
26 // The keys are stored as a dictionary keyed by the project name and the value
27 // is a base::Value representation of KeyProto.
28 //
29 // Note: users are responsible for registering the preference.
30 class KeyDataPrefsDelegate : public KeyData::StorageDelegate {
31  public:
32   KeyDataPrefsDelegate(PrefService* local_state, std::string_view pref_name);
33 
34   ~KeyDataPrefsDelegate() override;
35 
36   // KeyData::StorageDelegate:
37   bool IsReady() const override;
38   const KeyProto* GetKey(uint64_t project_name_hash) const override;
39   void UpsertKey(uint64_t project_name_hash,
40                  base::TimeDelta last_key_rotation,
41                  base::TimeDelta key_rotation_period) override;
42   void Purge() override;
43 
44  private:
45   FRIEND_TEST_ALL_PREFIXES(KeyDataPrefsDelegateTest, Purge);
46 
47   void LoadKeysFromPrefs();
48 
49   // Updates the prefs stored for |project_name_hash|.
50   void UpdatePrefsByProject(uint64_t project_name_hash,
51                             const KeyProto& key_proto);
52 
53   raw_ptr<PrefService> local_state_;
54 
55   // Name of the preference to store the
56   std::string pref_name_;
57 
58   // In-memory representation of the keys. Due to the StorageDelegate interface,
59   // the prefs value is unable to be used directly.
60   KeyDataProto proto_;
61 
62   SEQUENCE_CHECKER(sequence_checker_);
63 };
64 
65 }  // namespace metrics::structured
66 
67 #endif  // COMPONENTS_METRICS_STRUCTURED_KEY_DATA_PREFS_DELEGATE_H_
68