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/persistent_synthetic_trial_observer.h"
6
7 #include "base/task/sequenced_task_runner.h"
8 #include "components/metrics/persistent_system_profile.h"
9 #include "components/variations/synthetic_trials.h"
10
11 namespace metrics {
12 namespace {
13
PersistSyntheticFieldTrials(const std::vector<variations::SyntheticTrialGroup> & trials_updated,const std::vector<variations::SyntheticTrialGroup> & trials_removed)14 void PersistSyntheticFieldTrials(
15 const std::vector<variations::SyntheticTrialGroup>& trials_updated,
16 const std::vector<variations::SyntheticTrialGroup>& trials_removed) {
17 // Mark all the updated synthetic field trials in the persistent profile,
18 // update the removed trials first, then add the updated trials.
19 for (const auto& removed : trials_removed) {
20 metrics::GlobalPersistentSystemProfile::GetInstance()->RemoveFieldTrial(
21 removed.trial_name());
22 }
23 for (const auto& updated : trials_updated) {
24 if (updated.annotation_mode() ==
25 variations::SyntheticTrialAnnotationMode::kCurrentLog) {
26 metrics::GlobalPersistentSystemProfile::GetInstance()->AddFieldTrial(
27 updated.trial_name(), updated.group_name());
28 }
29 }
30 }
31
32 } // namespace
33
PersistentSyntheticTrialObserver()34 PersistentSyntheticTrialObserver::PersistentSyntheticTrialObserver()
35 : task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) {}
36
37 PersistentSyntheticTrialObserver::~PersistentSyntheticTrialObserver() = default;
38
OnSyntheticTrialsChanged(const std::vector<variations::SyntheticTrialGroup> & trials_updated,const std::vector<variations::SyntheticTrialGroup> & trials_removed,const std::vector<variations::SyntheticTrialGroup> & groups)39 void PersistentSyntheticTrialObserver::OnSyntheticTrialsChanged(
40 const std::vector<variations::SyntheticTrialGroup>& trials_updated,
41 const std::vector<variations::SyntheticTrialGroup>& trials_removed,
42 const std::vector<variations::SyntheticTrialGroup>& groups) {
43 // Synthetic trials may be registered in any task runner, so switch to correct
44 // task runner before storing.
45 if (task_runner_->RunsTasksInCurrentSequence()) {
46 PersistSyntheticFieldTrials(trials_updated, trials_removed);
47 } else {
48 task_runner_->PostTask(
49 FROM_HERE, base::BindOnce(&PersistSyntheticFieldTrials, trials_updated,
50 trials_removed));
51 }
52 }
53
54 } // namespace metrics
55