1 // Copyright 2023 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_LIB_KEY_DATA_PROVIDER_H_ 6 #define COMPONENTS_METRICS_STRUCTURED_LIB_KEY_DATA_PROVIDER_H_ 7 8 #include <optional> 9 #include <string> 10 11 #include "base/functional/callback_forward.h" 12 #include "base/observer_list.h" 13 #include "base/observer_list_types.h" 14 #include "components/metrics/structured/lib/key_data.h" 15 16 namespace metrics::structured { 17 18 class ChromeStructuredMetricsRecorder; 19 20 // Interface to provide key data to be used for hashing projects. 21 // 22 // There are two types of keys: device keys and profile keys. Device keys will 23 // be ready only InitializeDeviceKey has been called while profile keys should 24 // be ready once InitializeProfileKey has been called. 25 class KeyDataProvider { 26 public: 27 // Observer to be notified of events regarding the KeyDataProvider state. 28 class Observer : public base::CheckedObserver { 29 public: 30 // Called when a key is ready to be used. 31 virtual void OnKeyReady() = 0; 32 }; 33 34 KeyDataProvider(); 35 36 KeyDataProvider(const KeyDataProvider& key_data_provider) = delete; 37 KeyDataProvider& operator=(const KeyDataProvider& key_data_provider) = delete; 38 39 virtual ~KeyDataProvider(); 40 41 void AddObserver(Observer* observer); 42 void RemoveObserver(Observer* observer); 43 44 // Returns true if the keys are ready to be used. 45 virtual bool IsReady() = 0; 46 47 // Retrieves the ID for given |project_name|. 48 // 49 // If no valid key is found for |project_name|, this function will return 50 // std::nullopt. 51 virtual std::optional<uint64_t> GetId(const std::string& project_name) = 0; 52 53 // Retrieves the secondary ID for given |project_name|. 54 // 55 // If no valid secondary key is found for |project_name|, this function will 56 // return std::nullopt. 57 // 58 // TODO(b/290096302): Refactor event sequence populator so there is no 59 // dependency on concepts such as device/profile in //components. 60 virtual std::optional<uint64_t> GetSecondaryId( 61 const std::string& project_name); 62 63 // Retrieves the key data to be used for |project_name|. Returns nullptr if 64 // the KeyData is not available for given |project_name|. 65 virtual KeyData* GetKeyData(const std::string& project_name) = 0; 66 67 // Deletes all key data associated with the provider. 68 virtual void Purge() = 0; 69 70 protected: 71 // Notifies observers that the key is ready. 72 void NotifyKeyReady(); 73 74 private: 75 friend class ChromeStructuredMetricsRecorder; 76 77 base::ObserverList<Observer> observers_; 78 }; 79 80 } // namespace metrics::structured 81 82 #endif // COMPONENTS_METRICS_STRUCTURED_LIB_KEY_DATA_PROVIDER_H_ 83