File: cluster_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (614 lines) | stat: -rw-r--r-- 21,827 bytes parent folder | download | duplicates (6)
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
// Copyright 2024 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/compare/cluster_manager.h"

#include <optional>
#include <set>
#include <string>
#include <vector>

#include "base/barrier_callback.h"
#include "base/containers/contains.h"
#include "components/commerce/core/commerce_feature_list.h"
#include "components/commerce/core/commerce_utils.h"
#include "components/commerce/core/compare/candidate_product.h"
#include "components/commerce/core/compare/cluster_server_proxy.h"
#include "components/commerce/core/compare/product_group.h"
#include "components/commerce/core/product_specifications/product_specifications_service.h"

namespace commerce {
namespace {
// Check if a URL is currently open.
bool IsUrlOpen(
    GURL url,
    const ClusterManager::GetOpenUrlInfosCallback& get_open_url_infos_cb) {
  const std::vector<UrlInfo> url_infos = get_open_url_infos_cb.Run();
  for (const auto& info : url_infos) {
    if (url == info.url) {
      return true;
    }
  }
  return false;
}

std::optional<std::string> GetShortLabelForCategory(
    const CategoryLabel& category_label) {
  return category_label.category_short_label().empty()
             ? category_label.category_default_label()
             : category_label.category_short_label();
}

// Gets product label from the bottom of a product category. If
// `level_from_bottom` is 0, this returns the last level of the category. If
// `level_from_bottom` is 1, this returns the second to last level of the
// category, and so on.
std::optional<std::string> GetLabelFromBottom(const ProductCategory& category,
                                              int level_from_bottom) {
  int label_size = category.category_labels_size();
  if (label_size <= level_from_bottom) {
    return std::nullopt;
  }
  return GetShortLabelForCategory(
      category.category_labels(label_size - 1 - level_from_bottom));
}

std::string FindTitleForSimilarProducts(
    const std::map<GURL, std::optional<ProductInfo>>& product_infos) {
  // Calculate for each label (both bottom and second-to-bottom level), how
  // many products contain this label.
  //
  // Please note that a product can have multiple categories
  // and contain one label for multiple times (e.g. a product can belong to
  // category Car > Blue Car and Car > Race Car, second-to-bottom level label
  // `Car` appearing twice). In this case, we'll only count one product once for
  // one label.
  base::flat_set<std::string> bottom_labels;
  std::map<std::string, int> label_count;

  for (const auto& entry : product_infos) {
    if (!entry.second.has_value()) {
      continue;
    }

    base::flat_set<std::string> counted_labels;
    if (!entry.second.has_value()) {
      continue;
    }
    for (const auto& product_category :
         entry.second->category_data.product_categories()) {
      std::optional<std::string> bottom_label =
          GetLabelFromBottom(product_category, 0);
      if (bottom_label) {
        std::string bottom_label_string = bottom_label.value();
        bottom_labels.insert(bottom_label_string);
        if (!base::Contains(counted_labels, bottom_label_string)) {
          counted_labels.insert(bottom_label_string);
          label_count[bottom_label_string]++;
        }
      }
      std::optional<std::string> second_to_bottom_label =
          GetLabelFromBottom(product_category, 1);
      if (second_to_bottom_label) {
        std::string second_to_bottom_label_string =
            second_to_bottom_label.value();
        if (!base::Contains(counted_labels, second_to_bottom_label)) {
          counted_labels.insert(second_to_bottom_label_string);
          label_count[second_to_bottom_label_string]++;
        }
      }
    }
  }

  // Get the most common bottom label. When tie, picking the shorter label.
  int max_bottom_count = 0;
  std::string common_bottom_label;
  for (const std::string& bottom_label : bottom_labels) {
    if (label_count[bottom_label] < max_bottom_count) {
      continue;
    }
    if (common_bottom_label.size() == 0 ||
        bottom_label.size() < common_bottom_label.size()) {
      common_bottom_label = bottom_label;
      max_bottom_count = label_count[bottom_label];
    }
  }

  // Early return if we can find a bottom label shared by all products.
  if ((size_t)max_bottom_count == product_infos.size()) {
    return common_bottom_label;
  }

  // If we cannot find a bottom label shared by all products, see if we can find
  // a good second-to-bottom label. For a second-to-bottom label to be good
  // enough to become title, it has to be shared by all products.
  std::string alternate_title;
  for (const auto& pair : label_count) {
    if ((size_t)pair.second != product_infos.size()) {
      continue;
    }
    if (alternate_title.size() == 0 ||
        alternate_title.size() > pair.first.size()) {
      alternate_title = pair.first;
    }
  }

  return alternate_title.size() == 0 ? common_bottom_label : alternate_title;
}

bool ShouldCluster(const CategoryData& category_data) {
  for (const auto& product_category : category_data.product_categories()) {
    for (const auto& category_label : product_category.category_labels()) {
      if (!category_label.should_trigger_clustering()) {
        return false;
      }
    }
  }
  return true;
}

// Determines if two CategoryData are similar. If the bottom label from one of
// the categories in the first CategoryData matches either the bottom or the
// second to bottom label from one of the categories in the second CategoryData,
// they are considered similar.
bool AreCategoriesSimilar(const CategoryData& first,
                          const CategoryData& second) {
  if (!ShouldCluster(first) || !ShouldCluster(second)) {
    return false;
  }
  for (const auto& first_category : first.product_categories()) {
    std::optional<std::string> bottom_1 = GetLabelFromBottom(first_category, 0);
    std::optional<std::string> second_to_bottom_1 =
        GetLabelFromBottom(first_category, 1);
    for (const auto& second_category : second.product_categories()) {
      std::optional<std::string> bottom_2 =
          GetLabelFromBottom(second_category, 0);
      std::optional<std::string> second_to_bottom_2 =
          GetLabelFromBottom(second_category, 1);
      if (bottom_1) {
        if (bottom_1 == bottom_2 || bottom_1 == second_to_bottom_2) {
          return true;
        }
      }
      if (second_to_bottom_1 && second_to_bottom_1 == bottom_2) {
        return true;
      }
    }
  }
  return false;
}

bool IsProductSimilarToGroup(
    const CategoryData& category,
    const std::vector<CategoryData>& group_categories) {
  for (const auto& member : group_categories) {
    if (AreCategoriesSimilar(category, member)) {
      return true;
    }
  }
  return false;
}

bool IsCandidateProductInProductGroup(
    const GURL& candidate_product_url,
    const std::map<base::Uuid, std::unique_ptr<ProductGroup>>&
        product_group_map) {
  for (const auto& product_group : product_group_map) {
    if (product_group.second->member_products.find(candidate_product_url) !=
        product_group.second->member_products.end()) {
      return true;
    }
  }
  return false;
}

}  // namespace

ClusterManager::ClusterManager(
    ProductSpecificationsService* product_specification_service,
    std::unique_ptr<ClusterServerProxy> cluster_server_proxy,
    const GetProductInfoCallback& get_product_info_cb,
    const GetProductInfoBatchCallback& get_product_info_batch_cb,
    const GetOpenUrlInfosCallback& get_open_url_infos_cb)
    : cluster_server_proxy_(std::move(cluster_server_proxy)),
      get_product_info_cb_(get_product_info_cb),
      get_product_info_batch_cb_(get_product_info_batch_cb),
      get_open_url_infos_cb_(get_open_url_infos_cb) {
  product_specification_service->GetAllProductSpecifications(
      base::BindOnce(&ClusterManager::OnGetAllProductSpecificationsSets,
                     weak_ptr_factory_.GetWeakPtr()));
  obs_.Observe(product_specification_service);
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&ClusterManager::RemoveIneligibleGroupsForClustering,
                     weak_ptr_factory_.GetWeakPtr()),
      base::Days(1));
}

