1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
|
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/ash/components/growth/campaigns_manager.h"
#include <optional>
#include <string_view>
#include <utility>
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "base/base64.h"
#include "base/command_line.h"
#include "base/containers/enum_set.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/syslog_logging.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "chromeos/ash/components/growth/campaigns_logger.h"
#include "chromeos/ash/components/growth/campaigns_matcher.h"
#include "chromeos/ash/components/growth/campaigns_model.h"
#include "chromeos/ash/components/growth/campaigns_utils.h"
#include "chromeos/ash/components/growth/growth_metrics.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/tribool.h"
#include "components/user_manager/user_manager.h"
namespace growth {
namespace {
CampaignsManager* g_instance = nullptr;
static constexpr auto kAllSlotsSet =
base::EnumSet<Slot, Slot::kMinValue, Slot::kMaxValue>::All();
inline constexpr char kCampaignFileName[] = "campaigns.json";
inline constexpr char kEventKey[] = "event_to_be_cleared";
inline constexpr char kOobeCompleteFlagFilePath[] =
"/home/chronos/.oobe_completed";
// The synthetic trial name prefix for growth experiment. Formatted as
// `CrOSGrowthStudy{studyId}`, where `studyId` is an integer. For non
// experimental campaigns, `studyId` will be empty.
inline constexpr char kGrowthStudyName[] = "CrOSGrowthStudy";
// The synthetical trial group name for growth experiment. The campaign id
// will be unique for different groups.
inline constexpr char kGrowthGroupName[] = "CampaignId";
inline constexpr char kPayloadPath[] = "payload";
std::optional<base::Value::Dict> ParseCampaignsFile(
const std::string& campaigns_data) {
std::optional<base::Value::Dict> value =
base::JSONReader::ReadDict(campaigns_data);
if (!value) {
CAMPAIGNS_LOG(ERROR) << "Failed to parse campaigns file.";
CAMPAIGNS_LOG(VLOG) << "Malformed campaigns file: " << campaigns_data;
RecordCampaignsManagerError(CampaignsManagerError::kCampaignsParsingFail);
return std::nullopt;
}
return value;
}
std::optional<base::Value::Dict> ReadCampaignsFile(
const base::FilePath& campaigns_component_path) {
const auto campaigns_load_start_time = base::TimeTicks::Now();
std::string campaigns_data;
if (!base::ReadFileToString(
campaigns_component_path.Append(kCampaignFileName),
&campaigns_data)) {
CAMPAIGNS_LOG(ERROR) << "Failed to read campaigns file from disk.";
RecordCampaignsManagerError(CampaignsManagerError::kCampaignsFileLoadFail);
RecordCampaignsComponentReadDuration(base::TimeTicks::Now() -
campaigns_load_start_time);
return std::nullopt;
}
auto parse_result = ParseCampaignsFile(campaigns_data);
RecordCampaignsComponentReadDuration(base::TimeTicks::Now() -
campaigns_load_start_time);
return parse_result;
}
void LogCampaignInSystemLog(const Campaign* campaign, Slot slot) {
if (!campaign) {
return;
}
std::optional<int> id = growth::GetCampaignId(campaign);
if (!id) {
// TODO(b/308684443): Add error metrics in a follow up CL.
CAMPAIGNS_LOG(ERROR) << "Growth campaign id not found";
return;
}
CAMPAIGNS_LOG(SYSLOG) << "Growth Campaign " << *id
<< " is selected for slot: "
<< base::NumberToString(int(slot));
}
// Gets the Oobe timestamp on a sequence that allows file-access.
base::Time GetOobeTimestampBackground() {
base::File::Info file_info;
if (base::GetFileInfo(base::FilePath(kOobeCompleteFlagFilePath),
&file_info)) {
return file_info.creation_time;
}
// If the Oobe complete file is not found and there's no owner, assume that
// the user campaigns is matching during Oobe flow and return the current time
// as a close indicator of register time.
const AccountId& owner_account_id =
user_manager::UserManager::Get()->GetOwnerAccountId();
return owner_account_id.is_valid() ? base::Time::Min() : base::Time::Now();
}
} // namespace
// static
CampaignsManager* CampaignsManager::Get() {
return g_instance;
}
// static
void CampaignsManager::RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterListPref(ash::prefs::kGrowthPerksInterested);
}
CampaignsManager::CampaignsManager(CampaignsManagerClient* client,
PrefService* local_state)
: client_(client),
matcher_(client, local_state),
actions_map_(client->GetCampaignsActions()) {
CHECK_EQ(g_instance, nullptr);
g_instance = this;
}
CampaignsManager::~CampaignsManager() {
CHECK_EQ(g_instance, this);
g_instance = nullptr;
}
void CampaignsManager::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
if (campaigns_loaded_) {
// Do not notify the observer immediately in case blocking.
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&CampaignsManager::NotifyCampaignsLoaded,
weak_factory_.GetWeakPtr()));
}
}
void CampaignsManager::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void CampaignsManager::SetPrefs(PrefService* prefs) {
// Pass `prefs` to `CampaignsMatcher` to enable prefs related targettings.
matcher_.SetPrefs(prefs);
}
void CampaignsManager::LoadCampaigns(base::OnceClosure load_callback,
bool in_oobe) {
CAMPAIGNS_LOG(DEBUG) << "Start loading campaigns. `in_oobe`: "
<< ToString(in_oobe);
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(ash::switches::kGrowthCampaigns)) {
CAMPAIGNS_LOG(DEBUG)
<< "Switch `kGrowthCampaigns` is set. Loading campaigns from "
"encoded campaigns string.";
const auto& value =
command_line->GetSwitchValueASCII(ash::switches::kGrowthCampaigns);
std::string decoded_str;
if (base::Base64Decode(value, &decoded_str)) {
OnCampaignsLoaded(std::move(load_callback),
ParseCampaignsFile(decoded_str));
return;
} else {
CAMPAIGNS_LOG(ERROR) << "Failed decode base64 encoded campaigns string.";
}
}
campaigns_download_start_time_ = base::TimeTicks::Now();
client_->LoadCampaignsComponent(base::BindOnce(
&CampaignsManager::OnCampaignsComponentLoaded, weak_factory_.GetWeakPtr(),
std::move(load_callback), in_oobe));
}
const Campaign* CampaignsManager::GetCampaignBySlot(Slot slot) const {
CHECK(campaigns_loaded_)
<< "Getting campaign before campaigns finish loading";
RecordGetCampaignBySlotAttempt(slot);
const auto match_start = base::TimeTicks::Now();
auto* match_result = matcher_.GetCampaignBySlot(slot);
RecordCampaignMatchDuration(base::TimeTicks::Now() - match_start);
if (!match_result) {
CAMPAIGNS_LOG(DEBUG) << "No campaign is selected for slot "
<< static_cast<int>(slot);
return nullptr;
}
int campaign_id = growth::GetCampaignId(match_result).value();
CAMPAIGNS_LOG(DEBUG) << "Campaign: " << campaign_id
<< " is selected for slot " << static_cast<int>(slot);
RecordGetCampaignBySlot(slot, campaign_id);
LogCampaignInSystemLog(match_result, slot);
RegisterTrialForCampaign(match_result);
MaybeRecordImpressionForControl(match_result);
return match_result;
}
const GURL& CampaignsManager::GetActiveUrl() const {
return matcher_.active_url();
}
void CampaignsManager::SetActiveUrl(const GURL& url) {
matcher_.SetActiveUrl(url);
}
const std::string& CampaignsManager::GetOpenedAppId() const {
return matcher_.opened_app_id();
}
void CampaignsManager::SetOpenedApp(std::string app_id) {
if (!app_id.empty()) {
RecordEvent(GetEventName(CampaignEvent::kAppOpened, app_id));
}
matcher_.SetOpenedApp(std::move(app_id));
}
const Trigger& CampaignsManager::GetTrigger() const {
return matcher_.trigger();
}
void CampaignsManager::SetTrigger(const Trigger&& trigger_type) {
matcher_.SetTrigger(std::move(trigger_type));
}
void CampaignsManager::SetIsUserOwner(bool is_user_owner) {
matcher_.SetIsUserOwner(is_user_owner);
}
void CampaignsManager::PerformAction(int campaign_id,
std::optional<int> group_id,
const Action* action) {
// In rare case when the caller fails to check action, log
// an error metric if the action is not defined.
if (!action) {
CAMPAIGNS_LOG(ERROR) << "Missing action when performing action.";
RecordCampaignsManagerError(
CampaignsManagerError::kMissingActionPerformerAction);
return;
}
auto* params = action->GetParams();
auto action_type = action->GetActionType();
if (!action_type || !params) {
CAMPAIGNS_LOG(ERROR) << "Invalid action when performing action.";
RecordCampaignsManagerError(CampaignsManagerError::kInvalidAction);
return;
}
PerformAction(campaign_id, group_id, action_type.value(), params);
}
void CampaignsManager::PerformAction(int campaign_id,
std::optional<int> group_id,
const ActionType action_type,
const base::Value::Dict* params) {
auto& action_performer = actions_map_.at(action_type);
if (!action_performer) {
// TODO(b/306023057): Record unrecognized action error.
return;
}
action_performer->Run(
campaign_id, group_id, params,
base::BindOnce(
[](growth::ActionType action_type, growth::ActionResult result,
std::optional<growth::ActionResultReason> reason) {
if (result == growth::ActionResult::kSuccess) {
return;
}
CAMPAIGNS_LOG(ERROR)
<< "Error running action. Action type: " << int(action_type)
<< ". Error code:"
<< static_cast<int>(
reason.value_or(growth::ActionResultReason::kUnknown));
RecordCampaignsManagerError(
CampaignsManagerError::kPerformActionFailed);
},
action_type));
}
void CampaignsManager::ClearEvent(CampaignEvent event, std::string_view id) {
ClearEvent(GetEventName(event, id));
}
void CampaignsManager::ClearEvent(std::string_view event) {
std::map<std::string, std::string> conditions_params;
// Event can be put in any key starting with `event_`.
// Please see `components/feature_engagement/README.md#featureconfig`.
conditions_params[kEventKey] = base::StrCat(
{"name:", event, ";comparator:any;window:3650;storage:3650"});
client_->ClearConfig(conditions_params);
}
void CampaignsManager::ClearAllEvents() {
if (!ash::features::IsGrowthInternalsEnabled()) {
return;
}
for (const auto slot : kAllSlotsSet) {
const auto* targeted_campaigns = GetCampaignsBySlot(&campaigns_, slot);
if (!targeted_campaigns) {
continue;
}
for (auto& campaign_value : *targeted_campaigns) {
const auto* campaign = campaign_value.GetIfDict();
if (!campaign) {
continue;
}
const auto campaign_id = GetCampaignId(campaign);
if (!campaign_id) {
continue;
}
const auto* targetings = GetTargetings(campaign);
if (!targetings || targetings->empty()) {
continue;
}
for (const auto& targeting : *targetings) {
const auto* target = targeting.GetIfDict();
if (!target) {
continue;
}
const auto events_targeting =
RuntimeTargeting(target).GetEventsTargeting();
if (!events_targeting) {
continue;
}
ClearEventsByTargeting(*events_targeting, campaign_id.value(),
GetCampaignGroupId(campaign));
}
}
}
}
void CampaignsManager::RecordEvent(const std::string& event,
bool trigger_campaigns) {
const bool should_trigger_campaigns =
trigger_campaigns &&
ash::features::IsGrowthCampaignsTriggerByRecordEventEnabled();
if (!campaigns_loaded_) {
// Event is recorded before campaigns are loaded and feature engagement
// tracker is initialized, defer recording and trigger to
// `OnCampaignsComponentLoaded()` where campaigns are loaded and feature
// engagement is ready.
if (should_trigger_campaigns) {
queued_events_record_and_trigger_.insert(event);
} else {
queued_events_record_only_.insert(event);
}
RecordCampaignsManagerError(
CampaignsManagerError::kRecordEventBeforeCampaignsLoaded);
return;
}
client_->RecordEvent(event, should_trigger_campaigns);
}
void CampaignsManager::RecordQueuedEventsAndMaybeTrigger() {
CHECK(campaigns_loaded_);
for (const auto& event : queued_events_record_only_) {
RecordEvent(event, /*trigger_campaigns=*/false);
}
queued_events_record_only_.clear();
for (const auto& event : queued_events_record_and_trigger_) {
RecordEvent(event, /*trigger_campaigns=*/true);
}
queued_events_record_and_trigger_.clear();
}
void CampaignsManager::OnCampaignsComponentLoaded(
base::OnceClosure load_callback,
bool in_oobe,
const std::optional<const base::FilePath>& path) {
RecordCampaignsComponentDownloadDuration(
base::TimeTicks::Now() - campaigns_download_start_time_, in_oobe);
if (!path.has_value()) {
CAMPAIGNS_LOG(ERROR) << "Failed to load campaign component.";
RecordCampaignsManagerError(
CampaignsManagerError::kCampaignsComponentLoadFail);
OnCampaignsLoaded(std::move(load_callback), /*campaigns=*/std::nullopt);
return;
}
CAMPAIGNS_LOG(DEBUG) << "Getting device registered time.";
if (const auto registered_time = GetRegisteredTimeForTesting()) {
CAMPAIGNS_LOG(DEBUG) << "Registered time for test is set.";
OnOobeTimestampLoaded(std::move(load_callback), path,
registered_time.value());
return;
}
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&GetOobeTimestampBackground),
base::BindOnce(&CampaignsManager::OnOobeTimestampLoaded,
weak_factory_.GetWeakPtr(), std::move(load_callback),
path));
}
void CampaignsManager::OnCampaignsLoaded(
base::OnceClosure load_callback,
std::optional<base::Value::Dict> campaigns_dict) {
// Load campaigns into campaigns store.
if (campaigns_dict.has_value()) {
// Update campaigns store.
campaigns_ = std::move(campaigns_dict.value());
} else {
CAMPAIGNS_LOG(ERROR) << "No campaign is loaded.";
}
// Load campaigns into `CampaignMatcher` for selecting campaigns.
CAMPAIGNS_LOG(DEBUG) << "Filter and set campaigns.";
matcher_.FilterAndSetCampaigns(&campaigns_);
campaigns_loaded_ = true;
RecordQueuedEventsAndMaybeTrigger();
std::move(load_callback).Run();
NotifyCampaignsLoaded();
}
void CampaignsManager::OnOobeTimestampLoaded(
base::OnceClosure load_callback,
const std::optional<const base::FilePath>& path,
base::Time oobe_time) {
CAMPAIGNS_LOG(DEBUG) << "Device registered time is: "
<< oobe_time.InSecondsFSinceUnixEpoch();
matcher_.SetOobeCompleteTime(oobe_time);
CAMPAIGNS_LOG(DEBUG) << "Initializing feature_engagement::Tracker.";
if (tracker_initialized_for_test_) {
OnTrackerInitialized(std::move(load_callback), path,
/*init_success=*/true);
return;
}
client_->AddOnTrackerInitializedCallback(base::BindOnce(
&CampaignsManager::OnTrackerInitialized, weak_factory_.GetWeakPtr(),
std::move(load_callback), path));
}
void CampaignsManager::OnTrackerInitialized(
base::OnceClosure load_callback,
const std::optional<const base::FilePath>& path,
bool init_success) {
if (!init_success) {
// Only log error, but will continue loading campaigns.
CAMPAIGNS_LOG(ERROR) << "Failed to initialize feature_engagement::Tracker.";
RecordCampaignsManagerError(
CampaignsManagerError::kTrackerInitializationFail);
}
CAMPAIGNS_LOG(DEBUG) << "Initialized feature_engagement::Tracker.";
// Read the campaigns file from component mounted path.
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()}, base::BindOnce(&ReadCampaignsFile, *path),
base::BindOnce(&CampaignsManager::OnCampaignsLoaded,
weak_factory_.GetWeakPtr(), std::move(load_callback)));
}
void CampaignsManager::NotifyCampaignsLoaded() {
for (auto& observer : observers_) {
observer.OnCampaignsLoadCompleted();
}
}
void CampaignsManager::SetMantaCapabilityForTesting(signin::Tribool value) {
matcher_.SetMantaCapabilityForTesting(value); // IN-TEST
}
void CampaignsManager::SetBoardForTesting(std::optional<std::string> board) {
matcher_.SetBoardForTesting(board); // IN-TEST
}
void CampaignsManager::SetOobeCompleteTimeForTesting(base::Time time) {
oobe_complete_time_for_test_ = time;
}
void CampaignsManager::SetTrackerInitializedForTesting() {
tracker_initialized_for_test_ = true;
}
const Campaigns* CampaignsManager::GetCampaignsBySlotForTesting(
Slot slot) const {
return GetCampaignsBySlot(&campaigns_, slot);
}
std::optional<base::Time> CampaignsManager::GetRegisteredTimeForTesting() {
if (!oobe_complete_time_for_test_.is_null()) {
return oobe_complete_time_for_test_;
}
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(
ash::switches::kGrowthCampaignsRegisteredTimeSecondsSinceUnixEpoch)) {
CAMPAIGNS_LOG(DEBUG)
<< "Switch `kGrothCampaignsRegisteredTimeSecondsSinceUnixEpoch` is "
"set.";
const auto& value = command_line->GetSwitchValueASCII(
ash::switches::kGrowthCampaignsRegisteredTimeSecondsSinceUnixEpoch);
double seconds_since_epoch;
CHECK(base::StringToDouble(value, &seconds_since_epoch));
return base::Time::FromSecondsSinceUnixEpoch(seconds_since_epoch);
}
return std::nullopt;
}
void CampaignsManager::MaybeRecordImpressionForControl(
const Campaign* campaign) const {
if (!campaign) {
return;
}
const auto* payload = campaign->FindDict(kPayloadPath);
if (payload->empty()) {
// Record impression for campaign that has empty payload which is usually
// counterfactual control campaign.
// This is needed to avoid imbalance between experiment group and
// counterfactual control group that caused by impression cap.
std::optional<int> campaign_id = growth::GetCampaignId(campaign);
if (!campaign_id) {
// TODO(crbug.com/308684443): Add error metrics in a second CL.
CAMPAIGNS_LOG(ERROR) << "Growth campaign id not found";
return;
}
CAMPAIGNS_LOG(DEBUG) << "Record impression events for counterfactual "
<< "campaign: " << campaign_id.value();
client_->RecordImpressionEvents(campaign_id.value(),
GetCampaignGroupId(campaign));
}
}
void CampaignsManager::RegisterTrialForCampaign(
const Campaign* campaign) const {
if (!campaign) {
return;
}
std::optional<int> campaign_id = growth::GetCampaignId(campaign);
if (!campaign_id) {
// TODO(b/308684443): Add error metrics in a second CL.
CAMPAIGNS_LOG(ERROR) << "Growth campaign id not found";
return;
}
std::optional<int> study_id = GetStudyId(campaign);
// If `study_id` is not null, appends it to the end of `trial_name`.
std::string trial_name(kGrowthStudyName);
if (study_id) {
base::StringAppendF(&trial_name, "%d", *study_id);
}
std::string group_name(kGrowthGroupName);
base::StringAppendF(&group_name, "%d", *campaign_id);
client_->RegisterSyntheticFieldTrial(trial_name, group_name);
std::optional<bool> register_with_trigger_event =
ShouldRegisterTrialWithTriggerEventName(campaign);
if (!register_with_trigger_event.value_or(false)) {
return;
}
// Register synthetic field trail with `event` name if this campaign is
// triggered by `kEvent`. This is used for shared counterfactual control group
// to be able to slice by different triggerings, e.g. `DocsOpened`,
// `GmailOpened`, etc.
if (GetTrigger().type != TriggerType::kEvent) {
return;
}
// The first event name is used to register the synthetic field trail.
// TODO: b/367838684 - Currently, this is only used for the G1 campaigns,
// where it triggers at app open and has only one event. Extend this to
// support multiple events.
CHECK(!GetTrigger().events.empty());
group_name += GetTrigger().events[0];
client_->RegisterSyntheticFieldTrial(trial_name, group_name);
}
void CampaignsManager::ClearEventsByTargeting(
const EventsTargeting& events_targeting,
int campaign_id,
std::optional<int> group_id) {
if (!ash::features::IsGrowthInternalsEnabled()) {
return;
}
std::map<std::string, std::string> conditions_params =
CreateBasicConditionParams();
// Clear group impression and dismissal events.
if (group_id) {
// The cap value can be any number. The string here will be parsed as an
// EventConfig and only the name of the EventConfig is used to clear the
// database.
conditions_params[kEventKey] = CreateConditionParamForCap(
"Group", group_id.value(), "Impression",
events_targeting.GetGroupImpressionCap().value_or(1));
client_->ClearConfig(conditions_params);
conditions_params[kEventKey] = CreateConditionParamForCap(
"Group", group_id.value(), "Dismissed",
events_targeting.GetGroupDismissalCap().value_or(1));
client_->ClearConfig(conditions_params);
}
// Clear campaign impression and dismissal events.
conditions_params[kEventKey] =
CreateConditionParamForCap("Campaign", campaign_id, "Impression",
events_targeting.GetImpressionCap());
client_->ClearConfig(conditions_params);
conditions_params[kEventKey] = CreateConditionParamForCap(
"Campaign", campaign_id, "Dismissed", events_targeting.GetDismissalCap());
client_->ClearConfig(conditions_params);
// Clear events used by the campaign targeting.
const base::Value::List* conditions = events_targeting.GetEventsConditions();
if (!conditions) {
return;
}
for (const auto& condition : *conditions) {
if (!condition.is_list()) {
continue;
}
for (const auto& param : condition.GetList()) {
if (!param.is_string()) {
continue;
}
conditions_params[kEventKey] = param.GetString();
client_->ClearConfig(conditions_params);
}
}
}
} // namespace growth
|