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 #include "components/metrics/structured/key_data_provider_file.h" 6 7 #include <memory> 8 9 #include "base/functional/bind.h" 10 #include "base/logging.h" 11 #include "components/metrics/structured/lib/key_data.h" 12 #include "components/metrics/structured/lib/key_data_file_delegate.h" 13 #include "components/metrics/structured/recorder.h" 14 #include "components/metrics/structured/structured_metrics_validator.h" 15 16 namespace metrics::structured { 17 KeyDataProviderFile(const base::FilePath & file_path,base::TimeDelta write_delay)18KeyDataProviderFile::KeyDataProviderFile(const base::FilePath& file_path, 19 base::TimeDelta write_delay) 20 : file_path_(file_path), write_delay_(write_delay) { 21 key_data_ = std::make_unique<KeyData>(std::make_unique<KeyDataFileDelegate>( 22 file_path_, write_delay_, 23 base::BindOnce(&KeyDataProviderFile::OnKeyReady, 24 weak_ptr_factory_.GetWeakPtr()))); 25 } 26 27 KeyDataProviderFile::~KeyDataProviderFile() = default; 28 IsReady()29bool KeyDataProviderFile::IsReady() { 30 return is_data_loaded_; 31 } 32 GetId(const std::string & project_name)33std::optional<uint64_t> KeyDataProviderFile::GetId( 34 const std::string& project_name) { 35 DCHECK(IsReady()); 36 37 // Validates the project. If valid, retrieve the metadata associated 38 // with the event. 39 const auto* project_validator = 40 validator::Validators::Get()->GetProjectValidator(project_name); 41 42 if (!project_validator) { 43 return std::nullopt; 44 } 45 return key_data_->Id(project_validator->project_hash(), 46 project_validator->key_rotation_period()); 47 } 48 GetSecondaryId(const std::string & project_name)49std::optional<uint64_t> KeyDataProviderFile::GetSecondaryId( 50 const std::string& project_name) { 51 return std::nullopt; 52 } 53 GetKeyData(const std::string & project_name)54KeyData* KeyDataProviderFile::GetKeyData(const std::string& project_name) { 55 DCHECK(IsReady()); 56 return key_data_.get(); 57 } 58 Purge()59void KeyDataProviderFile::Purge() { 60 if (IsReady()) { 61 key_data_->Purge(); 62 } 63 } 64 OnKeyReady()65void KeyDataProviderFile::OnKeyReady() { 66 is_data_loaded_ = true; 67 NotifyKeyReady(); 68 } 69 70 } // namespace metrics::structured 71