ClusterManager::~ClusterManager() {
  observers_.Clear();
}

void ClusterManager::OnGetAllProductSpecificationsSets(
    const std::vector<ProductSpecificationsSet> sets) {
  for (const auto& set : sets) {
    OnProductSpecificationsSetAdded(set);
  }
}

void ClusterManager::OnProductSpecificationsSetAdded(
    const ProductSpecificationsSet& product_specifications_set) {
  if (!IsSetEligibleForClustering(product_specifications_set.uuid(),
                                  product_specifications_set.update_time())) {
    return;
  }
  base::Uuid uuid = product_specifications_set.uuid();
  product_group_map_[uuid] =
      std::make_unique<ProductGroup>(uuid, product_specifications_set.name(),
                                     product_specifications_set.urls(),
                                     product_specifications_set.update_time());
  const std::set<GURL>& urls = product_group_map_[uuid]->member_products;
  std::vector<GURL> url_list;
  for (const GURL& url : urls) {
    url_list.push_back(url);
  }
  get_product_info_batch_cb_.Run(
      url_list,
      base::BindOnce(
          [](base::WeakPtr<ClusterManager> manager, const base::Uuid& uuid,
             const std::set<GURL>& urls,
             std::map<GURL, std::optional<ProductInfo>> info_map) {
            if (!manager) {
              return;
            }
            std::vector<CategoryData> category_data;
            for (const auto& it : info_map) {
              category_data.push_back(it.second.has_value()
                                          ? it.second->category_data
                                          : CategoryData());
            }
            manager->OnAllCategoryDataRetrieved(uuid, urls, category_data);
          },
          weak_ptr_factory_.GetWeakPtr(), product_specifications_set.uuid(),
          urls));
}

