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
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/commerce/core/subscriptions/subscriptions_manager.h"
#include <queue>
#include <string>
#include "base/metrics/histogram_functions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "components/commerce/core/commerce_feature_list.h"
#include "components/commerce/core/feature_utils.h"
#include "components/commerce/core/subscriptions/commerce_subscription.h"
#include "components/commerce/core/subscriptions/subscriptions_observer.h"
#include "components/commerce/core/subscriptions/subscriptions_server_proxy.h"
#include "components/commerce/core/subscriptions/subscriptions_storage.h"
#include "components/session_proto_db/session_proto_storage.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace commerce {
namespace {
const int kDefaultTimeoutMs = 10000;
const char kTimeoutParam[] = "subscriptions_request_timeout";
constexpr base::FeatureParam<int> kTimeoutMs{&commerce::kShoppingList,
kTimeoutParam, kDefaultTimeoutMs};
} // namespace
const char kTrackResultHistogramName[] = "Commerce.Subscriptions.TrackResult";
const char kUntrackResultHistogramName[] =
"Commerce.Subscriptions.UntrackResult";
SubscriptionsManager::SubscriptionsManager(
signin::IdentityManager* identity_manager,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
SessionProtoStorage<
commerce_subscription_db::CommerceSubscriptionContentProto>*
subscription_proto_db,
AccountChecker* account_checker)
: SubscriptionsManager(
identity_manager,
std::make_unique<SubscriptionsServerProxy>(
identity_manager,
std::move(url_loader_factory)),
std::make_unique<SubscriptionsStorage>(subscription_proto_db),
account_checker) {}
SubscriptionsManager::SubscriptionsManager(
signin::IdentityManager* identity_manager,
std::unique_ptr<SubscriptionsServerProxy> server_proxy,
std::unique_ptr<SubscriptionsStorage> storage,
AccountChecker* account_checker)
: server_proxy_(std::move(server_proxy)),
storage_(std::move(storage)),
account_checker_(account_checker),
observers_(base::ObserverListPolicy::EXISTING_ONLY) {
SyncSubscriptions();
scoped_identity_manager_observation_.Observe(identity_manager);
}
SubscriptionsManager::SubscriptionsManager() = default;
SubscriptionsManager::~SubscriptionsManager() = default;
SubscriptionsManager::Request::Request(AsyncOperation operation,
base::OnceCallback<void()> callback)
: operation(operation), callback(std::move(callback)) {}
SubscriptionsManager::Request::Request(Request&&) = default;
SubscriptionsManager::Request::~Request() = default;
void SubscriptionsManager::Subscribe(
std::unique_ptr<std::vector<CommerceSubscription>> subscriptions,
base::OnceCallback<void(bool)> callback) {
if (!IsSubscriptionsApiEnabled(account_checker_)) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
CHECK(subscriptions->size() > 0);
SyncIfNeeded();
pending_requests_.emplace(
AsyncOperation::kSubscribe,
base::BindOnce(&SubscriptionsManager::HandleSubscribe,
weak_ptr_factory_.GetWeakPtr(), std::move(subscriptions),
std::move(callback)));
CheckAndProcessRequest();
}
void SubscriptionsManager::Unsubscribe(
std::unique_ptr<std::vector<CommerceSubscription>> subscriptions,
base::OnceCallback<void(bool)> callback) {
if (!IsSubscriptionsApiEnabled(account_checker_)) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
CHECK(subscriptions->size() > 0);
SyncIfNeeded();
pending_requests_.emplace(
AsyncOperation::kUnsubscribe,
base::BindOnce(&SubscriptionsManager::HandleUnsubscribe,
weak_ptr_factory_.GetWeakPtr(), std::move(subscriptions),
std::move(callback)));
CheckAndProcessRequest();
}
void SubscriptionsManager::SyncSubscriptions() {
if (!IsSubscriptionsApiEnabled(account_checker_)) {
return;
}
pending_requests_.emplace(AsyncOperation::kSync,
base::BindOnce(&SubscriptionsManager::HandleSync,
weak_ptr_factory_.GetWeakPtr()));
CheckAndProcessRequest();
}
void SubscriptionsManager::IsSubscribed(
CommerceSubscription subscription,
base::OnceCallback<void(bool)> callback) {
if (!IsSubscriptionsApiEnabled(account_checker_)) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
SyncIfNeeded();
pending_requests_.emplace(
AsyncOperation::kLookupOne,
base::BindOnce(&SubscriptionsManager::HandleLookup,
weak_ptr_factory_.GetWeakPtr(), std::move(subscription),
std::move(callback)));
CheckAndProcessRequest();
}
bool SubscriptionsManager::IsSubscribedFromCache(
const CommerceSubscription& subscription) {
return storage_->IsSubscribedFromCache(subscription);
}
void SubscriptionsManager::GetAllSubscriptions(
SubscriptionType type,
base::OnceCallback<void(std::vector<CommerceSubscription>)> callback) {
if (!IsSubscriptionsApiEnabled(account_checker_)) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback),
std::vector<CommerceSubscription>()));
return;
}
SyncIfNeeded();
pending_requests_.emplace(AsyncOperation::kGetAll,
base::BindOnce(&SubscriptionsManager::HandleGetAll,
weak_ptr_factory_.GetWeakPtr(), type,
std::move(callback)));
CheckAndProcessRequest();
}
void SubscriptionsManager::CheckTimestampOnBookmarkChange(
int64_t bookmark_subscription_change_time) {
pending_requests_.emplace(
AsyncOperation::kCheckOnBookmarkChange,
base::BindOnce(
&SubscriptionsManager::HandleCheckTimestampOnBookmarkChange,
weak_ptr_factory_.GetWeakPtr(), bookmark_subscription_change_time));
CheckAndProcessRequest();
}
void SubscriptionsManager::CheckAndProcessRequest() {
if (HasRequestRunning() || pending_requests_.empty())
return;
// If there is no request running, we can start processing next request in the
// queue.
has_request_running_ = true;
last_request_started_time_ = base::Time::Now();
Request request = std::move(pending_requests_.front());
pending_requests_.pop();
last_request_operation_ = request.operation;
std::move(request.callback).Run();
}
void SubscriptionsManager::SyncIfNeeded() {
if (!last_sync_succeeded_ && !HasRequestRunning()) {
SyncSubscriptions();
}
}
void SubscriptionsManager::OnRequestCompletion() {
has_request_running_ = false;
CheckAndProcessRequest();
}
void SubscriptionsManager::UpdateSyncStates(bool sync_succeeded) {
last_sync_succeeded_ = sync_succeeded;
if (sync_succeeded) {
// Always use the Windows epoch to keep consistency with the timestamp in
// bookmark.
last_sync_time_ =
base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds();
}
}
void SubscriptionsManager::HandleSync() {
if (account_checker_ && account_checker_->IsSignedIn() &&
account_checker_->IsAnonymizedUrlDataCollectionEnabled()) {
GetRemoteSubscriptionsAndUpdateStorage(
SubscriptionType::kPriceTrack,
base::BindOnce(&SubscriptionsManager::OnSyncStatusFetched,
weak_ptr_factory_.GetWeakPtr()));
}
}
void SubscriptionsManager::OnSyncStatusFetched(
SubscriptionsRequestStatus result) {
UpdateSyncStates(result == SubscriptionsRequestStatus::kSuccess);
OnRequestCompletion();
}
void SubscriptionsManager::HandleSubscribe(
std::unique_ptr<std::vector<CommerceSubscription>> subscriptions,
base::OnceCallback<void(bool)> callback) {
SubscriptionType type = (*subscriptions)[0].type;
// Make a copy of subscriptions to notify observers later.
std::vector<CommerceSubscription> notified_subscriptions = *subscriptions;
SubscriptionsRequestCallback wrapped_callback =
base::BindOnce(&SubscriptionsManager::OnSubscribeStatusFetched,
weak_ptr_factory_.GetWeakPtr(),
std::move(notified_subscriptions), std::move(callback));
if (!last_sync_succeeded_) {
std::move(wrapped_callback)
.Run(SubscriptionsRequestStatus::kLastSyncFailed);
return;
}
storage_->GetUniqueNonExistingSubscriptions(
std::move(subscriptions),
base::BindOnce(
&SubscriptionsManager::OnIncomingSubscriptionsFilteredForSubscribe,
weak_ptr_factory_.GetWeakPtr(), type, std::move(wrapped_callback)));
}
void SubscriptionsManager::OnSubscribeStatusFetched(
std::vector<CommerceSubscription> notified_subscriptions,
base::OnceCallback<void(bool)> callback,
SubscriptionsRequestStatus result) {
base::UmaHistogramEnumeration(kTrackResultHistogramName, result);
bool succeeded = result == SubscriptionsRequestStatus::kSuccess ||
result == SubscriptionsRequestStatus::kNoOp;
OnSubscribe(notified_subscriptions, succeeded);
std::move(callback).Run(succeeded);
// We sync local cache with server only when the product is successfully added
// on server. The sync states should be updated after notifying all observers
// and running the callback so |last_sync_time_| is larger than external
// timestamp (e.g. in bookmarks).
if (result == SubscriptionsRequestStatus::kSuccess) {
UpdateSyncStates(true);
}
OnRequestCompletion();
}
void SubscriptionsManager::OnIncomingSubscriptionsFilteredForSubscribe(
SubscriptionType type,
SubscriptionsRequestCallback callback,
std::unique_ptr<std::vector<CommerceSubscription>> unique_subscriptions) {
if (unique_subscriptions->size() == 0) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), SubscriptionsRequestStatus::kNoOp));
return;
}
server_proxy_->Create(
std::move(unique_subscriptions),
base::BindOnce(&SubscriptionsManager::HandleManageSubscriptionsResponse,
weak_ptr_factory_.GetWeakPtr(), type,
std::move(callback)));
}
void SubscriptionsManager::HandleUnsubscribe(
std::unique_ptr<std::vector<CommerceSubscription>> subscriptions,
base::OnceCallback<void(bool)> callback) {
SubscriptionType type = (*subscriptions)[0].type;
// Make a copy of subscriptions to notify observers later.
std::vector<CommerceSubscription> notified_subscriptions = *subscriptions;
SubscriptionsRequestCallback wrapped_callback =
base::BindOnce(&SubscriptionsManager::OnUnsubscribeStatusFetched,
weak_ptr_factory_.GetWeakPtr(),
std::move(notified_subscriptions), std::move(callback));
if (!last_sync_succeeded_) {
std::move(wrapped_callback)
.Run(SubscriptionsRequestStatus::kLastSyncFailed);
return;
}
storage_->GetUniqueExistingSubscriptions(
std::move(subscriptions),
base::BindOnce(
&SubscriptionsManager::OnIncomingSubscriptionsFilteredForUnsubscribe,
weak_ptr_factory_.GetWeakPtr(), type, std::move(wrapped_callback)));
}
void SubscriptionsManager::OnUnsubscribeStatusFetched(
std::vector<CommerceSubscription> notified_subscriptions,
base::OnceCallback<void(bool)> callback,
SubscriptionsRequestStatus result) {
base::UmaHistogramEnumeration(kUntrackResultHistogramName, result);
bool succeeded = result == SubscriptionsRequestStatus::kSuccess ||
result == SubscriptionsRequestStatus::kNoOp;
OnUnsubscribe(notified_subscriptions, succeeded);
std::move(callback).Run(succeeded);
// We sync local cache with server only when the product is successfully
// removed on server. The sync states should be updated after notifying all
// observers and running the callback so |last_sync_time_| is larger than
// external timestamp (e.g. in bookmarks).
if (result == SubscriptionsRequestStatus::kSuccess) {
UpdateSyncStates(true);
}
OnRequestCompletion();
}
void SubscriptionsManager::OnIncomingSubscriptionsFilteredForUnsubscribe(
SubscriptionType type,
SubscriptionsRequestCallback callback,
std::unique_ptr<std::vector<CommerceSubscription>> unique_subscriptions) {
if (unique_subscriptions->size() == 0) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), SubscriptionsRequestStatus::kNoOp));
return;
}
server_proxy_->Delete(
std::move(unique_subscriptions),
base::BindOnce(&SubscriptionsManager::HandleManageSubscriptionsResponse,
weak_ptr_factory_.GetWeakPtr(), type,
std::move(callback)));
}
void SubscriptionsManager::GetRemoteSubscriptionsAndUpdateStorage(
SubscriptionType type,
SubscriptionsRequestCallback callback) {
server_proxy_->Get(
type, base::BindOnce(
&SubscriptionsManager::HandleGetSubscriptionsResponse,
weak_ptr_factory_.GetWeakPtr(), type, std::move(callback)));
}
void SubscriptionsManager::HandleGetSubscriptionsResponse(
SubscriptionType type,
SubscriptionsRequestCallback callback,
SubscriptionsRequestStatus status,
std::unique_ptr<std::vector<CommerceSubscription>> remote_subscriptions) {
if (status != SubscriptionsRequestStatus::kSuccess) {
std::move(callback).Run(status);
} else {
storage_->UpdateStorage(type, std::move(callback),
std::move(remote_subscriptions));
}
}
void SubscriptionsManager::HandleManageSubscriptionsResponse(
SubscriptionType type,
SubscriptionsRequestCallback callback,
SubscriptionsRequestStatus status,
std::unique_ptr<std::vector<CommerceSubscription>> remote_subscriptions) {
if (status != SubscriptionsRequestStatus::kSuccess) {
VLOG(1) << "Fail to create or delete subscriptions on server";
std::move(callback).Run(status);
} else {
storage_->UpdateStorage(type, std::move(callback),
std::move(remote_subscriptions));
}
}
void SubscriptionsManager::HandleLookup(
CommerceSubscription subscription,
base::OnceCallback<void(bool)> callback) {
storage_->IsSubscribed(
std::move(subscription),
base::BindOnce(&SubscriptionsManager::OnLookupResult,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void SubscriptionsManager::OnLookupResult(
base::OnceCallback<void(bool)> callback,
bool is_subscribed) {
std::move(callback).Run(is_subscribed);
OnRequestCompletion();
}
void SubscriptionsManager::HandleGetAll(
SubscriptionType type,
base::OnceCallback<void(std::vector<CommerceSubscription>)> callback) {
storage_->LoadAllSubscriptionsForType(
type,
base::BindOnce(&SubscriptionsManager::OnGetAllResult,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void SubscriptionsManager::OnGetAllResult(
base::OnceCallback<void(std::vector<CommerceSubscription>)> callback,
std::unique_ptr<std::vector<CommerceSubscription>> subscriptions) {
std::move(callback).Run(std::move(*subscriptions));
OnRequestCompletion();
}
void SubscriptionsManager::HandleCheckTimestampOnBookmarkChange(
int64_t bookmark_subscription_change_time) {
// Do nothing if current local cache is newer than the bookmark change.
if (bookmark_subscription_change_time <= last_sync_time_) {
OnRequestCompletion();
return;
}
server_proxy_->Get(
SubscriptionType::kPriceTrack,
base::BindOnce(
&SubscriptionsManager::HandleGetSubscriptionsResponseOnBookmarkChange,
weak_ptr_factory_.GetWeakPtr()));
}
void SubscriptionsManager::HandleGetSubscriptionsResponseOnBookmarkChange(
SubscriptionsRequestStatus status,
std::unique_ptr<std::vector<CommerceSubscription>> remote_subscriptions) {
if (status != SubscriptionsRequestStatus::kSuccess) {
UpdateSyncStates(false);
OnRequestCompletion();
return;
}
storage_->UpdateStorageAndNotifyModifiedSubscriptions(
SubscriptionType::kPriceTrack,
base::BindOnce(&SubscriptionsManager::OnStorageUpdatedOnBookmarkChange,
weak_ptr_factory_.GetWeakPtr()),
std::move(remote_subscriptions));
}
void SubscriptionsManager::OnStorageUpdatedOnBookmarkChange(
SubscriptionsRequestStatus status,
std::vector<CommerceSubscription> added_subs,
std::vector<CommerceSubscription> removed_subs) {
if (status == SubscriptionsRequestStatus::kSuccess) {
if (added_subs.size() > 0) {
OnSubscribe(added_subs, true);
}
if (removed_subs.size() > 0) {
OnUnsubscribe(removed_subs, true);
}
}
UpdateSyncStates(status == SubscriptionsRequestStatus::kSuccess);
OnRequestCompletion();
}
void SubscriptionsManager::OnSubscribe(
const std::vector<CommerceSubscription>& subscriptions,
bool succeeded) {
for (SubscriptionsObserver& observer : observers_) {
for (auto& sub : subscriptions) {
observer.OnSubscribe(sub, succeeded);
}
}
}
void SubscriptionsManager::OnUnsubscribe(
const std::vector<CommerceSubscription>& subscriptions,
bool succeeded) {
for (SubscriptionsObserver& observer : observers_) {
for (auto& sub : subscriptions) {
observer.OnUnsubscribe(sub, succeeded);
}
}
}
void SubscriptionsManager::OnPrimaryAccountChanged(
const signin::PrimaryAccountChangeEvent& event_details) {
storage_->DeleteAll();
SyncSubscriptions();
}
bool SubscriptionsManager::HasRequestRunning() {
// Reset has_request_running_ to false if the last request is stuck somewhere.
// TODO(crbug.com/40241090): We should still be able to get the callback when
// the request times out. Also we should make the callback cancelable itself
// rather than having to wait for the next request coming.
if (has_request_running_ &&
(base::Time::Now() - last_request_started_time_).InMilliseconds() >
kTimeoutMs.Get()) {
has_request_running_ = false;
if (last_request_operation_ == AsyncOperation::kSubscribe) {
base::UmaHistogramEnumeration(kTrackResultHistogramName,
SubscriptionsRequestStatus::kLost);
} else if (last_request_operation_ == AsyncOperation::kUnsubscribe) {
base::UmaHistogramEnumeration(kUntrackResultHistogramName,
SubscriptionsRequestStatus::kLost);
}
}
return has_request_running_;
}
void SubscriptionsManager::AddObserver(SubscriptionsObserver* observer) {
observers_.AddObserver(observer);
}
void SubscriptionsManager::RemoveObserver(SubscriptionsObserver* observer) {
observers_.RemoveObserver(observer);
}
bool SubscriptionsManager::GetLastSyncSucceededForTesting() {
return last_sync_succeeded_;
}
int64_t SubscriptionsManager::GetLastSyncTimeForTesting() {
return last_sync_time_;
}
void SubscriptionsManager::SetHasRequestRunningForTesting(
bool has_request_running) {
has_request_running_ = has_request_running;
}
bool SubscriptionsManager::HasPendingRequestsForTesting() {
return !pending_requests_.empty();
}
void SubscriptionsManager::SetLastRequestStartedTimeForTesting(
base::Time time) {
last_request_started_time_ = time;
}
} // namespace commerce
|