void ClusterManager::OnProductSpecificationsSetUpdate(
    const ProductSpecificationsSet& before,
    const ProductSpecificationsSet& product_specifications_set) {
  OnProductSpecificationsSetAdded(product_specifications_set);
}

void ClusterManager::OnProductSpecificationsSetRemoved(
    const ProductSpecificationsSet& set) {
  // TODO(qinmin): Check if we still want to keep candidate product from
  // the removed product group in `candidate_product_map_` if tab is still
  // open.
  product_group_map_.erase(set.uuid());
}

void ClusterManager::WebWrapperDestroyed(const GURL& url) {
  RemoveCandidateProductURLIfNotOpen(url);
}

void ClusterManager::DidNavigatePrimaryMainFrame(const GURL& url) {
  if (candidate_product_map_.find(url) == candidate_product_map_.end()) {
    get_product_info_cb_.Run(
        url, base::BindOnce(&ClusterManager::OnProductInfoRetrieved,
                            weak_ptr_factory_.GetWeakPtr()));
  }
}

void ClusterManager::DidNavigateAway(const GURL& from_url) {
  RemoveCandidateProductURLIfNotOpen(from_url);
}

std::optional<ProductGroup> ClusterManager::GetProductGroupForCandidateProduct(
    const GURL& product_url) {
  if (candidate_product_map_.find(product_url) ==
      candidate_product_map_.end()) {
    return std::nullopt;
  }

  if (IsCandidateProductInProductGroup(product_url, product_group_map_)) {
    return std::nullopt;
  }

  CandidateProduct* candidate = candidate_product_map_[product_url].get();
  base::Time max_time = base::Time::Min();
  base::Uuid uuid;
  for (const auto& product_group : product_group_map_) {
    if (IsProductSimilarToGroup(candidate->category_data,
                                product_group.second->categories) &&
        product_group.second->update_time >= max_time) {
      max_time = product_group.second->update_time;
      uuid = product_group.first;
    }
  }
  if (uuid.is_valid()) {
    return *(product_group_map_[uuid]);
  }
  return std::nullopt;
}

void ClusterManager::OnProductInfoRetrieved(
    const GURL& url,
    const std::optional<const ProductInfo>& product_info) {
  if (!product_info) {
    return;
  }

  if (!IsUrlOpen(url, get_open_url_infos_cb_)) {
    return;
  }

  // If this candidate product already exists, nothing needs to be done.
  if (candidate_product_map_.find(url) != candidate_product_map_.end()) {
    return;
  }

  AddCandidateProduct(url, product_info);
  for (auto& observer : observers_) {
    observer.OnClusterFinishedForNavigation(url);
  }
}

void ClusterManager::OnAllCategoryDataRetrieved(
    const base::Uuid& uuid,
    const std::set<GURL>& urls,
    const std::vector<CategoryData>& category_data) {
  if (product_group_map_.find(uuid) == product_group_map_.end()) {
    return;
  }

  // Check whether product group has changed.
  if (product_group_map_[uuid]->member_products == urls) {
    product_group_map_[uuid]->categories = category_data;
  }
}

void ClusterManager::AddCandidateProduct(
    const GURL& url,
    const std::optional<const ProductInfo>& product_info) {
  std::set<GURL> similar_products;
  for (const auto& product : candidate_product_map_) {
    if (AreCategoriesSimilar(product_info->category_data,
                             product.second->category_data)) {
      similar_products.emplace(product.first);
      product.second->similar_candidate_products_urls.emplace(url);
    }
  }
  candidate_product_map_[url] =
      std::make_unique<CandidateProduct>(url, product_info.value());
  candidate_product_map_[url]->similar_candidate_products_urls =
      similar_products;
}


void ClusterManager::RemoveCandidateProductURLIfNotOpen(const GURL& url) {
  if (candidate_product_map_.find(url) != candidate_product_map_.end() &&
      !IsUrlOpen(url, get_open_url_infos_cb_)) {
    candidate_product_map_.erase(url);
    for (const auto& product : candidate_product_map_) {
      product.second->similar_candidate_products_urls.erase(url);
    }
  }
}

std::vector<GURL> ClusterManager::FindSimilarCandidateProductsForProductGroup(
    const base::Uuid& uuid) {
  std::vector<GURL> candidate_products;
  if (product_group_map_.find(uuid) == product_group_map_.end()) {
    return candidate_products;
  }

  ProductGroup* group = product_group_map_[uuid].get();
  for (const auto& candidate_product : candidate_product_map_) {
    // If the candidate product is in any product group, ignore it.
    if (IsCandidateProductInProductGroup(candidate_product.first,
                                         product_group_map_)) {
      continue;
    }
    if (IsProductSimilarToGroup(candidate_product.second->category_data,
                                group->categories)) {
      candidate_products.emplace_back(candidate_product.first);
    }
  }
  return candidate_products;
}

void ClusterManager::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void ClusterManager::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ClusterManager::GetComparableProducts(
    const EntryPointInfo& entry_point_info,
    GetEntryPointInfoCallback callback) {
  std::vector<uint64_t> product_cluster_ids;
  for (const auto& kv : entry_point_info.similar_candidate_products) {
    product_cluster_ids.push_back(kv.second);
  }
  cluster_server_proxy_->GetComparableProducts(
      std::move(product_cluster_ids),
      base::BindOnce(&ClusterManager::OnGetComparableProducts,
                     weak_ptr_factory_.GetWeakPtr(), entry_point_info,
                     std::move(callback)));
}

std::set<GURL> ClusterManager::FindSimilarCandidateProducts(
    const GURL& product_url) {
  std::set<GURL> similar_candidate_products;
  if (candidate_product_map_.find(product_url) ==
      candidate_product_map_.end()) {
    return similar_candidate_products;
  }

  if (IsCandidateProductInProductGroup(product_url, product_group_map_)) {
    return similar_candidate_products;
  }

  for (const auto& url :
       candidate_product_map_[product_url]->similar_candidate_products_urls) {
    // Remove products that are already in a group.
    if (IsCandidateProductInProductGroup(url, product_group_map_)) {
      continue;
    }
    similar_candidate_products.insert(url);
  }
  return similar_candidate_products;
}

void ClusterManager::GetEntryPointInfoForNavigation(
    const GURL& url,
    GetEntryPointInfoCallback callback) {
  // Don't trigger proactive entry points when the navigation url can be added
  // to an existing cluster.
  if (GetProductGroupForCandidateProduct(url).has_value()) {
    std::move(callback).Run(std::nullopt);
    return;
  }

  std::set<GURL> similar_urls = FindSimilarCandidateProducts(url);
  if (similar_urls.size() == 0) {
    std::move(callback).Run(std::nullopt);
    return;
  }

  similar_urls.insert(url);

  std::vector<GURL> url_list;
  for (const GURL& similar_url : similar_urls) {
    url_list.push_back(similar_url);
  }
  get_product_info_batch_cb_.Run(
      url_list, base::BindOnce(base::BindOnce(
                    &ClusterManager::OnProductInfoFetchedForSimilarUrls,
                    weak_ptr_factory_.GetWeakPtr(), std::move(callback))));
}

void ClusterManager::GetEntryPointInfoForSelection(
    const GURL& old_url,
    const GURL& new_url,
    GetEntryPointInfoCallback callback) {
  // Don't trigger proactive entry points when the selection urls can be added
  // to an existing cluster.
  if (GetProductGroupForCandidateProduct(new_url).has_value()) {
    std::move(callback).Run(std::nullopt);
    return;
  }

  std::set<GURL> similar_urls = FindSimilarCandidateProducts(old_url);
  if (similar_urls.find(new_url) == similar_urls.end()) {
    std::move(callback).Run(std::nullopt);
    return;
  }
  std::set<GURL> similar_urls_new = FindSimilarCandidateProducts(new_url);
  if (similar_urls_new.find(old_url) == similar_urls_new.end()) {
    std::move(callback).Run(std::nullopt);
    return;
  }
  similar_urls.merge(similar_urls_new);

  std::vector<GURL> url_list;
  for (const GURL& similar_url : similar_urls) {
    url_list.push_back(similar_url);
  }
  get_product_info_batch_cb_.Run(
      url_list, base::BindOnce(base::BindOnce(
                    &ClusterManager::OnProductInfoFetchedForSimilarUrls,
                    weak_ptr_factory_.GetWeakPtr(), std::move(callback))));
}

void ClusterManager::OnProductInfoFetchedForSimilarUrls(
    GetEntryPointInfoCallback callback,
    const std::map<GURL, std::optional<ProductInfo>> product_infos) {
  std::map<GURL, uint64_t> map;
  for (auto entry : product_infos) {
    if (entry.second.has_value() &&
        entry.second->product_cluster_id.has_value()) {
      map[entry.first] = entry.second->product_cluster_id.value();
    }
  }
  std::move(callback).Run(std::make_optional<EntryPointInfo>(
      FindTitleForSimilarProducts(product_infos), std::move(map)));
}

void ClusterManager::OnGetComparableProducts(
    const EntryPointInfo& entry_point_info,
    GetEntryPointInfoCallback callback,
    const std::vector<uint64_t>& cluster_product_ids) {
  std::map<GURL, uint64_t> product_cluster_id_map;
  const std::vector<UrlInfo> url_infos = get_open_url_infos_cb_.Run();
  for (const auto& kv : entry_point_info.similar_candidate_products) {
    // If the product Id cannot be clustered, skip it.
    if (!base::Contains(cluster_product_ids, kv.second)) {
      continue;
    }

    // Only add URLs that are still open.
    for (const auto& url_info : url_infos) {
      if (kv.first == url_info.url) {
        product_cluster_id_map.emplace(kv.first, kv.second);
      }
    }
  }

  if (product_cluster_id_map.empty()) {
    std::move(callback).Run(std::nullopt);
    return;
  }

  std::move(callback).Run(EntryPointInfo(entry_point_info.title,
                                         std::move(product_cluster_id_map)));
}

bool ClusterManager::IsSetEligibleForClustering(const base::Uuid& uuid,
                                                const base::Time& update_time) {
  // TODO(b/335724950): A set could become eligible again if it's opened,
  // despite that it's last update time has passed the limit. We need to handle
  // this case by checking if the product specifications page for a set is
  // opened.
  if (IsUrlOpen(GetProductSpecsTabUrlForID(uuid), get_open_url_infos_cb_)) {
    return true;
  }
  return base::Time::Now() - update_time <
         kProductSpecificationsSetValidForClusteringTime.Get();
}

void ClusterManager::RemoveIneligibleGroupsForClustering() {
  for (auto it = product_group_map_.begin(); it != product_group_map_.end();) {
    const auto& product_group = it->second;
    if (!IsSetEligibleForClustering(product_group->uuid,
                                    product_group->update_time)) {
      // If the product URLs in the removing set are open, add them back to
      // candidate products.
      for (const GURL& product_url : product_group->member_products) {
        if (IsUrlOpen(product_url, get_open_url_infos_cb_) &&
            candidate_product_map_.find(product_url) ==
                candidate_product_map_.end()) {
          get_product_info_cb_.Run(
              product_url,
              base::BindOnce(&ClusterManager::OnProductInfoRetrieved,
                             weak_ptr_factory_.GetWeakPtr()));
        }
      }
      it = product_group_map_.erase(it);
    } else {
      it++;
    }
  }

  // Re-schedule another remove in one day.
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&ClusterManager::RemoveIneligibleGroupsForClustering,
                     weak_ptr_factory_.GetWeakPtr()),
      base::Days(1));
}

}  // namespace commerce